Two classes in a Register screen

Asked

Viewed 84 times

1

-2

I’m starting at Django, and I have some questions:

1° In the code below, as you can see, has a class called Student that has relationship with the Responsible class, I would like to show in a registration screen the forms of the two classes to perform the registration, since it is necessary a Responsible to register student. I managed to do with the code below, but I don’t know if there is any better way. Follow a picture of how I want, and I got(https://imgur.com/bp6Aa2Z). But my question is, Is there any better way to accomplish this task?

2º I also wanted to take the height and weight of the student to perform his BMI. How do I do this? When I do the function that takes the height and weight, and compare it to EX: 18.5, it says that it is not possible to compare the function with the value. I also tried to put the calculation value in a variable, and also an error appears saying that it is not possible to compare a Floadinput value with Float. So any solution to this?

3º How do I do over there in the form of "Sex" Put options instead of the person type?

NOTE: There in the views.py realize that there is respform and cadform, the question #1, is in respect to this, is there any way I can do in only 1? Type, in cadform I perform the respform tbm?

Thank you, from now on!

Models:

class Responsavel(models.Model):
    nome_responsavel = models.CharField(max_length=50)
    telefone_responsavel = models.CharField(max_length=15)
    endereco_responsavel = models.CharField(max_length=50)

    def __str__(self):
        return self.nome_responsavel


class Aluno(models.Model):
    nome_aluno = models.CharField(max_length=50)
    idade_aluno = models.DateField()
    peso_aluno = models.FloatField()
    altura_aluno = models.FloatField()

    sexo = models.CharField(max_length=10)

    aluno_responsavel = models.ForeignKey(Responsavel, on_delete=models.CASCADE)

    def __str__(self):
        return self.nome_aluno

Views:

class cadform(ModelForm):
    class Meta:
        model = Aluno
        fields = ['nome_aluno', 'idade_aluno', 'peso_aluno', 'altura_aluno', 'sexo']

    class respform(ModelForm):
    class Meta:
        model = Responsavel
        fields = ['nome_responsavel', 'telefone_responsavel', 'endereco_responsavel']

    def cadastrar_aluno(request, template_name='contas/cadform.html'):
    resp = respform(request.POST or None)
    form = cadform(request.POST or None)
    if resp.is_valid() and form.is_valid():
        form.save()
        resp.save()
        return redirect('index')
    return render(request, template_name, {'form': form, 'resp': resp} )

HTML De Cadastro

   {% extends 'contas/base.html' %}
{% block title %}
Cadastro de Aluno
{% endblock title %}


{% block nav %}
Cadastrar Aluno
{% endblock  %}


{% block content %}
<form method="post">
    {% csrf_token %}
    {{ form.as_p }}
    {{ resp.as_p }}
    <button type="submit" class="btn btn-primary">
        Cadastrar
    </button>
</form>
{% endblock content %}

3 answers

0

check if you put it like this:

Already tested, look image:

inserir a descrição da imagem aqui

class cadform(ModelForm):
    SEX_CHOICES = (
        ('F', 'Female',),
        ('M', 'Male',),
        ('U', 'Unsure',),
    )
    sexo= forms.CharField(label='Select sex', widget=forms.Select(choices=SEX_CHOICES))
    class Meta:
        model = Aluno
        fields = ['nome_aluno', 'idade_aluno', 'peso_aluno', 'altura_aluno', 'sexo']


class respform(ModelForm):
    class Meta:
        model = Responsavel
        fields = ['nome_responsavel', 'telefone_responsavel', 'endereco_responsavel']

    def cadastrar_aluno(request, template_name='app/cadform.html'):
        resp = respform(request.POST or None)
        form = cadform(request.POST or None)
        if resp.is_valid() and form.is_valid():
            form.save()
            resp.save()
            return redirect('index')
        return render(request, template_name, {'form': form, 'resp': resp} )

  • Hi, I copied and pasted your code: https://imgur.com/a/HHgk3qk

  • I ended up stopping, getting discouraged at not being able to do this.

  • Hello there, don’t lose heart. The learning curve of a framework is always high, but then you will see that you will have a high productivity.

  • As for your code, since you didn’t share in the image before what you were using, I didn’t know how you were doing GET from the form, that’s what you’re missing there. I’ll enter the code for Forms.py.

0

The line I added to the.py urls, plus Forms.py, with the Alunoview class is that Django can load with the GET a form request to the view:

urls

 url(r'^cadastra', app.forms.AlunoView.as_view(), name='my-view'),

Forms

"""
Definition of forms.
"""

from django import forms
from django.views import View
from django.forms import ModelForm
from django.shortcuts import render
from django.contrib.auth.forms import AuthenticationForm
from django.utils.translation import ugettext_lazy as _
from .models import Aluno, Responsavel

class cadform(ModelForm):
    SEX_CHOICES = (
        ('F', 'Female',),
        ('M', 'Male',),
        ('U', 'Unsure',),
    )
    sexo= forms.CharField(label='Select sex', widget=forms.Select(choices=SEX_CHOICES))
    class Meta:
        model = Aluno
        fields = ['nome_aluno', 'idade_aluno', 'peso_aluno', 'altura_aluno', 'sexo']


class respform(ModelForm):
    class Meta:
        model = Responsavel
        fields = ['nome_responsavel', 'telefone_responsavel', 'endereco_responsavel']

    def cadastrar_aluno(request, template_name='contas/cadform.html'):
        resp = respform(request.POST or None)
        form = cadform(request.POST or None)
        if resp.is_valid() and form.is_valid():
            form.save()
            resp.save()
            return redirect('index')
        return render(request, template_name, {'form': form, 'resp': resp} )

class AlunoView(View):

    form_class = cadform
    template_name = 'contas/cadform.html'

    def get(self, request):
        form = self.form_class()
        return render(request, self.template_name, {'form': form})

0

The database attribute "sex" is, like others, an SCD table (Slowly Changing Dimension), will not have major changes over time, so you can switch to CHOICES in Django. Then the options will be rendered by the Django UI engine in {{ form.as_p }} and presents a dropdown list with the options.

class Aluno(models.Model):
    SEX_CHOICES = (
        ('F', 'Female',),
        ('M', 'Male',),
        ('U', 'Unsure',),
    )
    nome_aluno = models.CharField(max_length=50)
    idade_aluno = models.DateField()
    peso_aluno = models.FloatField()
    altura_aluno = models.FloatField()

    sexo = models.CharField(max_length=10, choices=SEX_CHOICES)
    aluno_responsavel = models.ForeignKey(Responsavel, on_delete=models.CASCADE)

    def __str__(self):
        return self.nome_aluno
  • Hi, it looks like this when I add Choice: https://imgur.com/a/ykGwcNd

  • Hi hi hi, I forgot that you are using your own custom template, if you activate the admin option in Django just that, in case you lack view import the models Choices, something like that from . models import SEX_CHOICES, and in the view cadForm sex = Forms.Choicefield(widget=Forms.Radioselect, Choices=SEX_CHOICES), in this example with radioselect or sex= Forms.Charfield(label='Select sex', widget=Forms.Select(Choices=SEX_CHOICES)).

  • Django.core.exceptions.Fielderror: Unknown field(s) (sex) specified for Aluno gave this error here, brother :(

Browser other questions tagged

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