How to make search bar working in django? - python

I made a search bar and I want it to search the titles which is in the site. Before typing nothing appears but whenever I type one title all the titles appear. How to resolve this issue?
index.html
def index(request):
query = request.GET.get('srh')
if query:
target1 = Destination.objects.filter(title__icontains=query)
target1 = a, b= [Destination() for __ in range(2)]
a.img = 'Article.jpg'
b.img = 'Micro Tasks.jpeg'
a.title = 'Article Writing'
b.title = 'Micro Tasks'
context = {'target1': target1}
return render(request, 'index.html', context)
else:
return render(request, 'index.html')
views.py
<form class="love" method="GET" action="">
{% csrf_token %}
<input type="text" placeholder='Search..' name="srh" value="{{request.GET.srh}}"> <br>
<button type="submit" class="btn btn-danger"> Search </button>
</form>
<div>
{% for dest1 in target1 %}
{% if dest1 %}
<div>
<a href="{{baseUrl}}/{{dest1.img}}">
<img src="{{hiUrl}}/{{dest1.img}}" alt="" />
<h3>{{dest1.title}}</h3>
</a>
</div>
{% endif %}
{%endfor%}
</div>

objects.filter reads from the database, but you have no objects in the database.
This should be enough:
def index(request):
query = request.GET.get('srh')
if query:
destinations = Destination.objects.filter(title__icontains=query)
context = {'target1': destinations}
return render(request, 'index.html', context)
else:
return render(request, 'index.html')
But of course it will not return any objects when the database is empty.

.py codes:
def paylasimlar(request):
keyword = request.GET.get("keyword")
if keyword:
paylasimlar = Makale.objects.filter(Q(baslik__contains=keyword) | Q(icerik__contains=keyword))
return render(request, "feed.html", {"paylasimlar": paylasimlar})
and .html
<form style="text-align: right">
{% csrf_token %}
<button type="submit" class="btn btn-default" style="float: right">
<i class="material-icons">search</i>
</button>
<input type="text" name="keyword" class="form-control" placeholder="Anı Ara..." style="border-radius: 20px;float: right;width: 20%" aria-label="Search" >

Related

Can't display picture on my django social app using imageField?

I need some fresh eyes, what am I missing here? In my Post Model imageField is defined as "picture" to be uploaded on the site, I seed it on my admin panel, it gets uploaded just fine but I can't seem to make it appear on the page: http://127.0.0.1:8000/posts/. I get ValueError at /posts/
The 'picture' attribute has no file associated with it. Highlited line is line 257, in post_comment_create_view
return render(request, 'network/posts.html', context)
Model:
class Post(models.Model):
# id is created automatically by Django
picture = models.ImageField(upload_to='images', blank=True, validators=[FileExtensionValidator(['png', 'jpg', 'jpeg'])])
content = models.TextField()
liked = models.ManyToManyField(Profile, blank=True, related_name="likes")
author = models.ForeignKey(Profile, on_delete=models.CASCADE, null=True)
updated = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ('-created',)
def __str__ (self):
return str(self.content[:20])
Forms:
class PostModelForm(forms.ModelForm):
content = forms.CharField(widget=forms.Textarea(attrs={'rows':2}))
class Meta:
model = Post
fields = ('content', 'picture')
Views:
#login_required
def post_comment_create_view(request):
qs = Post.objects.all()
profile = Profile.objects.get(user=request.user)
#Setting up pagination
p = Paginator(qs, 5)
page = request.GET.get('page')
post_list = p.get_page(page)
#Post form, comment form
p_form = PostModelForm()
c_form = CommentModelForm()
post_added = False
profile = Profile.objects.get(user=request.user)
if 'submit_pForm' in request.POST:
print(request.POST)
p_form = PostModelForm(request.POST, request.FILES)
if p_form.is_valid():
instance = p_form.save(commit=False)
instance.author = profile
instance.save()
p_form = PostModelForm()
post_added = True
if 'submit_cForm' in request.POST:
c_form = CommentModelForm(request.POST)
if c_form.is_valid():
instance = c_form.save(commit=False)
instance.user = profile
instance.post = Post.objects.get(id=request.POST.get('post_id'))
instance.save()
c_form = CommentModelForm()
context = {
'qs': qs,
'profile': profile,
'p_form': p_form,
'c_form': c_form,
'post_added': post_added,
'post_list': post_list,
}
return render(request, 'network/posts.html', context)
HTML:
{% block body %}
<div>
<div class="border border-light rounded" style="width: 25rem;">
{% if post_added %}
<div id="alertFade" class="alert alert-success" role="alert">Post added!</div>
{% endif %}
<form action="" method="POST" enctype="multipart/form-data" class="form-group">
{% csrf_token %}
{{p_form}}
<button type="submit" class="btn btn-sm btn-success" name="submit_pForm">Send Post</button>
</form>
</div>
{% for obj in post_list %}
<div class="card center" style="width: 30rem;">
<div class="card-head" style="background-color: #d0e2bc;">
<img width="50px" class="avatar img-thumbnail rounded-circle z-depth-2 ml-1" src={{obj.author.avatar.url}}> {{ obj.author.user }} - {{ obj.created|naturaltime }}
{% if request.user == obj.author.user %}
<button class="btn btn-sm btn-success float-right mt-2 mr-1">Delete</button>
<button class="btn btn-sm btn-success float-right mr-1 mt-2">Edit</button>
{% endif %}
</div>
<div class="card-body">
<img src={{obj.picture.url}}> <br>
<p class="card-text">{{obj.content|safe}}</p>
<hr>
</div>
<button class="cmt_btn ui button mb-5">show / hide comments</button>
<div class="comment-box">
{% if obj.comment_set.all %}
{% for c in obj.comment_set.all %}
<img width="20px" class="avatar img-thumbnail rounded-circle"src={{c.user.avatar.url}} alt="">
<span>{{ c.user }}</span>
<div class="mt-2">{{ c.body }}</div>
{% endfor %}
{% endif %}
There should be quotes around the src:
<img src={{obj.picture.url}}> <!-- will not work -->
Should be:
<img src="{{obj.picture.url}}"> <!-- works -->
This is for the tag attributes. For content within the tag, what you have is fine, no quotes. This is good:
<span>{{ c.user }}</span> <!-- works -->
I solved it, the solution is that I had to check if the img exists:
{% if obj.picture %}
<img src="{{obj.picture.url}}"> <br/>
{% endif %}

How to make a require object available whenever I type something in search bar in django?

I made a search bar but whenever I write something in it, the link shows http://127.0.0.1:8000/?srh=something and I am not understanding why the the specific picture with title is not showing. It is showing me all pics with title but I want only that pic with title which I write as a title in search bar. Which things to add in this code?
index.html
{% load static %}
{% static 'images/fulls' as baseUrl %}
{% static 'images/thumbs' as hiUrl %}
<form class="new" method="GET" action="">
<input type="text" placeholder='Search..' name="srh" value="{{request.GET.srh}}"> <br>
<button type="submit" class="btn btn-danger"> Search </button>
</form>
<div>
{% for dest1 in target1 %}
{% if dest1 %}
<div>
<a href="{{baseUrl}}/{{dest1.img}}">
<img src="{{hiUrl}}/{{dest1.img}}" alt="" />
<h3>{{dest1.title}}</h3>
</a>
</div>
{% endif %}
{%endfor%}
</div>
views.py
def index(request):
query = request.GET.get('srh')
if query:
match = Destination.objects.filter(title__icontains=query)
target1 = a, b= [Destination() for __ in range(2)]
a.img = 'Article.jpg'
b.img = 'Micro Tasks.jpeg'
a.title = 'Article Writing'
b.title = 'Micro Tasks'
context = {
'target1': target1,
}
return render(request, 'index.html', context)
else:
return render(request, 'index.html')
models.py
class Destination(models.Model):
title = models.CharField(max_length=255)
img = models.CharField(max_length=255)
price = models.IntegerField()
i don't understand why you use a and b but i think this will solve the problem
def index(request):
query = request.GET.get('srh')
if query:
match = Destination.objects.get(desc=query)
context = {
'match': match,
}
return render(request, 'index.html', context)
else:
return render(request, 'index.html')
<div>
{ % if match %}
<div>
<a href="{{baseUrl}}/{{match.img}}">
<img src="{{hiUrl}}/{{match.img}}" alt="" />
<h3>{{match.title}}</h3>
</a>
</div>
{% endif %}
</div>

How To Add 'Likes' On The Main Page For Multiple Objects With Django?

I have an Ajax Like/Dislike button that works for the product detail page. However, I want to add it on the main page, where multiple products are listed. Here is what I currently have in the models.py:
class Product(models.Model):
...
likes = models.ManyToManyField(User, blank=True, related_name='likes')
...
def total_likes(self):
return self.likes.count()
def is_liked(self, request):
return self.likes.filter(id=request.user.id).exists()
views.py:
def home(request):
products = Product.objects.all().order_by('-pub_date')
return render(request, 'product/home.html', {'product': products})
def detail(request, product_id):
product = get_object_or_404(Product, product_id=product_id)
is_liked = False
if product.likes.filter(id=request.user.id).exists():
is_liked = True
context = {
'product': product,
'is_liked': is_liked,
'total_likes': product.total_likes()
}
return render(request, 'product/detail.html', context)
def like_product(request):
product = get_object_or_404(Product, id=request.POST.get('id'))
if product.likes.filter(id=request.user.id).exists():
product.likes.remove(request.user)
is_liked = False
else:
product.likes.add(request.user)
is_liked = True
context = {
'product': product,
'is_liked': is_liked,
'total_likes': product.total_likes()
}
if request.is_ajax():
html = render_to_string('product/likes.html', context, request=request)
return JsonResponse({'form': html})
home.html:
<div class="album py-5 bg-dark">
<div class="container">
<div class="row">
{% for product in product.all %}
{% if product.featured %}
...
<div id="like-section-{{ product.id }}">{{ product.total_likes }} Like{{ product.total_likes|pluralize }}
<form action="{% url 'like_product' %}" method="post">{% csrf_token %}
{% if product.is_liked %}
<button type="submit" name="product_id" value="{{ product.id }}" class="btn btn-like btn-danger">Dislike</button>
{% else %}
<button type="submit" name="product_id" value="{{ product.id }}" class="btn btn-like btn-primary">Like</button>
{% endif %}
</form>
</div>
...
{% endif %}
{% endfor %}
</div>
</div>
</div>
Currently the status of Like/Dislike button is not being saved (When I press "Like", button changes to "Dislike" and the like is being recorded. However after I reload the page button changes back to "Like"). It seems like there is an issue in the is_liked function inside the Product class. Not sure how to fix that. Your help is much appreciated!

how to implement search form and post create form in single class based view

I'm trying to implement both searching posts and create a post in single view.
views.py
class HomeView(TemplateView):
template_name = 'home/home.html'
def get(self, request):
post_list = None
form = HomeForm(self.request.GET or None)
form1 = CommentForm(self.request.GET or None)
posts = Post.objects.filter(user = request.user).order_by('-created')
comments = Comment.objects.all()
users = User.objects.exclude(id=request.user.id)
query = request.GET.get('q')
if query:
post_list = Post.objects.filter(
Q(post__icontains=query)
)
context = {
'posts_list': post_list, }
print(post_list)
args = {
'form': form, 'posts': posts, 'users': users, 'form1':form1,
'comments':comments,'post_list':post_list,
}
return render(request, self.template_name, args)
def post(self, request):
form1 = CommentForm()
text = ''
if request.method=='GET' and 'btn1' in request.POST:
post_list = Post.published.all()
query = request.GET.get('q')
if query:
post_list = Post.objects.filter(
Q(post__icontains=query)
)
context = {
'posts_list': posts_list,
}
return redirect('home:home')
if request.method=='POST' and 'btn' in request.POST:
form = HomeForm(request.POST,request.FILES)
if form.is_valid():
post = form.save(commit=False)
post.user = request.user
post.save()
text = form.cleaned_data['post']
form = HomeForm()
form1 = CommentForm()
return redirect('home:home')
html code
<form enctype="multipart/form-data" class="form-inline my-2 my-lg-0" action=".">
<input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search" name='q'>
<button class="btn btn-outline-success my-2 my-sm-0" name="btn1" type="submit">Search</button>
{% block body %}
<div class="container">
<div class="col-md-8">
<h2>Home</h2>
<form method="POST" enctype="multipart/form-data" type = 'file'>
{% csrf_token %}
{{ form.post }}
{{ form.image }}
<br>
<button name="btn" type="submit">Submit</button>
</form>
<h2>{{ text }}</h2>
{% for post in posts %}
<h1>{{post.id}}.{{ post.post }}</h1>
<br>
<img src="{{ post.image.url }}" width = 240 >
<p>Posted by {{ post.user.get_full_name }} on {{ post.created }}</p>
<!-- <form action="{% url 'home:cmnt' pk=post.id %}" method="POST" enctype="multipart/form-data" type = 'file'>
{% csrf_token %}
{{ form1.content }}
<br>
<button type="submit">Submit</button>
</form> -->
{{comments.count}} comment{{comments|pluralize}}<br>
{% for comment in post.comment_set.all %}
<small><b>{{ comment.comment }}</b></small>
<p>commented by {{ comment.user.get_full_name }} on {{ comment.created }}</p>
{% endfor %}
{% endfor %}
</div>
</div>
{% endblock %}
from this code I get the query value entered by the user.
when I implement this code I need to fill both the forms post create and search form but, I need to submit only one form at a time
when I fill both the forms and submit I get URL like this
http://127.0.0.1:8000/home/?q=django+&csrfmiddlewaretoken=OsNRlkvRjSHHuNYMxhZS9MFushCzCTZtjFvgEb5qFFybovBhWI3X0uufvd8bO8WS&post=asdsad&image=7653_1792089421024273_590924154993413545_n.jpg&btn=
I need a code which implements:
when submitted post create form create the post and return
when submitted search form load the respective results from database

How do you fix this: IntegrityError at /restaurants/create? - NOT NULL constraint failed: restaurants_restaurantlocation.name

I'm trying to make a django developed website which is called MuyPicky. It is a website which allows you to find restaurants and other things based on your pickiness. I am currently making a page for forms which adds Restaurants to the database. As I am doing this I get this error:
IntegrityError at /restaurants/create.
NOT NULL constraint failed: restaurants_restaurantlocation.name
Is this why I get the error
Here is the forms.py:
class RestaurantCreateForm(forms.Form):
title = forms.CharField()
location = forms.CharField(required = False)
category = forms.CharField(required = False)
The form.html:
{% extends "base.html" %}
{% block title %}Add Restaurant || {{block.super}} {% endblock %}
{% block content %}
<div class="container-fluid">
<div class="container">
<div class="row">
<div class="col-md-offset-4 col-md-4 col-md-offset-4">
<h1>Add Restaurant</h1>
<form method="POST">{% csrf_token %}
<input title="Title" class="form-control" type="text" name="Title" placeholder="Title">
<br>
<input title="Location" class="form-control" type="text" name="Location" placeholder="Location"><br>
<input title="Category" class="form-control" type="text" name="Category" placeholder="Category"><br>
<!--<input title="Save" class="form-control btn btn-info " type="submit" value="Save" >--><br>
<button class="btn btn-success form-control btn-md center-block" type="submit">Save</button>
</form>
</div>
</div>
</div>
</div>
{% endblock %}
The view from views.py:
def restaurant_createview(request):
#if request.method == "GET":
# print("get data")
if request.method == "POST":
title = request.POST.get("title") #(request.POST["title"])
location = request.POST.get("location")
category = request.POST.get("category")
obj = RestaurantLocation.objects.create(
name = title,
location = location,
category = category
)
return HttpResponseRedirect("/restaurants/")
template_name = "restaurants/form.html"
context = {}
return render(request, template_name, context)
Lastly the urls.py:
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^/$', TemplateView.as_view(template_name="home.html")),
url(r'^restaurants/$', RestaurantListView.as_view()),
url(r'^restaurants/create/$', restaurant_createview),
url(r'^restaurants/(?P<slug>[\w-]+)/$', RestaurantDetailView.as_view()),
url(r'^contact/$', TemplateView.as_view(template_name="contact.html")),
url(r'^about/$',TemplateView.as_view(template_name="about.html"))]
Your fields have name Title, Location, Category but your Django code is looking for title, location and category. These need to be the same.

Categories

Resources