Essam
Essam

Reputation: 43

How to retrieve data from Form to Views

i can't Retrieving data from my Form choices(nationality) to check the values.

models.py

NATIONALITY_CHOICES = (('1', 'خليجي'), ('2', 'ليس خليجي'))
  nationality = models.CharField(max_length=250, 
choices=NATIONALITY_CHOICES, null=True)

when i check my fields in views it only redirect thank_you_not !

views.py

def form_page(request):
    if request.method == 'POST':
        form = UserForm(request.POST)
        if form.is_valid():
            form.save()
            if form.fields['nationality'].choices == 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,})

class UserForm(forms.ModelForm):
    class Meta:
        NATIONALITY_CHOICES = (('1', 'خليجي'), ('2', 'ليس خليجي'))
        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=NATIONALITY_CHOICES,attrs={'class': 'form-control'}),
        }

how can i solve it ?

Upvotes: 0

Views: 41

Answers (1)

Alex
Alex

Reputation: 2474

You can see field values from a form by inspecting cleaned_data:

if form.is_valid():
    nationality = form.cleaned_data['nationality']
    # do something based on nationality value

Later Edit:

Also, looking at how your choices are defined, you might run into a different set of problems with that if statement.

>>> one_str = '1'
>>> two_str = '2'
>>> one_str == 1
False

You defined strings as identifiers for your choice values. Change them to int to keep that logic intact. Otherwise, you'll never have field_valie == 1 evaluated to True.

Upvotes: 3

Related Questions