Trying to create a Display in Django, which would look like this.
link: http://i47.tinypic.com/2lk2mw2.png
the number of fruits everyday is dynamic and different everyday.
the comment field is to be editable by the admin. the input would
then be used to update the row in the database
problem: so far I'm uncertain about how to go about allowing users to edit the comment column and present the changes in the database
**
fruits.html
**
{% for item in nodes %}
<tr>
<td class = "tablebord"><a href ="/nodes/node/{{ item.nodeid }}/">{{
item.nodeid }}</a></td>
<td class = "tablebord">{{ item.lastseen }} </td>
<td class = "tablebord"><div contenteditable>{{ item.comment }} <p>
<form action="" method="get">
<input type="text" name="q">
<input type="submit" value="test">
</form>
</p> </div> </td>
<td class = "tablebord">{{ item.lastipaddr }} </td>
</tr>
{% endfor %}
One solution that occurs to me:
In HTML:
Change method in form to POST.
Add CSRF Token to form.
Add hidden input with nodeid for parsing in view.
Pre-fill input with current comment.
<!-- Comment Cell -->
<td class = "tablebord">
<div contenteditable>
<form action="" method="post"> {% csrf_token %}
<input type="text" name="comment" value={{ item.comment }} />
<input type="hidden" value={{ item.nodeid }} name="nodeid" />
<input type="submit" value="edit" />
</form>
</div>
</td>
In views.py:
Import decorator for CSRF Token and Node model
Decorate view with CSRF Protect.
Check if form is submitted.
If so, get node and change comment.
Render template.
# decorator
from django.views.decorators.csrf import csrf_protect
from app.Node.models import Node
# view to handle table
#csrf_protect
def fruits(request):
nodes = Nodes.objects.all()
# user is posting: get edited node, change comment, and save
if request.POST:
nodeid = request.POST.get('nodeid')
edited_node = nodes.get(nodeid=nodeid)
edited_node.comment = request.POST.get('comment')
edited_node.save()
# render template with nodes
return render(request, 'fruits.html', {'nodes':nodes})
Hope this answers your problem.
Related
I have a Search form that includes the query box, some checkbox items, and a start and end date. I am getting my information when I enter a query, so I know it is performing the search_results action, but the start and end date is not getting validated at all. I have yet to add the code to handle the start and end date in my results, but the issue is there is no client side validation happening on the form.
My form looks like this:
class SearchForm(forms.Form):
q = forms.CharField(max_length=64,required=False)
service_choices = forms.MultipleChoiceField(
required=True,
widget=forms.CheckboxSelectMultiple,
choices=CustomUser.SERVICE_CHOICES,
)
start_date = forms.DateField(required=False)
end_date = forms.DateField(required=False)
I tried using Class Based View, but did not get any fields at all, so I
tried using a function based view to get my search criteria.
The view looks like:
def get_search(request):
form = SearchForm()
return render(request, 'get_search.html', {'form':form})
My template is:
<!-- templates/get_search.html -->
{% extends "base.html" %}
{% block title %}Search{% endblock title %}
{% block content %}
{% if user.is_authenticated %}
<br><br>
<TABLE BORDER="0" WIDTH="100%">
<TR>
<TD ALIGN="Left"><B>Track X - search</B></TD>
<TD ALIGN="Center"><B>User: {{ user }}</B></TD>
<TD ALIGN="Right"><B>Service: {{ user.service }}</B></TD>
</TR>
</TABLE>
<form action="{% url 'search_results' %}" method="get"">
{% csrf_token %}
<TABLE BGCOLOR="#66CCCC" Border="2" WIDTH="100%">
<TR>
<TD ALIGN="Left" WIDTH="100"> Services:</TD>
<TD ALIGN="Right">Search expression:</TD>
<TD ALIGN="Left">
{{ form.q }}
<button type="submit" name="submit">Search TrackX</button>
</TD>
</TR>
<TR>
<TD WIDTH="100"> {{ form.service_choices }} </TD>
<TD COLSPAN="2" ALIGN="Center"> Start Date: {{ form.start_date }}
End Date: {{ form.end_date }}</TD>
</TR>
</TABLE>
</form>
{% else %}
<p>You are not logged in</p>
Log In |
Sign Up
{% endif %}
{% endblock content %}
The Search_results view just uses the query to build some Q Filter
queries, and it seems to be working correctly.
It originally used a GET Method, and was passing the parameters into the search results view just fine. It just doesn't validate the dates (or anything else I assume) before passing the parameters into the view.
Can anyone tell me what am I missing here?
As I see on the view that your posted, you are not actually checking if the form is valid, you can do that by using:
if request.method == 'POST':
form = SearchForm(request.POST)
form.is_valid()
This method will validate all your fields, and return the boolean value representing if its valid or not.
I have to enter marks obtained by all the students in a class. So I created a template with a text field to store the marks corresponding to each roll number. The id of each text field is the roll number of the corresponding student.
How do I pass these marks from each field to views.py so that they can be stored in the database?
I tried using Javascript but I so not know how to access a table in database(class in models) so as to extract the roll number of each student and access the text field.
models.py
class MarksForm(forms.Form):
exam_type = forms.CharField(label='Exam Name', widget=forms.Select(choices=EXAM_TYPES))
entered_marks = forms.FloatField(label='Marks', required=True)
def clean(self):
examtype = self.cleaned_data.get("exam_type")
enteredmarks = self.cleaned_data.get("entered_marks")
return self.cleaned_data
views.py
#csrf_protect
#login_required
def edit_marks(request, course_code):
print ('Inside Views')
user = request.user
extrainfo = ExtraInfo.objects.get(user=user)
if extrainfo.user_type == 'faculty':
instructor = Curriculum_Instructor.objects.filter(instructor_id=extrainfo)
for ins in instructor:
if ins.curriculum_id.course_code == course_code:
registered_students = Register.objects.filter(curr_id = ins.curriculum_id.curriculum_id)
for reg in registered_students:
identity = Register.objects.get(student_id=reg.student_id, curr_id=curriculum[0])
m_id = identity.r_id
student_marks = 'enteredmarks'+identity.student_id
score = request.POST.get(studentmarks)
exam = request.POST.get('examtype')
Marks.objects.create(
mid=m_id,
exam_type=exam,
marks=score
)
context= {'registered_students': registered_students }
return render(request, 'coursemanagement/viewperformance.html', context)
urls.py
urlpatterns = [
url(r'^$', views.viewcourses, name='viewcourses'),
url(r'^(?P<course_code>[A-z]+[0-9]+[A-z]?)/$', views.course, name='course'),
url(r'^(?P<course_code>[A-z]+[0-9]+[A-z]?)/edit_marks$', views.edit_marks, name='edit_marks'),
viewperformance.html
{% load static %}
{% block viewperformance %}
<div>
<form class="ui large form" id="entermarks" method="POST"> {% csrf_token %}
<select name="examtype" id = "examtype" style="width: 100px">
<option value = "1">Quiz 1</option>
<option value = "2">Quiz 2</option>
<option value = "3">Mid Sem</option>
<option value = "4">End sem</option>
</select>
<table class="ui very basic collapsing celled table">
<thead>
<tr>
<th>Students</th>
</tr>
</thead>
<tbody>
{% for x in registered_students %}
<tr>
<td>
<div class="content">
<p style="text-align:center">{{x.student_id}}</p>
var student = x.student_id;
</div>
</td>
<td>
<input type="number" id="enteredmarks{{x.student_id}}" required="true" />
</td>
</tr>
{% endfor %}
</tbody>
</table>
<input type="submit" class="ui primary button" id="submit_marks" value="Upload" href="/ocms/{{course.course_id}}/edit_marks"/>
</form>
</div>
{% endblock %}```
When I try to print something inside view.py, it does not appear. Why is html not getting linked to its corresponding view(edit_marks)?
Best way to do this in django is by using Django Formset
A formset is a layer of abstraction to work with multiple forms on the same page. Which is your requirement.
I am new to python and django. I started an online app with user login etc. Everything works as expected. But if I am at a page with the related view having #login_required decorator and I reload the page I get the Forbidden (403) CSRF verification failed. Request aborted. Just by reloading. All of my forms work perfectly as well. Can you tell me how can I fix this?
A view:
#login_required
def main(request):
user=request.user
if request.method=='POST':
projectid=request.POST['project']
project = Project.objects.get(pk=int(projectid))
if project:
change=Change(user=user, project=project,starttime=datetime.now())
change.save()
return render_to_response('ProjectLogging/timer.html', {'change':change}, context_instance=RequestContext(request))
else:
HttpResponse("Choose a valid project!")
HTML:
<div>
<span style="color:red">You have uncommitted changes:</span><br>
<table>
<tr>
<td><b><u>Project</u></b></td>
<td><b><u>Started</u></b></td>
<td><b><u>Finished</u></b></td>
</tr>
{%for f in unfinished_forms%}
<tr>
<td>{{form}}<td>
</tr>
{%endfor%}
</table>
</div>
{%endif%}
<div>
<form action="/main/" method="post" name="project_list">
{%csrf_token%}
{%for p in project_list%}
<input type="radio" name="project" value="{{p.id}}">{{p.title}}<br>
{%endfor%}
<input type="submit" value="Start working!">
</form>
</div>
Alright, here is what I want to do:
A user sees a number of assignments in a table, with each assignment paginated using paginator. A user can input a number in a field and click "go", he is then taken to the page.
Here's my code so far:
View:
def home(request):
if request.user.is_authenticated():
assignments = show_assignments(request)
form=GoToForm(request.POST or None)
if request.POST and form.is_valid():
form = form.cleaned_data
assignment = form["assignment"]
page = form["page"]
return HttpResponseRedirect("/coding/assignment/%i/?page=%i") % (assignment, page)
return render(request, 'account.html', {'assignments':assignments, 'form':form})
Template:
{% for assignment in assignments %}
<tr>
<td><a href="{% url 'coding:assignment' assignment.id %}">
{{ assignment.country }}: {{ assignment.start_date }} to {{ assignment.end_date }}</a></td>
<td>{{ assignment.finished_articles }} of {{ assignment.article_num}} articles finished </td>
<td>Start where I left off</td>
<td>
<form id="form" action="" method="post" accept-charset="utf-8">
{% csrf_token %}
Jump to page {{ form.page }}
<input type="hidden" name="" value="{{ assignment.id }}" id="id_assignment">
<input type="submit" value="Go">
</form>
</td>
</tr>
{% endfor %}
This isn't working.
Is this because I need to use formsets (because I have multiple GoToForms on one page), or is the HttpResponseRedirect not working?
If the GoToForm form class looks simple (e.g. it only has page field), then there's no need to use this form class at all. Just add form fields manually in template and validate them inside post view if needed.
Formset for this case would be overkill, unless you have a lot of input fields to work with.
Also remember to change id="form" to make it unique for each form or use class="form" instead.
Im new to Django and I am trying to create a form that contains a table of drop downs. This is for generating a script based on user selections in these drop downs when submit is clicked.
The problem is the following form template is creating duplicate form element ids
How do I create unique ids in the form template even though the drop downs are going to be repeated.
The following is the code of the drop down.
<html>
<table border="1">
<form action="/PrintTestScript/" method="post">
{% csrf_token %}
<tr>
<th>Action</th>
<th>Endpoint</th>
<th>Status</th>
<th>Box Type</th>
</tr>
{% for i in 0123456789|make_list %}
<tr>
<td>
{{form.action}}
</td>
<td>
{{form.series}}
</td>
<td>
{{form.epstatus}}
</td>
<td>
{{form.boxtype}}
</tr>
{% endfor %}
<tr>
<td>
<input type="submit" value="Submit" />
</td>
</tr>
</form>
</table>
</html>
The following is the form class definition.
class TestForm(ModelForm):
action = forms.ModelChoiceField(queryset=actions.objects.all(), empty_label="")
series = forms.ModelChoiceField(queryset=endpoints.objects.all(), empty_label="")
epstatus = forms.ModelChoiceField(queryset=status.objects.all(), empty_label="")
boxtype = forms.ModelChoiceField(queryset=boxtype.objects.all())
class Meta:
model = endpoints
exclude = ('end_point_alias', 'dial_num', 'ip_address')
This is where the view is getting created
def getvals(request):
form = TestForm()
return render_to_response('main.html', {'form':form}, context_instance=RequestContext(request))
Thanks for your help.
You need to put the <form> tag within the for loop, so that you are actually creating 10 different forms instead of 10 copies of the same form elements. But you still have the problem that you would need 10 separate submit buttons. If you're actually looking for a list of forms, check out the Django FormSet documentation.