首页 > 解决方案 > 如何使用外键和内联创建表单

问题描述

我只是想制作一个投票应用程序,只想有一个简单的 HTML 页面,我可以拥有poll_text和 3/4choice_text字段。

目前我的模型如下所示

#models.py
class Poll(models.Model):
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null = True
    )
    poll_text = models.CharField((""), max_length=250)
    pub_date = models.DateTimeField(default=timezone.now)


    def __str__(self):
        return self.poll_text

class Choice(models.Model):
    poll = models.ForeignKey(Poll, on_delete=models.CASCADE, default = '')
    choice_text = models.CharField( max_length=200)
    no_of_votes = models.IntegerField(default = 0)
    
    def __str__(self):
        return self.choice_text

这就是我的forms.py样子。

#forms.py
from django.forms import ModelForm
from .models import Poll, Choice

class CreatePollForm(ModelForm):
    class Meta:
        model = Poll
        fields = ('poll_text',)

最后admin.py,看起来像这样,这给了我在 localhost/admin 中的正确演示,以及我想要在 HTML 页面中的演示。

#admin.py
from django.contrib import admin
from .models import Poll, Choice
from django.contrib.auth.models import User
# Register your models here.

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


class PollAdmin(admin.ModelAdmin):
    
    fieldsets = [(None, {'fields': ('user','poll_text',)})]
    inlines = [ChoiceInLine] 

请指导我需要进行哪些更改,还请建议我如何调整我的模型以记录用户对此投票的投票。

标签: pythondjangodjango-forms

解决方案


您必须创建一个 html、urls 和视图文件。它应该看起来像这样。

索引.html

<!DOCTYPE html>
<html lang="en" dir="ltr">
    <head>
        <meta charset="utf-8">
        <title></title>
    </head>
    <body>
        {% for i in list%}
           {{i.poll}}
           {{i.choice_text}}
        {% endfor%}
    </body>
</html>

视图.py

from django.shortcuts import render, redirect
 
def index(request):
    list=Choice.objects.all()
    return render(request, 'signup.html', {'list': list})

网址.py

urlpatterns = [
    path('admin/', admin.site.urls),
    path('',app.views.index,name='index'),   #here you should change to the name off your current app
   ]

我可能有一些打字错误,但应该是这样的。


推荐阅读