35
It’s standard to redirect after form submission to prevent duplicates.
Just return a redirect to your form on success.
if form.is_valid():
form.save()
return http.HttpResponseRedirect('')
51
After saving form instead of showing post dict assign the empty form
form = EmployeeForm()
if request.method == "POST":
pDict = request.POST.copy()
form = EmployeeForm(pDict) #if not valid shows error with previous post values in corresponding field
if form.is_valid():
form.save()
form = EmployeeForm() # show empty form no need to give HttpResponseRedirect()
- [Django]-Django.request logger not propagated to root?
- [Django]-Filtering using viewsets in django rest framework
- [Django]-How to select a record and update it, with a single queryset in Django?
2
after save() you can return ‘form’ key with MessagesForm(request.GET) value.
return render(request, "profile.html", {
'username': username,
'form': MessagesForm(request.GET),
'messages': messages,
})
- [Django]-How to run own daemon processes with Django?
- [Django]-Django values_list vs values
- [Django]-Serving gzipped content from django
0
Usually you can initialize the same empty form after you have saved datas:
if request.method == "POST":
rf = RegistrationForm(request.POST)
if rf.is_valid():
print 'Saving datas..'
#logic to save datas
rf = PreRegistrationForm()
return render_to_response('registration/confirmation_required.html', {'settings': settings}, context_instance=RequestContext(request))
- [Django]-How to add data into ManyToMany field?
- [Django]-Django contrib admin default admin and password
- [Django]-No module named pkg_resources
0
Try using HttpResponseRedirect('/')
instead of HttpResponseRedirect('')
in @Karthikkumar’s answer, especially if your home view is an empty path, for instance you have in your urls.py file:
urlpatterns = [path('',views.home_view),]
I had similar issues as those discussed above where HttpResponseRedirect('')
directed me to a blank page. Let me know if adding the slash works for you!
- [Django]-ImportError: bad magic number in 'time': b'\x03\xf3\r\n' in Django
- [Django]-Django-rest-framework returning 403 response on POST, PUT, DELETE despite AllowAny permissions
- [Django]-'NOT NULL constraint failed' after adding to models.py
0
You can use this:
Sometimes you can use this idea take attrs={ "autocomplete":"off"} for each inputs.
- [Django]-Serving large files ( with high loads ) in Django
- [Django]-How to express a One-To-Many relationship in Django?
- [Django]-Create if doesn't exist
0
You can redirect back to the initial post
post_url = request.build_absolute_uri(post.get_absolute_url())
return HttpResponseRedirect(post_url)
please note that ‘post’ is an instance of the model created
- [Django]-How to seed Django project ? – insert a bunch of data into the project for initialization
- [Django]-Split views.py in several files
- [Django]-In Django models.py, what's the difference between default, null, and blank?
0
I am hoping you have already defined a logic for GET methods. In the case that you have, all you can do is simply add return request.META[‘HTTP_REFERER’] at the end.
See what I mean:
def profile(request, username):
if request.method == 'POST':
if request.user.is_authenticated():
new_message = Message(author = request.user)
form = MessagesForm(request.POST, instance = new_message)
else:
form = MessagesForm(request.POST)
if form.is_valid():
form.save()
else:
to_user = User.objects.get(username = username)
form = MessagesForm(initial = {'user': to_user.pk})
return HttpResponseRedirect(request.META['HTTP_REFERER'])
This should work, I just tested it.
- [Django]-AttributeError while using Django Rest Framework with serializers
- [Django]-Why Should I use Redis when I have PostgreSQL as my database for Django?
- [Django]-How to remove all of the data in a table using Django
0
**Maybe I am late but for Django 4.x developers can use: **
from .forms import TodoForm
from django.contrib import messages
from django.http import HttpResponseRedirect
def mytodos(request):
form = TodoForm()
if request.method =='POST':
form=TodoForm(request.POST)
if form.is_valid:
form.save()
messages.success(request,'Task saved successfully')
return HttpResponseRedirect('/todo/')
mycontext={'form':form}
return render(request, 'todo/todo.html',mycontext)
in my urls.py: , i have set path('todo/',views.mytodo, name='todolist')
As you can see, after saving form, mycode will redirect to /todo/ which is automatically refreshed after every submit and a fresh form comes again everytime. If you are a good django dev, you will understand what I did. Make sure to reply if you have any queries .Thanks
- [Django]-Pagination in Django-Rest-Framework using API-View
- [Django]-Django custom managers – how do I return only objects created by the logged-in user?
- [Django]-Django admin login suddenly demanding csrf token
0
When we reload the page (F5 or ctrl+shift+R)
, it submits the previously sent data. so instead of refreshing, we will directly hit the url using return HttpResponseRedirect('/posts/')
This way it will show the page with empty form (now even if you refresh it will only show data, won’t submit it previous data again)
from django.shortcuts import render, HttpResponseRedirect
from django.views import View
from .models import Post
from .forms import PostForm
class PostListView(View):
def post(self, request, *args, **kwargs):
posts = Post.objects.filter(author=request.user).order_by('-created_on')
form = PostForm(request.POST)
if form.is_valid():
new_post = form.save(commit=False)
new_post.author = request.user
new_post.save()
return HttpResponseRedirect('/posts/')
context = {
'post_list': posts,
'form': form
}
return render(request, 'social/post_list.html', context)
- [Django]-Manager isn't accessible via model instances
- [Django]-How can I use the variables from "views.py" in JavasScript, "<script></script>" in a Django template?
- [Django]-Django: Group by date (day, month, year)