python - 如何使用外键和内联创建表单
问题描述
我只是想制作一个投票应用程序,只想有一个简单的 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]
请指导我需要进行哪些更改,还请建议我如何调整我的模型以记录用户对此投票的投票。
解决方案
您必须创建一个 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
]
我可能有一些打字错误,但应该是这样的。
推荐阅读
- node.js - Angular 8 - 通过 USB 提供时获取 styles.js net::ERR_CONTENT_LENGTH_MISMATCH 200 (OK)
- sql-server - MS SQL -- 从第三个表添加另一个限制
- vue.js - v-bind:class 不使用数组变量
- sql-server - 如何在将数据添加到表中时动态插入日期?
- github - 什么是 GraphQL 查询以确定组织中是否存在 GitHub 包?
- servicestack - 是否可以在 Visual Studio 2017 或 2019 中使用 ServiceStack 模板?
- python - 改进 tensorflow 训练模型
- python - 从大流中选择一个随机元素有什么大不了的?
- javascript - 将 Json 数据映射到新的键值对 JavaScript 对象
- c++ - 如何使用 string::replace 方法写入文件?