Django.fun

django- createview with url parameter shows error

I have created a view with a generic view createview, to this view I pass a parameter by url, I have a form, but after clicking on the submit button it is redirected to the same url without parameter and shows error, I have tried to see if the form is invalid using "form_invalid" but it doesn't go there, it doesn't go to "form_valid" either and the "get_success_url" doesn't work, I don't know what's wrong. I want to redirect it to the same view with the parameter in the url.

enter image description here

url.py

app_name = 'gestionAsignacion'

urlpatterns = [
     
    path('asignacionContact/<int:pk>',AsignacionCreateView.as_view(), name='asignacion_contact'),
    path('detalle/asignacion/<int:pk>',descargarAsignacion.as_view(), name='descargar_asignacion'),
    path('asignacionGeneral/',asignacionGeneral.as_view(), name='asignacion_general'),
]


view.py

class AsignacionCreateView(CreateView):
    model=AsignacionContact
    form_class=AsignacionForm
    template_name='gestionAsignacion/asignacion_contact.html'
    # success_url = reverse_lazy('gestionAsignacion:asignacion_general')
    
    def get_initial(self):
        # call super if needed
       
        return {'idasignacion_general': self.kwargs['pk']}

    def form_valid(self, form):
        print('hola form_valid')
        isvalid = super().form_valid(form)
        return isvalid

    def form_invalid(self, form):
        print ("form is invalid")
        return super().form_invalid(form)
   
    def get_success_url(self):
        return HttpResponseRedirect(reverse('gestionAsignacion:asignacion_general'))


    def get_context_data(self, **kwargs):
        # Llame primero a la implementación base para obtener un contexto
        context = super().get_context_data(**kwargs)
       
        # Agregar un QuerySet de todos los libros
        context['asig_general'] = AsignacionGeneral.objects.get(id=self.kwargs['pk'])
        context['object_list'] = AsignacionContact.objects.filter(idasignacion_general=self.kwargs['pk'])
        
        return context

model.py

class AsignacionContact(models.Model):
    id = models.IntegerField(primary_key=True)
    idasignacion_general = models.ForeignKey('AsignacionGeneral', models.DO_NOTHING, db_column='idasignacion_general')
    nombre_asignacion = models.CharField(max_length=100, blank=True, null=True)
    fecha_inicio = models.DateField(blank=True, null=True)
    fecha_fin = models.DateField(blank=True, null=True)
    observacion = models.CharField(max_length=255, blank=True, null=True)
    def __str__(self):
        return self.nombre_asignacion
    class Meta:
         managed = False
         db_table = 'asignacion_contact'

form.py

class AsignacionForm(ModelForm):
    def __init__(self, *args, **kwargs):
        super(AsignacionForm, self).__init__(*args, **kwargs)
        for field in iter(self.fields):
            self.fields[field].widget.attrs.update({
                'class': 'form-control'
            })
    class Meta:
        model=AsignacionContact
        fields=['idasignacion_general','nombre_asignacion','fecha_inicio','fecha_fin','observacion']

This path('asignacionContact/<int:pk>',... means that the primary key of the object is required to show the view.

For example, an object with pk=1 would work for the URL path asignacion/asignacionContact/1.

You don't have a view that's just asignacion/asignacionContact/ in your urls.py.

That's why you are getting a Page not found (404).

I think you think <int:pk> in urls.py are GET querystrings. They are not. They are required URL values. GET parameters appear appended to the URL for example if you were to submit a form with a method="GET". The form data would appear in the URL.

Tutorials

Современный Python: начинаем проект с pyenv и poetry

Настройка проекта Python — виртуальные среды и управление пакетами

Использование requests в Python — тайм-ауты, повторы, хуки

Понимание декораторов в Python

ProcessPoolExecutor в Python: полное руководство

map() против submit() с ProcessPoolExecutor в Python

Понимание атрибутов, словарей и слотов в Python

Полное руководство по slice в Python

Выпуск Django 4.0

Безопасное развертывание приложения Django с помощью Gunicorn, Nginx и HTTPS

Автоматический повтор невыполненных задач Celery

Django REST Framework и Elasticsearch

Докеризация Django с помощью Postgres, Gunicorn и Nginx

Асинхронные задачи с Django и Celery

Релизы безопасности Django: 3.2.4, 3.1.12 и 2.2.24

Выпуски исправлений ошибок Django: 3.2.3, 3.1.11 и 2.2.23

Эффективное использование сериализаторов Django REST Framework

Выпуски безопасности Django: 3.2.2, 3.1.10 и 2.2.22

Выпущенные релизы безопасности Django: 3.2.1, 3.1.9 и 2.2.21

Обработка периодических задач в Django с помощью Celery и Docker

View all tutorials →