Form for relationship ForeignKey

1

is the following I created 3 models, one is the Person, another is aggressor and the other is Life . Being that Agressor inherits of person (I have made the inheritance). And the Life class can have an Aggressor-type object. How do I make this relationship Do I use ForeignKey? And to make this reflect at the time of creating the template, type to enter the values (input) of the created object?

class ForensicPessoa(models.Model):

    name = models.CharField(max_length=100, blank=True, null=True, verbose_name='Nome')
    birth = models.DateTimeField(blank=True, null=True, verbose_name='Data de Nascimento')
    rg = models.CharField(max_length=25, blank=True, null=True, verbose_name='RG')


class ForensicAgressor(ForensicPessoa):

    stature = models.DecimalField(max_digits=20, decimal_places=6, blank=True, null=True, verbose_name='Estatura')
    color_hair = models.CharField(max_length=100, blank=True, null=True, verbose_name='Cor do cabelo')


class ForensicVida(models.Model):

    agressor = models.ForeignKey(ForensicAgressor)
    belongings_victim_lf = models.CharField(max_length=100, blank=True, null=True, verbose_name='Pertences')

How do I access the attributes of the attacker (object) in the template?

{{ form_vida.agressor.name }}   ->agressor (objeto criado class ForensicVida)
    
asked by anonymous 12.05.2016 / 23:20

1 answer

1

Sara,

To link only one attribute I use ForeignKey.

Objects of this type are generated by django as a combobox (forms.Select). If you need to pass a specific object simply inform it in your view. In the example below note that a user is being set for the corresponding attribute in the class.

@login_required
def new(request):
    if request.method == "POST":
    form = ProcessoForm(request.POST)
    if form.is_valid():
        proc = form.save(commit=False)
        proc.usuarioInclusao = request.user
        proc.save()
        form.save_m2m()
        messages.success(request,"Registro "+str(proc.id)+" inserido com sucesso!")
        return redirect('new-proc')
    else:
        messages.error(request, "O formulário não foi preenchido corretamente.")
        return render(request, 'new.html', {'form': form})
form = ProcessoForm()
return render(request, 'new.html', {'form': form})

To access the attribute I believe it is correct. Considering that form_life is the variable you are returning in your render.

return render(request, 'index.html', {'form_vida': form})

I hope I've been able to help you:)

    
14.05.2016 / 01:56