将登录用户传递给表单

时间:2020-08-12 10:05:58

标签: python django forms authentication

我正在尝试将登录用户传递给我要保存的表单。

forms.py

class SpotForm(ModelForm):

def __init__(self, *args, **kwargs):
    super(SpotForm, self).__init__(*args, **kwargs)
    self.fields['gross_weight'].widget = forms.NumberInput(attrs={'min':0})
    self.fields['volume'].widget = forms.NumberInput(attrs={'min': 0})

class Meta:
    model = Spot
    fields = [
        'gross_weight','volume','origin_country','origin_port',
        'dest_country','dest_port','ship_week','requestor'
              ]

models.py

class Stakeholder(models.Model):
user = models.OneToOneField(User,null=True,blank=True,on_delete=models.CASCADE)
company_name = models.CharField(max_length=15)
mail = models.CharField(max_length=40)

def __str__(self):
    return self.mail
class Spot(models.Model):
STATUSES = (
    ('Open','Open'),
    ('Closed','Closed')
)
gross_weight = models.FloatField(null=False,default=0,validators=[MinValueValidator(0)])
volume = models.FloatField(null=False,default=0,validators=[MinValueValidator(0)])
origin_country = models.CharField(
    validators=[RegexValidator(regex='[A-Z]{2}', message='Country code is two letters')], max_length=2,null=True)
origin_port = models.CharField(
    validators=[RegexValidator(regex='[A-Z]{3}', message='Port code is three letters')], max_length=3,null=True)
dest_country = models.CharField(
    validators=[RegexValidator(regex='[A-Z]{2}', message='Country code is two letters')], max_length=2,null=True)
dest_port = models.CharField(
    validators=[RegexValidator(regex='[A-Z]{3}', message='Port code is three letters')], max_length=3,null=True)
time_registered = models.DateField(default=timezone.now)
spot_status = models.CharField(max_length=6,default='Open', choices=STATUSES)
ship_week = models.CharField(max_length=2,null=True)
requestor = models.ForeignKey(Stakeholder,null = True,on_delete=models.CASCADE)

def __str__(self):
    return self.origin_country + self.origin_port + '-' + self.dest_country +self.dest_port + '-' + self.ship_week

views.py

def register_spot(request):
my_user = Stakeholder.objects.get(user=request.user)
form = SpotForm()
if request.method =='POST':
    print("print",request.POST)
    form = SpotForm(request.POST)
    if form.is_valid():
        form.save()
        return redirect('/')
    else:
        print(form.errors)

context = {'form': form}
return render(request, 'spotrequesting/register_spot.html', context)

我提交表单时,在命令提示符中出现错误,指出“请求者”为“此字段必填”。之后,该字段的下拉列表出现在屏幕上,我可以从我拥有的两个注册用户中进行选择。但是,即使从该列表中选择某些内容,然后再次提交表单,也会给我同样的错误。

正在检查“ my_user”变量-显示我已登录。

是否可以传递到当前已登录用户的“ requestor”字段? 我只能通过从SpotForm的“字段”中删除“请求者”来保存表单(这最终使数据库中的该字段为“无”),但这并不是理想的结果。

任何建议将不胜感激。

1 个答案:

答案 0 :(得分:0)

您不是真的将stakeholder实例传递给表单中的requestor字段吗?因此,您必须这样做:

form = SpotForm(requestor = my_user)