V
V
Vitaly2016-08-19 13:18:31
Django
Vitaly, 2016-08-19 13:18:31

How to optimize given Django view code?

I'm doing it on the group's website, I wrote a presentation for inviting a person to the group by login. On the form there is a select from the list of logins, and a button for sending.
invite.html

<form method="post" action="">
    {% csrf_token %}
    {% if inv_inf %}
    {{ inv_inf }} <br><br>
    {% endif %}
    {{ form.to_user.label }}: {{ form.to_user }}
    <input type="submit" value="Invite">
</form>

I don't really like the code below and I'm not sure if it's correct. Please help me to optimize it and fix the wrong sections.
views.py
def invite_to_group(request, g_id):

    inv_inform = ''

    if request.method == 'POST':

        form = InviteUserToGroupForm(request.POST)
        if form.is_valid():
            to_user = User.objects.get(username=form.cleaned_data.get('to_user'))
            g = GroupExt.objects.get(id=g_id)   # GroupExt - разширеная группа Django с доп. полями
            g_members = User.objects.filter(groups=g)

            if to_user.username == request.user.username:
                inv_inform += 'Нене, себя ты не пригласишь'
                return render(request, template_name='invite.html', context={'form': form, 'inv_inf': inv_inform})

            if to_user in g_members: 
                inv_inform += 'Пользователь уже состоит в группе'
                return render(request, template_name='invite.html', context={'form': form, 'inv_inf': inv_inform})

            try:
                inv = Invite.objects.get(to_user=to_user, group=g)  # Invite - модель приглашения пользователя в группу
                inv_inform += 'Приглашение уже отправлено!'
                return render(request, template_name='invite.html', context={'form': form, 'inv_inf': inv_inform})
            except MultipleObjectsReturned:
                inv_inform += 'Приглашение уже отправлено!'
                return render(request, template_name='invite.html', context={'form': form, 'inv_inf': inv_inform})

            except Invite.DoesNotExist:
                inv = Invite.objects.create(to_user=to_user, group=g)
                inv.save()
                inv_inform += 'Отправлено!'
                return render(request, template_name='invite.html', context={'form': form, 'inv_inf': inv_inform})

    form = InviteUserToGroupForm()

    return render(request, template_name='invite.html', context={'form': form})

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman Kitaev, 2016-08-19
@deliro

Such things need to be done when validating the form using the clean_some_field methods (clean is the prefix).
You will also have to slightly redefine the initialization of the form, it will look something like this:

def __init__(self, user, *args, **kwargs):
    super().__init__(*args, **kwargs)
    self.user = user

To throw request.user from the view into the form and then validate inside the form.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question