Essam
Essam

Reputation: 43

How to redirect a user based on his choice in drop down?

I've made a form that has a gander Dropdown with two options, how can I redirect a user based on his option if he choices (1) and submit the form will redirect him to a URL and if his choices (2) will redirect him to a different URL. i want to solve it in views or form not in template.

models.py

class User(models.Model):
    first_name = models.CharField(max_length=100)
    second_name = models.CharField(max_length=100)
    E_mail = models.EmailField(max_length=254)
    COUNTRY_CHOICES = [('saudi arabia +966','SAUDI ARABIA +966'),
                       ('oman +968','OMAN +968'),
                       ('kuwait +965','KWUAIT +965'),
                       ('Qatar +948','QATAR +948')]
    country = models.CharField(max_length=250, choices=COUNTRY_CHOICES, null=True)
    phone = models.IntegerField(null=True)
    phone_code = models.IntegerField(null=True)
    birthday = models.IntegerField(null=True)
    GANDER = [('1','Male'),
                           ('2','Female')]
    gander = models.CharField(max_length=250, choices=GANDER, null=True)

    def __str__(self):
        return self.first_name

forms.py

class UserForm(forms.ModelForm):
    class Meta:
        GANDER = (('1', 'male'), ('2', 'female'))
        model = User
        fields = ('first_name', 'second_name', 'E_mail', 'country', 'phone', 'phone_code','birthday', 'nationality',)
        widgets = {
            'first_name': forms.TextInput(attrs={'placeholder': 'الاسم الاول'}),
            'second_name': forms.TextInput(attrs={'placeholder': 'الاسم الثاني'}),
            'E_mail': forms.EmailInput(attrs={'placeholder': '[email protected]'}),
            'nationality':  forms.Select(choices=GANDER,attrs={'class': 'form-control'}),
        }


views.py

def form_page(request):
    if request.method == 'POST':
        form = UserForm(request.POST)
        if form.is_valid():
            print(form)
            form.save()
            if form.nationality == 1:
                return redirect('LandingPage:thank_you')
            else:
                return redirect('LandingPage:thank_you_not')
    else:
        form = UserForm()
    posts = Article.objects.filter(published_date__lte=timezone.now()).order_by('published_date')
    return render(request, 'LandingPage/form_page.html', {'form': form, 'posts': posts,})

My Template

<!-- Nationalety -->
<div class="ui field">
    <label>الجنسية</label>
    {{form.nationality}}
</div>

Upvotes: 0

Views: 437

Answers (1)

MaximeK
MaximeK

Reputation: 2071

You did all the hard stuff, you just need to use form.gander (remove CAPS on Gander) :

if form.is_valid():
    form.save()
    if form.gander == 1:
        return redirect('LandingPage:thank_you_one')
    else:
        return redirect('LandingPage:thank_you_two')

Upvotes: 2

Related Questions