46๐
โ
You just need to exclude it from the form, then set it in the view.
class AnimalForm(ModelForm):
class Meta:
model = Animal
exclude = ('publisher',)
โฆ and in the view:
form = AnimalForm(request.POST)
if form.is_valid():
animal = form.save(commit=False)
animal.publisher = request.user
animal.save()
(Note also that the first else
clause โ the lines immediately following the redirect โ is unnecessary. If you leave it out, execution will fall through to the two lines at the end of the view, which are identical.)
๐คDaniel Roseman
9๐
Another way (slightly shorter):
You need to exclude the field as well:
class AnimalForm(ModelForm):
class Meta:
model = Animal
exclude = ('publisher',)
then in the view:
animal = Animal(publisher=request.user)
form = AnimalForm(request.POST, instance=animal)
if form.is_valid():
animal.save()
๐คmatino
- [Django]-Why does Django call it "views.py" instead of controller?
- [Django]-How to delete old image when update ImageField?
- [Django]-"Too many SQL variables" error in django with sqlite3
4๐
I would add it directly to the form:
class AnimalForm(ModelForm):
class Meta:
model = Animal
exclude = ('publisher',)
def save(self, commit=True):
self.instance.publisher = self.request.user
return super().save(commit=commit)
This is in my opinion the cleanest version and you may use the form in different views.
๐คmelbic
- [Django]-XML Unicode strings with encoding declaration are not supported
- [Django]-Non-database field in Django model
- [Django]-Change the width of form elements created with ModelForm in Django
0๐
If you are using ModelAdmin
you should add method get form on your ModelAdmin
class BlogPostAdmin(admin.ModelAdmin):
form = BlogPostForm
def get_form(self, request, **kwargs):
form = super(BlogPostAdmin, self).get_form(request, **kwargs)
form.request = request
return from
and you can now access request in your ModelForm
class ProductAdminForm(forms.ModelForm):
def save(self, commit: bool, *args, **kwargs):
self.instance.user = self.request.user
return super().save(commit=commit)
pass
- [Django]-Django Left Outer Join
- [Django]-Where to run collectstatic when deploying django app to heroku using docker?
- [Django]-Django: Can class-based views accept two forms at a time?
Source:stackexchange.com