Home > OS >  Check if the user who is making the request is the owner of the data, with "form_valid" dj
Check if the user who is making the request is the owner of the data, with "form_valid" dj

Time:12-20

I'm currently trying to improve my form, I would like to see if the connected user correspond to the user who own the data before rewriting it

The model:

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)

The 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, so it's automatically assigned.

<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 %}
        </div>

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

CodePudding user response:

You need to add inside the form_valid

  1. name= Task.objects.get(pk=self.object.id)

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

  • Related