我想创建一个邀请应用程序,其中包含发件人,收件人和邮件。 如何将当前登录的用户设置为不可变的发件人?
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)
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})
from django.forms import ModelForm
from .models import Invitation
from django.shortcuts import render
class InvitationForm(ModelForm):
class Meta:
model = Invitation
答案 0 :(得分:1)
您不能简单地默认为当前用户,因为Django ORM通常不知道Django身份验证系统。你应该:
1)在创建模型实例时传递request.user
,如:
invitation = Invitation(from_user=request.user)
或
2)使用中间件,每次保存时将当前用户添加到模型中。您可以尝试以下其中一个包:https://www.djangopackages.com/grids/g/model-audit/
答案 1 :(得分:0)
我为自己轻松解决了以下问题:
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)
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})
class InvitationForm(ModelForm):
class Meta:
model = Invitation
exclude = ['from_user']
我解决它真的很容易!使用:
{{ user.username }}