could you let me know how to pass my checkbox values to server?
views.py
def viewtest(request):
if request.method == "POST":
form=testForm(request.POST)
if(form.is_valid():
form.save()
elif request.method == "GET":
form=testForm()
return render(request,"test/register.html",{"testform":form})
forms.py
class testForm(forms.ModelForm):
workday=forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple(), choices=workdayType)
class Meta:
model=test
fields=('name','tel')
register.html
<table>
<form method="post" action="{% url "viewtest" %}">
{{testform.as_table}}
</form>
<input type="submit" value="register"/>
</table>
I can see like below checkboxes.
but at server, can't see multiple data. could you provide me some idea?
there was my silly stuff. because I've used getting POST data as request.POST['workday']. it was wrong. I SHOULD USE form.cleaned_data.get("workday"). that's for my solution. But don't know what is different yet.
Related
In my project, i have a template where i'm trying to put two forms for different use cases. I've never come across this problem before, so i don't really know where to go from here to use two forms in the same page.
At first i thought of creating another view to handle each form, but i think that this solution would create problems with the rendering of my templates, other than not being sustainable if i should have this problem again with another template.
After making some research, i found a solution but it works for class based views, but i'd like to avoid that since my view is already a function based view, and i would have to make a lot of changes in my code. However, if CBV is the best way to go, i can make the change.
Every advice is appreciated
First field
class FirstForm(forms.ModelForm):
firstfield = forms.CharField()
secondfield = forms.CharField()
class Meta:
model = MyModel
fields = ("firstfield", "secondfield")
def save(self, commit=True):
send = super(FirstForm, self).save(commit=False)
if commit:
send.save()
return send**
Second Form
class SecondForm(forms.ModelForm):
firstfield = forms.FloatField()
secondfield = forms.Floatfield()
thirdfield = forms.CharField()
class Meta:
model = MyModelTwo
fields = ("firstfield", "secondfield", "thirdfield")
def save(self, commit=True):
send = super(SecondForm, self).save(commit=False)
if commit:
send.save()
return send
Template
<h3> First Form </h3>
<form method="post" novalidate>
{% csrf_token %}
{% include 'main/includes/bs4_form.html' with form=form %}
<button type="submit" class="btn btn-danger" style="background-color: red;">SUBMIT</button>
</form>
<h3> Second Form </h3>
<form method="post" novalidate>
{% csrf_token %}
{% include 'main/includes/bs4_form.html' with form=form %}
<button type="submit" class="btn btn-danger" style="background-color: red;">SUBMIT</button>
</form>
views.py
def myview(request):
# if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = FirstForm(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:
send = form.save()
send.save()
messages.success(request, f"Success")
# if a GET (or any other method) we'll create a blank form
else:
form = FirstForm()
return render(request,
"main/mytemplate.html",
context={"form":form})
I have been told to use a context in my view, but i don't know how to integrate it in my view. Is this a doable solution, or is there a better way to do this?
context = {
'first_form': TradingForm(request.POST or None),
'second_form': LimitSellForm(request.POST or None),
}
Here's one approach. Add a name attribute to your buttons, like this:
<button name="button1" type="submit" class="btn btn-danger" style="background-color: red;">SUBMIT</button>
...
<button name="button2" type="submit" class="btn btn-danger" style="background-color: red;">SUBMIT</button>
Then in your view, you can check which form has been submitted by looking for the button name in the post:
def myview(request):
if request.method == 'POST':
if 'button1' in request.POST:
form1 = FirstForm(request.POST)
if form1.is_valid():
# do what needs to be done and redirect
if 'button2' in request.POST:
form2 = form = SecondForm(request.POST)
if form2.is_valid():
# do what needs to be done and redirect
else:
form1 = FirstForm()
form2 = SecondForm()
return render(request, "main/mytemplate.html",
context={'form1': form1, 'form2': form2})
you can use TemplateView instead for normal view function and add this below
def get_context_data(self, **kwargs):
context = {
'first_form': TradingForm(request.POST or None),
'second_form': LimitSellForm(request.POST or None),
}
you can check in the documentation:
https://docs.djangoproject.com/en/2.2/ref/class-based-views/base/#templateview
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)
Im new to django and was struck by using slug, now Im confused how to use the ID parameter and convert to slug
URL.py
url(r'^deletePost/(?P<slug>[\w-]+)/$', views.delete_post, name='delete_post')
Template
<form method="POST" action="{% url 'delete_post' id=post.id %}">{% csrf_token %}
<button type="submit" class="btn btn-danger">   Delete</button>
</form>
Views.py
def delete_post(request,slug):
posts=Post.objects.get(slug=slug)
if request.method == 'POST':
posts.delete()
return redirect("home")
How can i use slug & id to delete the post which is created
Any help is appreciated. Thanks in advance
Error for reference
In my opionion, you dont want to convert the id to slug. You can just make your application flexible enough so that you could delete by either slug or id. You just need to handle the parameters accordingly.
So, you can do something like this:
urls.py
url(r'^deletePost/(?P<slug>[\w-]+)/$', views.delete_post, name='delete_post_by_slug'),
url(r'^deletePost/(?P<id>[0-9]+)/$', views.delete_post, name='delete_post_by_id')
And in the views:
def delete_post(request, slug=None, id=None):
if slug:
posts=Post.objects.get(slug=slug)
if id:
posts=Post.objects.get(id=id)
#Now, your urls.py would ensure that this view code is executed only when slug or id is specified
#You might also want to check for permissions, etc.. before deleting it - example who created the Post, and who can delete it.
if request.method == 'POST':
posts.delete()
return redirect("home")
Note that you can compress the 2 URL patterns into a single one - but this approach keeps it readable, and understandable. I shall let you figure out the URL consolidation once you are comfortable with the django framework, etc..
If you want to use both slug and id, your URL pattern should look like this:
url(r'^deletePost/(?P<slug>[\w-]+)-(?P<id>[0-9]+)/$',
views.delete_post, name='delete_post')
And your view should look like this:
def delete_post(request, **kwargs):
# Here kwargs value is {'slug': 'qw', 'id': '1'}
posts = Post.objects.get(**kwargs)
if request.method == 'POST':
posts.delete()
return redirect('home')
# ... (I guess this view does not end here)
And your template also have to set both:
<form method="POST" action="{% url 'delete_post' slug=post.id id=post.id %}">{% csrf_token %}
<button type="submit" class="btn btn-danger">   Delete</button>
</form>
i have an custom form , whenever i fetch the form values to save in the database than it display an error ( applicationform() got an unexpected keyword argument 'job_title' ) and the values are not save in the table.
views.py :-
def applicationvalue(request):
if request.method == 'POST':
getjobtitle = request.POST['jobtitle']
getintable = applicationform(job_title=getjobtitle)
getintable.save()
print getjobtitle
return HttpResponse(getintable)
else:
return render_to_response('registration/applicationform.html')
my form is :-
<form method="POST" action="#" class="form-horizontal" id="applicationform" name="appform">
<input type="text" id="u_jobtitle" class="input-xlarge" name="jobtitle" value=" " />
<button class="btn btn-gebo" type="submit" name="usubmit">Save changes</button>
whenever i fetch the values from form to save the values in table field " job_title " than it will display an error :-
applicationform() got an unexpected keyword argument 'job_title'
Change input field name to job_title in your html
<input name="job_title" type="text" id="u_jobtitle" class="input-xlarge" value=" " />
-------------^ changed
and then in view do
def applicationvalue(request):
if request.method == 'POST':
#Dont need this
#getjobtitle = request.POST['jobtitle']
#---------------------------Use request.POST
getintable = applicationform(request.POST)
getintable.save()
print getjobtitle
return HttpResponse(getintable)
else:
return render_to_response('registration/applicationform.html')
It will be better if you use same form to render html instead of hand coding it.
The applicationform constructor should take the request.POST as argument.
But it seems to me that you are not using django forms in the "right" way. I think that your view doesn't follow the django philosophy for using form.
In your case, you should have a model:
from django.db import models
class Application(models.Model):
job_title = models.CharField(max_length=100)
Based on this model, you can declare a ModelForm:
from django import forms
from .models import ApplicationModel
class ApplicationForm(forms.ModelForm):
class Meta:
model = ApplicationModel
fields = ('job_title',)
Then you can use this form in your view
def applicationvalue(request):
if request.method == 'POST':
form = ApplicationForm(request.POST)
if form.is_valid():
#This is called when the form fields are ok and we can create the object
application_object = form.save()
return HttpResponse("Some HTML code") # or HttResponseRedirect("/any_url")
else:
form = ApplicationForm()
#This called when we need to display the form: get or error in form fields
return render_to_response('registration/applicationform.html', {'form': form})
finally you should have a registration/applicationform.html template with something like:
{% extends "base.html" %}
{% block content %}
<form action="" method="post">{% csrf_token %}
<table>
{{form.as_table}}
</table>
<input type="submit" value="Add">
</form>
{% endblock %}
I hope it helps
First of all I'm glad to be here, I read you lately and i found useful answers here.
This is my first post so please be kind with me, I'm a newbie in programming.
So, I'm writing my 1st web application in Django - a todo app and I don't know how to write the function that does this this. I found something in Django docs and in other related discussions but it doesn't work.
Here's my code:
#models.py
class Task(models.Model):
user = models.ForeignKey(User)
task = models.CharField(max_length=200)
initialized_at = models.DateTimeField(auto_now_add=True)
due_date = models.DateField(default=datetime.now)
done = models.BooleanField(default=False)
def __unicode__(self):
return self.task
#views.py
def edit_task(request, id):
if request.method == 'POST':
task_to_edit = Task.objects.get(pk=task_id)
form = TaskForm(request.POST, instance=task_to_edit)
form.save()
if form.is_valid():
task_to_edit = form.save()
return HttpResponseRedirect('/')
else:
form = TaskForm()
return render(request, 'todo/edit_task.html', {'form': form})
#urls.py
url(r'^edit_task/(?P<task_id>\w+)/$', 'todo.views.edit_task')
#edit_task.html
{% block content %}
<form action="/edit_task/" method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit" />
</form>
{% endblock content %}
When I submit the updated form I get this error:
Page not found (404)
Request Method: POST
Request URL: hxxp://127.0.0.1:8000/edit_task/
Using the URLconf defined in jbz.urls, Django tried these URL patterns, in this order:
^admin/
^$ [name='index']
^(?P<task_id>\d+)/$
^(?P<task_id>\d+)/$
^add-task/$
^delete-task/(?P<task_id>\w+)/$
^edit_task/(?P<id>\w+)/$
^done/(?P<task_id>\d*)/$
The current URL, edit_task/, didn't match any of these.
and the root urls.py looks like:
url(r'', include('todo.urls'))
#edit_task.html
{% block content %}
<form action="/edit_task/{{task.id}}" method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit" />
</form>
{% endblock content %}
Notice how I added {{task.id}} expression in <form action="/edit_task/{{task.id}}" method="post">
IMPORTANT NOTE: Substitute {{task.id}} to whatever variable accomplishes this in your template.
The reason why you get the error is because edit_task/ is not getting the other part, task_id to match the regular expression:
url(r'^edit_task/(?P<task_id>\w+)/$', 'todo.views.edit_task')
UPDATE: Also your edit_task view has potential errors as well>
def edit_task(request, id):
task_to_edit = Task.objects.get(pk=id)
if request.method == 'POST':
form = TaskForm(request.POST, instance=task_to_edit)
form.save()
if form.is_valid():
task_to_edit = form.save()
return HttpResponseRedirect('/')
else:
form = TaskForm(instance=task_to_edit)
# you don't pass any task variable to the view so the form view
# won't know which task to edit, you'll have to handle that
return render(request, 'todo/edit_task.html', {'form': form, 'task':task_to_edit})
Note: I corrected the code in the view a little. Now the task_to_edit is passed also to the Form to fill the fields when the view is requested via GET. Notice that in order to access to this view, the url in the browser should look like this http://www.example.com/edit_task/2
If other wise you try to access http://www.example.com/edit_task without passing the id you'll get Error 404.
Hope this helps!
I think your pattern for edit task expects an id - task name. Try changing your URL pattern:
'^edit_task/(?P<task_id>\w+)/$'
to
'^edit_task/$'
or providing the task id that you want to edit.
Just add name space to your url and according update your template.
#urls.py
url(r'^edit_task/(?P<task_id>\w+)/$', 'todo.views.edit_task', name= "edit_task")
#edit_task.html
{% block content %}
<form action="{% url 'edit_task' task_id %}" method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit" />
</form>
{% endblock content %}