我models.py認證的用戶的字段是固定形式視圖隱藏在Django
from django.db import models
from django.contrib.auth.models import User
class Question(models.Model):
asker = models.ForeignKey(User, related_name='questions')
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField(auto_now_add=True)
slug = models.SlugField(max_length=250, unique_for_date='publish')
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
forms.py
from django.forms import ModelForm
from .models import Question,Choice
from betterforms.multiform import MultiModelForm
class ChoiceForm(ModelForm):
class Meta:
model = Choice
exclude = ('question','votes','pub_date','slug')
class QuestionForm(ModelForm):
class Meta:
model = Question
exclude = ('asker','pub_date',)
class PollForm(MultiModelForm):
form_classes = {
'question':QuestionForm,
'choice':ChoiceForm,
}
views.py
class PollPost(CreateView):
form_class = PollForm
template_name = "blog/post.html"
def form_valid(self, form):
question = form['question'].save(commit=False)
question.asker = User.objects.get(username=request.user.username)
question.save()
choice = form['choice'].save(commit=False)
choice.question = question
choice.save()
return HttpResponse("congrat")
博客/ post.html
<div class="container">
<div class="jumbotron">
<form method="POST">
<div class="text-left">{% csrf_token %} {{ form.as_p }}
</div>
<button type="submit" class="btn btn-primary btn-outline">submit</button>
</form>
</div>
</div>
我用另一種觀點認爲,以發現問題,我認爲Django的認爲這是無效的形式 views.py
def poster(request):
if request.method =='POST':
form = PollForm(request.POST)
print(1)
if form.is_valid():
question = form['question'].save(commit=False)
question.asker = request.user
question.save()
choice = form['choice'].save(commit=False)
choice.question = question
choice.save()
return HttpResponse("congrat")
else :
print("unvalid")
return render(request, 'blog/post.html',
{'form': form})
else:
form = PollForm()
args = {'form': form}
return render(request, 'blog/post.html', args)
使用該視圖打印1然後打印unvalid代替2
現在該視圖不工作,因爲我希望它提供了提問者字段並讓用戶從用戶列表中進行選擇,並且不會隱藏它,並且在提交表單後數據庫中沒有任何更改,頁面也不會重定向也。
我應該如何編輯視圖做出的選擇的最高金額是三 並進行身份驗證的用戶是 由於事先
Django沒有錯誤? – Andreas
@Andreas完全沒有錯誤 –
你可以顯示模板嗎? – zaidfazil