user7718204
user7718204

Reputation: 13

django how to distinguish user's email ?

I want to user register their email's end "ac.uk". if it is not, they got some messages.

i do not know how to handle.. plz help me.. if not request.FILES['email'].endswith("ac.uk"): bring MultiValueDictKeyError at /LanguageExchange/.

this is my view.

def register(request):
 registered = False
 if request.method == 'POST':
    user_form = UserCreationForm(data=request.POST)
    if user_form.is_valid():       
        if not request.FILES['email'].endswith("ac.uk"):
             messages.warning(request, 'You need to use ac ID', extra_tags='alert') 
             return redirect('/LanguageExchange/')
        else:
            user = user_form.save()
            user.save()
            if 'Profile_image' in request.FILES:
                user.Profile_image = request.FILES['Profile_image'
                user.save()
                registered = True

    else:
        print(user_form.errors)

else:
    user_form = UserCreationForm()

return render(request,
            'LanguageExchange/register.html',
            {'user_form': UserCreationForm,
            'registered': registered})

Upvotes: 0

Views: 64

Answers (1)

Alasdair
Alasdair

Reputation: 308999

You get the MultiValueDictKeyError because email is not a file field - the value is in request.POST not request.FILES. However you should avoid accessing data from request.POST where possible, and use form.cleaned_data['email'] instead.

Having said that, it would probably be nicer to validate the email inside the form, rather than redirecting in the view.

class MyUserCreationForm(UserCreationForm):
    def clean_email(self):
        email = self.cleaned_data['email']
        if not email.endswith('ac.uk'):
            raise forms.ValidationError('You need to use ac ID')
        return email

Then you can replace UserCreationForm with MyUserCreationForm and remove the email check from your view.

In your view, you pass user_form to the template context, so that you can see any form errors.

return render(request,
             'LanguageExchange/register.html',
             {'user_form': user_form,
              'registered': registered})

Upvotes: 2

Related Questions