I got an error message: "submission() takes exactly 2 arguments (1 given)" and I suspect that I didn't pass the 2 parameters successfully. I have struggled it for over 2 days now. Can anyone give me a quick diagnosis of what went wrong?
Here is my submission.html
<form method="post" action="{% url 'submission' %}" enctype="multipart/form-data">
{% csrf_token %}
<div>
<td>{{ form.title.label_tag }}</td>
<td>{{ form.title }}</td>
</div>
<div>
<td>{{ form.message.label_tag }}</td>
<td>{{ form.message }}</td>
</div>
<div>
<input type="text" name="image_id" />
<input type="hidden" name="next" value="{{ next }}" />
<input type="submit" value="Store Post" />
</div>
Register for an account<br>
Login<br>
Logout<br>
See All Comments<br>
Submit
</form>
Here is part of my view.py. the purpose is trying to upload image files.
def submission(request, image_id):
form = PostForm()
if request.user.is_authenticated() and request.method == 'POST':
form = PostForm(request.POST)
if form.is_valid() == True:
post_to_submit = Post()
post_to_submit.post_title = form.cleaned_data['title']
post_to_submit.post_text = form.cleaned_data['message']
post_to_submit.pub_date = datetime.datetime.now()
post_to_submit.user = request.user
post_to_submit.save()
image = Image.objects.get(id=image_id)
image.comments.add(post_to_submit)
template = loader.get_template('discussion/index.html')
post_list = Post.objects.order_by('-pub_date')
context = {'post_list': post_list, 'image_id' : image_id}
else:
return HttpResponse(form.errors.__str__())
elif request.user.is_authenticated() and request.method != 'POST':
form = PostForm()
template = loader.get_template('discussion/submission.html')
context = {'form' : form, 'image_id' : image_id}
elif request.user.is_authenticated() == False:
template = loader.get_template('registration/login.html')
context = {}
return HttpResponse(template.render(context, request, {'image':image}))
I am not sure that will only get the issue that you have posted, because I see many bugs in your codes... The structure is not good. Explanations
Hopefully this will help you spot out where you've messed up in your codes.
1) User Authenticated / Request.GET: redirect to submission template with form and id as variables. In that templates, the form action needs a required argument image_id because it's shown clearly in def submission(request, image_id):.
By this link Submit, I actually realize that you did not set your urls to receive any arguments.
return HttpResponse(template.render(context, request, {'image':image})) will generate NameError: name 'image' is not defined
2) User Not Authenticated / Any Request: you render the template registration/login.html with no context variables.
In that case
this line return HttpResponse(template.render(context, request, {'image':image})) will generate NameError: name 'image' is not defined
3) User Authenticated / Request.POST: when the user submit the form.
you will not get any error if form is valid, because the image variable exists:
'''your codes'''
image = Image.objects.get(id=image_id)
image.comments.add(post_to_submit)
Possible ways to fix the issue posted
you can send the image_id through context and send it back via an hidden input inside the form rather than via form action url. No need to have argument in your view. def submission(request):
<input type="hidden" value="{{ image_id }}" name="image_id" />
In case you need the image_id inside the url, just set up your urls.py properly by adding the regex argument, and edit your form action url by adding the image_id argument
<form method="post" action="{% url 'submission' image_id %}" enctype="multipart/form-data">
Related
I am new to django. My current plan is displaying user name on different html pages, once user have successfully logged in. At the moment, the page after login page can successfully display the user name with the django tag in html which is {{ username }}. But once it has successfully passed to my second page, my second page CAN NOT pass it to my third page. The attached images are my html codes for second.html and third.html. Thanks for your help.
Second.html
<form action="/SecondPageSub/" method="POST">
{% csrf_token %}<br>
<b>NTID:</b><br>
<label name="usrnm">{{username}}</label>
<button type="submit" name="SecondPageSub">
SUBMIT
</button>
</form>
Third.html
<form action="/ThirdPageSub/" method="POST">
{% csrf_token %}<br>
<b>NTID:</b><br>
<label name="usrnm">{{username}}</label>
<button type="submit" name="ThirdPageSub">
SUBMIT
</button>
</form>
Python codes in view.py
def ActionGet(request):
if request.method == "POST":
if 'login' in request.POST:
usrname = request.POST.get("usrnm", None)
passwrd = request.POST.get("pwd", None)
dic={}
dic['username']=usrname
dic['password']=passwrd
return render(request, "Second.html",dic)
if 'SecondPageSub' in request.POST:
usrname = request.POST.get("usrnm", None)
dic={}
dic['username']=usrname
return render(request, "Third.html",dic)
if 'ThirdPageSub' in request.POST:
usrname = request.POST.get("usrnm", None)
dic={}
dic['username']=usrname
return render(request, "Forth.html",dic)
by default django gives you {{ request.user.username }} through out your templates. So you can call it on any templates
You aren't passing the usrnm in your post request with SUBMIT on your SecondPageSub
I have a simple form in my template, index.html:
{% if stripped_thumbnail_file_list %}
{% for thumbnail_name in stripped_thumbnail_file_list %}
<div class="">
<div class="">
This is my form
<form class="" action="{% url 'index' %}" method="post">
{% csrf_token %}
<input type="image" value="{{ thumbnail_name }}" src="{{ MEDIA_URL}}thumbnails/{{ thumbnail_name }}.jpg">
</form>
</div>
</div>
{% endfor %}
{% else %}
<p>No videos are available.</p>
{% endif %}
I want the index view to pull the {{ thumbnail_name }} value from this form and use it as a variable when the index view redirects to a different view that will use that name to play a matching video.
I have been unsuccessful in trying to pull that value from the form as I have it. I suspect this may because I'm not creating a Django form object. I tried to create that object, but I can't find any examples of a Django form object as an image like I have in my form.
What should that look like? Or, can someone make a recommendation on how to pull the value from the form as is?
EDIT: adding views.py snippet:
def index(request):
# if this is a POST request we need to process the form data
if request.POST:
# get thumbnail_name from form
# redirect to a new URL (hardcode thumbnail name for now):
return HttpResponseRedirect('2017-02-01_04-29-10/video/')
thumbnail_file_list = get_file_list(target_directory, ".jpg")
stripped_thumbnail_file_list = strip_file_extension(thumbnail_file_list)
template = loader.get_template('dash/index.html')
context = {
'stripped_thumbnail_file_list': stripped_thumbnail_file_list,
}
return HttpResponse(template.render(context, request))
def video(request, file_name):
print("this is the file name passed: " + file_name)
template = loader.get_template('dash/video.html')
context = {
'file_name': file_name,
}
return HttpResponse(template.render(context, request))
First: you need to declare the 'name' attribute on your form imput.
<input name="thumbnail_name" type="image" value="{{ thumbnail_name }}" src="{{ MEDIA_URL}}thumbnails/{{ thumbnail_name }}.jpg">
Second: Why don't you just set the 'action' of the form to your 'video' function (when you perform a redirect, you are losing all your POST data).Then, from there you could retrieve the value: something like that
def video(request):
file_name = request.POST.get('thumbnail_name')
print("this is the file name passed: " + file_name)
template = loader.get_template('dash/video.html')
context = {
'file_name': file_name,
}
return HttpResponse(template.render(context, request))
Hope it helps
I'm trying to show a confirmation/success message to the user in my Flask app, but I can't figure out how to display it in a modal.
#app.route("/", methods=["POST"]
def sendForm():
form = ContactForm(request.form)
if request.method == 'POST':
if form.validate():
# do stuff with form data
return render_template("contact.html", form=form)
else:
# display error message
else:
return render_template("index.html")
The part where I return the contact.html template is where I need help, I think. Because that page is basically refreshed and shown again after the POST request successfully completes. Need to display a confirm message to the user in a modal instead.
On the front-end, my form is looks like this:
<form method="POST" action="{{ url_for('sendForm') }}">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}" />
{{ render_field(form.email) }}
{{ render_field(form.name) }}
<input id="submit-form" type="submit" value="Send">
</form>
I would do some form of this...
Pass a boolean in your render_template:
submission_successful = True #or False. you can determine this.
render_template("contact.html", form=form, submission_successful=submission_successful))
Then in your template place an if statement
{% if submission_successful %}
// modal elements here
{% endif %}
I'm getting this error when submit:
CSRF verification failed. Request aborted.
I've got this far following the documentation, but I don't fully understand it and it's definitely wrong. I just want to take a query word from my search box(form) and pass it to a python script as an argument. I'm new to Django and getting stuck on the easiest things.
In models.py:
class QueryForm(forms.Form):
query = forms.CharField(label='query',max_length=100)
I added this line to my urls.py
url(r'^results/$', 'tweemo.views.results'),
On my homepage where my search box is I have this code for my form:
<form action="/home/results/" method="post">
<label for="query">Search:</label>
<input id="query" type="text" name="query" value="{{ current_query }}">
<input type="submit" value="ok">
</form>
In views.py I added these two functions:
def get_query(request):
if request.method == 'POST':
form = QueryForm(request.POST)
if form.isvalid():
return HttpResponseRedirect('/thanks/')
else:
form = QueryForm()
return render(request, 'results.html', {'form': form})
def results(request):
return render_to_response('results.html',{'here':TwitterStream.objects.all() })
MY results.html contains just this:
<form action="/home/results/" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit"/>
</form>
You must just add the {% csrf_token %} tag inside EVERY <form></form> tag which has method to be post in your template.
So the below markup should be corrected:
<form action="/home/results/" method="post">
{% csrf_token %}
<label for="query">Search:</label>
<input id="query" type="text" name="query" value="{{ current_query }}">
<input type="submit" value="ok">
</form>
Well the problem is that you are not passing the csrf token to the form , you need to pass the csrf token to the render function in order for it to be applied in the form . To accomplish this you need to associate the csrf token to the request.
def get_query(request):
if request.method == 'POST':
form = QueryForm(request.POST)
if form.isvalid():
return HttpResponseRedirect('/thanks/')
else:
form = QueryForm()
args = {}
args.update(csrf(request))
args['form'] = form
return render_to_response('results.html', args)
def results(request):
return render_to_response('results.html',{'here':TwitterStream.objects.all() })
This is my form:
from django import forms
class UploadFileForm(forms.Form):
titl = forms.CharField(max_length=50)
ffile = forms.FileField()
This is my views.py file:
def handle_uploaded_file(file_path):
print "handle_uploaded_file"
dest = open(file_path.name,"wb")
for chunk in file_path.chunks():
dest.write(chunk)
dest.close()
def handle_upload(request):
c = {}
c.update(csrf(request))
if request.method == "POST":
form = UploadFileForm(request.POST)
if form.is_valid():
handle_uploaded_file(request.FILES["ffile"])
return HttpResponseRedirect("/thanks")
else:
form = UploadFileForm()
c.update({"form":form})
return render_to_response("upload.html",c)
And this is the content of upload.html:
<form enctype="multipart/form-data" method="post" action="/handle_upload/">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Upload it"/>
</form>
Whenever I try to submit the form, I get a "This field is required" for the ffile field. What am I doing wrong? Just to mention, I am uploading a file each time.
Just for future reference. I had the same error, though I included request.FILES in form initialization. The problem was in the template: I forgot to add enctype="multipart/form-data" attribute to the <form> tag.
form = UploadFileForm(request.POST, request.FILES)
If you have included request.FILES and added the enctype="multipart/form-data", but are still seeing this error, it could be you are not declaring the <input> correctly.
For example, if explicitly declare the input html in your template like:
<input type="file" value="Upload CSV File" />
You may not be passing the expected input id or name attributes of the input form element.
Be sure that your template is using the form element tag, i.e. {{ form.file }},
which django will then render as: <input id="id_file" name="file" type="file" required=""> on the page.