clear form field after a submit in django - django

this my view code
if request.method == 'POST':
if 'cancel' in request.POST:
return redirect('incident.views.index')
if 'password' in request.POST:
registerform = UserRegisterForm(request.POST)
registerform = UserRegisterForm(request.POST)
createprofileform = UserCreateProfileForm(request.POST)
if registerform.is_valid() and createprofileform.is_valid():
result = registerform.save(commit=False)
result.set_password(request.POST['password'])
result.save()
member.user_id = user.id
member.member_id = result.id
member.save()
member_profile = UserProfile.objects.get(user=result.id)
createprofileform = UserCreateProfileForm(request.POST, instance=member_profile)
createprofileform.save()
is_member_screen = True
member_save_msg = 'New member has been added.'
return render(request, 'incident/about_me.html',
registerform':registerform,
'createprofile':createprofileform,
'member_save_msg': member_save_msg,
})
After every form submit,i want to clear the posted data,actually the form is holding the submitted data.I don't want to redirect the page to some other page as save success message will appear after every save.How to clear the posted data from form on every submit.
Thanks

Re-init the forms registerform and createprofileform to empty forms - no POST data, when you want to clear the data.
Sample:
if request.method == 'POST':
if 'cancel' in request.POST:
return redirect('incident.views.index')
if 'password' in request.POST:
registerform = UserRegisterForm(request.POST)
registerform = UserRegisterForm(request.POST)
createprofileform = UserCreateProfileForm(request.POST)
if registerform.is_valid() and createprofileform.is_valid():
# your code
...
#reset forms
registerform = UserRegisterForm()
createprofileform = UserCreateProfileForm()
return render(request, 'incident/about_me.html',
registerform':registerform,
'createprofile':createprofileform,
'member_save_msg': member_save_msg,
})

Related

Django- how to save formset model

I have the following view code
def edit_pal(request,pal_id):
pals=palabout.objects.get(id=pal_id)
form2=editpalForm(request.POST or None,instance=pals)
RecipeIngredientFormset = modelformset_factory(palabout, form=editspalForm,extra=0)
formset = RecipeIngredientFormset(request.POST or None,prefix=pals)
context={
"formset": formset,
"form2":form2,
"pals":pals
}
if request.method == 'POST':
if form2.is_valid() and formset.is_valid():
parent = form2.save(commit=False)
parent.save()
for form in formset:
child = form.save(commit=False)
child.recipe = parent
child.save()
context['message']='Data Saved'
return redirect('hod:manage_pal')
return render(request,"edit-pal.html",context)
I remove formset.is_validso it's working but it's not working when i added more for used formset.is_validso why isn't saving file or details show? Can anyone help this?
I think you need to only redirect if the forms are valid so try this view:
from django.shortcuts import get_object_or_404
def edit_pal(request,pal_id):
pals=get_object_or_404(palabout,id=pal_id)
if request.method == 'POST':
form2=editpalForm(request.POST,instance=pals)
RecipeIngredientFormset = modelformset_factory(palabout, form=editspalForm,extra=0)
formset = RecipeIngredientFormset(request.POST,prefix=pals)
if form2.is_valid() and formset.is_valid():
parent = form2.save(commit=False)
parent.save()
for form in formset:
child = form.save(commit=False)
child.recipe = parent
child.save()
context['message']='Data Saved'
return redirect('hod:manage_pal')
else: # if the form is not valid
return redirect("hod:some_error_page")
else: # GET request
RecipeIngredientFormset = modelformset_factory(palabout, form=editspalForm,extra=0)
formset = RecipeIngredientFormset(prefix=pals)
context={
"formset": formset,
"form2":editpalForm(instance=pals),
"pals":pals
}
return render(request,"edit-pal.html",context)

"RESOLVED" two forms one submit button error | IndentationError: expected an indented block

[RESOLVED] I FOUND THE SOLUTION AND UPDATED WITH THE WORKING CODE BELOW
I'm trying to submit two forms with one button.
I check a few other posts in here, but I'm not sure if the code below is the correct.
def cars_detail(request, car_id):
car = Car.objects.get(id=car_id)
profile_form = ProfileForm()
booking_form = BookingForm()
return render(request, 'cars/detail.html', { 'car': car, 'booking_form': booking_form, 'profile_form': profile_form })
def addbooking(request, car_id):
if request.method == 'POST':
profile_form = ProfileForm(request.POST)
booking_form = BookingForm(request.POST)
print(request.POST)
if profile_form.is_valid() or booking_form.is_valid():
# do stuff here
# form = ProfileForm(request.POST)
new_profile = profile_form.save(commit=False)
new_profile.car_id = car_id
new_profile.user_id = request.user.id
new_profile.save()
# do stuff here
# form = BookingForm(request.POST)
new_booking = booking_form.save(commit=False)
new_booking.car_id = car_id
new_booking.user_id = request.user.id
new_booking.save()
return redirect('detail', car_id=car_id)
else:
profile_form = ProfileForm(prefix="profile_form")
booking_form = BookingForm(prefix="booking_form")
You have no code in the block after the “if”.
If there’s nothing to do in that instance negate the condition and remove the “else”
But do you want to reset both forms if only one of them is invalid? You might want this instead
if !profile_form.is_valid():
profile_form = Profile_form(prefix="profile_form")
if !booking_form.is_valid():
booking_form = Booking_form(prefix="booking_form")

I have some problem with clean method in Django

Here is
my form.py
class DepartamentForm(forms.ModelForm):
class Meta:
model = Department
fields = ['name','company','city', 'special_id','active']
def clean_code(self):
code = self.cleaned_data.get('special_id')
qm = Department.objects.filter(special_id=code)
if qm.exists():
raise forms.ValidationError("Email jest już używany!!" )
return code
my view.py
def dictionary_department_add(request):
current_user = request.user
if request.method == "POST":
form = DepartamentForm(request.POST)
if form.is_valid():
x_form = form.save(commit=False)
x_form.date_add = now.strftime("%Y-%m-%d %H:%M")
x_form.user_add = current_user.username
x_form.save()
return redirect('/dictionaries/dictionary_department/')
else:
return render(request, 'add_department.html',{form': form})
else:
form = DepartamentForm()
return render(request, 'add_department.html', {'form': form})
If I try to add a new position department using this code, the error isn't showed, and submit works for some reason.
I want that before submit form, method check if field special_id exists in database, and if exists than show message in form and stop submit

Formset shows invalid when updating the form

Can anyone help me why my formset is showing invalid when trying to update the form. It works perfectly when creating the form. The normal form is editing but the formset is not.
`def content_edit_view(request, id):
course = get_object_or_404(Course, id=id)
LectureFormset = modelformset_factory(Lecture, fields=('lecture_title', 'lecture_content', 'youtube_url'), extra=0)
if course.user != request.user:
raise Http404()
if request.method == 'POST':
content_edit_form = ContentEditForm(request.POST or None, request.FILES or None, instance=course)
formset = LectureFormset(request.POST or None, request.FILES or None)
if content_edit_form.is_valid():
content_edit_form.save()
data = Lecture.objects.filter(course=course)
# give index of the item for a formset item strting form 0 and (f)the item itself
if formset.is_valid():
for index, f in enumerate(formset):
if f.cleaned_data:
if f.cleaned_data['id'] is None:
video = Lecture(course=course, lecture_title=f.cleaned_data.get('lecture_title'), lecture_content=f.cleaned_data.get('lecture_content'), youtube_url=f.cleaned_data.get('youtube_url'))
video.save()
else:
video = Lecture(course=course, lecture_title=f.cleaned_data.get('lecture_title'), lecture_content=f.cleaned_data.get('lecture_content'), youtube_url=f.cleaned_data.get('youtube_url'))
d = Lecture.objects.get(id=data[index].id) #get slide id which was uploaded
d.lecture_title = video.lecture_title # changing the database tiitle with new title
d.lecture_content = video.lecture_content #changing the database content with new content
d.youtube_url = video.youtube_url # changing the database content with new content
d.save()
return redirect('teacher-profile')
else:
print('formset is invalid')
else:
print("form is invalid")
else:
content_edit_form = ContentEditForm(instance=course)
formset = LectureFormset(queryset=Lecture.objects.filter(course=course))
context = {
'contentForm': content_edit_form,
'course': course,
'formset': formset,
}
return render(request, 'apps/contentEdit.html', context)`

Saving modelform - won't validate

I'm doing something wrong here, but I can't find it.
I'm using a model form:
class ArtistInfo(ModelForm):
class Meta:
model = Onesheet
fields = (
'name',
'genre',
'location',
'biography',
)
And trying to save the data entered for an existing record.
def edit_artist_info(request, onesheet):
onesheet = Onesheet.objects.get(id = onesheet)
if request.method == 'POST':
form = ArtistInfo(request.POST, instance=onesheet)
if form.is_valid():
test = form.save(commit=False)
test.save()
HttpResponseRedirect('/')
form = ArtistInfo(instance=onesheet, label_suffix='')
variables = RequestContext(request, {
'onesheet':onesheet,
'form': form,
})
return render_to_response('edit_artist_info.html', variables)
But it's not saving. It just reloads the page with whatever the user changed, but if you actually refresh the page (grabbing the value from the DB), it's the old value.
Any ideas? If it's because the form isn't actually validating, I dont know why it's not validating.
try just
if request.method == 'POST':
form = ArtistInfo(request.POST, instance=onesheet)
if form.is_valid():
form.save()
return HttpResponseRedirect('/')
You were missing the return statement in your code, and the extra save() was unnecessary