0

Good day.

I have a function-based view and would like to know how to pass the self.update parameter that is in my forms.py exactly in the init function.

Form.py

class AnuncioForm(forms.ModelForm):
     justificacion = forms.CharField(widget=forms.Textarea)
     motivo = forms.ModelChoiceField(queryset=Catalogo.objects.filter(tipo=MOTIVO_DE_RECTIFICACIONES))
     class Meta:
        model = Anuncio

     def __init__(self, *args, **kwargs):
         self.update = kwargs.pop('update', None) # THIS PARAMETER
         super(AnuncioForm, self).__init__(*args, **kwargs)
         if self.update:
             self.fields['motivo'].required = True
             self.fields['justificacion'].required = True

Function-Based Views:

def Anuncio_create_update(request, pk=None):
if pk:
    anuncio = Anuncio.objects.get(pk=pk)
    nave = anuncio.nave
    navefoto = NaveFotos.objects.filter(nave_id=nave.id).first()
    tipo_navefoto = TipoNave.objects.filter(anu_tipo_nave=anuncio.id).values_list('foto')
    historial_anuncio = anuncio.historialedicionanuncios_set.all().select_related('usuario').order_by('-fecha').all()
    update = True

    anuncio_tmp = anuncio.has_bodega_reporte()
    tiene_bodega = anuncio_tmp[0]
    title_meta = u'Anuncio de Naves: Actualización'
    title = u'Anuncio de Naves'
    nav = (
        ('Panel Mando', '/'),
        ('Anuncio de naves', reverse('anuncio_list')),
        (u'Actualización', '')
    )

    # muelle = TarjaMuelle.objects.filter(anuncio=pk, tipo_autorizacion=COMUN_SALIDA)

    # if muelle is not get_es_directo(tipo_operacion=OPE_EMBARQUE_INDIRECTO):
    #     pass

else:
    anuncio = Anuncio()
    tiene_bodega = False
    update = False
    title_meta = u'Anuncio de Naves: Registro'
    title = u'Anuncio de Naves'
    nav = (
        ('Panel Mando', '/'),
        ('Anuncio de Naves', reverse('anuncio_list')),
        ('Registro', '')
    )

unidad_operativa_id = request.session.get(SESION_UNIDAD_OPERATIVA_ID)

tipo_nave = TipoNave.objects.all().values_list('id', 'descripcion')
tipo_trafico = Catalogo.objects.filter(tipo='16').values_list('id', 'nombre')
lineas = Catalogo.objects.filter(tipo='02').values_list('id', 'nombre')
lista_tipo_carga = get_tipo_carga()

# formset
AnuncioBodegaFormSet = inlineformset_factory(
    Anuncio,
    AnuncioBodega,
    extra=0,
    can_delete=True,
    fields=(
        'anuncio', 'bodega', 'total', 'bultos', 'id')
)

# Planificacion
ArticulosFormSet = inlineformset_factory(
    Anuncio,
    ArticuloPorAnuncio,
    extra=0, can_delete=True,
    fields=(
        'articulo', 'cantidad_maxima_vehiculos')
)

ProyectosFormSet = inlineformset_factory(
    Anuncio, AnuncioProyectos, extra=0, can_delete=True,
    fields=(
        'escala',
        'actividad',
        'tipo_trafico',
        'ambito',
        'articulo',
        'tipo_producto'
    )
)

if request.method == 'POST':
    next = request.GET.get('next')
    form = AnuncioForm(request.POST, request.FILES, instance=anuncio)
    # navefoto = NaveFotos(request.POST, request.FILES, instance=navefoto)
    # tipo_navefoto = TipoNaveForm(request.POST, request.FILES, instance=tipo_navefoto)
    articulosFormSet = ArticulosFormSet(request.POST, instance=anuncio)
    proyectosformset = ProyectosFormSet(request.POST, instance=anuncio)
    tipo_nave_id = form.data.get('tipo_nave', None)
    will_redirect = False
    if tipo_nave_id:
        tipo_nave_obj = TipoNave.objects.get(id=int(tipo_nave_id))
        if tipo_nave_obj.requiere_bodega:
            anuncioBodegaFormSet = AnuncioBodegaFormSet(request.POST, instance=anuncio)

            if form.is_valid() and articulosFormSet.is_valid() and anuncioBodegaFormSet.is_valid() and \
                    proyectosformset.is_valid():
                if update:
                    user = request.user
                    motivo = form.cleaned_data['motivo']
                    justificacion = form.cleaned_data['justificacion']
                    HistorialEdicionAnuncios.objects.create(historial_anuncios=anuncio, motivo=motivo,
                                                        observacion=justificacion, usuario=user)
                anuncio = form.save()
                anuncioBodegaFormSet.save()
                articulosFormSet.save()
                proyectosformset.save()
                will_redirect = True

        else:
            if form.is_valid() and articulosFormSet.is_valid() and proyectosformset.is_valid():
                if update:
                    user = request.user
                    motivo = form.cleaned_data['motivo']
                    justificacion = form.cleaned_data['justificacion']
                    HistorialEdicionAnuncios.objects.create(historial_anuncios=anuncio, motivo=motivo,
                                                        observacion=justificacion, usuario=user)
                anuncio = form.save()
                articulosFormSet.save()
                proyectosformset.save()
                will_redirect = True

        if will_redirect:
            if pk == None:
                return redirect(anuncio.get_anuncio_codigo())
            if next == 'new':
                return redirect(reverse('anuncio_create'))
            if next == 'self':
                return redirect(anuncio.get_anuncio_update_url())
            else:
                return redirect('anuncio_list')

else:
    form = AnuncioForm(instance=anuncio)
    anuncioBodegaFormSet = AnuncioBodegaFormSet(instance=anuncio)
    articulosFormSet = ArticulosFormSet(instance=anuncio)
    proyectosformset = ProyectosFormSet(instance=anuncio)

return render('servicio/anuncio_form.html', locals(), context_instance=ctx(request))

I understand that in a class-based view there is a function called get_form_kwargs and there you could put something like this form_kwargs['update'] = True and that's it. But I'm trying with the function-based view and I have no idea how to do it. I would appreciate any correction on this view based on function, I have been learning these views based on function recently and because the truth is that I am a novice on that subject.

Ty.

1 Answer 1

1

You pass update to the form the same way you would pass any other kwarg, for example:

form = AnuncioForm(request.POST, request.FILES, instance=anuncio, update=True)

Remember to update the GET branch as well if you need to.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.