I need to make a simple form. I can't understand why I don't see it. When I press a button which must show it, I see POST not GET request in my console. Which is not correct. Here is code:
form:
class DeviceAddForm(django.forms.Form):
name = django.forms.CharField(widget = django.forms.TextInput(attrs = {'size':'2','value':'1','class':'device',}))
device_slug = django.forms.CharField(widget = django.forms.HiddenInput())
model_name = django.forms.CharField(widget = django.forms.TextInput(attrs = {'size':'2','value':'1','class':'device',}))
platfrom = django.forms.ComboField(widget = django.forms.CheckboxInput())
sdk = django.forms.ComboField(widget = django.forms.CheckboxInput())
def __init__(self,request=None,*args,**kwargs):
self.request = request
super(DeviceAddForm,self).__init__(*args,**kwargs)
def clean(self):
if self.request:
if not self.request.session.test_cookie_worked():
raise django.forms.ValidationError("Cookies must be enabled")
return self.cleaned_data
saving data:
DEVICE_ID_SESSION_KEY = 'device_id'
def _device_id(request):
if request.session.get(DEVICE_ID_SESSION_KEY,'') == '':
request.session[DEVICE_ID_SESSION_KEY] = _generate_device_id()
return request.session[DEVICE_ID_SESSION_KEY]
def _generate_device_id():
device_id = ''
chars = '0123456789'
device_id_len = 5
for i in range (device_id_len):
device_id +=chars[random.randint(0,len(chars)-1)]
def get_device(request):
return Device.objects.filter(device_id= _device_id(request))
def add_device(request):
postdata = request.POST.copy()
device_slug = postdata.get('device_slug','')
name = postdata.get('name','')
model_name = postdata.get('model_name','')
platform = postdata.get('platform','')
sdk = postdata.get('SDK','')
d = get_list_or_404(Device, slug = device_slug)
dev = Device()
# dev = d
dev.name = name
dev.model_name = model_name
#dev.sdkID
#dev.plID
dev.id = _device_id(request)
dev.save()
view:
#csrf_exempt
def show_device(request, template_name = "onep_web/deviceForm.html"):
d = get_list_or_404(Device,slug = DeviceAddForm.device_slug)
if request.method == 'POST':
postdata = request.POST.copy()
form = DeviceAddForm(request,postdata)
if form.is_valid():
device.add_device(request)
if request.session.test.cookie_worked():
request.session.delete_test_cookie()
url = urlresolvers.reverse('show_device')
return HttpResponseRedirect(url)
else:
form = DeviceAddForm(request=request, label_suffix=':')
form.field['device_slug'].widget.attr['value'] = DeviceAddForm.device_slug
request.session.set_test_cookie()
# return render_to_response(template_name, locals(),csrf(context_instance RequestContext(request)))
return render_to_response(template_name, {'form':form})
urls:
urls form the app
urlpatterns = patterns('onep_web.views',
(r'^$','show_device',{'template_name':'onep_web/deviceForm.html'},'show_device'))
and some more urls:
urls.py from project
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
#url(r'^$', 'welcome_page.home', name='home'),
#url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^welcome_page/', 'one_web.views.welcome_page'),
url(r'^onep_web/', include('onep_web.urls')),
url(r'^device_page/', 'one_web.views.device_page'),
url(r'^configuration_page/', 'one_web.views.configuration_page'),
url(r'^log_page/', 'one_web.views.log_page'),
)
templates :
it's one from which I call the form
<title>OnePK Web Tool - {%block page %}{% endblock %}</title>
</head>
<body>
<div >
<br>
<div> Welcome to OnePK web-tool</div>
</div>
<form >
<br>
<br>
<br>Username:
<input type="text" name="Username">
<br>Password:
<input type="password" name="pwd">
<br>
<br>
{% block content %}
<h4>List of devices and IP addresses:</h4>
<table border="1">
<tr>
<td>Dev1</td>
<td>Dev2</td>
<td>Dev3</td>
<td>Dev4</td>
</tr>
<tr>
<td>{{a.getIP}}</td>
<td>{{a.getIP}}</td>
<td>{{a.getIP}}</td>
<td>{{a.getIP}}</td>
</tr>
</table>
{% endblock %}
<br>
<br>
<br>
<button type="button" onclick="ping()">Ping elenent</button>
<script>
function ping()
{
}
</script>
<br>
<br>
<label>Connection status</label>
<br>
<button type="button" onclick="openDev()">Connect to element</button>
<script>
function openDev()
{
window.open("p2t.html");
}
</script>
</form>
<form method = "post" action = "." class = "device">
{% csrf_token %}
{{form.as_p}}
<br />
<input type="submit" value="Add a new network device" name="submit" alt="Add a new network device"/>
</form>
<div class="cb"></div>
</body>
</body>
</html>
deviceForm:
{ % extends "p1t.html" % }
{ %block content% }
<h1> Add a new Device </h1>
Device info: { { device_data} }
<label for="name">Name</label><input type="text" id = "name" value = ""/>
{ %endblock% }
Related
This will be a lengthy post, please have patience with me, I just started with Django and try to wrap my head around it.
I created a site that will go thru exam questions one at a time, displaying the question and the multiple choice answers like on countless other websites.
The challenge I experience is when the user clicks "NEXT" on the pagination buttons, I would like for the selected answer(option) to be saved back to the database.
I tried it with AJAX scripts but the view never got executed.
Maybe there is a better way to do this or could you please point me into the right direction? I will post all of my code and hope someone can please assist me.
Thank you for taking the time to look at this.
I start with the models.py:
from django.db import models
class QuesModel(models.Model):
question = models.TextField(null=True)
code_snippet = models.TextField(null=True)
op1 = models.CharField(max_length=200,null=True)
op2 = models.CharField(max_length=200,null=True)
op3 = models.CharField(max_length=200,null=True)
op4 = models.CharField(max_length=200,null=True)
ans = models.CharField(max_length=200,null=True)
def __str__(self):
return self.question
class Answer(models.Model):
ans_id = models.AutoField(primary_key=True)
question_id = models.ForeignKey(QuesModel, on_delete=models.CASCADE)
fname = models.CharField(max_length=50)
lname = models.CharField(max_length=50)
examdate = models.DateField(auto_now_add =True)
answer = models.PositiveSmallIntegerField()
def __int__(self):
return QuesModel.question[self.question_id]
template is home.html:
{% extends 'Quiz/dependencies.html' %}
{% block content %}
{% load static %}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div class="container">
<h1>Welcome to my Quiz</h1>
{% for q in page_obj %}
<form method="post" action="{% url 'submit_answers' %}">
{% csrf_token %}
<input type="hidden" name="question_id" value="{{ q.id }}">
<!-- <input type="hidden" name="answer" value="{{ answer }}"> -->
<input type="hidden" name="date" value="{{ default_date }}">
<div class="form-group">
<div class="card text-bg-light mb-0" style="max-width: 50rem;">
<div class="card-header">
<code>
Question {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}<br>
{{q.question}}
</code>
</div>
<div class="card-body">
<class="card-text">
<label for="question">
<pre class="python"><code>{{q.code_snippet|linebreaks|escape}}</code></pre>
</label>
</div>
</div>
<br>
<div class="form-check">
<input class="form-check-input" type="radio" name="{{ q.question }}" id="option1" value="1" data-question-id="{{ q.id }} required>
<label class="form-check-label" for="option1">
{{ q.op1 }}
</label>
</div>
<div class="form-check">
<input class="form-check-input" type="radio" name="{{ q.question }}" id="option2" value="2" data-question-id="{{ q.id }} required>
<label class="form-check-label" for="option2">
{{ q.op2 }}
</label>
</div>
<div class="form-check">
<input class="form-check-input" type="radio" name="{{q.question}}" id="gridRadios1" data-question-id="{{ q.id }} value="3">
<label class="form-check-label" for="gridRadios1">
{{q.op3}}
</label>
</div>
<div class="form-check">
<input class="form-check-input" type="radio" name="{{q.question}}" id="gridRadios2" data-question-id="{{ q.id }} value="4">
<label class="form-check-label" for="gridRadios2">
{{q.op4}}
</label>
</div>
<br>
</div>
</div>
</div>
</div>
{% endfor %}
<div class="container">
<nav aria-label="Page navigation example">
<ul class="pagination">
{% if page_obj.has_previous %}
<li class="page-item">
<a class="page-link" href="?page={{ page_obj.previous_page_number }}">Previous</a>
</li>
{% endif %}
<li class="page-item disabled">
<a class="page-link" tabindex="-1" aria-disabled="true">Question {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}</a>
</li>
{% if page_obj.has_next %}
<li class="page-item">
<a class="page-link" href="{% url 'home' %}?page={{ page_obj.next_page_number }}" >Next</a>
</li>
{% endif %}
</ul>
</nav>
</div>
<div class="container">
<input id='timer' type='hidden' name="timer" value="">
<br>
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
{% block script %}
<script>
const timer=document.getElementById('displaytimer')
console.log(timer.textContent)
const inputtag = document.getElementById('timer')
t=0
setInterval(()=>{
t+=1
timer.innerHTML ="<b>Timer: " +t+" seconds</b>"
inputtag.value = t
},1000)
</script>
{% endblock script %}
</div>
{% endblock %}
Last is the views.py:
from django.shortcuts import redirect,render
from django.contrib.auth import login,logout,authenticate
from .forms import *
from .models import *
from django.http import HttpResponse
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
import datetime
def home(request):
print("HOMEVIEW")
print("REQUEST METHOD=" + request.method) # Debugging line
print("POST=")
print(request.POST) # Debugging line
# Render the question page
if request.method == 'POST':
print("IN POST")
questions=QuesModel.objects.all()
paginator = Paginator(questions, 1)
page_number = request.GET.get('page')
try:
page_obj = paginator.page(page_number)
except PageNotAnInteger:
# If the page is not an integer, show the first page of results
page_obj = paginator.page(1)
except EmptyPage:
# If the page is out of range, show the last page of results
page_obj = paginator.page(paginator.num_pages)
context = {
'page_obj': page_obj,
'answer': request.POST.get('answer'), # define and pass answer to template
}
return render(request,'Quiz/home.html',context)
def save_answer(request):
print("XXXXXXX")
print(request.method) # Debugging line
print(request.POST) # Debugging line
if request.method == 'POST':
# answer = request.POST['answer']
# question_id = request.POST['question_id']
# # Save the answer to the database
# answer = Answer(question_id=question_id, examdate=default_date, answer=answer)
# answer.save()
return HttpResponse('Success')
#Return an error response if the request method is not 'POST'
return HttpResponse('Error: Invalid request method')
def submit_answers(request):
print("submit_answers")
if request.method == 'POST':
print(request.POST)
questions=QuesModel.objects.all()
score=0
wrong=0
correct=0
total=0
incorrect_answers = []
for q in questions:
items = {'op1': q.op1, 'op2': q.op2, 'op3': q.op3, 'op4': q.op4}
total+=1
answer = request.POST.get(q.question) # Gets user’s choice, i.e the key of answer
print(request.POST.get(q.question))
print(q.ans)
print()
if q.ans == request.POST.get(q.question):
score+=10
correct+=1
else:
if q.ans != request.POST.get(q.question):
wrong += 1
testvar=request.POST.get(q.question)
incorrect_answers.append({'question': q.question, 'correct_answer': q.ans, 'user_answer': request.POST.get(q.question) } )
percent = score/(total*10) *100
context = {
'score':score,
'time': request.POST.get('timer'),
'correct':correct,
'wrong':wrong,
'percent':percent,
'total':total,
'incorrect_answers': incorrect_answers, # pass list to template
}
return render(request,'Quiz/result.html',context)
def default_date():
return datetime.datetime.now()
def pageme(request):
print("pageme_here")
questions = QuesModel.objects.all()
paginator = Paginator(questions, 1)
page_number = request.GET.get('page')
try:
page_obj = paginator.page(page_number)
except PageNotAnInteger:
page_obj = paginator.page(1)
except EmptyPage:
page_obj = paginator.page(paginator.num_pages)
context = {
'page_obj': page_obj,
}
return render(request, 'Quiz/pageme.html', context)
def saveme(request):
# Perform some actions here, such as saving data to the database
print("saveme_here") # Debug statement
return HttpResponse("Save successful") # Return a response to the client
# def save_answer(request):
# if request.method == 'POST':
# answer = request.POST['answer']
# question_id = request.POST['question_id']
# # Save the answer to the database
# answer = Answer(question_id=question_id, examdate=default_date, answer=answer)
# answer.save()
# return HttpResponse('Success')
# return HttpResponse('Error')
# def home(request):
# if request.method == 'POST':
# print(request.POST)
# questions=QuesModel.objects.all()
# #answer
# answer = request.POST.get('answer')
# question_id = request.POST.get('question_id')
# examdate = request.POST.get('date')
# answer = Answer(question_id=question_id, examdate=examdate, answer=answer)
# answer.save()
# #end answer
# score=0
# wrong=0
# correct=0
# total=0
# incorrect_answers = []
# for q in questions:
# items = {'op1': q.op1, 'op2': q.op2, 'op3': q.op3, 'op4': q.op4}
# total+=1
# answer = request.POST.get(q.question) # Gets user’s choice, i.e the key of answer
# print(request.POST.get(q.question))
# print(q.ans)
# print()
# if q.ans == request.POST.get(q.question):
# score+=10
# correct+=1
# else:
# if q.ans != request.POST.get(q.question):
# wrong += 1
# testvar=request.POST.get(q.question)
# incorrect_answers.append({'question': q.question, 'correct_answer': q.ans, 'user_answer': request.POST.get(q.question) } )
# percent = score/(total*10) *100
# context = {
# 'score':score,
# 'time': request.POST.get('timer'),
# 'correct':correct,
# 'wrong':wrong,
# 'percent':percent,
# 'total':total,
# 'incorrect_answers': incorrect_answers, # pass list to template
# }
# return render(request,'Quiz/result.html',context)
# else:
# questions=QuesModel.objects.all()
# paginator = Paginator(questions, 1)
# page_number = request.GET.get('page')
# try:
# page_obj = paginator.page(page_number)
# except PageNotAnInteger:
# page_obj = paginator.page(1)
# except EmptyPage:
# page_obj = paginator.page(paginator.num_pages)
# context = {
# 'page_obj': page_obj,
# }
# return render(request,'Quiz/home.html',context)
def addQuestion(request):
if request.user.is_staff:
form=addQuestionform()
if(request.method=='POST'):
form=addQuestionform(request.POST)
if(form.is_valid()):
form.save()
return redirect('/')
context={'form':form}
return render(request,'Quiz/addQuestion.html',context)
else:
return redirect('home')
def registerPage(request):
if request.user.is_authenticated:
return redirect('home')
else:
form = createuserform()
if request.method=='POST':
form = createuserform(request.POST)
if form.is_valid() :
user=form.save()
return redirect('login')
context={
'form':form,
}
return render(request,'Quiz/register.html',context)
def loginPage(request):
if request.user.is_authenticated:
return redirect('home')
else:
if request.method=="POST":
username=request.POST.get('username')
password=request.POST.get('password')
user=authenticate(request,username=username,password=password)
if user is not None:
login(request,user)
return redirect('/')
context={}
return render(request,'Quiz/login.html',context)
def logoutPage(request):
logout(request)
return redirect('/')
Please excuse this messy code, I tried all kinds of things and now I hope I can finish it with your help.
Here, I have tried to change your code and made some changes.
models.py
from django.db import models
class QuesModel(models.Model):
question = models.TextField(null=True)
code_snippet = models.TextField(null=True)
op1 = models.CharField(max_length=200,null=True)
op2 = models.CharField(max_length=200,null=True)
op3 = models.CharField(max_length=200,null=True)
op4 = models.CharField(max_length=200,null=True)
ans = models.CharField(max_length=200,null=True)
def __str__(self):
return self.question
class Answer(models.Model):
ques = models.ForeignKey(QuesModel, on_delete=models.CASCADE)
fname = models.CharField(max_length=50)
lname = models.CharField(max_length=50)
examdate = models.DateField(auto_now_add =True)
answer = models.CharField(max_length=200,null=True)
def __int__(self):
return self.ques__question
Note: Django provides a default "id" field for each model so no need for ans_id and in the Answer model 'question' field is updated with alias 'ques'
Then go to your command line and execute commands
python manage.py makemigrations
python manage.py migrate
Add some questions and answers
views.py
from django.contrib.auth import login,logout,authenticate
from .forms import *
from .models import *
from django.http import HttpResponse, JsonResponse
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
import datetime
import json
from django.views.decorators.csrf import csrf_exempt
from django.shortcuts import render, redirect
# here Disabling CSRF protection for this view function
#csrf_exempt
def home(request):
if request.method == "GET":
questions=QuesModel.objects.all()
paginator = Paginator(questions, 1)
page_number = request.GET.get('page')
try:
page_obj = paginator.get_page(page_number)
except PageNotAnInteger:
page_obj = paginator.page(1)
except EmptyPage:
page_obj = paginator.page(paginator.num_pages)
context = {
'page_obj': page_obj,
'default_date': default_date
}
return render(request,'Quiz/home.html',context)
# Render the question page
if request.method == 'POST':
parse_json = json.loads(request.body)
for k,v in parse_json.items():
ques = QuesModel.objects.get(id=int(k))
answer = v
obj, created = Answer.objects.update_or_create(
ques=ques, answer=answer,
defaults={'answer': answer, 'examdate': default_date, 'fname': "Bhavesh", "lname": "Patil"})
return redirect('get-results')
# GET Result Page
def get_result(request):
score=0
wrong=0
correct=0
total= (QuesModel.objects.all().count()) * 10
# Note you have to map user here I am keeping user static with fname -> Bhavesh and lname -> Patil ... Its me
get_answers = Answer.objects.filter(fname='Bhavesh', lname='Patil')
for i in get_answers:
if i.answer == i.ques.ans:
score += 10
correct += 1
else:
wrong += 1
percentage = score/total*100
context = {'percent': round(percentage,2), 'correct':correct, 'wrong': wrong, 'total':total, 'score': score}
return render(request, 'Quiz/results.html', context)
def default_date():
return datetime.datetime.now()
def addQuestion(request):
if request.user.is_staff:
form=addQuestionform()
if request.method=='POST':
form=addQuestionform(request.POST)
if form.is_valid():
form.save()
return redirect('/')
context={'form':form}
return render(request,'Quiz/addQuestion.html',context)
else:
return redirect('home')
def registerPage(request):
if request.user.is_authenticated:
return redirect('home')
else:
form = createuserform()
if request.method=='POST':
form = createuserform(request.POST)
if form.is_valid() :
user=form.save()
return redirect('login')
context={
'form':form,
}
return render(request,'Quiz/register.html',context)
def loginPage(request):
if request.user.is_authenticated:
return redirect('home')
else:
if request.method=="POST":
username=request.POST.get('username')
password=request.POST.get('password')
user=authenticate(request,username=username,password=password)
if user is not None:
login(request,user)
return redirect('/')
context={}
return render(request,'Quiz/login.html',context)
def logoutPage(request):
logout(request)
return redirect('/')
Note: Be careful while copying the code ... it may give Indentation error so check that as well
Now just replace your home template with this home.html
(here, I didn't have any idea of 'dependencies.html' so I haven't extended that so I have created home.html and results.html )
add below two templates in folder "Quiz". Quiz will have this templates
Quiz |--- home.html
|--- results.html
|--- dependencies.html
|--- ...
home.html
{% comment %}<!-- {% extends 'Quiz/dependencies.html' %} --> {% endcomment %}
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.3.1/dist/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
{% block content %}
{% load static %}
<div class="container">
<h1>Welcome to my Quiz</h1>
{% for q in page_obj %}
<form>
<input type="hidden" name="question_id" value="{{ q.id }}" id="questionID">
<!-- <input type="hidden" name="answer" value="{{ answer }}"> -->
<input type="hidden" name="date" value="{{ default_date }}">
<div class="form-group">
<div class="card text-bg-light mb-0" style="max-width: 50rem;">
<div class="card-header">
<code>
Question {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}<br>
{{q.question}}
</code>
</div>
<div class="card-body">
<class="card-text">
<label for="question">
<pre class="python"><code>{{q.code_snippet|linebreaks|escape}}</code></pre>
</label>
</div>
</div>
<br>
<div>
<div class="form-check">
<input class="form-check-input" type="radio" name="question" id="option1" value="{{ q.op1 }}" data-question-id="{{ q.id }}" onchange="submitValue(this)">
<label class="form-check-label" for="option1">
{{ q.op1 }}
</label>
</div>
<div class="form-check">
<input class="form-check-input" type="radio" name="question" id="option2" value="{{ q.op2 }}"" data-question-id="{{ q.id }}" onchange="submitValue(this)">
<label class="form-check-label" for="option2" >
{{ q.op2 }}
</label>
</div>
<div class="form-check">
<input class="form-check-input" type="radio" name="question" id="option3" data-question-id="{{ q.id }}" value="{{ q.op3 }}" onchange="submitValue(this)">
<label class="form-check-label" for="option3" >
{{q.op3}}
</label>
</div>
<div class="form-check">
<input class="form-check-input" type="radio" name="question" id="option4" data-question-id="{{ q.id }}" value="{{ q.op4 }}" onchange="submitValue(this)">
<label class="form-check-label" for="option4">
{{q.op4}}
</label>
</div>
</div>
<br>
</div>
</div>
</div>
</div>
{% endfor %}
<div class="container">
<nav aria-label="Page navigation example">
<ul class="pagination">
{% if page_obj.has_previous %}
<li class="page-item">
<a class="page-link" href="?page={{ page_obj.previous_page_number }}">Previous</a>
</li>
{% endif %}
<li class="page-item disabled">
<a class="page-link" tabindex="-1" aria-disabled="true">Question {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}</a>
</li>
{% if page_obj.has_next %}
<li class="page-item">
<a class="page-link" href="{% url 'home' %}?page={{ page_obj.next_page_number }}" >Next</a>
</li>
{% endif %}
</ul>
</nav>
</div>
<div class="container">
<input id='timer' type='hidden' name="timer" value="">
<br>
<button type="submit" onclick="submitResult()" class="btn btn-primary">Submit</button>
</div>
</form>
{% block script %}
<script>
const timer=document.getElementById('displaytimer')
console.log(timer.textContent)
const inputtag = document.getElementById('timer')
t=0
setInterval(()=>{
t+=1
timer.innerHTML ="<b>Timer: " +t+" seconds</b>"
inputtag.value = t
},1000)
</script>
{% endblock script %}
</div>
{% endblock %}
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script>
// this function will store user choose answer in session storage
// you can see this storage -> just google it "how to see session storage in browser?"
function submitValue(ele){
var questionID = document.getElementById('questionID').value
var answer = ele.value
sessionStorage.setItem(questionID, answer);
}
</script>
<script>
// this script will keep track of user activity i.e retrive user answers from session storage. ie if you move to previous or next page user's choosed answers will be displayed.
$(window).on('load', function(){
console.log(sessionStorage)
var questionID = document.getElementById('questionID').value
var arrayElements = document.getElementsByClassName('form-check-input')
if (sessionStorage.length){
var value = sessionStorage.getItem(questionID)
// console.log(arrayElements)
const ele = Array.prototype.filter.call(arrayElements, (ele) => ele.value == value)
console.log(ele)
if (ele.length > 0){
ele[0].checked = true;
}
}
});
</script>
<script>
// this function will send user result to server and redirect to result page
function submitResult(){
fetch("{% url 'home' %}", {
method: "POST",
body: JSON.stringify(sessionStorage),
headers: {
"Content-type": "text/html; charset=UTF-8"
}
}).then((response) => {
window.location.replace("{% url 'get-results' %}");
sessionStorage.clear();
});
}
</script>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.14.7/dist/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.3.1/dist/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</body>
</html>
Next step, Add results.html to quiz
results.html
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.3.1/dist/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<title>Results</title>
</head>
<body>
<div class="m-4">
<table class="table table-bordered">
<thead>
<tr>
<th colspan="2">Result</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">Wrong Answers</th>
<td>{{wrong}}</td>
</tr>
<tr>
<th scope="row">Correct Answers</th>
<td>{{correct}}</td>
</tr>
<tr>
<th scope="row">Total Score</th>
<td>{{score}} / <span><b>{{total}}</b></span></td>
</tr>
<tr>
<th scope="row">Percentage</th>
<td>{{percent}} %</td>
</tr>
</tbody>
</table>
</div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.14.7/dist/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.3.1/dist/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</body>
</html>
Note: : Here you can customize above template...I kept it simple and focused on your problem statement
Final step is route urls,
urls.py
from django.contrib import admin
from django.urls import path
from .views import *
urlpatterns = [
path('admin/', admin.site.urls),
path('', home, name='home'),
path('get-result/', get_result, name='get-results'),
# ... your url routes
]
This all took my day so please verify and let me know whether this solves your problem or not...
Thank You
models.py
from django.db import models
from django.utils.translation import gettext_lazy as _
# Create your models here.
# from django.utils.encoding import smart_unicode
from enum import Enum
from django.contrib.auth.models import AbstractUser
from django import forms
class CommentForm(forms.Form):
name = forms.CharField()
comment = forms.CharField(widget=forms.Textarea)
class Username(AbstractUser):
firstName = models.CharField(max_length=200, null=True)
lastName = models.CharField(max_length=200, null=True)
email = models.EmailField(unique=True, default=None, null=True)
password = models.CharField(max_length=32)
REQUIRED_FEILDS = []
def __str__(self):
return self.username
class Option(models.TextChoices):
OPTION1 = 'OPTION1', _('OPTION1')
OPTION2 = 'OPTION2', _('OPTION2')
OPTION3 = 'OPTION3', _('OPTION3')
OPTION4 = 'OPTION4', _('OPTION4')
class Question(models.Model):
# id = models.AutoField(primary_key=True)
question=models.CharField(max_length=600)
option1=models.CharField(max_length=200, default=None)
option2=models.CharField(max_length=200, default=None)
option3=models.CharField(max_length=200, default=None)
option4=models.CharField(max_length=200, default=None)
difficulty=models.PositiveIntegerField()
exam=models.BooleanField()
key=models.CharField(max_length=100)
correct_answer = models.CharField(max_length=7,choices=Option.choices,default=None,)
def __str__(self):
return str(self.id)
class Answer(models.Model):
username=models.ForeignKey(Username,max_length=200, null=True,on_delete=models.CASCADE)
question_id = models.ForeignKey(Question, on_delete=models.CASCADE)
answer = models.CharField(
max_length=7,
choices=Option.choices,
default=None,
)
surety=models.PositiveIntegerField( null=True)
difficulty=models.PositiveIntegerField( null=True)
def __str__(self):
return self.answer
views.py
from django.shortcuts import render, redirect
from .models import *
from django.http import JsonResponse
from django.contrib.auth import authenticate, login, logout
# from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
from django.contrib.auth import get_user_model
from django.template import loader
from django.views.generic import ListView
from django.core.paginator import Paginator
from ada.models import Question
from django.db.models.functions import Lower
from django import forms
# class TestScreen(ListView):
# paginate_by = 6
# model = Question
# from .forms import CommentForm
# def post_comment(request, username_id):
# if request.method == 'POST':
# form = CommentForm(request.POST)
# if form.is_valid():
# data = form.cleaned_data
# blog = get_object_or_404(Practise, id=username_id)
# Comment.objects.create(
# question_id = question_id)
def viewtemplate(request, username):
student = Answer.objects.get(id = username)
form = templateform(request.POST)
if request.method == "POST":
if form.is_valid():
form = form.save(commit=False)
form.username = student
form.save()
return redirect('index')
else:
form = templateform()
return render(request, 'practise.html', {'form': form})
def index(request):
if request.user.is_authenticated:
return render(request,'index.html')
# #login_required(login_url = '/login')
# def quiz(request, myid):
# quiz = Quiz.objects.get(id=myid)
# return render(request, "quiz.html", {'quiz':quiz})
def Signup(request):
if request.user.is_authenticated:
return redirect('/')
if request.method=="POST":
username = request.POST['username']
email = request.POST['email']
first_name=request.POST['first_name']
last_name=request.POST['last_name']
password = request.POST['password1']
confirm_password = request.POST['password2']
if password != confirm_password:
return redirect('/register')
User = get_user_model()
user = User.objects.create_user(username, email, password)
user.first_name = first_name
user.last_name = last_name
user.save()
return render(request, 'login.html')
return render(request, "signup.html")
# def testscreen(request):
# return render(request, 'questions.html')
# def quizData (request):
# context = {'quiz' : quizData }
# return render (request, testscreen, context)
def Login(request):
if request.user.is_authenticated:
return redirect('/')
if request.method=="POST":
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user is not None:
login(request, user)
return redirect("/")
else:
return render(request, "login.html")
return render(request, "login.html")
def Practise(request):
questions_list = Question.objects.get_queryset().order_by('id')
paginator = Paginator(questions_list, 1)
page_number = request.GET.get('page')
page_obj = paginator.get_page(page_number)
# if request.user.is_authenticated:
# return render(request, 'practise.html',)
if request.method=="POST":
answer = request.POST.get('html')
print(request.POST)
# difficulty = request.POST['difficulty']
# surety=request.POST['surety']
# answer.save()
return render(request, 'practise.html' ,{'page_obj': page_obj})
def Profile(request):
if request.user.is_authenticated:
return render(request, 'users-profile.html')
def FAQ(request):
if request.user.is_authenticated:
return render(request, 'pages-faq.html')
def Contact(request):
if request.user.is_authenticated:
return render(request, 'pages-contact.html')
def Logout(request):
logout(request)
return redirect(request,'login.html')
def question(request):
# questions_list = Question.objects.all().order_by(Lower("key"))
questions_list = Question.objects.get_queryset().values("key").annotate(n=models.Count("pk"))
practise_questions = Question.objects.filter(key= 'questions_list').all()
print(practise_questions)
# a = Question.objects.filter(key='C.1.1')
# print(a.count())
if request.user.is_authenticated:
return render(request, 'questions.html', {'questions_list': questions_list})
def practise(request):
print(request)
questions_list = Question.objects.get_queryset().order_by('id')
# answers_list = Answer.objects.all()
# print(answers_list)
paginator = Paginator(questions_list, 1)
page_number = request.POST.get('page_no')
page_obj = paginator.get_page(page_number)
print(request.GET)
# if request.user.is_authenticated:
# return render(request, "try.html",{'page_obj': page_obj})
if request.method=="POST":
answer = request.POST.get('answer')
difficulty = request.POST.get('myRange')
surety=request.POST.get('surety')
# Answer = ()
# answer_submit = Answer(answer='answer')
# answer_submit.save()
# answer_submit.answer = answer
# answer_submit.difficulty = difficulty
# answer_submit.surety = surety
# answer_submit.save()
# print(request.POST)
# User_ans = get_user_model()
# user = User_ans.objects.create_user(answer, difficulty, surety)
#user.answer = answer
# user.difficulty = difficulty
#user.save()
return render(request, "try.html", {'page_obj': page_obj})
try.html
{% extends 'base.html' %}
{% block title %}Practise Test {% endblock %}
{% block css %}
<style>
.head1 {
color: bisque;
font-size: 2rem;
font-weight: bold;
height: 50px;
font-family: 'Lucida Sans';
}
.head2 {
color: cyan;
font-size: 2rem;
font-weight: bold;
font-family: 'Lucida Sans';
}
</style>
{% endblock %}
{% block body %}
<div class="btn-wrapper">
<div class="row py-5 p-4 bg-white rounded shadow-sm">
<div class="col-lg-6">
<div class="bg-light rounded-pill px-4 py-3 text-uppercase font-weight-bold"
style="color:black;font-weight:bold">Practise Test</div>
<br>
{% for question in page_obj %}
<form class="row g-4" method="POST" action="/try/">{% csrf_token %}
<div class="col-md-12">
<li class="list-group-item active font-weight-bold">{{ question.id }}. {{ question.question }}</legend></li>
<label for="{{ question.option1 }}" class="form-label" style="font-weight: bold;"><i>
{{ question.option1 }}</i></label>
<input type="radio" style="text-align: center;"value="{{ question.option1 }}"
class="form-control" id="html1" name="option">
</div>
<div class="col-md-12">
<label for="{{ question.option2 }}" class="form-label" style="font-weight: bold;"><i>
{{ question.option2 }}</i></label>
<input type="radio" style="text-align: center;" value="{{ question.option2 }}"
class="form-control" id="html2" name="option">
</div>
<div class="col-md-12">
<label for="{{ question.option3 }}" class="form-label" style="font-weight: bold;"><i>
{{ question.option3 }}</i></label>
<input type="radio" style="text-align: center;"value="{{ question.option3 }}"
class="form-control" id="html3" name="option">
</div>
<label for="{{ question.option4 }}" class="form-label" style="font-weight: bold;"><i>
{{ question.option4 }}</i></label>
<input type="radio" style="text-align: center;"value="{{ question.option4 }}"
class="form-control" id="html4" name="option">
</div>
{% endfor %}
<div class="slid">
<h3>
<b> <i> Difficulty </i> </b>
</h3>
<p>Slide according to difficulty of question:</p>
<div class="slidecontainer">
<input
type="range"
min="1"
max="5"
value="value"
class="slider"
id="myRange"
name="difficulty_slider"
/>
<p>Value: <span id="demo"></span></p>
</div>
</div>
<script>
var slider = document.getElementById("myRange");
var output = document.getElementById("demo");
output.innerHTML = slider.value;
slider.oninput = function () {
output.innerHTML = this.value;
};
</script>
<h3>Surety: </h3>
<div class="slidecontainer">
<input
type="range"
min="1"
max="5"
value="value"
class="slider"
id="justRange"
name="surety_slider"
/>
<p>Value: <span id="realDemo"></span></p>
<script>
var slider = document.getElementById("myRange");
var output = document.getElementById("demo");
output.innerHTML = slider.value;
slider.oninput = function () {
output.innerHTML = this.value;
};
var slider = document.getElementById("justRange");
var display = document.getElementById("realDemo");
display.innerHTML = slider.value;
slider.oninput = function () {
display.innerHTML = this.value;
};
</script>
{% if page_obj.has_previous %}
<button method="post" type="submit" class="action-btn checkRequired Submit" name="action" value="Submit"> previous</button>
<input type="hidden" name="page_no" value="{{ page_obj.previous_page_number }}">
{% endif %}
Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}
{% if page_obj.has_next %}
<button method="post" type="submit" class="action-btn checkRequired Submit" name="action" value="Submit"> next</button>
<input type="hidden" name="page_no" value="{{ page_obj.next_page_number }}">
{% endif %}
<!-- <button type="submit" class="btn btn-primary">Submit</button> -->
</form>
<br>
</div>
</div>
</div>
{% endblock %}
I have attached the necessary views, models and html files for references. Also,
In html page there are radio buttons inside of form, where clicking Submit button has to save all selected radio buttons into the database. Is there any way to do that? Any solution would be of lot more help.
in views.py you can use:
# If not using required attribute in HTML
seleted_option = request.POST.get('option')
# If using required it is suggested to use
seleted_option = request.POST['option']
I am writing and Update View for a model that I have created. The model is a Product Backlog Item. The UpdateView is unable to find a reverse match for my view.
The NoReverseMatch error is saying that Django cannot find a matching url pattern.
My code as below:
UpdatePBI View
class updatePBI(LoginRequiredMixin, UpdateView):
pk_url_kwarg = 'pbipk'
kwargs={'pk_url_kwarg': 'pbipk'}
model = PBI
fields = ['priority', 'summary', 'story_points', 'effort_hours']
login_url = '/accounts/login'
redirect_field_name = '/home'
template_name = 'backtrack/PBIdetail.html'
def dispatch(self, request, *args, **kwargs):
print(kwargs)
return super().dispatch(request, *args, **kwargs)
def get_success_url(self):
return "{}?all=0".format(reverse('pb', kwargs={'pk': self.kwargs['pk']}))
def get_object(self, queryset=None):
obj = get_object_or_404(self.model,pk=self.kwargs['pbipk'])
return obj
def form_valid(self, form):
PBIList = getPBIfromProj(self.kwargs['pk'], '0')
remove = []
priorityData = form.cleaned_data['priority']
if int(priorityData) < self.object.priority:
# Remove all PBI with priority higher than post data priority
# and lesser or equal than current PBI priority
for PBIObj in PBIList:
if PBIObj.priority < int(priorityData) or PBIObj.priority >= self.object.priority:
remove.append(PBIObj.priority)
PBIList = [
PBIObj for PBIObj in PBIList if PBIObj.priority not in remove]
# Increase each objects priority by one
for PBIObj in PBIList:
PBIObj.priority += 1
PBIObj.save()
else:
# Remove all PBI with priority higher than post PBI priority
# and lesser than and equal to Post data priority
for PBIObj in PBIList:
if PBIObj.priority <= self.object.priority or PBIObj.priority > int(priorityData):
remove.append(PBIObj.priority)
PBIList = [
PBIObj for PBIObj in PBIList if PBIObj.priority not in remove]
# Decrease each objects priority by one
for PBIObj in PBIList:
PBIObj.priority -= 1
PBIObj.save()
return super().form_valid(form)
model.py
from django.urls import reverse
# Create your models here.
class PBI(models.Model):
status = models.CharField(max_length=1,
choices=[("N", "Not Done"), ("P", "In Progress"), ("D", "Done")], default="N")
story_points = models.FloatField()
effort_hours = models.FloatField()
summary = models.TextField(default = None)
priority = models.IntegerField(default=0)
Project = models.ForeignKey('Project', on_delete=models.CASCADE, related_name='pbi')
def __str__(self):
return self.summary
class Meta:
db_table = "PBI"
verbose_name = 'PBI'
verbose_name_plural = 'PBIs'
class Project(models.Model):
name = models.CharField(max_length=256)
def __str__(self):
return self.name
class Meta:
db_table = "Project"
urls.py
from django.conf.urls import url
from backtrack import views
from django.shortcuts import redirect
urlpatterns = [
path('', lambda x: redirect('1/'),name='home'),
path('<int:pk>/', views.HomeView.as_view(),name = 'home-project'),
path('<int:pk>/pb/', views.ProductBacklogView.as_view(),name='pb'),
path('<int:pk>/pb/add/', views.AddPBI.as_view(),name='add'),
path('<int:pk>/pb/<int:pbipk>/update', views.updatePBI.as_view(),name='detail'),
path('<int:pk>/pb/<int:pbipk>/delete', views.DeletePBI.as_view(),name='delete')
]
Product Backlog Page
{% block content %}
<h1 class="page-header"><i class="fa fa-file"></i> Product BackLog</h1>
<div class="row placeholders"></div>
{% if data|length == 0 %}
<h4>There are no PBIs</h4>
{% endif %}
<h2 class="sub-header">
<div class="dropdown">
<button class="btn btn-light dropdown-toggle pull-left" type="button" data-toggle="dropdown" style="margin-bottom: 10px;">Filter By
<span class="caret"></span></button>
<ul class="dropdown-menu">
<li>Priority</li>
<li>Story Points</li>
<li>Effort Hours</li>
</ul>
<div class="btn-group btn-toggle">
<button class="btn btn-xs btn-primary active toggle">NOT DONE</button>
<button class="btn btn-xs btn-default toggle">ALL</button>
</div>
<button type="button" class="btn btn-light" style="margin-bottom: 10px;"><i class="fa fa-plus" id="A"></i>ADD</button>
<button type="button" class="btn btn-light" style="margin-bottom: 10px;"><i class="fa fa-times" id="A"></i>DELETE</button>
</div>
</h2>
<div class="table-responsive">
<table class="table table-striped">
<thead>
<tr>
<th> </th>
<th>Priority</th>
<th>Summary</th>
<th>Status</th>
<th>Story Points</th>
<th>Cumulative Story Points</th>
<th>Effort hours</th>
<th>Cumulative Effort hours</th>
</tr>
</thead>
<tbody>
{% for PBI in data %}
<tr>
<td><input type="checkbox"></td>
<td>
{% if PBI.status == "N" %}
{{PBI.priority}}
{% else %}
--
{% endif %}
</td>
<td><a style="text-decoration: none; color: cornflowerblue;" href={% url 'detail' pk=1 pbipk=PBI.id %}>{{PBI.summary}}</a></td>
<td>
{% if PBI.status == "N" %}
Not Done
{% elif PBI.status == "P" %}
In Progress
{% else %}
Done
{% endif %}
</td>
<td>{{PBI.story_points}}</td>
<td>{{PBI.sum_story_points}}</td>
<td>{{PBI.effort_hours}}</td>
<td>{{PBI.sum_effort_hours}}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<script>
$.urlParam = function (name) {
var results = new RegExp('[\?&]' + name + '=([^&#]*)')
.exec(window.location.search);
return (results !== null) ? results[1] || 0 : false;
}
$(document).ready(function () {
if($.urlParam('all') == '1'){
$(this).find('.toggle').toggleClass('active');
if ($(this).find('.btn-primary').length>0) {
$(this).find('.toggle').toggleClass('btn-primary');
}
}
var getUrl = window.location;
var baseUrl = getUrl.protocol + "//" + getUrl.host + getUrl.pathname;
$('.btn-toggle').click(function(){
console.log($.urlParam('all') == '0')
if($.urlParam('all') == '0')
window.location.replace(baseUrl + "?all=1");
else
window.location.replace(baseUrl + "?all=0");
})
});
</script>
{% endblock content %}
I am getting this error
NoReverseMatch at /home/1/pb/50/update
Reverse for 'detail' with keyword arguments '{'pk': 1, 'pbipk': ''}' not found. 1 pattern(s) tried: ['home/(?P<pk>[0-9]+)/pb/(?P<pbipk>[0-9]+)/update$']
Update
I have found that the error is because I am setting the form action with the PBI.id but the Update view is not passing a PBI to my template. How do I fix this?
Okay. I found what I was doing wrong. I have to override the get_context_data() function of the template view mixin and pass the PBI in the context after calling super().get_context_data(form).
i am trying to post the data from html form to my db, however i get the error that the url does not exist. what am trying to do is later on turn the test form into dynamic add fields using HTML and Jquery rather than using formset for ease UI designing and handle it in dango back end.
also note that am assigning the foreign key which is the startup_name by passing it through the url to test view.
the code is as following:
models.py:
class Startup(models.Model):
author = models.ForeignKey(User, on_delete=models.CASCADE)
startup_name = models.CharField('Startup Name', max_length = 32, null = False, blank = False)
class Team (models.Model):
str_team = models.ForeignKey(Startup, on_delete=models.CASCADE)
name = models.CharField('Name',max_length = 32, null = False, blank = False)
position = models.CharField('Title/Position', max_length = 32, null = False, blank = False)
qualification = models.CharField('Degrees/Qualifications', max_length=32,null=False,blank=False)
views.py:
def create_startupform(request):
if request.method == 'POST':
form = startupform(request.POST)
if form.is_valid():
result = form.save(commit=False)
result.author = request.user
result.save()
return redirect('test', startup_id = result.pk)
else:
form = startupform()
return render(request, 'str_name.html', {'form': form})
def test (request, startup_id):
e = Startup.objects.values('startup_name')
if request.method == 'POST':
na = request.POST.get("name")
po = request.POST.get("position")
qu = request.POST.get("qualification")
ref = Team(name = na, position = po, qualification = qu, str_team = e)
ref.save()
return redirect('str_dashboard')
return render(request, 'test.html')
forms.py:
class startupform(forms.ModelForm):
class Meta:
model = Startup
fields = ('startup_name',)
widgets = {
'startup_name': forms.TextInput(attrs = {'class':'form-control'}),
}
def clean(self):
super ( ).clean ( )
startup_name = self.cleaned_data.get ( 'startup_name' )
startup_qs = Startup.objects.filter ( startup_name = startup_name )
if startup_qs.exists ( ):
raise forms.ValidationError ( 'This Startup Already Exist!' )
test.html:
<form id="add-extra" class="form" method="post" action = "{% url 'test' %}">{% csrf_token %}
<div class="form-row profile-row">
<div class="col-md-8 col-lg-12">
<hr />
<h4>Startup Core Team</h4>
<div class="form-row">
<div class="col-sm-12 col-md-6 col-lg-12">
<div class="form-group">
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th>Name</th>
<th>Position</th>
<th>Qualification</th>
</tr>
</thead>
<tbody>
<tr>
<td><input class="form-control" type="text" name="candidate_name" /></td>
<td><input class="form-control" type="text" name="position"/></td>
<td><input class="form-control" type="text" name="qualification"/></td>
<td><button class="btn btn-primary d-lg-flex align-items-lg-center" type="button" style="margin-top: 4px;margin-left: 15px;background-color: rgb(24,130,7);"><i class="fas fa-plus"></i></button></td>
</tr>
<tr></tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
<hr />
<div class="form-row">
<div class="col-md-12 content-right"><button class="btn btn-primary text-center border rounded d-lg-flex justify-content-lg-end align-items-lg-center form-btn" type="post" style="margin-left: 1040px;padding: 6px;">SAVE </button></div>
</div>
</div>
</div>
URLS:
from django.urls import path
from . import views
urlpatterns = [
path ( 'str_dashboard/' , views.str_dashboard , name = 'str_dashboard' ),
path ( 'create_startupform/' , views.create_startupform, name = 'create_startupform' ),
path('test/', views.test, name='test'),
]
Error:
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/test/
Using the URLconf defined in sourcing.urls, Django tried these URL patterns, in this order:
You are trying an url which is not in the urls.py:
urlpatterns = [
...
path('test/<int:startup_id>/', views.test, name='test'),
path('test/', views.test, name='test_base'), # add this
]
The url 'http://127.0.0.1:8000/test/' won't match because it would need to have 'startup_id' attached with your urls.py.
http://127.0.0.1:8000/test/1 would work.
If you do like i wrote above, make sure that your view is taking startup_id as optional. Or use another function for the call without startup_id.
Consider my template:
entry_detail.html
<form class="navbar-form navbar-right" action="." method="get">
<!-- add -->
<!-- <p name="filter_link" class="pull-right">Produtos em baixo estoque</p> -->
<a name="new_customer" href="{% url 'proposal_list' %}">
<button type="button" class="btn btn-primary">
<span class="glyphicon glyphicon-plus"></span> Criar Orçamento
</button>
</a>
</form>
And considerer my view:
views.py
class EntryDetail(DetailView):
template_name = 'core/entry/entry_detail.html'
model = Entry
def create_proposal(self, employee_pk=8):
if 'new_customer' in self.request.GET:
employee = Employee.objects.get(pk=employee_pk)
num_last_proposal = NumLastProposal.objects.get(
pk=1) # sempre pk=1
entry = Entry.objects.get(pk=self.request.GET[self.id])
obj = Proposal(
num_prop=num_last_proposal.num_last_prop + 1,
type_prop='R',
category=entry.category,
description=entry.description,
work=entry.work,
person=entry.person,
employee=employee,
seller=entry.seller,
)
obj.save()
entry.is_entry = True
entry.save()
num_last_proposal.num_last_prop += 1
num_last_proposal.save()
Question: How to make this work this. How to get entry.pk in DetailView for use in
entry = Entry.objects.get(pk=self.request.GET[self.id])
In manage.py shell its work
shell_create_proposal.py
from core.models import Entry, Proposal, Employee, NumLastProposal
employee = Employee.objects.get(pk=8)
num_last_proposal = NumLastProposal.objects.get(pk=1)
entry = Entry.objects.get(pk=1)
obj = Proposal(
num_prop=num_last_proposal.num_last_prop + 1,
type_prop='R',
category=entry.category,
description=entry.description,
work=entry.work,
person=entry.person,
employee=employee,
seller=entry.seller,
)
obj.save()
entry.is_entry = True
entry.save()
num_last_proposal.num_last_prop = num_last_proposal.num_last_prop + 1
num_last_proposal.save()
Specify the pk in the url and the detail view should handle it for you
url(r'^yourview/(?P<pk>\d+)/' , YourDetailView.as_view() , name='your_view_name' ),
Look at the get_object method here:
http://ccbv.co.uk/projects/Django/1.8/django.views.generic.detail/DetailView/
it gets the pk as follows:
pk = self.kwargs.get(self.pk_url_kwarg, None)