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.
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 })
author
field upon the form save. If so, all you need isHouses.author=request.user
beforeHouses.save()
. Also you should changeUser
tosettings.AUTH_USER_MODEL
in author field definition. See the docs – wolfrevokcats Mar 12 '18 at 23:47