134👍
✅
Why don’t you just use ModelForm?
# forms.py
# ...
class MyForm(forms.ModelForm):
class Meta:
model = MyModel
# views.py
# ...
def my_view(request, id):
instance = get_object_or_404(MyModel, id=id)
form = MyForm(request.POST or None, instance=instance)
if form.is_valid():
form.save()
return redirect('next_view')
return render(request, 'my_template.html', {'form': form})
See https://docs.djangoproject.com/en/3.0/topics/forms/modelforms/#the-save-method for more details.
15👍
Update for Django 1.6 and further version
# forms.py
# ...
class MyForm(forms.ModelForm):
class Meta:
model = MyModel
# views.py
# ...
def my_view(request, id):
instance = MyModel.objects.get(id=id)
form = MyForm(request.POST or None, instance=instance)
if form.is_valid():
form.save()
return redirect('next_view')
return direct_to_template(request, 'my_template.html', {'form': form})
- [Django]-ImageField overwrite image file with same name
- [Django]-Can I make list_filter in django admin to only show referenced ForeignKeys?
- [Django]-Detect whether Celery is Available/Running
Source:stackexchange.com