我是Django的新手,我真的需要帮助,
我不知道如何将表单数据保存到数据库。我对views.py
有问题我将填写填写到外键字段中的表单的用户ID。
如果有任何链接或示例可以帮助我,我感谢您。
# views.py
@login_required(login_url="home")
def melk_new(request):
form = MelkForm()
???
return render(request, 'melk_new.html',{'form': form})
# models.py
class Melk(models.Model):
category = models.CharField(max_length=50)
city = models.CharField(max_length=100)
person = models.ForeignKey('CustomUser', on\_delete=models.CASCADE)
def \_\_str\_\_(self):
return self.category
class CustomUser(AbstractUser):
def __str__(self):
return self.email
---------------------------------------------------------------------------
# forms.py
class MelkForm(forms.ModelForm):
class Meta:
model = Melk
fields = ('category', 'city')
class CustomUserCreationForm(UserCreationForm):
class Meta(UserCreationForm):
model = CustomUser
fields = ('username', 'email')
答案 0 :(得分:0)
要获取当前登录的用户,您可以在request.user
对象中找到它。但是在您假设当前有一个登录用户之前,您需要验证一下该身份,以便您拥有2个广为人知的选项:
request.user.is_authenticated()
@login_required()
,则使用 from django.contrib.auth.decorators import login_required
装饰器
if request.user.is_authenticated():
Car.objects.create(model_id=some_id, person=request.user)
注意:
@login_required()
被添加到函数上方
答案 1 :(得分:0)
@login_required(login_url="home")
def melk_new(request):
form = MelkForm(request.POST)
if form.is_valid():
instance = form.save(commit=False)
instance.user_id = request.user.id
instance.save()
return render(request,'melk_new.html', { 'form': form})