Search code examples
pythondjangodjango-formsdjango-generic-views

Django form_valid error. Can anyone find the error?


I am trying to use the value from the URL on CreateView

My models are like that: Categoria > Serie

I have made a URL that path('nova-serie/<categoria>', NovaSerie.as_view(), name='nova_serie'),

The URL to create a new Serie is like that: /nova-serie/3

I am trying to use form_valid but I am receiving this message:

Cannot assign "'3'": "Serie.categoria" must be a "Categoria" instance.

views.py

class NovaSerie(CreateView):
    model = Serie
    form_class = SerieForm
    template_name = 'nova_serie.html'
    success_url = reverse_lazy('home')

    def form_valid(self, form):
        url = self.request.path_info
        parte_final_url = url.replace('/nova-serie/', '')
        form.instance.categoria = parte_final_url
        return super(NovaSerie).form_valid(form) 

forms.py

class SerieForm(forms.ModelForm):
    class Meta:
        model = Serie
        fields = (
            'serie',

        )
        widgets = {
            'title': forms.TextInput(),  # attrs={class="title"}
        }

Can anyone here give me a help?


Solution

  • There is no need to do string processing on the path. You can obtain the URL parameters with self.kwargs. Furthermore if you want to specify the id of the .categoria, you should set .categoria_id:

    class NovaSerie(CreateView):
        model = Serie
        form_class = SerieForm
        template_name = 'nova_serie.html'
        success_url = reverse_lazy('home')
    
        def form_valid(self, form):
            form.instance.categoria_id = self.kwargs['categoria']
            return super().form_valid(form)

    I would furthermore advise to specify the categoria URL parameter as an int:

    path('nova-serie/<int:categoria>', NovaSerie.as_view(), name='nova_serie'),

    that way if the value is not an integer it will not fire the view.