I have a few forms in my forms variable, which I took from my DB.
views.py:
def settings(request):
new_form = TrafficSourcesForm()
forms = [TrafficSourcesForm(instance=x) for x in TrafficSources.objects.all()]
return render(request, 'mainpage/dashboard.html', {'new_form': new_form, 'forms': forms, 'error': error})
MY HTML:
<h3>{{ error }}</h3>
{% for form in forms %}
<form method="POST" id="{{form.name.name}}">{% csrf_token %}</form>
{% endfor %}
<form method="POST" id="new-form"> {% csrf_token %}</form>
{% for form in forms %}
<tr>
<td>{{ form.name }}</td>
<td>{{ form.token }}</td>
<td><button class="btn btn-lg btn-success w-100">Save</button></td>
</tr>
{% endfor %}
<tr>
<td><input class="form-control" placeholder="Name" form="new-form"></td>
<td><input class="form-control" placeholder="API-token" form="new-form"></td>
<td><button class="btn btn-lg btn-success w-100" form="new-form">Add</button></td>
</tr>
I am making a kind of editable grid and using a table for my layout ( so I cannot put a form direct to a row). So I am making the forms separately with the new HTML 5 form tag.
But I cannot take out the name(HTML attr on my inputs) which == the name field in the DB. So I could make different forms for every single row in my database. Can you help me?
I was thinking about setting the id of the form from my forms object but it makes the same forms for every row.
Related
I am trying to save my form in my data base. But my code adds a new row instead of save changes to the existing one. where is my mistake?
view.py
def settings(request):
error = ''
if request.method == 'POST':
new_form = TrafficSourcesForm(request.POST)
if new_form.is_valid():
new_form.save()
else:
error = 'Something went wrong!'
new_form = TrafficSourcesForm()
forms = [TrafficSourcesForm(instance=x) for x in TrafficSources.objects.all()]
return render(request, 'mainpage/dashboard.html', {'new_form': new_form, 'forms': forms, 'error': error})
template
<div class="table table-striped table-hover">
<div class="table-row">
<th style="width: 42%">Name</th>
<th style="width: 43%">Token</th>
<th style="width: 15%">Action</th>
</div>
{% for form in forms %}
<div class="table-row">
<form method="POST">
{% csrf_token %}
<div class="table-cell">{{ form.name }}</div>
<div class="table-cell">{{ form.token }}</div>
<div class="table-cell"><button class="btn btn-lg btn-success w-100"">Save</button></div>
</form>
</div>
</div>
If its not clear: I am showing all the table from my databese on the page. I want to edit them and save again to the database.
Because you are using POST data and form to create a new instance on every request:
...
if request.method == 'POST':
new_form = TrafficSourcesForm(request.POST)
if new_form.is_valid():
new_form.save()
...
To edit an object, you first need to retrieve the instance, which is normally done using its unique identifier (pk). Although normally you would send this ID using the url dispatcher captured value. I am using a hidden field in this case:
mainpage/dashboard.html
<body>
{% if forms %}
<table class="table table-striped table-hover">
<thead>
<tr>
<th style="width: 42%">Name</th>
<th style="width: 43%">Token</th>
<th style="width: 15%">Action</th>
</tr>
</thead>
<tbody>
{% for form in forms %}
<form method="POST">
{% csrf_token %}
<tr>
<td>{{ form.name }}</td>
<td>{{ form.token }}</td>
<input type="hidden" value="{{ form.instance.pk }}" name="id">
<td class="table-cell"><button class="btn btn-lg btn-success w-100">Save</button></td>
</tr>
</form>
{% endfor %}
</tbody>
</table>
{% endif %}
<form method="POST">
{% csrf_token %}
{{new_form.as_p}}
<div class="table-cell"><button class="btn btn-lg btn-success w-100">Create</button></div>
</form>
</body>
views.py
def settings(request):
error = ''
if request.method == 'POST':
new_form = TrafficSourceForm(request.POST)
pk = request.POST.get('id')
if new_form.is_valid():
if pk:
TrafficSource.objects.filter(id=pk).update(**new_form.cleaned_data)
else:
TrafficSource.objects.create(**new_form.cleaned_data)
else:
error = 'Something went wrong!'
new_form = TrafficSourceForm()
forms = [TrafficSourceForm(instance=x) for x in TrafficSource.objects.all()]
return render(request, 'mainpage/dashboard.html', {'new_form': new_form, 'forms': forms, 'error': error})
Id recommend getting the specific object you want to modify. Ex. traffic_source = TrafficSources.objects.get(id=<id_here>)
I want to update data using multiple checkbox
this is my view.py
def update_kel_stat(request, id):
if request.method == "POST":
cursor = connection.cursor()
sql = "UPDATE keluargapeg_dipkeluargapeg SET KelStatApprov='3' WHERE (PegUser = %s )" % id
cursor.execute(sql)
and this is my template.html
<form method="post" action="" name="kel" enctype="multipart/form-data">
{% for keluarga in kels %}
<tr id="{{ keluarga.KelID }}">
<td>
{{ keluarga.KelNamaLengkap }}
</td>
<td>{{ keluarga.KelStatApprov }}</td>
<td>{{ keluarga.KelKetRevisi }}</td>
<td><input type="checkbox" name="kel[]"
value="{{ keluarga.KelID }}"></td>
</tr>
{% endfor %}
<tr>
<td>
<button type="button" name="btn_delete" id="btn_delete"
class="btn btn-success"
onClick="setDeleteAction();">Approve
</button>
</td>
</tr>
</form>
how to get multiple value from checkbox in template.html to django view.py?
First of all it is not recommended to user raw SQL for such simple queries. It is quite easy to update some record with django ORM:
Entry.objects.filter(id=10).update(comments_on=False)
As for your question you can do it this way. In your template:
{% for keluarga in kels %}
<input type="checkbox" name="kel" id="kel{{ forloop.counter }}" value="{{ keluarga.KelID }}">
<label for="kel{{ forloop.counter }}">Choice {{ forloop.counter }}</label>
{% endfor %}
And in your view:
kels = request.POST.getlist('kel')
Kel.objects.filter(id__in=kels).update(StatApprov=3)
I'm a django newbie, I'm making a little app to record work calls received during nighttime.
At the moment the app works fine. I have made a form to fill call data, which is then presented as a table using a generic ListView.
class IndexView(LoginRequiredMixin, generic.ListView):
login_url = '/login/'
redirect_field_name = 'redirect_to'
template_name = 'chiamate/list_full.html'
context_name = 'lista_chiamate'
def get_queryset(self):
return Chiamata.objects.all
Here is the code for the template:
{% extends 'chiamate/base.html' %}
{% block content %}
{% if user.is_authenticated %}
<i class="fa fa-plus-square-o fa-lg" aria-hidden="true"></i> Nuova Chiamata
<p></p>
{% else %}
<p>Welcome, Guest please [login]</p>
{% endif %}
<div class="table-responsive">
<table class="table table-striped">
<form action="{{ action }}" method="post">
{% csrf_token %}
{% for chiamata in object_list %}
{% if chiamata.data_chiusura.weekday == 4 or chiamata.data_chiusura.weekday == 5 or chiamata.data_chiusura.weekday == 6 %}
<tr class="info">
{% elif chiamata.data_chiusura == None %}
<tr class="danger">
{% else %}
<tr>
{% endif %}
<td><input class="checkbox" name="chiamata_mail" type="checkbox" id="checkbox_{{ chiamata.id }}"value="{{ chiamata.id }}"></td>
<td class="txtdata">{{ chiamata.utente.get_full_name|wordwrap:5 }}</td>
<td class="txtdata">{{ chiamata.data_chiamata|date:"l d M Y H:i" }}</td>
<td>{{ chiamata.interlocutore }}</td>
<td>{{ chiamata.testo_chiamata|truncatechars:200 }}</td>
<td class="txtdata">{{ chiamata.reperibile|wordwrap:5 }}</td>
<td>{{ chiamata.data_chiusura|date:"H:i" }}</td>
<td></i> Edit</td>
<td><i class="fa fa-trash-o fa-lg" aria-hidden="true"></i> Delete</td>
</tr>
{% endfor %}
<input id="send_selected" type="submit" value="Send" />
</form>
</table>
</dv>
{% endblock %}
I've already tried to add the checkboxes here. When I do, they show on the page but then when I press the send button (currently implemented as a form send, but I want to use a bootstrap button) I don't know how to pass the objects to the email function, or at least show them in a new page.
You should define the post method of your view:
class IndexView(LoginRequiredMixin, generic.ListView):
def post(self, request, *args, **kwargs):
return ChiamataUpdateView.as_view()(request)
And handle the post data on the other view.
Also, you get_queryset isn't returning a queryset since you're not calling all(). It should be:
return Chiamata.objects.all()
I am trying to render the images of the choices next to their respective choice. Attempting to do so will not save the form as valid so I have become lost at what to do. I've tried both methods below and I have no idea why one works and the other doesn't, could I get some tips?
#Form:
class ServerGroupForm(forms.Form):
OPTIONS = (
("pic1", "https://i.imgur.com/tMahp6U.png"),
("pic2", "https://i.imgur.com/b76nwsj.gif"),
("pic3", "https://i.imgur.com/qzEcfyX.png Lover"),
("pic4", "https://i.imgur.com/kdc7UF7.png"),
("pic5", "https://i.imgur.com/ynWJ13W.gif"),
("pic6!", "https://i.imgur.com/goHFWsp.png"),
("pic7", "https://i.imgur.com/b76nwsj.gif"),
("pic8", "https://i.imgur.com/KPgKm79.png"),
("pic9", "https://i.imgur.com/7KtEV1i.png"),
("pic10", "https://i.imgur.com/7KtEV1i.png"),
("pic11", "https://i.imgur.com/FXfo773.png")
)
servergroups = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=OPTIONS)
#View:
def sendmessage(msg):
#Other code sends msg to user, not includes so this isn't long
def select_server_group(request):
form = ServerGroupForm(request.POST)
if form.is_valid():
servergroups = form.cleaned_data['servergroups']
sendmessage(msg=servergroups)
return redirect('/')
return render_to_response('webts3/selcectsgroup.html', {'form':form },
context_instance=RequestContext(request))
#HTML: Works but no icons
<section class="login">
<div class="titulo">Create a channel</div>
<form method="post" action="." enctype="multipart/form-data">{% csrf_token %}
<table border="0">
{{ form.as_table }}
</table>
<input type="submit" class="btn btn-block btn-danger" value="Submit" style="margin-top: 10px;">
</form>
</section>
#HTML: Icons but not working
<form method='post' action="." enctype="multipart/form-data">{% csrf_token %}>
<table>
{% for x,y in form.fields.servergroups.choices %}
<tr>
<td><input type="checkbox" name="{{ x }}" value="{{ x }}"><img src={{ y }}</img></td>
</tr>
{% endfor %}
</table>
<input type='submit' value='submit'>
</form>
The name attribute of the field should not be {{ x }}. It should be "servergroups".
Note you'd also need to have some logic that determines if the field is already selected, for when for example the form is being redisplayed after validation errors.
i found an error when i insert data to postgres database by django model,when i put csrf package in comment then my oage was found successfully else its shows an forbidden error my code and screen shot is below
here is html file:
{% extends "homepage/index.html" %}
{% block title %}
Contact
{% endblock %}
{% block content %}
This is Contact us Page.
<form action="/ins/" method="POST">
{% csrf_token %}
<table>
<tr>
<td>Created Date</td>
<td><input type="text" name="cid"></td>
</tr>
<tr>
<td>Updated Date</td>
<td><input type="text" name="uid"></td>
</tr>
<tr>
<td>Title</td>
<td><input type="text" name="tid"></td>
</tr>
<tr>
<td>Text</td>
<td><input type="text" name="txid"></td>
</tr>
<tr>
<td>Published Date</td>
<td><input type="text" name="pid"></td>
</tr>
<tr>
<input type="hidden" name="fdfdf" value="{{ csrf_token }}">
<td><input type="submit" value="Insert"></td>
<td><input type="reset" value="Reset"></td>
</tr>
</table>
</form>
{% endblock %}
views.py file:
def ins(request):
#c = {}
#c.update(csrf(request))
cr = request.POST.get('cid','')
up = request.POST.get('uid','')
tit = request.POST.get('tid','')
tx = request.POST.get('txid','')
pd = request.POST.get('pid','')
e = Entry(created=cr,updated=up,title=tit,text=tx,published=pd)
e.save()
return HttpResponse("Inserted SuccessFuly..")
I'm not sure why you're doing so much work by hand. Here's what you need to do:
# forms.py
from django import forms
from your_app.models import Entry
class EntryForm(forms.ModelForm):
class Meta:
model = Entry
# views.py
from django.shortcuts import render
from your_app.forms import EntryForm
def ins(request):
form = EntryForm(request.POST or None)
if request.method == 'POST' and form.is_valid():
form.save()
return render(request, 'homepage/index.html', {'form': form})
# index.html
{# code shortened for demonstration purposes #}
<form action="." method="post" enctype="application/x-www-form-urlencoded">
{{ form.as_table }}
{% csrf_token %}
<button type="submit">Insert</button>
</form>
Pulling form values directly out of the request.POST dictionary without passing them through your form's validation is a horrible idea - please don't do that.