Home > front end >  Django - Error received when anonymous user submits form
Django - Error received when anonymous user submits form

Time:12-06

In one of my views I have a form where when a user logs in and submits the form, it works fine.

However, when an anonymous user submits the form I get the following error:

Cannot assign "<SimpleLazyObject: <django.contrib.auth.models.AnonymousUser object at 0x1052fd3a0>>": "User_Inquiries.user" must be a "CustomUser" instance.

This form needs to be submitted whether a user is anonymous or logged in. What do I need to do in order to resolve this issue?

Code below.

Any help is gladly appreciated. Thanks!

views.py

def account_view_contact(request):
    form = ContactUsForm(request.POST or None, request.FILES or None,)
    user_profile = User_Inquiries.objects.all()
    user_profile = User_Info.objects.all()
    user = request.user
    if request.method == "POST":  # checking if request is POST or Not
        # if its a post request, then its checking if the form is valid or not
        if form.is_valid():
            contact_instance = form.save(commit=False)  # "this will return the 'Listing' instance"
            contact_instance.user = user # assign 'user' instance
            contact_instance.save() # calling 'save()' method of model
            return redirect("home")         
    
    context = {
         'form': form, 'user_profile': user_profile
    }

    return render(request, 'contact.html', context)

models.py

class User_Inquiries(models.Model):
    email = models.EmailField(max_length=100, null=True)
    name = models.CharField(max_length=100, null=True)
    subject = models.CharField(max_length=100, null=True)
    message = models.CharField(max_length=100, null=True)
    user = models.ForeignKey(settings.AUTH_USER_MODEL, null=False, on_delete=models.CASCADE)
    date_submitted = models.DateTimeField(auto_now_add=True, null=True)
    
    class Meta:
        verbose_name_plural = "User Inquiries"
        
    @property
    def user_message(self):
        return truncatechars(self.message, 30)

CodePudding user response:

the User_Inquiries model user should be blank = True and null = True. In the view check if the user is logged in before setting the contact_instance.user to user.

models.py

class User_Inquiries(models.Model):

    user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, on_delete=models.CASCADE)

views.py

def account_view_contact(request):
    form = ContactUsForm(request.POST or None, request.FILES or None,)
    user_profile = User_Inquiries.objects.all()
    user_profile = User_Info.objects.all()
    # check if the user is authenticated
    if request.user.is_authenticated:
        user = request.user

    if request.method == "POST":  # checking if request is POST or Not
        # if its a post request, then its checking if the form is valid or not
       if form.is_valid():
            contact_instance = form.save(commit=False)  # "this will return the 'Listing' instance"
            contact_instance.user = user # assign 'user' instance
            contact_instance.save() # calling 'save()' method of model
            return redirect("home")         

    context = {
         'form': form, 'user_profile': user_profile
    }

    return render(request, 'contact.html', context)

check if user is authenticated in django

set null and blank = True

CodePudding user response:

What you can do is :

First, add a user field with null=True

class User_Inquiries(models.Model):
    # ....
    user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, on_delete=models.CASCADE)
    # ...

Second, in your view, you need to provide the user field only if the user is authenticated. Because AnonymousUser can be saved in the database.

def account_view_contact(request):
    user_profile = User_Info.objects.all()
    
    # If it's a post request
    if request.method == "POST":
        form = ContactUsForm(request.POST, request.FILES or None,)
        if form.is_valid():
            if request.user is authenticated:
                # Only authenticated user can be assigned
                contact_instance = form.save(commit=False)
                contact_instance.user = request.user
                contact_instance.save()
                return redirect("home")
            else:
                # Save the form without user because no user is logged in
                form.save()
    
    # Handle no POST request
    else:
        form = ContactUsForm()
        context = {
            'form': form, 'user_profile': user_profile
        }
        
        return render(request, 'contact.html', context)
            
        
    
    

CodePudding user response:

I tried the above solutions and it worked. I also used CreateView to figure this out and it worked flawlessly. Code below:

class account_view_contact(CreateView):
    model = User_Inquiries
    form_class = ContactUsForm
    template_name = "contact.html"
    success_url = reverse_lazy("home")

    def form_valid(self, form):
        if self.request.user.is_authenticated:
            self.object = form.save(commit=False)
            self.object.created_by = self.request.user
            self.object.save()
        else:     
            self.object = form.save(commit=False)
            self.object.save()
        return super().form_valid(form)

Thanks Everyone!

  • Related