tibas
tibas

Reputation: 199

Assign username to field in models.py table

Let’s say I have a Table1 that contains 5 data,

> class Table1(models.Model):
>     code     = models.CharField(max_length=16,unique=True)
> 
>     author_Up    = models.CharField(max_length=16,default=User)
>     date_Up      = models.DateTimeField(auto_now=True)
>     post_date    = models.DateTimeField(default=timezone.now)
>     author       = models.ForeignKey(User,on_delete=models.CASCADE)
>     def __str__(self):
>         return self.code

I am using formes.py as:

class Table1_F(forms.ModelForm):
    code = forms.CharField(label='Code',max_length=16)
    class Meta:
        model= Table1
        fields=['code']

The Problem is I need to assign a new values of (author_Up) and (date_Up) every time that another user make an update and keep the initial author.

How do I solve this Please?

Upvotes: 2

Views: 715

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476594

I would advise to work with a ForeignKey to refer to the autohr, and furthermore work with auto_now_add for the post_date field:

from django.conf import settings

class Table1(models.Model):
    code = models.CharField(max_length=16,unique=True)
    author_Up = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        related_name='updated_posts',
        on_delete=models.CASCADE
    )
    date_Up = models.DateTimeField(auto_now=True)
    post_date = models.DateTimeField(auto_now_add=True)
    author = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        related_name='written_posts',
        on_delete=models.CASCADE
    )
    
    def __str__(self):
        return self.code

In the UpdateView, we can now update the user model:

from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import UpdateView

class MyUpdateView(LoginRequiredMixin, UpdateView):
    model = Table1
    form = Table1_F

    def form_valid(self, form):
        form.instance.author_Up = self.request.user
        return super().form_valid(form)

In the CreateView, we can set the author, and the authorUp if necessary:

from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import CreateView

class MyUpdateView(LoginRequiredMixin, CreateView):
    model = Table1
    form = Table1_F  # might be another form

    def form_valid(self, form):
        form.instance.author_Up = self.request.user
        form.instance.author = self.request.user
        return super().form_valid(form)

Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.

Upvotes: 2

Related Questions