Check if the user who is making the request correspond to the connected user, inside "form_valid" django

I'm currently trying to improve my form, I would like to check if the connected user correspond to the user who publish the data

is it possible to add a condition inside the form_valid to see if the user from the model correspond to user from the request before posting the form


class Task(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True)
    title = models.CharField(max_length=200, null=True, blank=True)

view :

class TaskUpdate(LoginRequiredMixin, UpdateView):
    model = Task
    template_name = "tasks/task_form.html"
    form_class = DateInputForm

I already tried to do that :

def form_valid(self, form):

    if self.request.user.is_staff and self.object.user != self.request.user:
        return super().form_valid(form)

    if self.object.user != self.request.user:
        form.add_error(None, "You can't do that")
        return super().form_invalid(form)

also if I'm not a staff user, I can't have access to the input to select users, it's automatically assigns

<form action="" method="post">
    <div style="flex-direction: column">
        {% csrf_token %}

        <div style="margin-bottom: 10px">
            {% if admin %}
                <label for="user">User name : </label>
                {{ form.user }}
            {% endif %}

I also thought of doing an sql query to see if the user making the query corresponds to the user registered for the task.

no solution for the moment

You need to add inside the form_valid

  1. name= Task.objects.get(

After you can set the condition

  1. if name.user != self.request.user:...

now we can verify that the user who posts the form, is the owner

Back to Top