如何在Django中设置模型的默认值?

时间:2022-10-04 22:39:48

I want to create a Invitation app which has a sender, receiver and message. How can I set the current logged in user as a sender which is immutable?

我想创建一个邀请应用,它有一个发送方,接收方和消息。如何将当前登录的用户设置为不可变的发送方?

In the model.py

class Invitation(models.Model):
    from_user = models.CharField(max_length=100)
    to_user = models.ForeignKey(User, related_name="invitations_received")
    message = models.CharField(max_length=300)
    timestap = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return "{} to {}: {}".format(self.from_user, self.to_user, self.message)

In the views.py

from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from .models import Game
from .models import Invitation
from .forms import InvitationForm

@login_required

def new_invitation(request):
    if request.method == 'POST':
        form = InvitationForm(data=request.POST, from_user=request.user)
        if form.is_valid():
            form.save()
            return redirect('profiles_home')
    else:
        form = InvitationForm()
    return render(request, "arosis/new_invitation.html", {'form': form})

In the forms.py

from django.forms import ModelForm
from .models import Invitation
from django.shortcuts import render




class InvitationForm(ModelForm):
    class Meta:
        model = Invitation

2 个解决方案

#1


1  

You cannot simply default to the current user because Django ORM is not normally aware of Django authentication system. You should either:

不能简单地默认为当前用户,因为Django ORM通常不知道Django身份验证系统。你应该:

1) Pass the request.user while creating the model instance, like:

1)通过请求。用户在创建模型实例时,如:

invitation = Invitation(from_user=request.user)

or

2) Use a middleware that adds the current user to the model each time it is saved. You can try one of these packages: https://www.djangopackages.com/grids/g/model-audit/

2)使用一个中间件,在每次保存当前用户时将其添加到模型中。您可以尝试这些包中的一个:https://www.djangopackages.com/grids/g/model-audit/

#2


0  

I solved it easily for myself as below:

我简单地为自己解决了如下问题:

In the models.py:

class Invitation(models.Model):
    from_user = models.ForeignKey(User, related_name="invitations_sent")
    to_user = models.ForeignKey(User, related_name="invitations_received",
                                verbose_name="User to invite",
                                help_text="Please Select the user you want.")
    message = models.CharField("Optional Message", max_length=300, blank=True,
                               help_text="Adding Friendly Message")
    timestap = models.DateTimeField(auto_now_add=True)
    def __str__(self):
        return "{} to {}: {}".format(self.from_user, self.to_user, self.message)

In the views.py:

def new_invitation(request):
    if request.method == 'POST':
        invitation = Invitation(from_user=request.user)
        form = InvitationForm(data=request.POST, instance=invitation)
        if form.is_valid():
            form.save()
            return redirect('arosis_invite')
    else:
        form = InvitationForm(data=request.POST)
    return render(request, "arosis/new_invitation.html", {'form': form})

In the forms.py:

class InvitationForm(ModelForm):
    class Meta:
        model = Invitation
        exclude = ['from_user']

And in the template file:

I solved it really easy! by using:

我很容易就解决了!通过使用:

{{ user.username }}

#1


1  

You cannot simply default to the current user because Django ORM is not normally aware of Django authentication system. You should either:

不能简单地默认为当前用户,因为Django ORM通常不知道Django身份验证系统。你应该:

1) Pass the request.user while creating the model instance, like:

1)通过请求。用户在创建模型实例时,如:

invitation = Invitation(from_user=request.user)

or

2) Use a middleware that adds the current user to the model each time it is saved. You can try one of these packages: https://www.djangopackages.com/grids/g/model-audit/

2)使用一个中间件,在每次保存当前用户时将其添加到模型中。您可以尝试这些包中的一个:https://www.djangopackages.com/grids/g/model-audit/

#2


0  

I solved it easily for myself as below:

我简单地为自己解决了如下问题:

In the models.py:

class Invitation(models.Model):
    from_user = models.ForeignKey(User, related_name="invitations_sent")
    to_user = models.ForeignKey(User, related_name="invitations_received",
                                verbose_name="User to invite",
                                help_text="Please Select the user you want.")
    message = models.CharField("Optional Message", max_length=300, blank=True,
                               help_text="Adding Friendly Message")
    timestap = models.DateTimeField(auto_now_add=True)
    def __str__(self):
        return "{} to {}: {}".format(self.from_user, self.to_user, self.message)

In the views.py:

def new_invitation(request):
    if request.method == 'POST':
        invitation = Invitation(from_user=request.user)
        form = InvitationForm(data=request.POST, instance=invitation)
        if form.is_valid():
            form.save()
            return redirect('arosis_invite')
    else:
        form = InvitationForm(data=request.POST)
    return render(request, "arosis/new_invitation.html", {'form': form})

In the forms.py:

class InvitationForm(ModelForm):
    class Meta:
        model = Invitation
        exclude = ['from_user']

And in the template file:

I solved it really easy! by using:

我很容易就解决了!通过使用:

{{ user.username }}