Get data from Django view

Asked

Viewed 878 times

0

When registering a new user he chooses which group he is part of through a select. Each group has a responsible person, how do I get the email of this responsible person to send an access request email?

In this code I send email but to the email that the user filled and not to the responsible of the group that was chosen.

py.models

class Grupo(models.Model):

    grupo = models.CharField(max_length=255)
    divisao = models.ForeignKey(Divisao)
    responsavel = models.ForeignKey(User)

    @property
      def get_responsavel(self):
        return self.responsavel
    def __unicode__(self):
        return self.grupo


class Perfil(User):
    telefone = models.CharField(max_length=255)
    ramal = models.CharField(max_length=255)
    data_inicio = models.DateField(default=datetime.now, blank=True)
    data_fim = models.DateField(null=True, blank=True)
    e_responsavel = models.BooleanField(default=False)
    vinculo = models.ForeignKey(Vinculo)
    grupos = models.ForeignKey(Grupo)
    divisao = models.ForeignKey(Divisao)

    def __unicode__(self):
        return self.first_name

py views.

def cadastro(request, group_id=None):
    if request.method == 'POST':
        form = UserForm(request.POST)
        formulario = form.save()

        if form.is_valid():
            formulario.set_password(form.cleaned_data['password'])
            formulario.save()

            # Envio de email
            current_site = get_current_site(request)
            message = render_to_string('acc_active_email.html', {
                'user': formulario,
                'domain': current_site.domain,
                'uid': urlsafe_base64_encode(force_bytes(formulario.pk)),
                'token': account_activation_token.make_token(formulario),
            })
            mail_subject = 'Novo usuario no sistema'


            group = Grupo.objects.get(pk=group_id)
            responsavel = group.get_responsavel()
            to_email = responsavel.email
            email = EmailMessage(mail_subject, message, to=[to_email])
            email.send()

            return HttpResponseRedirect('/cadastro/login/')

    else:
        form = UserForm()
    return render(request, 'cadastro.html', {
        'form': form,

    })

2 answers

0

Hello!

You can make a filter, to get the group the user chose, you can do so, need to get the group id by submitting the form, there you make the filter:

To catch the moderator, you can make a Decorator in your group model

Ex:

class Grupo(models.Model):
    grupo = models.CharField(max_length=255)
    divisao = models.ForeignKey(Divisao)
    responsavel = models.ForeignKey(User)

    @property
    def get_responsavel(self):
        return self.responsavel

    def __unicode__(self):
        return self.grupo

with this you can catch the moderator of the group

group = Grupo.objects.get(pk=group_id)
responsavel = group.get_responsavel()
responsavel.email

It’s a simple tip, but if you have more questions, it would be interesting to see how your models are, to get the right relationships

  • I updated putting the models, as you can see I use a single form, Userform and I need to take the responsavel_id within the class groups and with that go to the Profile class to get the email by the id of this responsible

  • Hello Bianca, check that I updated the answer, see if you understand?

  • Hi José, thanks for the reply, but returned the following message: Grupo matching query does not exist.

0

At the model instance the return of the email can be specified by

def __str__(self):
    return self.email

If there’s a warning like:

str_ returned non-string

Fix the return that is not a string.

def __str__(self):
    return str(self.email)

In User, has the email registration,name and so on... (correct ?)
And then it indicates what kind of person and what group this is.

And by group want to recover user email in a proper rating.

usuario_logago = request.user.id
Grupo.objects.filter(responsavel_id=usuario_logago)

or

Grupo.objects.filter(responsavel__id__exact=usuario_logago)

By the model that registers the user is using the function that returns the email

def __str__(self):
        return self.email

the return will be presented:

<Queryset [<Group: [email protected]>, <Group: [email protected]>]>

If the person is in other groups the emails will be presented.

In case of use of lookups, could recover by passing the email however does not apply to what needs, but gets the reference

request.user.id : returns the id of the logged in user
request.user : retrieves the name of the logged in user

lookups, recovers change erases record.

In the documentation it is mentioned how to use lookups to recover data from other referenced tb.

field-lookups

I hope it helped, anything only questions :)

Browser other questions tagged

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