Variable form action="/" - django

There is a web application that collects data from different sites. The form on the home page is presented in the form of two fields where you can choose from several variants of languages and cities. When you press the search button, the result is displayed only for one pair of languages and cities, regardless of the selected variant in the form, as there is only one url in the form action='''. How to make a dynamic change of form action='' depending on the choice of variant in the form on the main page. I hope I have explained it clearly. Thank you for any help!
https://ibb.co/VNcQqDp screenshot
models.py
from django.db import models
class Page(models.Model):
language = models.CharField(max_length=100)
city = models.CharField(max_length=100)
def __str__(self):
return self.language
views.py
from django.shortcuts import render, redirect
from .forms import PageForm
from page.parsers.kiev_python_parser import *
from page.parsers.kiev_javascript_parser import *
from page.parsers.kiev_java_parser import *
from page.parsers.kiev_c_parser import *
def index_page(request):
form = PageForm()
return render(request, 'page/index_page_form.html', context=
{'form':form})
def kiev_python(request):
kiev_python_main()
return render(request, 'page/kiev_python_result.html', context=
{'workua_data': workua_data, 'rabotaua_data':rabotaua_data})
def kiev_javascript(request):
kiev_javascript_main()
return render(request, 'page/kiev_javascript_result.html',
context={'workua_data': workua_data, 'rabotaua_data':rabotaua_data})
def kiev_java(request):
kiev_java_main()
return render(request, 'page/kiev_java_result.html', context=
{'workua_data': workua_data, 'rabotaua_data':rabotaua_data})
def kiev_c(request):
kiev_c_main()
return render(request, 'page/kiev_c_result.html', context=
{'workua_data': workua_data, 'rabotaua_data':rabotaua_data})
forms.py
from django import forms
from django.forms import ModelForm
from .models import Page
class PageForm(forms.ModelForm):
class Meta:
model = Page
fields = ['language', 'city']
lang_options = [
('1', 'Python'),
('2', 'Javascript'),
('3', 'Java'),
('4', 'C#'),
]
city_options = [
('1', 'Киев'),
]
language = forms.ChoiceField(required=True, choices=lang_options)
city = forms.ChoiceField(required=True, choices=city_options)
index_page_form.html
{% extends 'base.html' %}
{% block title %}
Main page
{% endblock %}
{% block content %}
<h1 class="mt-5 mb-5 text-center">Сервис поиска работы</h1>
<p class="text-center">Это веб приложение позволяет осуществить поиск вакансий для программистов с популярнейших ресурсов работодателей Украины</p>
<form action="/" method="post" class="mt-5 mb-5 text-center">
{% csrf_token %}
<div class="form-row">
<div class="form-group col-md-6">
<label for="language-field">Выберите язык:</label>
<select class="form-control" name="language" id="language-field">
<option name="kiev_python" value="1">Python</option>
<option name="kiev_javascript" value="2">Javascript</option>
<option name="kiev_java" value="3">Java</option>
<option name="kiev_c" value="4">C#</option>
</select>
</div>
<div class="form-group col-md-6">
<label for="city-field">Выберите город:</label>
<select class="form-control" name="city" id="city-field">
<option value="1">Киев</option>
</select>
</div>
</div>
<button class="btn btn-outline-primary btn-block mt-3" type="submit">Поиск</button>
</form>
{% endblock %}
urls.py
from django.urls import path
from .views import *
urlpatterns = [
path('', index_page, name='index_page_url'),
path('result/kiev_python/', kiev_python, name='kiev_python_url'),
path('result/kiev_javascript/', kiev_javascript, name='kiev_javascript_url'),
path('result/kiev_java/', kiev_java, name='kiev_java_url'),
path('result/kiev_c_sharp/', kiev_c, name='kiev_c_url'),
]

You use django template so you can use a tag of the context which is dynamic. Something like this:
form action="/{{ your_path}}" method="post" class="mt-5 mb-5 text-center">

Related

How do I display my form in a Django template?

I am trying to display my stat update form in my Django template, however it isn't displaying. My stats below show up correctly, just not the form.
{{ stats.user }} | {{ stats.weight }} | {{ stats.date }}
Template:
{% block content %}
<div class="container-fluid">
<div class="row">
<div class="col-sm-12 text-center">
<h1>My Health</h1>
</div>
</div>
</div>
<div class="container-fluid">
<div class="col-auto text-center p-3 form-group">
<form method="post" style="margin-top: 1.3em;">
{{ update_form }}
{% csrf_token %}
<button type="submit" class="btn btn-signup btn-lg">Submit</button>
</form>
</div>
<div class="row justify-content-center">
<div class="col-auto text-center p-3">
<p class="text-center"> {{ stats.user }} | {{ stats.weight }} | {{ stats.date }} </p>
</div>
</div>
</div>
{% endblock content %}
forms.py:
class StatUpdateForm(forms.Form):
class Meta:
model = Stats
fields = ('user', 'weight', 'date')
models.py:
class Stats(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
date = models.DateField(auto_now=True)
weight = models.DecimalField(max_digits=5, decimal_places=2)
class Meta:
db_table = 'health_stats'
ordering = ['-date']
def __str__(self):
return f"You currently weigh {self.weight}, {self.user}"
views.py:
from django.shortcuts import render
from .models import Stats
from .forms import StatUpdateForm
from django.views import generic, View
from django.shortcuts import get_object_or_404
# from django.contrib.auth import authenticate
# from django.core.exceptions import ValidationError
# from .forms import RegistrationForm, LoginForm
def home(request):
return render(request, 'home.html')
class MyHealth(View):
def get(self, request, *args, **kwargs):
stats = Stats
context = {
'stats': stats,
"update_form": StatUpdateForm(),
'user': stats.user,
'weight': stats.weight,
'date': stats.date,
}
return render(request, 'MyHealth.html', context)
I've tried redefining the form in my views.py, but I'm unsure why it isn't pulling through, as the other parts of the context are.
Any help would be appreciated!
In the form, since you are using a model, you must extend from forms.ModelForm instead forms.Form, try to change that line in the forms.py
class StatUpdateForm(forms.ModelForm): # extends from forms.ModelForm
class Meta:
model = Stats
fields = ('user', 'weight', 'date')
I assume the form fields are rendering and the fields just aren't loaded with the correct values.
do this: StatUpdateForm(instance=stats) to make it an edit form

Making the user active when tapping a button in html, and using a DetailView (Django)

I'm trying to make a user active when I tap a button, and I'm using a DetailView.
views.py
from .models import Model
from django.contrib.auth.models import User
from django.shortcuts import redirect
class UserInspectView(DetailView):
model = Model
template_name = 'user-inspect.html'
# Make the user is_active = True
def accept (request, pk):
user = User.objects.get(id=pk)
user.is_active
return redirect('home')
...
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('inspect/<slug:slug>/', views.UserInspectView.as_view(), name='user-inspect'),
path('inspect/<int:pk>/accept/', views.accept, name="user-accept"),
...
]
user-inspect.html
{% extends 'base.html' %}
{% block title %} <title>User Inspection</title> {% endblock %}
{% block content %}
<div class="d-flex justify-content-center">
<div class="container d-flex flex-column">
<div class="ms-5 ps-5" >
<h3><strong>User:</strong> {{model.user}}</h3>
<br>
<h3><strong>Name:</strong> {{model.name}}</h3>
</div>
</div>
</div>
<br><br><br>
<div class="d-flex justify-content-center">
<div class="btn-toolbar" role="toolbar" aria-label="Toolbar with button groups">
<div class="btn-group me-2 me-5 pe-5" role="group" aria-label="First group">
<form method="post" action="{% url 'user-accept' model.user.pk %}">
{% csrf_token %}
<button type="submit" class="btn btn-primary">Accept</button>
</form>
</div>
<div class="btn-group me-2 me-5 ps-5" role="group" aria-label="First group">
Back
</div>
</div>
</div>
{% endblock %}
models.py
from django.db import models
from django.contrib.auth.models import User
class Model(models.Model):
name = models.CharField(max_length=100)
user = models.ForeignKey(User, on_delete=models.CASCADE)
slug = models.SlugField(unique=True, blank=False, null=False)
Before my accept view looked like this
def accept (request, pk):
user = User.objects.get(id=pk)
user.is_active()
user.save()
return redirect('home')
but I changed it, because I got this error
TypeError at inspect/30/accept/
'bool' object is not callable
When I tap the Accept button, it takes me to the redirect that I have in the accept view, but the user is still inactive.
user.is_active is a boolean not a function.
def accept (request, pk):
user = User.objects.get(id=pk)
user.is_active = True
user.save()
return redirect('home')

Populating a drop-down from Database in Django

Hi so basically I am trying to populate a drop-down menu from a database I currently have. This will enable a 'Teacher' to select a 'Student' they input grades for. I am struggling to understand any of the tutorials online due to most of them being for django 1.9 whereas I am using 2.1.
Please if you could help, it would be much appreciated.
Template:
<form action="{% url 'subject1_view' %}" method="post">
{% csrf_token %}
<div class="form-group row">
<label class="col-2 col-form-label" for="information">Student Name</label>
<div class="col-10">
<form method="POST">
<select class="form-control" name="student_name" id="information">
{% for ?? %}
<option value="{{ ?? }}">{{ ?? }}</option>
{% endfor %}
</select>
</form>
</div>
</div>
URLs:
from django.urls import path, include
from . import views
urlpatterns = [
path('teacher_login', views.teacher_login, name='teacher_login'),
path('t_dashboard', views.t_dashboard, name='t_dashboard'),
path('subject1_view', views.subject1_view, name='subject1_view'),
path('loguserout', views.loguserout, name='loguserout'),
]
Views:
def subject1_view(request):
if request.method == 'POST':
student_name = (request.POST.get('student_name'))
current_grade = (request.POST.get('current_grade'))
previous_grade = (request.POST.get('previous_grade'))
target_grade = (request.POST.get('target_grade'))
incomplete_homework = (request.POST.get('incomplete_homework'))
behaviour_rank = (request.POST.get('behaviour_rank'))
i = Subject1(student_name=student_name, current_grade=current_grade, previous_grade=previous_grade,
target_grade=target_grade, incomplete_homework=incomplete_homework, behaviour_rank=behaviour_rank)
i.save()
return render(request, 'Teacher/dashboard.html')
else:
return render(request, 'Teacher/subject1.html')
Models:
from django.db import models
from Student.models import Student
# Create your models here.
class Subject1(models.Model):
student_name = models.ForeignKey(Student, on_delete=models.CASCADE)
current_grade = models.CharField(max_length=2)
previous_grade = models.CharField(max_length=2)
target_grade = models.CharField(max_length=2)
incomplete_homework = models.CharField(max_length=2)
behaviour_rank = models.CharField(max_length=2)
def __str__(self):
return self.student_name
Use a Django Form, and populate the choices on the form's init method:
class SelectForm(forms.Form):
student = forms.ChoiceField(widget=forms.Select(attrs={'class': 'form-control'}))
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['student'].choices= [(student.id, student.name) for student in Student.objects.all()]
Template:
<form action="{% url 'subject1_view' %}" method="post">
{% csrf_token %}
<div class="form-group row">
<label class="col-2 col-form-label" for="information">Student Name</label>
<div class="col-10">
{{ form }}
</div>
</div>
</form>
Also add add form to context from View.

Django 2 make comment filed error

recently I decide to add a comment block to my template in my django app but when I add it to my app , I faced to this error :
add_comment_to_post() got an unexpected keyword argument 'item_id'
my template.html:
{% block content %}
<form action="#" method="post" novalidate="novalidate">
{% csrf_token %}
{{ form.as_p }}
<div class="row">
<div class="col-md-4">
<p><label>Name*</label><input type="text" name="your-name" value=""
size="60" class=""
aria-required="true"
aria-invalid="false"></p>
</div>
<div class="col-md-4">
<p><label>Email*</label><input type="text" name="your-email"
value=""
size="60" class=""
aria-required="true"
aria-invalid="false"></p>
</div>
<div class="col-md-4">
<p><label>Website</label><input type="text" name="your-website"
value=""
size="60" class=""
aria-required="true"
aria-invalid="false"></p>
</div>
<div class="col-md-12">
<p><label>Message</label><textarea name="your-message" cols="60"
rows="3" class=""
aria-invalid="false"></textarea>
</p>
</div>
</div>
<div class="dividewhite2"></div>
<p>
<button type="button" href="{% url 'add_comment_to_post' pk=item.pk %}"
class="btn btn-lg btn-darker">Post Comment
</button>
</p>
</form>
{% endblock %}
my models.py :
from django.db import models
from datetime import date
from django.utils import timezone
# Create your models here.
class Blogs(models.Model):
main_image = models.ImageField(upload_to='Blogs/', help_text='This Image Is Gonna To Be Show At Blogs Page.',
blank=False, default='')
class Comment(models.Model):
post = models.ForeignKey('Blog.Blogs', on_delete=models.CASCADE, related_name='comments')
author = models.CharField(max_length=200)
text = models.TextField()
created_date = models.DateTimeField(default=timezone.now)
approved_comment = models.BooleanField(default=False)
def approve(self):
self.approved_comment = True
self.save()
def __str__(self):
return self.text
my form.py:
from django.forms import ModelForm
from .models import Blogs, Comment
class CommentForm(ModelForm):
class Meta:
model = Comment
fields = ('author', 'text',)
my views.py :
from django.shortcuts import render, get_object_or_404, redirect
from Blog.forms import CommentForm
from .models import Blogs, Comment
def item(request, items_id):
items = get_object_or_404(Blogs, pk=items_id)
return render(request, 'Blog/Items.html', {'item': items, 'comments': Comment})
def add_comment_to_post(request, pk):
post = get_object_or_404(Blogs, pk=pk)
if request.method == "POST":
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save(commit=False)
comment.post = post
comment.save()
return redirect('post_detail', pk=post.pk)
else:
form = CommentForm()
return render(request, 'blog/Items.html', {'form': form})
and my urls.py:
from django.urls import path
from Blog import views
from Blog import models
urlpatterns = [
path('<int:item_id>/', views.add_comment_to_post, name='add_comment_to_post'),
path('<int:items_id>/', views.item, name='Itemz'),
]
I checked my code many times but I can't understand what is my problem.
is any body know to how can I add comment to my app or what is my problem?
In addition, I'm sorry for writing mistakes in my question.
change this
def add_comment_to_post(request, pk):
To:
def add_comment_to_post(request, item_id):
Then change everywhere inside the function you wrote pk to item_id
views.py
def add_comment_to_post(request, item_id):
post = get_object_or_404(Blogs, pk=item_id)
if request.method == "POST":
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save(commit=False)
comment.post = post
comment.save()
return redirect('post_detail', pk=post.pk)
else:
form = CommentForm()
return render(request, 'blog/Items.html', {'form': form, 'item': post})
and in your template:
<button type="button" href="{% url 'add_comment_to_post' item.pk %}"
class="btn btn-lg btn-darker">Post Comment
</button>
Double check your url patterns maybe? Try:
urlpatterns = [
path('<int:pk>/', views.add_comment_to_post, name='add_comment_to_post'),
The variable name in your view method needs to match the variable name in the url. Therefore you need both to be pk or both to be item_id
The Problem happen because in urls.py there were two subject that was pass to one views.
change views to this :
urlpatterns = [
path('<int:pk>/', views.item, name='Itemz'),
]
then change html part to this :
{% if not user.is_authenticated %}
<p><a href="{% url 'login' %}" class="btn btn-gr btn-xs">Login To Send
A Command.</a></p>
{% endif %}
<div class="dividewhite2"></div>
{% if user.is_authenticated %}
<form method="post" novalidate="novalidate">
{% csrf_token %}
{{ form.as_p }}
<div class="dividewhite2"></div>
<p>
<button href="{% url 'Itemz' item.id %}" type="submit"
class="btn btn-lg btn-darker">Post Comment
</button>
</p>
</form>
{% endif %}
now the Django project will run properly.

Django adding basic search in navbar

In process of adding basic search bar for searching the menu titles in my menu list I am getting this error
django.core.exceptions.FieldError: Cannot resolve keyword 'title_icontains' into field. Choices are: id, menu_title, price, title_content
Do I have to make a model for the search??
my form view in basic.html looks like this
<form class="form-inline my-2 my-lg-0" action="/search/" method="get">
<input class="form-control mr-sm-2" type="search" name="q" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-success my-2 my-sm-0" type="submit" value="Search">Search</button>
</form>
my views.py
from django.shortcuts import render
from django.http import HttpResponse,Http404,HttpResponseRedirect,HttpResponseNotFound
from resturant.models import Carousel
from resturant.models import Menu
from django.db.models import Q
from django import forms
def search(request):
if 'q' in request.GET and request.GET['q']:
q = request.GET['q']
menu_item = Menu.objects.filter(title_icontains = q)
return render(request, 'sources/search_results.html',{'menu_item':menu_item, 'query': q})
else:
return HttpResponse('Please submit a search term.')
my search_results.html
{% if menu_item %}
<p>Found {{ menu_item|length }} item{{ menu_item|pluralize }}.</p>
<ul>
{% for s in menu_item %}
<li class="wow fadeInUp" data-wow-duration="300ms" data-wow-delay="300ms">
<div class="item">
<div class="item-title">
<h2>{{ s.menu_title }}</h2>
<div class="border-bottom"></div>
<span>$ {{s.price}}</span>
</div>
<p>{{s.title_content}}</p>
</div>
</li>
{% endfor %}
</ul>
{% else %}
<p>No Menu_Items matched your search criteria.</p>
{% endif %}
And my urls.py
from django.conf.urls import url
from . import views
from django.contrib.auth.views import login
urlpatterns =[
url(r'^$', views.index , name= "index"),
url(r'^menu/$', views.menu , name= "menu"),
url(r'^check/$',views.check,name='check'),
url(r'^search/$',views.search, name='search')
]
Sorry for not posting menu models it looks like this
class Menu(models.Model):
menu_title = models.CharField(max_length = 100,)
price = models.IntegerField()
title_content = models.CharField(max_length = 500,)
def search(request):
if 'q' in request.GET and request.GET['q']:
q = request.GET['q']
menu_item = Menu.objects.filter(menu_title_icontains = q)
return render(request, 'sources/search_results.html',{'menu_item':menu_item, 'query': q})
else:
return HttpResponse('Please submit a search term.')
change menu_item = Menu.objects.filter(title_icontains = q) to menu_item = Menu.objects.filter(menu_title_icontains = q)
Make sure that there 2 underscore symbol between field name and "icontains":
menu_item = Menu.objects.filter(title__icontains = q)