Get parameters in a CreateView view

1

I have a CreateView view to which I am sending a parameter by url, my question is how can I take that parameter to save it in one of the fields of the model?

View:

class ReferenciarSimpatizanteCreateView(CreateView):
    model = Referencia
    template_name = 'referido/form/form.html'
    form_class = ReferidoForm
    page_title = 'Referenciar Simpatizantes'


    def get_context_data(self, **kwargs):
        context = super(ReferenciarSimpatizanteCreateView,self).get_context_data(**kwargs)
        context['page_title'] = self.page_title
        return context

    def get_success_url(self):
        return reverse('simpatizante.refer.list')

Form:

class ReferidoForm(forms.ModelForm):
    error_css_class = 'error'
    required_css_class = 'required'
    label_suffix = ':'

    class Meta:
        model = Referencia
        fields = ['referenciador']
        widgets = {
            'referenciador': forms.TextInput(),
        }

Model: (the parameter I need to save it in the field referenced when the form is sent)

class Referencia(TimeStampedModel):
    referenciador = models.ForeignKey(Simpatizante, related_name="referido_referenciador", on_delete=models.PROTECT)
    referenciado = models.ForeignKey(Simpatizante, related_name="referido_referenciado", on_delete=models.PROTECT)
    fecha = models.DateField()
    creado_por = models.ForeignKey(User, null=True, blank=True, related_name='referido_creado_por', verbose_name=_('creado_por'), on_delete=models.PROTECT)
    actualizado_por = models.ForeignKey(User, null=True, blank=True, related_name='referido_actualizado_por', verbose_name=_('actualizado_por'), on_delete=models.PROTECT)

    class Meta:
        verbose_name = _('referido')
        verbose_name_plural = _('referidos')
        unique_together = ("referenciador", "referenciado")

    def clean(self, *args, **kwargs):
        if not self.referenciador.es_lider:
            raise ValidationError({'referenciador': ["Seleccione un lider",]})

        if self.referenciador == self.referenciado:
            raise ValidationError({'referenciado': ["No se puede refenciar el mismo lider ",]})

    def save(self, *args, **kwargs):
        import datetime

        self.fecha = datetime.datetime.now()

        return super(Referencia, self).save(*args, **kwargs)

URL:

url(r'^refer/(?P<pk>\d+)/$', login_required(views.ReferenciarSimpatizanteCreateView.as_vi‌​ew()), name="simpatizante.refer")
    
asked by Mauricio Villa 11.07.2017 в 19:53
source

2 answers

1

Considering your URL:

url(r'^refer/(?P<pk>\d+)/$', login_required(views.ReferenciarSimpatizanteCreateView.as_vi‌​ew()), name="simpatizante.refer")

You should be able to access pk from your get_context_data method:

    def get_context_data(self, **kwargs):
        context = super(ReferenciarSimpatizanteCreateView,self).get_context_data(**kwargs)
        context['page_title'] = self.page_title
        pk = self.kwargs.get('pk') # El mismo nombre que en tu URL
        return context
    
answered by 13.07.2017 / 17:20
source
1

That depends on how you have the configuration of the url, if what you want is to pass it by url the id of the referenced would be more or less like this:

url(^'referencia/(?P<id_referencia>[0-9]+)/crear/$', ReferenciarSimpatizanteCreateView.as_view())

and in the view if the request to create the model is done by POST (which is the most advisable) you would have to rewrite the post method:

def post(self, request, *args, **kwargs):
    # obtener el id_referencia que se paso por url
    referencia_id = args['id_referencia']
    # obtener la referencia que pertenece a ese id
    referencia = Referencia.objects.get(id=referencia_id)
    # actualizo el modelo y lo salvo
    self.model.referenciador = referencia
    self.save()
    return super(ReferenciarSimpatizanteCreateView, self).post(request, *args, **kwars)
    
answered by 12.07.2017 в 15:50