1

I have followed the django docs starter app and have added in a login and register system using django.auth. I am looking to make it so that a user who has logged in can create a new poll and link the choices to the question automatically. Just like it is done in the django admin panel (see photo).

In the admin.py, you use admin.TabularInLine and fieldsets but I am not sure how I can do this reuglarly in forms.py or views.py I can't seem to find much in the docs or anywhere else so if someone could get, that would be great..

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

procoder22
  • 11
  • 1

1 Answers1

0

I guess this is what you asking for. If you want to do this on your own, I recommend you to look source code of django admin forms (option 2 in answer). You can start researching from here.

Deniz Kaplan
  • 1,549
  • 1
  • 13
  • 18