2017-06-30 85 views
2

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

現在該視圖不工作,因爲我希望它提供了提問者字段並讓用戶從用戶列表中進行選擇,並且不會隱藏它,並且在提交表單後數據庫中沒有任何更改,頁面也不會重定向也。

我應該如何編輯視圖做出的選擇的最高金額是三 並進行身份驗證的用戶是 由於事先

+0

Django沒有錯誤? – Andreas

+0

@Andreas完全沒有錯誤 –

+0

你可以顯示模板嗎? – zaidfazil

回答

2

我應該如何編輯視圖以使最大的選擇量爲三,並使得經過身份驗證的用戶成爲問題的提問者。

你可以使用Django inline formsets。內聯表單集是模型表單集上的一個小抽象層。這些簡化了通過外鍵處理相關對象的情況。

然後,你forms.py會,

from django.forms import inlineformset_factory 

class ChoiceForm(ModelForm): 

    class Meta: 
     model = Choice 
     exclude = ('question','votes') 

class QuestionForm(ModelForm): 

    class Meta: 
     model = Question 
     exclude = ('asker','pub_date', 'slug') 


QuestionFormset = inlineformset_factory(Question, 
             Choice, 
             fields=('choice_text',), 
             extra=3,#put number of choices here. 
             ) 

你views.py,

from django.contrib.auth.mixins import LoginRequiredMixin 

class PollPost(LoginRequiredMixin, CreateView): 
    model = Question 
    form_class = QuestionForm 
    template_name = "blog/post.html" 

    def get_context_data(self, **kwargs): 
     context = super(PollPost, self).get_context_data(**kwargs) 
     if self.request.POST: 
      context['formset'] = QuestionFormset(self.request.POST, self.request.FILES) 
     else: 
      context['formset'] = QuestionFormset() 
     return context 

    def form_valid(self, form): 
     context = self.get_context_data() 
     formset = context['formset'] 
     if formset.is_valid() and form.is_valid(): 
      form.instance.asker = self.request.user 
      self.object = form.save() 
      for choice_obj in formset: 
       choice = choice_obj.save(commit=False) 
       choice.question = self.object 
       choice.save() 
     return self.render_to_response(self.get_context_data(form=form, formset=formset)) 

會有在模板中的微小變化,

<div class="container"> 
    <div class="jumbotron"> 

    <form method="POST"> 
     <div class="text-left">{% csrf_token %} {{ form.as_p }} 
     {{ formset.management_form }} 
     {{ formset }} 
     </div> 

     <button type="submit" class="btn btn-primary btn-outline">submit</button> 
    </form> 
    </div> 

+0

非常感謝你的回覆 IGOT這個時間errorin模板 ValidationError在/博客/職位/ ['ManagementForm數據丟失或被篡改'] 並突出顯示{{formset}} –

+0

您正在使用哪個django版本? – zaidfazil

+0

(1,11,2,'final',0)@Fazil Zaid –

1

我不太明白爲什麼的ModelForm沒有問題的提問者排除提問者字段,但是您可能要簡化您的看法:

class PollPost(CreateView): 
    form_class = PollForm 
    template_name = "blog/post.html" 

    def form_valid(self, form): 
     form.instance.asker = self.request.user 
     form.save() 
     return super(PollPost, self).form_valid(form) 

您也可能希望使用LoginRequiredMixin的觀點,以確保你總是有self.request.user。

+0

還是一樣的結果不能修復它 –