python - 如何通过登录用户向问题模型添加选择

标签 python django

我正在学习 django,我有一个想法来修改 django 教程中的民意调查应用程序。我想添加注册和登录的可能性,然后我想做一个表单,用户可以在其中创建问题并添加选择。首先,我尝试以一种观点进行制作,但我认为会有问题,因为我在不同的模型中进行选择和提问。然后我尝试为“createChoice”创建一个 vReverse,但没有找到任何参数。尝试了 1 个模式:['polls\\/(?P<pk>[0-9]+)\\/choice$']iew for creating question and one for creating Choices, but here i've got this error: 我想请教一些关于如何做的建议。如果我能在一页内完成它那就太好了。

这是我的代码:

模型.py

from django.db import models
from django.utils import timezone
import datetime
from django.contrib import auth
# Create your models here.

User = auth.get_user_model()

class Question(models.Model):
    question_text = models.CharField(max_length=200)
    author = models.ForeignKey(User, on_delete=models.CASCADE, null=False)


    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=200)
    votes = models.IntegerField(default=0)
    def __str__(self):
        return self.choice_text

class User(auth.models.User, auth.models.PermissionsMixin):

    def __str__(self):
        return "@{}".format(self.username)

url.py

from django.urls import path, include
from django.contrib.auth import views as auth_views
from . import views

app_name = 'pollapp'
urlpatterns = [
    path('', views.IndexView.as_view(), name='index'),
    path('createdPolls/', views.ListView.as_view(), name='createdPolls'),
    path('<int:pk>/', views.DetailView.as_view(), name='detail'),
    path('<int:pk>/results/', views.ResultsView.as_view(), name='results'),
    path('<int:question_id>/vote/', views.vote, name='vote'),
    path('login/', auth_views.LoginView.as_view(template_name='registration/login.html'), name='login'),
    path('logout/', auth_views.LogoutView.as_view(), name='logout'),
    path('signup/', views.SignUp.as_view(), name='signup'),
    path('createPoll/', views.CreatePoll.as_view(), name='createPoll'),
    path('<int:pk>/choice', views.CreateChoicePoll.as_view(), name='createChoice')
]

View .py

class CreatePoll(LoginRequiredMixin, generic.CreateView):
    form_class = forms.CreatePollForm
    template_name = 'polls/createPoll.html'
    success_url = reverse_lazy('pollapp:createChoice')

    def form_valid(self, form):
        poll = form.save(commit=False)
        poll.author = self.request.user
        poll.save()
        return super().form_valid(form)

class CreateChoicePoll(LoginRequiredMixin, generic.CreateView):
    form_class = forms.CreateChoiceForm
    template_name = 'polls/createChoice.html'
    success_url = 'pollapp:index'

表单.py

class CreatePollForm(forms.ModelForm):

    class Meta:
        model = Question
        fields = ('question_text',)

class CreateChoiceForm(forms.ModelForm):

    class Meta:
        model = Choice
        fields = ('choice_text',)

最佳答案

您需要在 View 中传递pk 的值。您可以通过覆盖 .get_success_url(..) method [Django-doc] 来做到这一点:

from django.urls import <b>reverse</b>

class CreatePoll(LoginRequiredMixin, generic.CreateView):
    form_class = forms.CreatePollForm
    template_name = 'polls/createPoll.html'

    def form_valid(self, form):
        <b>self.object =</b> poll = form.save(commit=False)
        poll.author = self.request.user
        poll.save()
        return super().form_valid(form)

    def <b>get_success_url</b>(self):
        return reverse('pollapp:createChoice', kwargs={'pk': self.object.pk})

关于python - 如何通过登录用户向问题模型添加选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60423322/

相关文章:

python - 如何使用openCV检测卫星航拍图像中的街道线?

python - 如何在 JSON avro 模式中创建枚举数组?

python - django 在 Raspberry PI 中使用热敏打印机

python - django 错误(外部 IP)

Python:如何才能获得变量的值而不是其地址

python - 使用 python3 脚本创建 unix 别名

Python:计算 GTIN-8 数字,代码可以工作,但有时会返回负条形码数字

django 检查模板上下文变量是否存在

Django:mark_safe 位于哪里

python - django 聚合 : sum then average