简体   繁体   中英

How to assign objects to specific user?

I am working on a tasks app using Django, I want to assign a task to the user who created it.

the app model:

class Task(models.Model):
    title = models.CharField(max_length=200)
    content = models.TextField(blank=True)
    pub_date = models.DateField(default=timezone.now().strftime("%Y-%m-%d"))
    due_date = models.DateField(default=timezone.now().strftime("%Y-%m-%d"))
    completed = models.BooleanField(default=False)
    completed_date = models.DateField(blank=True, null=True)
    created_by = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        null=True,
        blank=True,
        on_delete=models.CASCADE,
    )
    class Meta:
        ordering = ["-pub_date"] # Ordering by the pub date field
    def __str__(self):
        return self.title

the app views:

class TaskListView(LoginRequiredMixin, ListView):
    model = Task
    template_name = 'task_list.html'
    login_url = 'login'


class TaskCreateView(LoginRequiredMixin, CreateView):
    model = Task
    template_name = 'task_create.html'
    fields = ('title', 'content')
    login_url = 'login'

    def get_success_url(self):
        return reverse('task_list')

class TaskUpdateView(LoginRequiredMixin, UpdateView):
    model = Task
    template_name = 'task_update.html'
    fields = ('title','content',)
    login_url = 'login'

    def get_success_url(self):
        return reverse('task_list')

class TaskDeleteView(DeleteView):
    model = Task
    template_name = 'task_delete.html'
    success_url = reverse_lazy('task_list')

any help would be helpful to me since I am just a beginner:D

In the create view, define an new function:

def form_valid(self, form):
    form.instance.create_by = self.request.user
    form.instance.update_by = self.request.user  # this is for the update view.
    return super().form_valid(form)

Another small hint:

def get_success_url(self) could just be success_url = reverse('task_list') (as a class variable) in your case as you don't use self in you function anyway.

Another small hint:

No need to put login_url = 'login' in each view if you define LOGIN_REDIRECT_URL = '/' , LOGIN_URL = '/login/' and LOGOUT_REDIRECT_URL = '/login/' in the settings.py

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