how to set dynamic initial values to django modelform field
i'm kinda new to django, i need to set a dynamic initial value to my modelform field. i have a database field in my model name 'author' it has a foreignkey that connects it to the django user model. i need to automatically set this to the current user anytime a user fills in information into the form. from what i gathered about this problem, i'd have to define an init function inside the MyHouseEditForm below, i'm new to django and all the examples i've seen a pretty confusing. really nned help 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')
i need to set the value of 'author' to the current user anytime a user logs in.
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/33754.html
上一篇: 用Django中的自定义字段扩展用户模型