djangodjango-viewsdjango-class-based-viewscreate-view

CreateView redirect with parameter created from the same view


I have this CreateView that creates an object for me and after creating it I would like it to render me inside that object through its 'nome_scheda' which is a text field.

views.py

class SchedaCreateView(CreateView):
  model = Schede
  fields = ['nome_scheda','data_inizio','data_fine']
  template_name = 'crea/passo1.html'

  def form_valid(self, form):
    form.instance.utente = self.request.user
    return super().form_valid(form)

urls.py

path('crea/<nome>/', creazione, name="creazione_passo1"),

Solution

  • You can override the .get_success_url(…) method to return the URL to redirect to by the browser:

    class SchedaCreateView(CreateView):
        model = Schede
        fields = ['nome_scheda','data_inizio','data_fine']
        template_name = 'crea/passo1.html'
    
        def form_valid(self, form):
            form.instance.utente = self.request.user
            return super().form_valid(form)
    
        def get_success_url(self):
            return reverse('creazione_passo1', kwargs={ 'nome': self.object.nome })