How to call in django index.html fle for "GET" "POST" method for get data from id (fields)? - html

In django I have create query like wise if someone want information:
In district parameter select Pune, then output gives data for pune district only.
for example :
http:127.0.0.1/api/?district=Pune
htt:127.0.0.1:8000/?crop = groundnut
and so on.
Next,I want to create a Html page for my starting django page(index.html)
if I runserver http:127.0.0.1:8000/
display my html file , where Our models fields(paramter) is id and then user submit the question "if" condition will be trigger and searching information for that parameters.
like wise:
District = __________ submit
gives data only for selected district name only
also
Crop = ______________ submit
gives data only for selected crop name only
likewise run this query
http:/api/?crop=groundnut
if user choose crop name is groundnut,
if use choose crop name is guava, then http:/api/?crop=guava query will be run.
So,now I want to create index.html file multiple parameters works.(AND query will apply)
http:/api/district=Pune&crop=groundnut
So, I want to create html page which call to this query and its show me this type
Distrcit : ________ Crop : __________ submit
here is my models.py
from django.db import models
from mongoengine import Document, fields
class Tool(Document):
crop = fields.StringField(required=True)
district = fields.StringField(required=True)
def __str__(self):
return self.crop
def save(self,*args, **kwargs):
super().save(*args, **kwargs)
class Meta:
verbose_name_plural ='tool'
project/urls.py
from django.conf import settings
from django.conf.urls.static import static
from django.conf.urls import include, url
from django.contrib import admin
from app.views import *
from routers import HybridRouter
router = HybridRouter()
router.register(r'tool', ToolViewSet, r"tool")
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^api/', include(router.urls, namespace='api')),
url(r'^$', index_view, {}, name='index'),
]
app/views.py
from django.template.response import TemplateResponse
from rest_framework_mongoengine.viewsets import ModelViewSet as MongoModelViewSet
from app.serializers import *
class ToolViewSet(MongoModelViewSet):
serializer_class = ToolSerializer
my_filter_fields = ('crop', 'district',) # specify the fields on which you want to filter
def get_kwargs_for_filtering(self):
filtering_kwargs = {}
for field in self.my_filter_fields: # iterate over the filter fields
field_value = self.request.query_params.get(field) # get the value of a field from request query parameter
if field_value:
filtering_kwargs[field] = field_value
return filtering_kwargs
def get_queryset(self):
queryset = Tool.objects.all()
filtering_kwargs = self.get_kwargs_for_filtering() # get the fields with values for filtering
if filtering_kwargs:
queryset = Tool.objects.filter(**filtering_kwargs) # filter the queryset based on 'filtering_kwargs'
return queryset
from .models import Tool
from django.shortcuts import render
def index_view(request):
questions=None
if request.GET.get('crop'):
crop = request.GET.get('crop')
questions = Tool.objects.filter(crop__icontains=crop)
district = request.GET.get('district')
query = Tool.object.create(crop=crop, district=district)
query.save()
return render(request, 'index.html',{
'questions': questions,
})
what I have to change in views.py file for index.html to get parameter and gives exact information after user click on submit button ?
index.html
<form method="GET">
Crop: <input type="text" name="crop"><br/>
Taluka: <input type="text" name="taluka"><br/>
<input type="submit" value="Submit" />
</form><br/><br/>
{% for question in questions %}
<p>{{question}}</p>
{% endfor %}
can you help me how to get data and run the query ?
where I need to changes ?

Its a TYPO error in this line :
query = Tool.object.create(crop=crop, district=district)
object should be objects ,like this :
query = Tool.objects.create(crop=crop, district=district)
Update your code like this :
from .models import Tool
from django.shortcuts import render
def index_view(request):
questions=None
if request.GET.get('crop'):
crop = request.GET.get('crop')
questions = Tool.objects.filter(crop__icontains=crop)
district = request.GET.get('district')
query = Tool.objects.create(crop=crop, district=district)
query.save()
return render(request, 'index.html',{
'questions': questions,
})
And, Update the save method of your Tool model like this :
class Tool(Document):
crop = fields.StringField(required=True)
district = fields.StringField(required=True)
def __str__(self):
return self.crop
def save(self,*args, **kwargs):
super(Tool, self).save(*args, **kwargs)

In your index.html file, change {{question}} to {{question.crop}}. You have to refer to the field (in your case crop) on the model you want to render on your page.
Also, the default manager is located at Tool.objects not Tool.object.
In your models.py, super should be super(Tool, self). Also model Tool should inherit from django.db.models.Model. Your fields must be from django.db.models
class Tool(Model):
crop = models.CharField()

Related

Need help about redirecting views in Django (New)

I have posted a question with the same title as this one, everyone can see it from this link
Unfortunately, because that was my first time making a question, some format mistakes were made and that question is closed for the moment. I have edited it and resubmitted for opening again but I don't know how long will that take so I might as well make a new one.
I'm working on a web application for reading novels and currently I'm stuck at a certain part in directing views using urls. I use Django as the back end with PostgreSQL as the database and HTML with bootsrap as front end. I will post my code below:
This is my urls.py (from the project folder):
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('app.urls')),
]
urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
This is my urls.py (from the app folder):
from django.contrib import admin
from django.urls import path, include
from django.contrib.auth import views as auth_views
from . import views
urlpatterns = [
path('', views.home),
path('book/<slug:book_slug>/<slug:chapter_slug>/', views.detail, name='detail'),
path('genre/<slug:category_slug>', views.category_detail, name='category_detail'),
path('book/<slug:book_slug>', views.book_detail, name='book_detail'),
path('register/', views.register, name="register"),
path('login/',auth_views.LoginView.as_view(template_name="app/login.html"), name="login"),
path('logout/',auth_views.LogoutView.as_view(next_page='/'),name='logout'),
]
This is my models.py:
from django.db import models
# Create your models here.
class Category(models.Model):
name = models.CharField(max_length=50)
slug = models.SlugField(max_length=50, unique=True, blank=True, editable=True)
def __str__(self):
return self.name
class Chapter(models.Model):
chapter = models.Count
chapter_name = models.CharField(max_length=100)
book = models.ForeignKey('Book', on_delete=models.CASCADE, null=True, related_name = 'Books')
detail = models.TextField()
slug = models.SlugField(max_length=100, unique=True, blank=True, editable=True)
def __str__(self):
return self.chapter_name
class Book(models.Model):
title = models.CharField(max_length=100)
slug = models.SlugField(max_length=100, unique=True, blank=True, editable=True)
cover_image = models.ImageField(upload_to= 'images/', blank= True, null = True)
author = models.CharField(max_length=100)
summary = models.TextField()
category = models.ForeignKey('Category', on_delete=models.CASCADE, null = True, related_name = 'books')
#date = models.DateField(auto_now_add=True)
recommended_book = models.BooleanField(default=False)
recommended_book_hot = models.BooleanField(default=False)
recommended_book_new = models.BooleanField(default=False)
recommended_book_finish = models.BooleanField(default=False)
def __str__(self):
return self.title
My views.py:
from django.shortcuts import render
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from .forms import RegistrationForm
from .models import Book, Category, Chapter
from gtts import gTTS
from django.urls import reverse
from django.shortcuts import get_object_or_404
# Create your views here.
def home(request):
recommended_book = Book.objects.filter(recommended_book = True)
recommended_book_hot = Book.objects.filter(recommended_book_hot = True)
recommended_book_new = Book.objects.filter(recommended_book_new = True)
recommended_book_finish = Book.objects.filter(recommended_book_finish = True)
return render(request, 'app/home.html', {'recommended_book': recommended_book, 'recommended_book_hot': recommended_book_hot, 'recommended_book_new': recommended_book_new, 'recommended_book_finish': recommended_book_finish})
def detail(request, book_slug, chapter_slug):
book = get_object_or_404(Chapter, book__slug = book_slug,slug = chapter_slug)
title = book.slug
return render(request, 'app/detail.html', {'detail': book, 'title':title})
def register(request):
form = RegistrationForm()
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/')
return render(request, 'app/register.html', {'form': form})
def category_detail(request, category_slug):
category = Category.objects.get(slug = category_slug)
books = Category.objects.prefetch_related('books')
return render(request, 'app/genre_detail.html', {'category':category})
def book_detail(request, book_slug):
book = Book.objects.get(slug = book_slug)
book_category = book.category.first()
similar_books = Book.objects.filter(category__name__startswith = book_category)
return render(request, 'app/book_detail.html', {'book': book, 'similar_books': similar_books, 'book_category': book_category})
With the configurations in urls.py, I have managed to go from homepage to a specific novel index page with the url: localhost:8000/book/book.slug then read a chapter using urL:localhost:8000/book/book.slug/chapter.slug, I then place an HTML link to go back to the index page in case I want to stop reading the chapter that goes like this:
<div class="container p-2">
Home /
{{detail.book}}/
{{detail.chapter_name}}
</div>
This is where I'm met with issues as what I have in mind was that when clicked, the link will lead to the index page again which is localhost:8000/book/book.slug. But what actually happened was that it showed a NoReveseMatch error upon the chapter page reload again.
From what I can inferred after seeing the logs, there should have been a slug as an argument for the view Book_detail() to work, such as 'test' (slug for a novel name "Test"). But instead, the argument show a blank '('',)' which made the link failed to direct to Book_detail().
Does anyone know what I did wrong ? Any helps or suggestions are appreciated
Edit 1: The NoReverseMatching error has been fixed but now clicking on the url will return a DoesNotExist at book/chapter.slug error instead.
Edit 2: This question has been answered, you can see the answers below.
Change this to:
{{detail.book}}/
Try this
{{detail`.book}}
The problem about DoesNotExist has been fixed !
I found out that by adding another definition in views.py at detail() that goes like this:
def detail(request, book_slug, chapter_slug):
book = get_object_or_404(Chapter, book__slug = book_slug,slug = chapter_slug)
index = Book.objects.get(slug = book_slug)
title = index.slug
return render(request, 'app/detail.html', {'detail': book, 'title':title})
then add it to the HTML like this:
<div class="container p-2">
Home /
{{detail.book}}/
{{detail.chapter_name}}
</div>
I can now return to the Index page !
Thank you, everyone, for your helps and suggestions. I have also realized that a lot of clumsy mistakes were made and they weren't really that hard to solve, actually. It's just that I overlooked them.

Putting additional data to CRUD django model- iterating with id,pk/ Python3/Django/CRUD

this is in models.py
class Word(models.Model):
english = models.CharField( max_length=100)
polish = models.CharField( max_length=100)
this is in views.py
words=[]
def dictionary(request):
words= Word.objects.all()
context={'words':words}
return render(request, 'base/dictionary.html', context) `
``
def word(request, pk):
word= Word.objects.get(id=pk)
context={'word':word}
return render(request, 'base/word.html', context)
I would like to add this dictionary from my workplace to already existing database with models - English-Polish pair. I've created a CRUD model of this type of simple dictionary, yet I am wondering if I have to put all the words inside by myself , or there will be a possibility to append each pair with specific id , ready to be rendered into html template and database ?
words=['fallopian tube' : 'jajowód',
'mrsa bacteria' : 'bakteria gronkowca złocistego',
'carotid aneurysm': 'tętniak tętnicy szyjnej',...]

How can I access my sqlite3 database through the html template using Django?

I have a Django application where most of my backend code is in views.py. In the frontend, I'm using an html template, but currently I have hardcoded options that the user can choose from a drop down menu. Those hardcoded options are all available in the sqlite3 database which is used extensively in views.py. Is there a way that I read those fields of database from the html file directly instead of hardcoding them?
Yes, if you have a model that will store the data from the fields you defined in your template then you can create a form that will store the data about that models fields, then you can just pass the form to the template, for example:
models.py
class Person(models.Model):
name = models.CharField(max_length=20)
age = models.IntegerField(default=1)
forms.py
from django import forms
from .models import Person
class PersonForm(forms.ModelForm)
class Meta:
model = Person
fields = '__all__' # or pass an iterable with your model field names as strings
views.py
from .models import Person
from .forms import PersonForm
def create_person(request):
if request.method == 'POST':
form = PersonForm(request.POST)
if form.is_valid():
person = form.save() # creates and saves a new Person instance
return redirect('person', pk=person.pk) # redirect to the view that displays the person
else:
form = PersonForm()
return render(request, 'create_person.html', {'form': form}) # pass the form to the view in a context dictionary
def person(request, pk): # pass the primary key of a person to the view
person = Person.objects.get(pk=pk)
return render(request, 'person.html', {'person': person})
create_person.html ( this is the view that will have the form )
<form method="post">
{% csrf_token %}
{{ form.as_p }} <!-- render form fields inside <p> tags ( you can also use table or list ) -->
<button type="submit" value="Save"></button>
</form>
person.html
<p>This is the page that belongs to the {{ person.name }}</p>
<p>The {{ person.name }} is {{ person.age }} years old.</p>
And finally set up the urls.py for your views:
from django.urls import path
from . import views
urlpatterns = [
path('create_person', views.create_person, name="create_person"),
path('person/<int:pk>/', views.person, name="person") # pass the pk argument into the url path here
]

Django how to ManyToManyField show in template as Select widget

My models.py:
class Model2(models.Model)
choice_field = models.ManyToManyField(to=Model)
my views.py:
def func(request):
if request.method == 'POST':
form = ModelForm(request.POST)
if form.is_valid:
form.save()
return.........................................
And so what I need to do with form request?
my template.html:
<div>
{{ form.choice_field }}
</div>
I get a values list and can a scroll and choose what I want. But i want to use Select with options for this values in template.
You can define widget for each field of your model manually. Assuming you using built-in ModelForm your code in forms.py can be something like this:
from django.forms import ModelForm, Select
class Model2Form(ModelForm):
class Meta:
model = Model2
fields = [
'choice_field',
]
widgets = {
'choice_field': Select(),
}

Passing Django forms' result to a page

I have worked on this for sometime now and I have decided to seek for your help. I have an ongoing project and I am using the django framework to build the site.
I have an html page that requests for user input, I have been able to extract the given data using the form.cleaned_data['']. A
#This is my views.py;
from django.shortcuts import render_to_response
from django.template import RequestContext
from forms import CarloanForm
def index(request):
form = CarloanForm()
if request.POST:
form = CarloanForm(request.POST)
if form.is_valid():
form.save()
else:
form = CarloanForm()
return render_to_response('carloan/index.html', {'form': form},
context_instance=RequestContext(request))
#I am extracting the user inputs using;
amount_of_vehicle = form.cleaned_data['cost_of_vehicle_Naira']
tenure = form.cleaned_data['loan_repayment_tenure_Months']
interest_rate = form.cleaned_data['interest_rate_Percentage']
equity = form.cleaned_data['equity_contrib_rate_Percentage']
depreciation_rate = form.cleaned_data['depreciation_rate_Percentage']
What I need to do and don't know how to go about it are;
Carry out some operations on the data (extracted using form.cleaned_data['']) and I have written some lines of code to that effect;
class LoanCalc:
def __init__(self,amount_of_vehicle,tenure,interest_rate,equity,depreciation_rate):
self.amount_of_vehicle = float(amount_of_vehicle)
self.tenure = float(tenure)
self.interest_rate = float(interest_rate)
self.equity = float(equity)
self.depreciation_rate = float(depreciation_rate)
def interest(self):
return (self.interest_rate/100) * self.amount_of_vehicle *(self.tenure/12)
def management_fee(self):
return 0.01 * (self.amount_of_vehicle + user.interest())
def processing_fee(self):
return 0.0025 *(self.amount_of_vehicle + user.interest())
def legal_fee(self):
return 0.0075 * (self.amount_of_vehicle + user.interest())
def residual_amount(self):
return 0.01 * (self.amount_of_vehicle - ((self.depreciation_rate/100) * self.amount_of_vehicle *(self.tenure/12)))
def equity_contribution(self):
return (self.equity/100) * self.amount_of_vehicle
def LoanPaymentPlan(self):
months = 1
total_amount = self.amount_of_vehicle+user.interest()+user.management_fee()+user.processing_fee()+user.legal_fee()+user.residual_amount()
upfront_payment = user.management_fee()+user.processing_fee()+user.legal_fee()+user.equity_contribution()+user.residual_amount()
opening_balance = total_amount - upfront_payment
balance = opening_balance
while months <= self.tenure:
if balance > 0:
monthly_instalment =(opening_balance/self.tenure)
monthly_interest = (((self.interest_rate/100) * balance)/ 12)
loan_payment = monthly_instalment - monthly_interest
closing_balance = balance - monthly_instalment
print' ',months,' ',round(balance,2),' ', round(monthly_instalment,2),' ',round(monthly_interest,2) \
, ' ',' ',round(loan_payment,2),' ',round(closing_balance,2)
balance = closing_balance
months += 1
return 'Thank you for using the Loan Calculator App'
and i want to carry out the operations in the code above on the extracted data.
I am thinking of doing it in such a way like this;
Create an empty dictionary;
user = {}
user = LoanCalc(amount_of_vehicle,tenure,interest_rate,equity,depreciation_rate)
result= user.interest()
result1 = user.management_fee()
. .
. .
. .
result10 = user.LoanPaymentPlan()
Pass the result(s) obtained from (question 2) to the same template that generated the form.
Please help me out guys, i am still very new to django. Thanks
This is the full stack of the referenced error am getting:
Environment:
Request Method: GET
Request URL: http://127.0.0.1:9000/result/
Django Version: 1.4.1
Python Version: 2.5.4
Installed Applications:
('django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'carloan')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware')
Traceback:
File "C:\Python25\Lib\site-packages\django\core\handlers\base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "C:\Users\AJIBIKE\Documents\Circuit Atlantic\calculator\carloan\views.py" in result_page
226. 'carloan': instance,
def result_page(request):
if request.POST:
form = Carloan_formForm(request.POST)
if form.is_valid():
instance = form.save(commit=False)
instance.interest = (instance.interest_rate/100) * instance.amount_of_vehicle * (instance.tenure/12)
instance.save()
else:
form = Carloan_formForm()
return render_to_response('carloan/result.html', {'carloan': instance,'form': form},
context_instance=RequestContext(request))
Exception Type: UnboundLocalError at /result/
Exception Value: local variable 'instance' referenced before assignment
Latest
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponseRedirect, HttpResponse
from forms import Carloan_formForm
def index(request):
if request.POST:
form = Carloan_formForm(request.POST)
if form.is_valid():
instance = form.save()
return HttpResponseRedirect ('/result/')
form = Carloan_formForm()
kwvars = {
'form': form,
}
return render_to_response('carloan/index.html', kwvars,
context_instance=RequestContext(request))
def result_page(request):
instance = None
if request.POST:
form = Carloan_formForm(request.POST)
if form.is_valid():
instance = form.save(commit=False)
instance.interest = (instance.interest_rate_Percentage/100) * instance.cost_of_vehicle_Naira * (instance.loan_repayment_tenure_Months/12)
instance.management_fee = 0.01 * (instance.cost_of_vehicle_Naira + instance.interest)
instance.processing_fee = 0.0025 * (instance.cost_of_vehicle_Naira + instance.interest)
instance.legal_fee = 0.0075 * (instance.cost_of_vehicle_Naira + instance.interest)
#i get syntax error starting from this line, and when i comment it out and the lines below, there is no syntax error.
instance.residual_amount = 0.01 * ((instance.cost_of_vehicle_Naira - ((instance.depreciation_rate_Percentage/100) * instance.cost_of_vehicle_Naira * (instance.tenure/12)))
instance.equity_contribution = (instance.equity_contrib_rate_Percentage/100) * instance.cost_of_vehicle_Naira)
instance.save()
else:
form = Carloan_formForm()
return render_to_response('carloan/result.html', {'instance': instance, 'form': form},
context_instance=RequestContext(request))
forms.py
from django import forms
from django.forms import ModelForm
from models import Carloan_form
class Carloan_formForm(ModelForm):
class Meta:
model = Carloan_form
exclude = ('interest', 'management_fee', 'processing_fee', 'legal_fee', \
'residual_amount', 'equity_contribution')
1 Save the result of the operations carried out on the extracted data in the Django Administration. (N.B: I already know how to save the user input)
Create a model to save the user's entries. app/models.py
class Carloan(models.Model) :
# In addition to your model fields add the functions that are part of your LoanCalc
...
Then create a ModelForm: app/forms.py
class CarLoanForm(forms.ModelForm) :
class Meta:
model = Carloan
Use CarLoanForm the same way you normally would except: app/views.py
if request.POST:
form = CarloanForm(request.POST)
if form.is_valid():
carloan = form.save()
#pass carloan (the instance) to the template and
#call its functions(from LoanCalc) instead of
#passing all of the values separately
Lastly, register this Model so it appears in the admin section app/admin.py
from django.contrib import admin
from app.models import Carloan
admin.sites.register(Carloan)
2 I have divided the page into two(one for the form and the other for
the result) and i want to pass the result to one-half of the page to
enable the user to see it.
Using the steps above, carloan will be passed to the view. go ahead and render its values.
Additionally:
Refactor index
your index definition should be refactored slightly, or your POST bound form will never make it to the template:
def index(request):
if request.POST:
form = CarloanForm(request.POST)
if form.is_valid():
instance = form.save()
else :
form = CarloanForm()
return render_to_response('carloan/index.html', {'form': form},
context_instance=RequestContext(request))
Refactor your ModelForm
Carry out some operations on the data (extracted using form.cleaned_data['']) and I have written some lines of code to that effect; - using a ModelForm instead of a regular django form you will get an instance of the model with the user's values already filled in, you reference them with instance.field.
and i want to carry out the operations in the code above on the extracted data. - the fields that you plan to calculate values for are listed in exclude they will not factor into form validation.
class CarLoanForm(forms.ModelForm) :
class Meta:
model = Carloan
# exclude fields that are calculated from user input
# NOTE: these fields must be in your model
exclude = ('interest', 'management_fee'...)
Refactor result page
Carry out some operations on the data (extracted using form.cleaned_data['']) and I have written some lines of code to that effect;
in results_page under the form.is_valid check, ther is a line: instance = form.save(commit=False) this gets all of the values that the user submitted in a instance of the Carloan Model that has NOT been saved yet.
further down: instance.interest = (instance.interest_rate/100) * instance.amount_of_vehicle *(instance.tenure/12) in this line I am calculating one of the excluded fields values (this calculation is a copy of your code).
lastly (after all of the operations on the data have been completed) I save the instance of the model.
then pass the instance to the template for display.
code:
def result_page(request):
if request.POST:
form = CarloanForm(request.POST)
if form.is_valid():
# get an instance from the form but don't save it
instance = form.save(commit=False)
# calculate excluded field values
instance.interest = (instance.interest_rate/100) * instance.amount_of_vehicle *(instance.tenure/12)
...
# after you have calculated all of the excluded fields save the instance
instance.save()
else :
form = CarloanForm()
return render_to_response('carloan/result.html', {'carloan' : instance, 'form' : form},
context_instance=RequestContext(request))
Error:
reference before error assignment - What does it say was referenced before assignment? Paste the entire stack trace please.
One of the simpler ways would be to store the data in the session in one view, retrieve it in the next. The docs will help.1
Having said that - there are a few other ways to approach the problem. It has been discussed more than once on SO:
Django Passing data between views
How do you pass or share variables between django views?
how to pass a list between views in django