Answer the question
In order to leave comments, you need to log in
Why does form_valid end with super(), or how can I pass parameters from one form to another related model form?
Simple example from django_tutorial:
class AuthorCreate(CreateView):
model = Author
fields = ['name']
def form_valid(self, form):
form.instance.created_by = self.request.user
return super(AuthorCreate, self).form_valid(form)
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField(default=datetime.datetime.now())
class Choice(models.Model):
question = models.ForeignKey(Question)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
class QuestionCreate(LoginRequiredMixin, CreateView):
template_name = "polls/create_question.html"
model = Question
fields = ['question_text']
#success_url = reverse_lazy('create_choices')
def form_invalid(self, form):
pass
def form_valid(self, form):
# Код сохраннеия модели
# Какой-то return
#или нижнюю функцию тоже сделать классом и наследовать от CreateView?
def create_choices(request, question_id):
form = ChoiceForm()
try:
question = Question.objects.get(pk = question_id)
except Question.DoesNotExist:
raise Http404
return render(request, "polls/create_choices.html", {"form": form, "question": question})
url(r'create/$', views.QuestionCreate.as_view(), name='create_question'),
url(r'create/(?P<question_id>\d+)/$', views.create_choices, name='create_choices'),
class QuestionForm(forms.ModelForm):
class Meta:
model = Question
fields = ('question_text',)
extra = 1
class ChoiceForm(forms.ModelForm):
class Meta:
model = Choice
fields = ('choice_text',)
extra = 6
#В темплейте 6 полей choice_text не выводит, только одно, с формой явно что то не так
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question