简体   繁体   中英

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.

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 })

No need to show author field in form. It would automatically populate with logged in user.

request.user gives you logged in user object. So, you may remove 'author' filed from forms field section and do this:

Houses = form.save(commit=False)
Houses.author = request.user
Houses.save()

I did something like this in the serializer.

I defined a custom create method like this:

class MyhousesSerializer(FlexFieldsModelSerializer):
...

    def create(self, validated_data):
        validated_data['author'] = self.context['request'].user

        newhouse = Myhouses.objects.create(**validated_data)

        return newhouse

It shouldn't matter if you use a more regular model serializer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM