In my rendered index.html, I have:
<form action="???" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit">
</form>
In my views.py, I have:
class weather(base.TemplateView):
# Generates the above html
def get_hours(request):
# do something with request.Post
return shortcuts.render(request, "index.html", {"form": form})
How do I make the form action call the get_hours? I want to post to the same page the form is on so the page won't refresh and will display the results on the same page.
Never mind, found it.
class weather(base.TemplateView):
.....
def post(request, *args, **kwargs):
# do something with request.Post
return shortcuts.render(request, "weather/index.html", {"form": form})
Related
I want to create a form in my navigation bar. I am using a context processor for that.
I created themeChoice field in my UserProfile model. What I want to is when user click submit button, form will be save. I tried something but it did not work, my view prints nothing. How can I do that?
Note: my context processor is working.
views.py
def approval_context_processor(request):
...
if request.method == 'POST':
form_theme = UserThemeChoiceform(request.POST)
if form_theme.is_valid():
user_who = request.POST.get('user_who', None)
user = UserProfile.objects.get(id=user_who)
print(user_who)
form_theme.save()
return redirect('home')
context= {
...
'form': form_theme,
}
return context
navigation.html
<form method="POST" id="theme" action="#">
{% csrf_token %}
<input type="hidden" name="user_who" value="{{ request.user }}" >
<button type="submit" class="btn btn-success">Send</button>
</form>
so, I made the registration page with django and it doesn't show the form
register.html
<form method="post">
{{ form.as_table }}
{% csrf_token %}
<input type='submit' value="Register">
</form>
and this is the views.py
from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.contrib.auth.forms import UserCreationForm
def register(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
return redirect('login')
else:
form = UserCreationForm()
return render(request, 'register.html', { 'form ' : form})
def login(request):
return render(request, 'login.html')
And all it shows is the register button
Could be one of two things:
Put the {% csrf_token %} before the form variable in your template.
Don't put any whitspace in the form key in your context dictionary (so instead of ' form ' it should be 'form')
I think you mistakenly wrote "form " instead of "form" and also put {% csrf_token %} in the form tag right before the rendering
I have a simple form in Django, and in my template I want to display each individual object for the whole queryset which I am saving the form to. The error I am getting is that my form does not seem to submit on the first attempt. Only when I click the submit button, manually refresh the page and then 'confirm form resubmission' do I see my updated queryset objects displayed in the template.
I am saving my form like this in my views:
exercise_name = ExerciseName.objects.all()
if request.method == 'POST':
form = ExerciseNameForm(request.POST)
if form.is_valid():
form.save(commit=True)
else:
form = ExerciseNameForm()
and passing the queryset to the template through the following context:
{ 'exercise_name': exercise_name }
and iterating through it like
{% for exercise_title in exercise_name %}
#content displaying each iteration
{% endfor %}
with my form to update it like:
<div>
<form method = "POST">{% csrf_token %}
{{form.as_p}}
<button type="submit" class="save btn btn-default">Save</button>
</form>
</div>
I am not sure why it is making me refresh the page and resubmit the form again in order to see the updated queryset after submitting the form?
You should be doing something like this:
if request.method == 'POST':
form = ExerciseNameForm(request.POST)
if form.is_valid():
form.save(commit=True)
return HttpResponse("data submitted successfully")
else:
return render(request, "your_template.html", {'form':form})
else:
form = ExerciseNameForm()
return render(request, "your_template.html", {'form':form})
So i'm developing an app using Django framework, and i need HTML forms to insert/delete and update data from the database. I was able to make the form to Update the data, but i can't seem to find any info on how to make a Create form and a delete button.
I tried this, with no success:
HTML
<form action="{% url 'conta_details_html' conta.id %}" data-method="delete">
<input type="submit" value="delete">
</form>
Views:
class ContaDetailsHTML(APIView):
renderer_classes = [TemplateHTMLRenderer]
template_name = 'conta_details.html'
def get(self, request, pk):
user = request.user
conta = get_object_or_404(Conta, pk=pk,user=user)
serializer = ContaDetailsSerializerHTML(conta)
return Response({'serializer': serializer, 'conta': conta})
def delete(self,request,pk):
"""Deletes a transaccao"""
user = request.user
if not user.is_authenticated:
return Response(status=status.HTTP_403_FORBIDDEN)
conta = get_object_or_404(Conta, pk=pk, user=user)
serializer = ContaDetailsSerializerHTML(conta,many=False)
if conta:
conta.delete()
return Response(status=status.HTTP_200_OK)
return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST)
Maybe im not getting the syntax correct on the html, but the update form was pretty easy, like this:
<form action="{% url 'conta_details_html' conta.id %}" method="POST">
{% csrf_token %}
{% render_form serializer %}
<input type="submit" value="Save">
</form>
any idea ?
Edit:
URL:
url(r'^api/html/contas/(?P<pk>[0-9]+)/$', views.ContaDetailsHTML.as_view(), name='conta_details_html'),
Oh even for delete is it's easy. You missed out on a few things here.
1. DELETE is a HTTP Verb, Your method field in the form can take one of this.
<form action="{% url 'conta_details_html' conta.id %}" data-method="delete" method="DELETE">
<input type="submit" value="delete">
</form>
In your delete view, you are trying to serialiaze but you don't need to.
def delete(self, request, pk):
"""Deletes a transaccao"""
user = request.user
if not user.is_authenticated:
return Response(status=status.HTTP_403_FORBIDDEN)
conta = get_object_or_404(Conta, pk=pk, user=user)
conta.delete()
return Response(status=status.HTTP_200_OK)
I am using model formsets to add multiple instances of a model at once. and I am using class based views. This is my views.py part for creating a "Library"
class LibraryCreate(View):
model = Library
def post(self, request, *args, **kwargs):
LibraryFormSet = modelformset_factory(
Library, form=create_library, extra=2)
if request.method == 'POST':
formset = LibraryFormSet(request.POST, request.FILES)
if formset.is_valid():
# do something with the formset.cleaned_data
pass
else:
formset = LibraryFormSet()
return render_to_response(
'trial1/library_form.html', {'formset': formset})
def get(self, request, *args, **kwargs):
LibraryFormSet = modelformset_factory(
Library, form=create_library, extra=2)
formset = LibraryFormSet(queryset=Library.objects.none())
return render_to_response(
'trial1/library_form.html', {'formset': formset})
and this is my template
<form method="post" action="{% url "library_create" %}">
{% csrf_token %}
{{ formset.management_form }}
<table>
{% for form in formset %}
{{ form }}
{% endfor %}
</table>
<input type="submit" value="create" />
now for some reason when I try to submit the form it returns a 403 forbidden because "CSRF token missing or incorrect.". I don't get why this is not working and its getting really frustrating.
Use render instead of render_to_response so that the request is included in the template context.
return render(request, 'trial1/library_form.html', {'formset': formset})
You are missing the RequestContext object. The CSRF token is added by the CsrfMiddleware to the RequestContext object. When you do not include the object, the token will be empty (inspect the form element in your browser and you will see it is missing).
https://docs.djangoproject.com/en/1.8/ref/templates/api/#django.template.RequestContext
Use the render method or add the RequestContext to your view
return render_to_response('trial1/library_form.html',
{'formset': formset},
context_instance=RequestContext(request))
https://docs.djangoproject.com/en/1.8/topics/http/shortcuts/#render
https://docs.djangoproject.com/en/1.8/topics/http/shortcuts/#render-to-response (see context_instance attribute)