1👍
✅
Initial values you pass with initial=...
are only displayed for "unbound forms", i.e. forms not having request data. Since you pass request.POST
or even None
that do not work. The usual idiom is:
if request.method == "POST":
# May skip passing initial here unless you use `form.has_changed()`
form = CustomerForm(request.POST, initial=initial)
if form.is_valid():
form.save()
return redirect(...)
else:
form = CustomerForm(initial=initial)
# pass either an invalid or a new form to template ...
If you need to pass initial values from a model instance it usually makes sense to use a ModelForm
and use instance=...
instead of initial=...
.
👤Suor
0👍
def create_customer(request, pk=None):
form = CustomerForm(request.POST or None)
if request.method == 'GET':
if pk is not None:
instance = Contact.objects.get(pk=pk)
form = CustomerForm(request.POST or None, instance=instance)
elif request.method == 'POST':
if form.is_valid():
form.save()
messages.success(request, 'Klient został pomyślnie utworzony')
return HttpResponseRedirect(reverse('xxx'))
return render(request, 'xxx', {'form': form})
I changed the whole concept, sent a link to the get to view methods where I used the method from a friend who posted here.
The optional parameter is because the function serves as a normal addition without a parameter as well
Regards and thanks for your help
- [Answered ]-Django – clean() with hidden form
- [Answered ]-Django Model; saving extra items in a ManyToMany field on save
- [Answered ]-Curl -d to Alamofire
- [Answered ]-Install mod-wsgi in a poetry virtual environment
- [Answered ]-Is a directory Error in Django deployment
Source:stackexchange.com