我是django的新手,我需要为我的modelform字段设置一个动态初始值。我的模型名称“author”中有一个数据库字段,它有一个将其连接到django用户模型的外键。当用户将信息填入表单时,我需要自动将其设置为当前用户。
从我收集的关于这个问题的内容来看,我必须在下面的MyHouseEditForm中定义一个__init__
函数,我是django的新手,我看到的所有例子都非常令人困惑。
forms.py
from django import forms from django.contrib.auth.models import User from .models import Myhouses class MyHouseEditForm(forms.ModelForm): class Meta: model = Myhouses fields = ('author','name_of_accomodation', 'type_of_room', 'house_rent', 'availability', 'location', 'nearest_institution', 'description', 'image')
我需要在用户登录时随时将“author”的值设置为当前用户。
models.py
from django.db import models from django.contrib.auth.models import User class Myhouses(models.Model): author = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True, related_name='author') Available = 'A' Not_Available = 'NA' Availability = ( (Available, 'Available'), (Not_Available, 'Not_Available'), ) name_of_accomodation = models.CharField(max_length=200) type_of_room = models.CharField(max_length=200) house_rent = models.IntegerField(null=True) availability = models.CharField(max_length=2, choices=Availability, default=Available,) location = models.CharField(max_length=200) nearest_institution = models.CharField(max_length=200) description = models.TextField(blank=True) image = models.ImageField(upload_to='profile_image') def __str__(self): return self.name_of_accomodation
views.py
@login_required def addlisting(request): if request.method == 'POST': form = MyHouseEditForm(request.POST, files=request.FILES) if form.is_valid(): Houses = form.save(commit=False) Houses.save() return redirect('addlisting') else: form = MyHouseEditForm() return render(request, 'houses/addlisting.html', {'form':form })
答案 0 :(得分:0)
无需在表单中显示作者字段。它会自动以登录的用户填充。
request.user 使您可以登录用户对象。因此,您可以从“表单”字段部分删除“作者”并执行以下操作:
Houses = form.save(commit=False)
Houses.author = request.user
Houses.save()
答案 1 :(得分:0)
我在序列化程序中做了类似的事情。
我定义了这样的自定义创建方法:
class MyhousesSerializer(FlexFieldsModelSerializer):
...
def create(self, validated_data):
validated_data['author'] = self.context['request'].user
newhouse = Myhouses.objects.create(**validated_data)
return newhouse
使用更常规的模型序列化器没关系。