繁体   English   中英

Django - 如何根据当前登录的用户在管理面板中默认填充 model 的用户字段?

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

我正在尝试在 django 中创建一个问答论坛,只有管理员能够回答所有注册用户提出的问题。

模型.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))

管理员.py

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

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

视图.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)

截至目前,管理面板提供了一个下拉菜单,我可以根据它 select 一个用户,但我需要 model 默认情况下在 Z20F35E630DAF44DBFA4C3F68F5399D8 中显示经过身份验证的管理员用户。

这就是它目前的样子。

current_admin

默认情况下,如何将下拉列表 select 设为当前登录用户?

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 = ()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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