简体   繁体   中英

Having issues with Django forms

I just started developing with Django and I'm having a bit of an issue with the use of a form I've created.

Currently I have a model named SignUp which allows users to "sign up" on the site by inputting their first and last names and their email address.

A feature I'm trying to implement deletes a user who is already signed up by the user submitting the email address they signed up with.

I have a form set up that's just a simple email field but I can't seem to figure out how to get my view to match up the form to the user and then successfully delete the user from the database.

Here is the code for the form:

class DeleteUserForm(forms.Form):
    email_address = forms.EmailField()

And here is the code for the view:

class DeleteUserView(generic.edit.FormView):
    template_name = 'signups/delete_user_form.html'
    form_class = DeleteUserForm
    success_url = '/users/delete/success/'

    def form_valid(self, form):

        for user in SignUp.objects.all():
            if user.email == form:    # The email attribute holds the user's
                user.delete()         # email address and the form should be
                                      # the address the user submitted to be
                                      # deleted?
                return redirect(self.success_url)

        return redirect('/users/delete/failure/')

Every time I try to submit an email address, I get no match, no user is deleted, and I just get redirected to my failure directory.

Anybody have an idea of what's going on? Thanks

Simplest solution:

duplicates = SignUp.objects.filter(email=form.cleaned_data['email_address'])

if duplicates:
    duplicates.delete()

    return redirect(self.success_url)

return redirect('/users/delete/failure/')

Right, fixed the relation lookup.

Using Kamil's logic, I rewrote the field lookup and this code works:

duplicates = SignUp.objects.filter(email__iexact=form.cleaned_data['email_address'])
    if duplicates:
        duplicates.delete()
        return redirect(self.success_url)

But does anyone know why the code I was using before didn't work?

您可以通过form.cleaned_data字典访问字段值:

if user.email == form.cleaned_data['email_address']:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM