A
A
Alex2019-08-20 17:52:39
Django
Alex, 2019-08-20 17:52:39

How to combine get and form_valid methods in django?

I'm sorry for the stupid question, but how can you use the get method from the class view to get the view parameter and then add that parameter to the form. If there is another way, please tell me. Here is the code:

class PostCreate(FormView):
    template_name = 'form.html'
    form_class = PostForm
    success_url = 'http://127.0.0.1:8000/'

    def form_valid(self, form, **kwargs):                 #kwargs - словарь с параметром(условно)
        form.cleaned_data['city'] = City.objects.get(title=kwargs['title'])   #сюда, вместо kwargs['title'], надо засунуть переданный параметр
        Post.objects.create(**form.cleaned_data)
        return redirect(self.get_success_url())

    def get(self, request, **kwargs):
        --------

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2019-08-20
@SenderD

All options are available internally form_validin self.argsand self.kwargs, you getdon't need to use them. Instead Post.objects.create(**form.cleaned_data), you can use a model form and do justform.save()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question