How to save output into single drop-down with django - python

I have a scraper that scraper data on cruises, I am grabbing the title of the cruise. My aim was to output these results into a single drop down menu so I can select one of these from the drop-down. However, it instead produces multiple input options and only a single title in the drop down. I.E.
My script:
models.py:
from django.db import models
class Cruises(models.Model):
title = models.TextField(max_length=200)
views.py:
from django.shortcuts import render
from .models import Cruises
def basic(request):
long_list = Cruises.objects.values('title')
return render(request, 'cruise_control/basic.html', context = {'long_list':long_list})
basic.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Cruises</title>
</head>
<body>
<h1> Cruise Control </h1>
{% for lng_l in long_list %}
<form action="/action_page.php">
<label for='destination'>Destination</label>
<input type="text" list="destination" />
<datalist id="destination">
<option>{{lng_l.title}}</option>
</datalist>
<!label for="cruisetime">Departure date</label>
<!input type="date" id="cruisetime" name="cruisetime" min={{dep_l.departureDate}}>
<!input type="submit">
</form>
{% endfor %}
</body>
</html>

Your class Cruises contains only one title. As for the loops in the template, you are looping the forms. Whereas you want one in a form with many options.
I think you should be interested in a many-to-many relationship. Then you will be able to assign multiple options to a particular object.
Also you should see documentation about forms.

Related

How do I get user input from search bar to display in a page? Django

Django is very challenging and I still need to get used to the code and currently, I just want the search bar to display every time a user input a text and it will display like a title I really don't how to interpret the code to tell that every time the user inputs in the search bar, It is supposed to display the user input on a page like a title.
Example: user input in the search bar: cat and it displays cat title
Display on the current page:
Result search: "Cat"
HTML Code
<!-- Search Bar -->
<form action="{% url 'enc:search' %}" method="GET">
{% csrf_token %}
<input class="search" type="text" name="q" placeholder="Search">
</form>
In my views.py I only write this code and I don't know what to write it.
views.py
def search (request):
title = request.GET.get("q", "")
urls.py
urlpatterns = [
path("", views.index, name="index"),
path("search/", views.search, name="search"),
Right now just a simple display from the search bar input later I will code it in a data search where there is some file to integrate the search but right now I really need some help my brain is cracking. It's kinda sad I mean I know it be a simple code but I don't know why I can't figure it out.
please do help me if you have tips on how to be better on Django and python too it be much help for me and thank you for your time I really appreciate it very much.
searchpage.html :
<!-- Search Bar -->
<form action="{% url 'enc:search' %}" method="POST">
{% csrf_token %}
<input class="search" type="text" name="q" placeholder="Search">
<input type="submit" value="Submit">
</form>
views.py:
from django.shortcuts import render
def search (request):
#defines what happens when there is a POST request
if request.method == "POST":
title = request.POST.get("q")
return render(request,'new_template.html', { 'title' : title })
#defines what happens when there is a GET request
else:
return render(request,'searchpage.html')
new_template.html:
<!DOCTYPE html>
{% load static %}
<html>
<head>
<title>search term</title>
</head>
<body>
<h1> {{ title }} </h1>
</body>
</html>

Django can't search "method not allowed"

im new to django and im currently doing a website for my friend. he wants me to make a system where the users can search the database and the website gives the relevent items according to their serial number.
i followed a tutorial from the following site: https://learndjango.com/tutorials/django-search-tutorial to figure out how to do db searchs which helped a lot, but im still having a problem: my search bar works, and the result page also works but it only works when i manually type the query on the searchbar myself (e.x. results/?q=number1). However when i search using the input bar and the submit button it sends me to /results/ page and the page gives this:
This page isn’t working
If the problem continues, contact the site owner.
HTTP ERROR 405
-when i open up pycharm to see the error in terminal it says:
Method Not Allowed (POST): /result/
Method Not Allowed: /result/
[27/Oct/2020 20:06:02] "POST /result/ HTTP/1.1" 405 0
here are my codes(python3.7,pycharm) websites/urls:
from . import views
from django.urls import path
from django.contrib.auth import views as auth_views
urlpatterns = [
path('register/',views.UserFormView.as_view(), name='register'),
path('login/', auth_views.LoginView.as_view(), name='login'),
path('', views.IndexViews.as_view(), name='index'),
path('scan/', views.ScanView.as_view(), name='scan'),
path('result/', views.SearchResultsView.as_view(), name='result'),
]
websites/views:
class IndexViews(generic.ListView):
template_name = "websites/index.html"
context_object_name = "object_list"
def get_queryset(self):
return Website.objects.all()
class ScanView(TemplateView):
form_class = SerialFrom
template_name = 'websites/scan.html'
class SearchResultsView(ListView):
model = SerialNumber
template_name = 'websites/result.html'
def get_queryset(self): # new
query = self.request.GET.get('q')
context = self.get_context_data(object=self.object)
object_list = SerialNumber.objects.filter(
Q(number__iexact=query)
)
return object_list
scan.html:
{% extends 'websites/base.html' %}
{% block albums_active %}active{% endblock %}
{% block body %}
<head>
<meta charset="UTF-8">
<title>Scan</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<form class="box" action="{% url 'result' %}" method="POST">
<h1>Product Check</h1>
<p> Please enter the serial id of your product to check it.</p>
{% csrf_token %}
<input type="text" name="q" placeholder="Serial Number">
<input type="submit" name="q" placeholder="Check">
</form>
</body>
{% endblock %}
thank you for taking your time and reading, please help me i really need to do this.
A ListView [Django-doc] by default does not implement a handler for a POST request. Searching is normally done through a GET request, so you should use:
<form class="box" action="{% url 'result' %}" method="GET">
<h1>Product Check</h1>
<p> Please enter the serial id of your product to check it.</p>
<input type="text" name="q" placeholder="Serial Number">
<input type="submit" placeholder="Check">
</form>
Furthermore the <input type="submit"> should not have a name="q" attribute.
As #Melvyn says, you can also alter the type to type="search" [mozilla] for the text box:
<form class="box" action="{% url 'result' %}" method="GET">
<h1>Product Check</h1>
<p> Please enter the serial id of your product to check it.</p>
<input type="search" name="q" placeholder="Serial Number">
<input type="submit" placeholder="Check">
</form>

How do we show the result of calculation on Front End done based on the user input in Django?

I am working on a Django Project, where a student will write his/her course name in a form and click on Calculate button and the system will use the Fuzzy Logic to calculate the performance of students based on the details of that specific course and then show the result of that calculation below the Calculate Button.
What I have done so far are below.
views.py:
from django.shortcuts import render, redirect
from django.contrib import messages
from .forms import PerformanceCalculatorForm
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from .models import Subject, Detail
from .fuzzy_logic_algo import fuzz_algo
def performanceCalculator(request):
if request.method == 'POST':
performance_form = PerformanceCalculatorForm(request.POST)
if performance_form.is_valid():
sub = performance_form.cleaned_data.get('subject')
skype = Details.objects.filter(subject__subject=sub, user__username=User.username).get('skype_session_attendance')
internal_course = Details.objects.filter(subject__subject=sub, user__username=User.username).get('internal_course_marks')
prg_lab = Details.objects.filter(subject__subject=sub, user__username=User.username).get('programming_lab_activity')
mid_marks = Details.objects.filter(subject__subject=sub, user__username=User.username).get('mid_term_marks')
final_marks = Details.objects.filter(subject__subject=sub, user__username=User.username).get('final_term_marks')
result = fuzz_algo(skype, internal_course, prg_lab, mid_marks, final_marks)
context = {
'result': result,
}
return render(request, 'users/performance_calculator.html', context)
else:
performance_form = PerformanceCalculatorForm()
return render(request, 'users/performance_calculator.html', {'performance_form': performance_form})
models.py:
from django.db import models
from django.contrib.auth.models import User
from PIL import Image
class Subject(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
subject = models.CharField(max_length=100)
def __str__(self):
return '{} ({})'.format(self.subject, self.user.username)
class Detail(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
subject = models.OneToOneField(Subject, on_delete=models.CASCADE)
skype_session_attendance = models.FloatField()
internal_course_marks = models.FloatField()
programming_lab_activity = models.FloatField()
mid_term_marks = models.FloatField()
final_term_marks = models.FloatField()
def __str__(self):
return f'{self.subject, (self.user.username)} Details'
forms.py:
from django import forms
class PerformanceCalculatorForm(forms.Form):
class Meta:
fields = ['subject']
performance_calculator.html:
{% load static %}
<!DOCTYPE html>
<html>
<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://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="{% static 'esacp/main.css' %}">
<title>Expert System for Assessing Programming Course Performance</title>
</head>
<body>
<main role="main" class="container">
<div class="row">
<div class="col-md-8">
{% if messages %}
{% for message in messages %}
<div class="alert alert-{{ message.tags }}">
{{ message }}
</div>
{% endfor %}
{% endif %}
{% if not request.user.is_superuser and not request.user.is_staff %}
<div class="account-heading">
<h2>
Performance Calculator
</h2>
</div>
<div class="content-section">
<form method="POST">
{% csrf_token %}
<fieldset class="form-group">
<legend class="border-bottom mb-4">Profile</legend>
{{ performance_form|crispy }}
{{ result }}
</fieldset>
</form>
</div>
{% endif %}
</div>
</div>
</main>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
</body>
</html>
Can anyone tell me that how would I accomplish it that a user (student) enters the course name in the form when he/she is on .../performance_calculator.html, his record is saved, and matched with the courses assigned to him, after the matched, the activity details of student that course is taken and those are assigned to separate variables, the those variables are passed to fuzz_algo() function, then the result of that function is printed on the Front End?
I have been working on it since 2 days and not getting it. Any help will be surely appreciated.
Let me go with some really problematic things first. Your PerformanceCalculator view, in the POST conditional, you never save() the form, and therefore your next queries will return empty objects, which I believe the fuzz_algo will return None (Assumption) and displays nothing on the render.
Actually best practice is: on the last line of your POST conditional, use redirect instead of render as it will load you again the page without the POST data.
And I think that all the above thing you have tried already (because you said you tried 2 days), but wonder why it still renders nothing, because by redirect it will ask again with a GET request and will lose the data in the variable result.
Now with the "not so important" thing, as I see in your code and you don't have intention of saving your form in database, this is probably a better approach on the Client Side instead of Server Side. To do it on the server side please check https://docs.djangoproject.com/en/3.0/topics/http/sessions/ to use sessions variables to keep it alive and not lose after redirect, also there is EASY work around (but doesn't work in all the cases) is to .. let's say "abuse" the messages library of django, it will pass a message to the client side on your next LOAD.
So on your views.py import the messages library and add this before redirect
messages.success(request, result)
Now in your template add this
{% if messages %}
{% for message in messages %}
{{ message }}
{% endfor %}
{% endif %}
I'm new to Django, but I think I did something similar to what you are trying to do.
1. With a model similar to yours - had the user fill out the form and then made sure the model was populated with the data from the form. I didn't realize at first that I needed to make sure every field in the form was filled out or nothing would be saved to the model. (It is in the docs, I just didn't pick up on it).
2. Then when I wanted to use the data in the model, I just made sure that the model was imported.I also imported a separate python file to perform the computation on the parameters.
Then in the view I assigned a variable = to the model object for example for the Model Search_Profile in my case I had
params=Search_Profile.objects.last()
since in my case I just wanted the last profile, but you could make it any object you wanted.
With that information I could then import the function from a .py file In my case
C=calculate(params.keyword_string,params.other_string)
At that point I could then render the template with both the parameters and whatever I needed from the calculation function in the .py file by using
return render(request,'mainapp/show_calculation.html',{'params':params,'new_entries':new_entries,'C':C})
It took me a while to figure that this worked, and maybe there are better ways, but it at least worked for what I was trying to do.
Looking at your code, I suspect you're a better coder than I am, but maybe the above might help. In your form you only have the subject field and don't have the user field. In my situation I think that led to my model not being filled.
The other thing I had to do to figure it out for my case was to get away from crispy forms or widget-tweeks, but I don't think that matters much.

Django: is_valid() method is always return why?

I'm just practicing django and creating simple app that take user name and profile pic and then save it in database.is_valid() method is always return false when i do form validation.
views.py
from django.shortcuts import render,redirect
from django.http import HttpResponse
from .models import student,photo
from .forms import student_data
# Create your views here.
def my_data(request):
check=0
myform=student_data()
if (request.method=="POST"):
myform=student_data(request.POST,request.FILES)
if (myform.is_valid()):
stu_name=myform.cleaned_data['name']
stu_image=myform.cleaned_data['image']
d=photo.objects.filter(name=stu_name)
myform.save()
if not d:
new_data=photo(image=stu_image,name=stu_name)
photo.save(self=new_data)
else:
check=1
else:
myform=student_data
return render(request,'show.html',{'student':stu_name,'check':check})
forms.py
from django import forms
#from .models import student
class student_data(forms.Form):
name=forms.CharField(widget=forms.TextInput,max_length=20)
image=forms.ImageField()
models.py
from django.db import models
class photo(models.Model):
image=models.ImageField()
name=models.CharField(max_length=20)
class Meta:
db_table='photo'
html file for form.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div>
<form name="form" action="/payment/show/" method="POST">
{% csrf_token %}
{{form.as_p}}
<button type="submit">Add Me</button>
</form>
</div>
</body>
</html>
If you submit both data and files, the encoding type of the form should be multipart/form-data, so:
<form name="form" action="/payment/show/" method="POST" enctype="multipart/form-data">
{% csrf_token %}
{{form.as_p}}
<button type="submit">Add Me</button>
</form>
Note: It is normally better to make use of the {% url … %} template tag [Django-doc]
than to write hardcoded urls. It makes it easier to understand to what view you
are referring, if you later change the URL, the url resolution will change as
well, and it will encode the url values if necessary.

Django can't process html form data

I have a simple Django site and I want to pass data from the first box, and return that value plus 5 to the second form box on the page. I later plan on doing math with that first value but this will get me started. I am having a lot of trouble retrieving the form data. I know I need to create a function in my views.py file to process the form, and I need to put something in URLs.py to retrieve the form data. I have tried everything in tutorials, etc, but can't figure it out.
My html template is a simple page that has a form with two fields and a submit button. Django runserver pulls up the html page just fine. Here is my code:
Views.py
from django.shortcuts import render
from django.http import HttpResponse
from django.template import loader
from django import forms
def index(request):
return render(request, 'brew/index.html')
#Here I want a function that will return my form field name="input",
#and return that value plus 5 to the form laveled name="output".
#I will later us my model to do math on this, but I cant get
#this first part working
urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
]
Here is my html template, index.html:
<html>
<head>
<title>Gravity Calculator</title>
</head>
<body>
<h1>Gravity Calculator</h1>
<p>Enter the gravity below:</p>
<form action="/sendform/" method = "post">
Enter Input: <br>
<input type="text" name="input"><br>
<br>
Your gravity is: <br>
<input type="text" name="output" readonly><br>
<br>
<input type="submit" name="submit" >
</form>
</body>
</html>
You will need to populate the result to context variable which the template can access.
view:
def index(request):
ctx = {}
if request.method == 'POST' and 'input' in request.POST:
ctx['result'] = int(request.POST.get('input', 0)) + 5
return render(request, 'brew/index.html', ctx)
then in your template:
<html>
<head>
<title>Gravity Calculator</title>
</head>
<body>
<h1>Gravity Calculator</h1>
<p>Enter the gravity below:</p>
<form action="/sendform/" method = "post">
Enter Input: <br>
<input type="text" name="input"><br>
<br>
Your gravity is: <br>
<input type="text" name="output" value="{{ result }}" readonly><br>
<br>
<input type="submit" name="submit" >
</form>
</body>
</html>
Looks like you are quite new at Django, I recommend:
use method based views, until you are comfortable with it, then
start using class based views, advantage being code reusability, but ultimately class based views spits out view methods, a good
reference site is ccbv.co.uk
using form class

Categories