Form for Foreignkey Relationship

Asked

Viewed 1,063 times

2

is the following created 3 models, one is the Person, another is the aggressor and the other is Life . Being that Aggressor inherits from person (I have already done the inheritance). And the class Life can have an object of the type Aggressor. How do I make this relationship Do I use Foreignkey? And to make it reflect when 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)

1 answer

1

Sara,

To link only one attribute I use Foreignkey.

Objects of this type are generated by Jango as a combobox (Forms.Select). If you need to pass a specific object just inform it in your view. In the example below note that a user is being set to 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. Whereas form_vida 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 :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.