O
O
Oleg2022-01-25 22:18:11
Django
Oleg, 2022-01-25 22:18:11

How to transfer the created record for editing to another user?

I just started learning django, right after learning python, which I've been learning for a couple of months. So, please, be indulgent) I decided to make a "project" for work, so that it would be more interesting to study this library.

There is a "Report" which is created by the user.
The report author's models and the report model itself.

The code

from django.db import models
from django.contrib.auth.models import User
from django.urls import reverse
import uuid
from datetime import date

class Author(models.Model):
    """
    Модель представляющая автора.
    """
    user = models.OneToOneField(User, on_delete=models.CASCADE, null=True)
    first_name = models.CharField(max_length=100)
    last_name = models.CharField(max_length=100)

    class Meta:
        verbose_name = 'Пользователь'
        verbose_name_plural = 'Пользователи'

    POSITION = [
        ("Operator", "Оператор"),
        ("Admin", "Администратор"),
        ("Engineer", "Ведущий инженер"),
    ]
    post = models.CharField("Должность", max_length=10, choices=POSITION, blank=True, default='Operator')

    def get_absolute_url(self):
        """
        Возвращает url для доступа к определенному экземпляру автора.
        """
        return reverse('user-detail', args=[str(self.id)])


    def __str__(self):
        """
        Строка представляющая модель объекта.
        """
        return '{0} {1}'.format (self.last_name, self.first_name)


The code

class Note(models.Model):
    """
    Модель для представления формы отчета
    """
    title = models.CharField("Заголовок", max_length=100)
    user = models.ForeignKey('Author', on_delete=models.SET_NULL, null=True, verbose_name='Ответственный')
    date = models.DateField("Дата создания",null=True, blank=True)
    textarea = models.TextField("Поле для отчета", max_length=1000)

    tags = models.ManyToManyField(Tags, help_text="Выберите тэг", blank=True, verbose_name='Теги')

    class Meta:
        verbose_name = 'Отчет'
        verbose_name_plural = 'Отчеты'

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('note-detail', args=[str(self.id)])

    def display_tags(self):
        return ', '.join([ tags.name for tags in self.tags.all() ])
        
    display_tags.short_description = 'Теги'


Report Pass Model
The code

class NoteInstance(models.Model):
    """
    Модель представляющая копию поставленной задачи
    """
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text="Уникальный ID для этой задачи")
    note = models.ForeignKey('Note', on_delete=models.SET_NULL, null=True)
    must_do = models.DateField("Выполнить до", null=True, blank=True)
    responsible = models.ForeignKey(Author, on_delete=models.SET_NULL, null=True, blank=True)

    LOAN_STATUS = (
        ('В работе', 'В работе'),
        ('Выполнил', 'Выполнил'),
        ('Отложено', 'Отложено'),
        ('Открыто', 'Открыто'),
    )
    
    status = models.CharField(max_length=10, choices=LOAN_STATUS, blank=True, default='Открыто', help_text='Статус задачи', verbose_name='Статус')

    @property
    def is_overdue(self):
        if self.must_do and date.today() > self.must_do:
            return True
        return False

    class Meta:
        ordering = ["must_do"]

        verbose_name = 'Задача'
        verbose_name_plural = 'Задачи'

    def __str__(self):
        return '{0} {1}'.format (self.id, self.note.title)


But this model only makes a note under the report that it has been transferred to someone. How to let another user edit the report? Or, how to make a copy of the report and transfer it to another user so that he continues editing it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
Kadabrov, 2022-01-26
@Screpka

There are several options
. The first option is to give the rights to edit posts in the admin panel and the author, who was given the rights to edit posts.
Permissions
the second option in the view to write a check that the author is allowed to edit this post
in the NoteInstance model, check responsible if it matches the logged in user, then return true and pass it through the context to the template. In the template, we check through if and either show a link to edit, or not

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question