简体   繁体   中英

Django - How do I populate the user field of a model by default in the admin panel based on the current user logged in?

I am trying to create a question-answer forum in django where only the admins are able to respond to a question asked by all the registered users.

models.py

from django.db import models
from django.contrib.auth.models import User
from datetime import datetime

# Create your models here.
class Question(models.Model):

    username=models.ForeignKey(User, on_delete=models.DO_NOTHING)
    question=models.CharField(max_length=100)
    date=models.DateTimeField(default=datetime.now, blank=True)

    def __str__(self): 
        return self.question

class Comments(models.Model):

    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    content = models.TextField()
    timestamp = models.DateTimeField(auto_now_add=True)


    def __str__(self):

        return '{}-{}'.format(self.question.question, str(self.user.username))

admin.py

from django.contrib import admin
from . models import Question, Comments
# Register your models here.

admin.site.register(Question)
admin.site.register(Comments)

views.py

from django.shortcuts import render, redirect
from . models import Question, Comments
from .forms import CommentForm
# Create your views here.

def addQuestion(request):

    if request.method == 'POST':

        username = request.user
        question = request.POST['question']

        question = Question(username=username, question=question)
        question.save()
        # note=Note(title=title, description=description, username=username)
        # note.save()

        return redirect('/dashboard')

    else:

        return render(request, "dashboard/question.html")

def viewQuestion(request, question_id):

    viewquestion=Question.objects.get(id=question_id)
    comments = Comments.objects.filter(question=viewquestion).order_by('-question_id')


    context = {

        'viewquestion':viewquestion,
        'comments':comments
    }

    return render (request, 'dashboard/questionview.html', context)

As of now, the admin panel provides a drop down based on which I can select a user, but I need the model to display the authenticated admin user by default in the model before adding a comment rather than an admin manually choosing the username.

This is how it looks like currently.

current_admin

How do I make the dropdown select the current logged in user by default?

Step 1:-

# Pass request params to your model form

admin.py

class CommentsAdmin(admin.ModelAdmin):

    def get_form(self, request, obj=None, **kwargs):
        ModelForm = super(CommentsAdmin, self).get_form(request, obj, **kwargs)

        class ModelFormMetaClass(ModelForm):
            def __new__(cls, *args, **kwargs):
                kwargs['request'] = request
                return ModelForm(*args, **kwargs)
        return ModelFormMetaClass

    fields = (('question'), ('user'), ('content',),)
    form = CommentsForm

admin.site.register(Comments, CommentsAdmin)


Step 2:- 

# Create your form which you have specified for your admin class of comments model (CommentsAdmin)

form.py

class CommentsForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('request', None)
        super(CommentsForm, self).__init__(*args, **kwargs)
        self.fields['user'].initial = self.request.user

    class Meta:
        model = Comments
        exclude = ()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM