如何将动态初始值设置为django模型表单字段
我有点新django,我需要设置一个动态的初始值到我的模型表单字段。 我在我的模型名'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')
我需要在用户登录时将“作者”的值设置为当前用户。
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 })链接地址: http://www.djcxy.com/p/33753.html
上一篇: how to set dynamic initial values to django modelform field
下一篇: Remove/hiding username field in django admin edit user form