A
A
Alexander2017-08-15 13:44:02
Django
Alexander, 2017-08-15 13:44:02

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)

I figured out Super and linearization, but I didn’t figure out what the functions should return ...
So, what does the function return in this case? As for me, this is a call to the same function, but it seems incomprehensible to me
...
with a form to create and bind a list of questions by this id?) How to get the id of the saved model from the form?
models:
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)

view:
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})

urls:
url(r'create/$', views.QuestionCreate.as_view(), name='create_question'),
    url(r'create/(?P<question_id>\d+)/$', views.create_choices, name='create_choices'),

forms.py
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 не выводит, только одно, с формой явно что то не так

As a result, the first form should save the name of the question, and with this question go to the second form with the addition of answer options and, when filling out, add the associated id to the Choice table and answer options ... I didn’t understand the formset, I decided to try it, and then do everything in ajax on one page(is it possible?_)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander, 2017-08-16
@koshalex

Please answer the first question

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question