I met this strange problem when doing a pre-populated form.
In my template, the form method is clearly stated as POST:
<form class="form-horizontal" role="form" action="" method="post" enctype="multipart/form-data">{% csrf_token %}
But in my view function, the request.method turns out to be GET.
Below is my view function:
def editProfile(request,template_name):
theprofile = request.user.profile
print theprofile.fullname
notificationMSG = ''
print request.method
if request.method == 'POST':
form = UserProfileForm(request.POST,request.FILES, instance=theprofile)
if form.is_valid():
form.save()
notificationMSG = "success!"
else:
form = UserProfileForm()
print "error"
dic = {'form':form,
'notificationMSG':notificationMSG}
return render_to_response(template_name, dic, context_instance=RequestContext(request))
When I run it, it prints out GET.
Anyone met this odd before?
In my case I was missing a "/" at the end of action in the HTML Template, while posting.
When you are loading the form and retrieving remote data by hitting a url, the request method is GET.
When you fill the form values and submit the form(with post method) i.e. insert/update remote data, the request method is POST.
So, in your code when you print request.method, the output is GET when you are loading the form. This has nothing to do with your pre-populated form.
Here are the steps I needed so far to solve this kind of error:
Add method="post" to your <form> element
Add a missing "/" at the end of the url at the action property on your <form> element
Add a type="submit" to your <button> element
Ps. Don't forget to add {% csrf_token %} after your <form>.
Every time I submitted my form with action="" I was getting a GET response, but once I filled the actual URL action="/client/" it went through as a POST.
I am also facing this problem but, In my case, in input type, I have written
type =" button" when I change it to type="submit" it get resolved.
Sorry, I get misunderstood when again I face the same problem then I got actual solution.
Related
Basically when a POST request is made, I want to redirect to another page.
def sample(request):
if request.method != "POST":
return render(request,"user/sample.html")
else:
return redirect("https://www.djangoproject.com")
This code works fine when it receives a GET request but when I submit
information, instead of redirecting to the page above, it appends the the template name into the url, Something like this :
http://localhost:8000/sample/sample
No matter what I type into the redirect(), even completely random things it still redirects to sample/sample
I've created multiple django-projects and in every one of them I still get this problem.
I've fixed the problem, leaving this here for anyone in the future.
My problem was in the html file
<form action="" method="POST">
{% csrf_token %}
{{form}}
<input type="submit">
the <form action=""> must be an empty string, otherwise it is going to append that to the url.
The problem had nothing to do with the redirect() function.
I am new to programming, I hope my question is not very basic. Here I am trying to taking the input and showing output on the same page.
I went through an article that said I should use GET method to do so.
my view
def calc(request):
if request.method == 'GET':
form = CalculationForm(request.GET)
if form.is_valid():
number1 = form.cleaned_data.get('first_number')
number2 = form.cleaned_data.get('second_number')
sum = number1 + number2
sum.save()
return render(request, 'calculation\calculator.html', {'sum': sum})
else:
form = CalculationForm()
return render(request, 'calculation\calculator.html', {'form': form})
my HTML
<body>
<form method="get" action=".">{% csrf_token %}
{{ form }}
<input type="submit" name="Register" value="Submit" />
{{sum}}
</body>
Here I am showing the user simple form
user input numbers in two fields
Add the numbers
showing it back to the user on the same page
My form is getting rendered and the fields are displaying I am able to enter the number in the field but when I click submit I get an error. Anyone
When you get an error, you should show it in your question, rather than just saying "I get an error".
The main issue here is that the request method is always GET, because that's how your form is being submitted. So your if statement is always true, even on first display of the page.
You need to switch on something else. One idea would be to use the fact that the Submit button is an input like the others, so would be included in the submitted data. So:
if 'Submit' in request.GET:
form = CalculationForm(request.GET)
...
Note that you will have another error, when you call sum.save(). The sum here is an integer, so it's not clear what you are trying to do when you call "save" on it.
I have a simple form and whenever the user does something wrong on the form I'd like to raise a validation error on Django. The problem is that I set up the form validation but when the form is submitted with wrong values, it goes through. I was wondering why it's happening and how I can avoid that?
Here is the html form:
<form id="ask-project" method="post" action="{% url 'ask-project' %}">
{% csrf_token %}
<input required="required" class="form-control form-text required" id="prenom" name="prenom" type="text">
<button class="btn btn-default submit">Submit</button>
</form>
views.py:
def askProject(request):
if request.method == 'POST':
form = AskProjectForm(request.POST)
if form.is_valid():
save_it = form.save(commit=False)
save_it.save()
return redirect('/merci/') #success
forms.py:
class AskProjectForm(forms.ModelForm):
class Meta:
model = AskProject
fields = ['prenom']
def clean_prenom(self):
prenom = self.cleaned_data['prenom']
if len(prenom) < 3:
raise ValidationError('Votre prénom doit etre plus long que 1 caractère.')
return prenom
Am I doing something wrong?
With the pattern that you are using, this sort of problem is inevitable and order of the day. The first thing is not to render the form manually as you appear to be doing. That means you are not showing any feedback when the user enters invalid data. Consider using {{ form }}, {{ form.as_table }} etc or rendering the fields with all information as described here: https://docs.djangoproject.com/en/1.11/topics/forms/#rendering-fields-manually
Second problem is that you are redirecting when the form is submitted, regardless of whether it's valid or not. The recommended pattern is to redirect only when the form is valid. So even if you apply the suggestion in the first para, you are still not getting the required feedback. Consider implementing the form as suggested in the manual. A straight copy past follows
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = NameForm(request.POST)
# check whether it's valid:
if form.is_valid():
# process the data in form.cleaned_data as required
# ...
# redirect to a new URL:
return HttpResponseRedirect('/thanks/')
# if a GET (or any other method) we'll create a blank form
else:
form = NameForm()
return render(request, 'name.html', {'form': form})
Finally getting onto the specific case of why your form validation doesn't work, add a print statement in your clean method to print out both the string and it's length see if it tallies (or if your method even gets called)
This is my first django project and I'm struggling to finish it.
I've been working to function that editing post. When user clicks button, it send no(int)for that article, and get information related to no and display on page. User can edit that post in the same form and when user click submit, it redirect to home.html
However, the function I made keep sending me an error message that it takes 2 arguments even though I did not use any function that takes 2 arguments.
Here is views.py
#login_required
def edit_article(request, article_no):
article = Article.objects.filter(pk=article_no)
form = ArticleForm(request.POST, instance=request.article)
if form.is_valid():
form.save()
messages.add_message(request, messages.SUCCESS, _('Article correctly saved.'))
# If the save was successful, redirect to another page
redirect_url = reverse('blog/home.html')
return HttpResponseRedirect(redirect_url)
else:
form = ArticleForm(instance=request.article)
return (request, {'form': form}, context)
This is form in detail.html where send no value to edit_article.html
<form action="{% url 'blog:edit_article' %}" method="post" style="display: inline;">
{% csrf_token %}
<input type="hidden" name="no" value="{{ item.no }}" />
<button type="submit">edit></button>
</form>
The article_no arg does not magically find its way into the function call via the POST submit. You need to provide it to the url tag:
{% url 'blog:edit_article' item.no %}
This assumes, of course, that you have a url pattern with an appropriate named group associated with this view/view name.
If You are talking about this function, it does recieve more than one Arg, it recieves the No you are talking about, and the request object
def edit_article(request, article_no):
...
If your view needs arguments you must give the arguments in the url templatetag, like this :
{% url 'accounts:detail_account' username = username %}
I have such problem:
I have form, that displays on every page of a web-site. So, the action is for specified(separate) view:
def subscribe(request):
if request.method == "POST":
form = SubscriptionForm(data=request.POST)
if form.is_valid():
form.save()
return redirect() # there is a problem
else:
raise Http404
After success handling of form, I want to redirect a user to the page, from which form was sent.
But if I use request.path - it returns me an url that handles this form. But I need the url of a page...
Do you understand? What should I do?
Thanks a lot!
You'll need to add an additional field to your form to let your view know where to redirect to. The simplest way to do this is to add a hidden input to your form:
<form action="/some/url/" method="post">
...
<input type="hidden" name="next" value="{{ request.path }}">
</form>
The value of request.path is the path of the page before the user submits the form.
In your view, you can use the parameter next to redirect the user back to the page they came from.
def subscribe(request):
...
next = request.POST.get('next', '/some/default/url/here/')
return redirect(next)