Django为用户轮询应用程序管理员的表单

问题描述 投票:1回答:1

我遵循了django docs入门应用程序,并使用django.auth添加了登录和注册系统。我希望这样做,以便已登录的用户可以创建新的民意调查并自动将选择链接到问题。就像在Django管理面板中完成操作一样(参见照片)。

[在admin.py中,您使用admin.TabularInLine和fieldsets,但是我不确定如何在forms.py或views.py中做到这一点,我似乎在文档或其他任何地方都找不到太多,所以如果有人可以得到,那太好了。

admin.py

from django.contrib import admin
from .models import Question, Choice


class ChoiceInLine(admin.TabularInline):
    model = Choice
    extra = 3


class QuestionAdmin(admin.ModelAdmin):
    fieldsets = [
        (None, {'fields': ['question_text']}),
        ('Date information', {'fields': ['date_posted']})
    ]
    inlines = [ChoiceInLine]
    list_display = ('question_text', 'date_posted',  'was_published_recently')
    list_filer = 'date_posted'


admin.site.register(Question, QuestionAdmin)

models.py

from django.db import models
from django.utils import timezone
import datetime


class Question(models.Model):
    question_text = models.CharField(max_length=200)
    date_posted = models.DateTimeField('Date published')

    def was_published_recently(self):
        now = timezone.now()
        return now - datetime.timedelta(days=1) <= self.date_posted <= now

    was_published_recently.admin_order_field = 'date_posted'
    was_published_recently.boolean = True
    was_published_recently.short_description = 'Posted recently?'

    def __str__(self):
        return self.question_text


class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=100)
    votes = models.IntegerField(default=0)

    def __str__(self):
        return self.choice_text

photo of admin form I would like to replicate

python django python-3.x django-forms
1个回答
0
投票

我想this就是您要的。如果要自己执行此操作,建议您查看django管理表单的源代码(答案中的选项2)。您可以从here开始研究。

© www.soinside.com 2019 - 2024. All rights reserved.