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)
Related
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')
I am building an e-commerce store with Django, and I have added some products to a collection. I want to be able to display each collection separately with the products that have been added to it.
Here is my models.py code
#Collections model Fields
class Collections(models.Model):
title = models.CharField(max_length=100)
products = models.ManyToManyField(Product)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('collections', kwargs={'slug': self.slug})
Here is my Views.py:
def collectionsPage(request, slug):
collections = Collections.objects.get(slug=slug)
products = Product.objects.all()
context = {"products": products, "collections":collections,}
return render(request, "collections.html", context)
Here is my urls.py:
urlpatterns = [
path('collections/<slug:slug>', views.collectionsPage, name="collections"),
]
Here is my HTML Code:
{% for collection in collections %}
<form action="{{collection.products.get_absolute_url}}" method="post">
{% csrf_token %}
<button class="polaroid" style="background-color:white; border:none">
<div>
<img src="{{collection.products.imageURL}}" alt="iPhone image">
<h3 class="container">{{collection.products.title}}</h3>
<h4 class="container">{{collection.products.price}}</h4>
</div>
</button>
</form>
{% endfor %}
I have been able to solve the problem as follows:
#Nothing to change in Models.py
#Views.py
def collectionsPage(request, slug):
collections = Collections.objects.get(slug=slug).products.all() ###
data = cartData(request)
cartItems = data["cartItems"]
context = {"collections":collections, "cartItems":cartItems}
return render(request, "collections.html", context)
#HTML code:
{% for product in collections %}
<form action="{{product.get_absolute_url}}" method="post">
{% csrf_token %}
<button class="polaroid" style="background-color:white; border:none">
<div>
<img src="{{product.imageURL}}" alt="iPhone image">
<h3 class="container">{{product.title}}</h3>
<h4 class="container">{{product.price}}</h4>
</div>
</button>
</form>
{% endfor %}
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">
I have a situation where I want to have published functionality for articles, and I have it. The problem is that I can't get my unit test to work properly, trying to post True to the published field.
Here's what my tests look like.
class ArticleDetailViewTest(TestCase):
def setUp(self):
email = 'testuser#gmail.com'
first_name = 'test'
last_name = 'user'
password = 'test15146'
user = User.objects.create_user(email, first_name, last_name, password)
self.client = Client()
self.client.login(username='testuser#gmail.com', password='test15146')
def test_can_publish_article_from_POST(self):
other_article_two = Article.objects.create(name='Test Name One', author=User.objects.get(email='testuser#gmail.com'))
correct_article_two = Article.objects.create(name='Test Name Two', author=User.objects.get(email='testuser#gmail.com'))
response = self.client.post(reverse('publish_article', kwargs={'pk' : correct_article_two.pk}))
self.assertEqual(response.status_code, 302)
self.assertRedirects(response, f'/articles/{correct_article_two.pk}/')
self.assertEqual(correct_article_two.published, True)
Here's what my publish article view looks like.
def publish_article(request, pk):
article = get_object_or_404(models.Article, pk=pk)
if request.method == "POST":
article.published = True
article.save(update_fields=['published'])
return redirect('article_detail_view', pk=article.pk)
else:
raise Http404
Here are my urls.
from django.urls import path
from . import views
urlpatterns = [
path('', views.HomePageView.as_view(), name='home'),
path('new/', views.ArticleCreateView.as_view(), name='article_new'),
path('<int:pk>/', views.ArticleDetailView.as_view(), name='article_detail_view'),
path('<int:pk>/publish/', views.publish_article, name='publish_article'),
path('<int:pk>/unpublish/', views.unpublish_article, name='unpublish_article'),]
Here are my models.
from django.conf import settings
from django.db import models
from django.urls import reverse
from django import forms
class Article(models.Model):
name = models.CharField(max_length=255, blank=False)
author = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
)
published = models.BooleanField(default=False)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('article_detail_view', args=[str(self.id)])
class ArticleForm(forms.ModelForm):
class Meta:
model = Article
fields = ['name',]
Lastly, here is the template.
{% extends 'base.html' %}
{% block title %}{{ article.name }}{% endblock %}
{% block content %}
{% if article.author_id == user.pk %}
<div class="row">
<div class="col-6 col-centered">
<h2 class="text-center">{{ article.name }}</h2>
<p class="text-center">by {{ article.author.first_name }} {{ article.author.last_name }}</p>
{% if article.published %}
<small class="form-text text-muted mb-1">This article is public.</small>
<form method="post" action="/articles/{{ article.pk }}/unpublish/">
{% csrf_token %}
<input type="submit" name="unpublish" value="Unpublish Article" id="id_unpublish_button" class="btn btn-primary btn-md"/>
</form>
{% else %}
<small class="form-text text-muted mb-1">This article is private.</small>
<form method="post" action="/articles/{{ article.pk }}/publish/">
{% csrf_token %}
<input type="submit" name="publish" value="Publish Article" id="id_publish_button" class="btn btn-primary btn-md"/>
</form>
{% endif %}
</div>
</div>
{% elif article.published %}
<div class="row">
<div class="col-6 col-centered">
<h2 class="text-center">{{ article.name }}</h2>
<p class="text-center">by {{ article.author.first_name }} {{ article.author.last_name }}</p>
</div>
</div>
{% else %}
<div class="row">
<div class="col-6 col-centered">
<p class="text-center">This article is private.</p>
</div>
</div>
{% endif %}
{% endblock %}
This is the error message I'm getting from my test. The issue seems to be I can post to the URL with self.client.post . Any help would be greatly appreciated.
FAIL: test_can_publish_article_from_POST (articles.tests.ArticleDetailViewTest)
Traceback (most recent call last):
File "/Users/christopher.chough/article_directory/articles/tests.py", line 126, in test_can_publish_article_from_POST
self.assertEqual(correct_article_two.published, True)
AssertionError: False != True
Ran 17 tests in 2.340s
FAILED (failures=1)
Object in your test method not updated. You can use refresh_from_db method to update it after changes:
def test_can_publish_article_from_POST(self):
other_article_two = Article.objects.create(name='Test Name One', author=User.objects.get(email='testuser#gmail.com'))
correct_article_two = Article.objects.create(name='Test Name Two', author=User.objects.get(email='testuser#gmail.com'))
response = self.client.post(reverse('publish_article', kwargs={'pk' : correct_article_two.pk}))
correct_article_two.refresh_from_db() # Add this line
self.assertEqual(response.status_code, 302)
self.assertRedirects(response, f'/articles/{correct_article_two.pk}/')
self.assertEqual(correct_article_two.published, True)
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.