How to Display subcategory under Category in Django? - django

I have some issue with displaying WebSubCategory under WebCategory in Django. I have already displayed WebCategory but I am unable to display WebSubCategory under WebCategory.
Here is my models.py file:
class WebCategory(models.Model):
name = models.CharField(max_length=50, unique=True, verbose_name='Category name')
slug = models.SlugField(verbose_name='Slug')
title = models.CharField(max_length=165, null=True)
metadesc = models.TextField(max_length=165, null=True)
created_at = models.DateTimeField(auto_now_add=True, null=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
verbose_name_plural = 'WebCategory'
def save(self, *args, **kwargs):
self.slug = slugify(self.name)
super(WebCategory, self).save(*args, **kwargs)
def __str__(self):
return self.name
class WebSubCategory(models.Model):
category = models.ForeignKey('WebCategory', related_name='subcategory', on_delete=models.CASCADE, blank=True,
null=True, verbose_name='Select category')
name = models.CharField(max_length=50)
slug = models.SlugField(unique=True, null=True)
title = models.CharField(max_length=100, null=True)
metadesc = models.TextField(max_length=165, null=True)
description = RichTextField(blank=True, null=True)
created_at = models.DateTimeField(auto_now_add=True, null=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
verbose_name_plural = 'WebSubCategory'
def __str__(self):
return self.name
Here is my views.py file
def home(request):
context = RequestContext(request)
category_list = WebCategory.objects.order_by('-created_at')[:5]
subcategory_list = WebSubCategory.objects.order_by('-created_at')[:5]
context_dict = {'webcat': category_list, 'websubcat':category_list}
return render_to_response('home.html', context_dict, context)
And here is my header.html file, where i want to diplay category and subcategory
<ul class="nav nav-pills" id="mainNav">
{%if webcat %}
{% for category in webcat %}
<li class="dropdown dropdown-mega">
<a class="dropdown-item dropdown-toggle" href="JavaScript:void()">
{{category.name}}
</a>
{% if websubcat.webcat %}
<ul class="dropdown-menu">
<li>
<div class="dropdown-mega-content">
<div class="row">
{% for subcategory in websubcat.webcat %}
<div class="col-lg-3">
<span class="dropdown-mega-sub-title">Elements 1</span>
<ul class="dropdown-mega-sub-nav">
<li><a class="dropdown-item" href="elements-accordions.html">{{subcategory.name}}</a></li>
</ul>
</div>
{% endfor %}
</div>
</div>
</li>
</ul>
{% else %}
<p>Not Found Submenu</p>
{% endif %}
</li>
{% endfor %}
{% else %}
<p>No Category Found</p>
{% endif %}
Blog
Please help me to display the WebSubCategory under WebCategory.

{% if webcat_set.all|length > 0 %}
{% for subcategory in webcat_set.all %}
<div class="col-lg-3">
<span class="dropdown-mega-sub-title">Elements 1</span>
<ul class="dropdown-mega-sub-nav">
<li><a class="dropdown-item" href="elements-accordions.html"> {{subcategory.name}}</a></li>
</ul>
</div>
{% endfor %}
{% endif %}

Related

How do I view objects per Foreign Key in one HTML (Django)?

I am using Django Framework and creating a notification. I would like to create a notification that can filter by id of the foreign key. But when i tried it, i got all the results, i am not sure how to filter by id so that per id I can view the flow of the incidents.
View
def user_reports(request):
profile = get_object_or_404(UserProfile, user=request.user)
incidentReports = IncidentGeneral.objects.all().order_by('-updated_at')
# incident_general = IncidentGeneral.objects.filter(pk=request.id)
notifications = Notification.objects.all().order_by('-date')
paginator = Paginator(incidentReports, 10)
page_number = request.GET.get('page')
page_obj = paginator.get_page(page_number)
if request.method == 'POST':
for i in incidentReports:
x = request.POST.get(str(i.id))
print(x)
if str(x) == 'on':
b = IncidentGeneral.objects.get(id=i.id)
b.soft_delete()
# b.is_deleted = True
# b.deleted_at = timezone.now()
messages.success(request, 'User Report successfully deleted')
context = {
'profile': profile,
'incidentReports': page_obj,
'notifications': notifications,
# 'IncidentGeneral': IncidentGeneral
}
return render(request, 'pages/user_report.html', context)
Model - Notification
class Notification(models.Model):
TYPES = ((1, 'Reports'), (2, 'User Accounts'), (3, 'Inbox'), (4, 'Attributes Builder'))
incident_report = models.ForeignKey('incidentreport.IncidentGeneral', on_delete=models.CASCADE, blank=True, null=True)
sender = models.ForeignKey('accounts.User', on_delete=models.CASCADE, blank=True, null=True, related_name="noti_from_user")
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="noti_user")
notification_type = models.IntegerField(choices=TYPES)
remarks = models.CharField(max_length=90, blank=True)
text_preview = models.CharField(max_length=90, blank=True)
date = models.DateTimeField(auto_now_add=True)
is_seen = models.BooleanField(default=False)
Model - IncidentGeneral
class IncidentGeneral(SoftDeleteModel):
PENDING = 1
APPROVED = 2
REJECTED = 3
STATUS = (
(PENDING, 'Pending'),
(APPROVED, 'Approved'),
(REJECTED, 'Rejected')
)
IF_DUPLICATE = (
('Duplicate', 'Duplicate'),
('Possible Duplicate', 'Possible Duplicate'),
('Not Duplicate', 'Not Duplicate')
)
WEATHER = (
('Clear Night', 'Clear Night'),
('Cloudy', 'Cloudy'),
('Day', 'Day'),
('Fog', 'Fog'),
('Hail', 'Hail'),
('Partially cloudy day', 'Partially cloudy day'),
('Partially cloudy night', 'Partially cloudy night'),
('Rain', 'Rain'),
('Rain', 'Rain'),
('Wind', 'Wind'),
)
LIGHT = (
('Dawn', 'Dawn'),
('Day', 'Day'),
('Dusk', 'Dusk'),
('Night', 'Night'),
)
SEVERITY = (
('Damage to Property', 'Damage to Property'),
('Fatal', 'Fatal'),
('Non-Fatal', 'Non-Fatal'),
)
user = models.ForeignKey(User, on_delete=models.CASCADE, editable=False, null=True, blank=True)
generalid = models.CharField(max_length=250, unique=True, null=True, blank=True)
description = models.TextField(max_length=250, blank=True)
address = models.CharField(max_length=250)
country = models.CharField(max_length=50, blank=True, null=True)
state = models.CharField(max_length=250, blank=True, null=True)
city = models.CharField(max_length=50, blank=True, null=True)
pin_code = models.CharField(max_length=6, blank=True, null=True)
latitude = models.FloatField(max_length=20, blank=True, null=True)
longitude = models.FloatField(max_length=20, blank=True, null=True)
geo_location = gismodels.PointField(blank=True, null=True, srid=4326) # New field
upload_photovideo = models.FileField(upload_to=incident_image_upload_path, blank=True, null=True)
date = models.DateField(auto_now_add=False, auto_now=False, blank=True, null=True)
time = models.TimeField(auto_now_add=False, auto_now=False, blank=True, null=True)
status = models.PositiveSmallIntegerField(choices=STATUS, blank=True, null=True)
duplicate = models.CharField(choices=IF_DUPLICATE,max_length=250, blank=True, null=True)
duplicate_general = models.ForeignKey('incidentreport.IncidentGeneral', on_delete=models.CASCADE, null=True, blank=True)
accident_factor = models.ForeignKey(AccidentCausation, on_delete=models.SET_NULL, blank=True, null=True)
collision_type = models.ForeignKey(CollisionType, on_delete=models.SET_NULL, blank=True, null=True)
crash_type = models.ForeignKey(CrashType, on_delete=models.SET_NULL, blank=True, null=True)
weather = models.CharField(choices=WEATHER, max_length=250,blank=True, null=True)
light = models.CharField(choices=LIGHT,max_length=250, blank=True, null=True)
severity = models.CharField(choices=SEVERITY, max_length=250, blank=True, null=True)
movement_code = models.CharField(max_length=250, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def get_status(self):
if self.status == 1:
incident_status = 'Pending'
elif self.status == 2:
incident_status = 'Approved'
elif self.status == 3:
incident_status = 'Rejected'
return incident_status
def save(self, *args, **kwargs):
# super(IncidentGeneral, self).save(*args, **kwargs)
if self.latitude and self.longitude:
self.geo_location = Point(float(self.longitude), float(self.latitude))
super(IncidentGeneral, self).save(*args, **kwargs)
Snippets of HTML
{% for incident in incidentReports %}
{% if incident.user.username %}
<tr>
{% if incident.status == 2 %}
<td>
{% comment %} <input type="checkbox" name="{{incident.id}}" id="check" disabled> {% endcomment %}
</td>
{% else %}
<td><input type="checkbox" name="{{incident.id}}" id="check"></td>
{% endif %}
<td>{{incident.user.username}}</td>
<td>{% if incident.user.role %}{{incident.user.get_role}}{% endif %}</td>
<td>{{incident.description}}</td>
<td>{{incident.address}}</td>
{% comment %} <td>{{incident__incident_general.accident_factor}}</td>
<td>{{incident.collision_type}}</td> {% endcomment %}
<td>{{incident.date}}</td>
<td>{{incident.time}}</td>
<td>
{% if incident.status == 1 %}
<span class="badge badge-warning">{{incident.get_status}}</span>
{% elif incident.status == 2 %}
<span class="badge badge-success">{{incident.get_status}}</span>
{% elif incident.status == 3 %}
<span class="badge badge-danger">{{incident.get_status}}</span>
{% endif %}
</td>
<td>
<a href="{% url 'incident_report_general_view' incident.id %}"><i class='bx bxs-folder-open'
title="View"></i></a>
{% if incident.status == 2 %}
{% else %}
<a href="#" data-toggle="modal" data-target="#deleteModal{{ incident.id }}"><i class='bx bx-trash'
data-toggle="tooltip" title="Delete" ></i></a>
{% endif %}
</td>
<td>
<a href="#" data-toggle="collapse"
data-target="#collapse{{incident.id}}" onclick=""><i class="fa-sharp fa-solid fa-circle-arrow-right"></i></a>
</td>
</tr>
<tr>
<td id="collapse{{incident.id}}" class="collapse" colspan="10" >
<div class="columns is-mobile is-centered">
<div class="column is-half">
{% for notification in notifications %}
{% if notification.incident_report.id == 15 %}
{% if notification.remarks == "new incident" %}
<div class="notification">
<article class="media">
<figure class="media-left">
<p class="image is-64x64">
{% if notification.user.userprofile.profile_picture %}
<img src="{{ notification.user.userprofile.profile_picture.url }}" alt="Placeholder image">
{% else %}
<img src="https://bulma.io/images/placeholders/96x96.png" alt="Placeholder image">
{% endif %}
</p>
</figure>
<div class="media-content">
<div class="content">
<strong>{{ notification.user.first_name }} {{ notification.user.last_name }}</strong> <small><{{ notification.user.username }}></small>
<br>
<p>{{ notification.sender.first_name }} {{ notification.sender.last_name }} <{{ notification.sender.username }}> {{ notification.text_preview }}</p>
<strong><small>{{ notification.date|naturaltime }}</small></strong>
</div>
</div>
<div class="media-right">
<figure class="image is-128x128">
<img src="{{ notification.post.picture.url }}">
</figure>
</div>
</article>
</div>
{% endif %}
{% endif %}
{% if notification.remarks == "update incident status" %}
<div class="notification">
<article class="media">
<figure class="media-left">
<p class="image is-64x64">
{% if notification.user.userprofile.profile_picture %}
<img src="{{ notification.user.userprofile.profile_picture.url }}" alt="Placeholder image">
{% else %}
<img src="https://bulma.io/images/placeholders/96x96.png" alt="Placeholder image">
{% endif %}
</p>
</figure>
<div class="media-content">
<div class="content">
<strong>{{ notification.user.first_name }} {{ notification.user.last_name }}</strong> <small><{{ notification.user.username }}></small>
<br>
<p>{{ notification.user.first_name }} {{ notification.user.last_name }} <{{ notification.user.username }}> <strong> {{ notification.text_preview }} </strong>
with {{ notification.incident_report.address }} from {{ notification.sender.first_name }} {{ notification.sender.last_name }} <{{ notification.sender.username }}> on reported date {{ notification.incident_report.created_at }}
</p>
<strong><small>{{ notification.date|naturaltime }}</small></strong>
</div>
</div>
<div class="media-right">
<figure class="image is-128x128">
<img src="{{ notification.post.picture.url }}">
</figure>
</div>
</article>
</div>
{% endif %}
{% endfor %}
</div>
</div>
</div>
</td>
</tr>
in views.py filter:
if your url is like http://url/?id_collapse=id
id_collapse = request.GET.get('id_collapse')
incidentReports = IncidentGeneral.objects.get(id=id_collapse).order_by('-updated_at')
notifications = Notification.objects.filter(incident_report__in=incidentReports).order_by('-date')
# your other codes

using .all() gives me everything inside the Primary Model How can i change it to gives what i needed

I have 2 models Album and Primary when I go to the Albums Templates and clicking the viewAlbum templates it's shows me every Students from every Album I have created, instead of showing the only students inside the album I have choosing during creating a new student.
the create album template:
<div class="row">
<div class="col-md-3">
Create Album
</div>
<!--Albums-->
{% for my_album in albums %}
<div class="col-md-9">
<div class="card" style="width: 18rem;">
<img src="{{ my_album.image.url }}" alt="" class="card-img-top">
<div class="card-body">
<p>{{ my_album.name }}</p>
<br>
viewAlbum
</div>
</div>
</div>
{% endfor %}
</div>
</div>
the viewAlbum view:
def viewAlbum(request, pk):
primaries = Primary.objects.all()
post = get_object_or_404(Album, id=pk)
my_album = Album.objects.get(id=pk)
return render(request, 'viewAlbum.html', {'primaries': primaries, 'post':post,
'my_album':my_album})
the students templates:
<div class="container">
<div class="row">
<div class="col">
Create Students
</div>
</div>
</div>
<br>
<div class="container">
<div class="row justify-content-center">
{% for prima in primaries %}
<div class="col">
<div class="card my-2" style="width: 18rem;">
<img src="{{ prima.profilePicture.url }}" alt="" class="card-img-top">
<div class="card-body">
<p>{{ prima.firstName }}</p>
<br>
view Students
</div>
</div>
</div>
</div>
{% endfor %}
</div>
the models:
class Album(models.Model):
image = models.ImageField(null=False, blank=False)
name = models.CharField(max_length=100, null=False, blank=False)
def __str__(self):
return self.name
class Primary(models.Model):
profilePicture = models.ImageField(blank=False, null=False)
firstName = models.CharField(max_length=25, blank=False, null=False)
sureName = models.CharField(max_length=25, blank=False, null=False)
lastName = models.CharField(max_length=25, blank=False, null=False)
address = models.CharField(max_length=50, blank=False, null=False)
classOf = models.CharField(max_length=20, blank=False, null=False)
yearOfGraduations = models.CharField(max_length=20, blank=False, null=False)
hobbies = models.TextField(blank=False, null=False)
dateOfBirth = models.CharField(max_length=20)
year = models.ForeignKey(Album, on_delete=models.CASCADE)
def __str__(self):
return self.firstName
the urls.py
path('viewAlbum/<int:pk>/', views.viewAlbum, name='view-Album'),
path('view/<int:pk>/', views.viewStudent, name='view-Student'),
change this code
def viewAlbum(request, pk):
primaries = Primary.objects.all()
post = get_object_or_404(Album, id=pk)
my_album = Album.objects.get(id=pk)
return render(request, 'viewAlbum.html', {'primaries': primaries, 'post':post,
'my_album':my_album})
to this code
def viewAlbum(request, pk):
post = get_object_or_404(Album, id=pk)
my_album = Album.objects.get(id=pk)
primaries = Primary.objects.filter(year_id=my_album.pk)
# another way:
# primaries = my_album.primary_set.all()
return render(request, 'viewAlbum.html', {'primaries': primaries, 'post':post,
'my_album':my_album})

How to use dynamic tabs in django?

I am trying to implement dynamic tabs in my project that gives multiple tabs based on the values stored in the database.
In my case, I have two values stored in database so it's displaying just two, If I will increase more, it will show accordingly.
Category.objects.filter(category='MEDICINES')
Out[14]: <QuerySet [<Category: FRUITS>, <Category: GRAINS>]>
Here is my models.py file,
from django.db import models
from django.contrib.auth.models import User
STATUS = ((0, "Draft"), (1, "Publish"))
class Category(models.Model):
category_names = (
('DISEASES','DISEASES'),
('MEDICINES','MEDICINES'),
('ENCYCLOPEDIA','ENCYCLOPEDIA'),
)
category = models.CharField(max_length=100, choices=category_names)
sub_category = models.CharField(max_length=100, unique=True)
def __str__(self):
return self.sub_category
class Medicine(models.Model):
title = models.CharField(max_length=200, unique=True)
display_name = models.CharField(max_length=17, unique=True)
slug = models.SlugField(max_length=200, unique=True)
author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='medicine_posts')
category = models.ForeignKey(Category, on_delete=models.CASCADE)
updated_on = models.DateTimeField(auto_now=True)
content = models.TextField()
created_on = models.DateTimeField(auto_now_add=True)
status = models.IntegerField(choices=STATUS, default=0)
class Meta:
ordering = ["-created_on"]
def __str__(self):
return self.title
def get_absolute_url(self):
from django.urls import reverse
return reverse("medicine_detail", kwargs={"slug": str(self.slug)})
Here it my views.py file,
from django.views import generic
from .models import Medicine, Category
from django.shortcuts import render, get_object_or_404
class MedicineList(generic.ListView):
queryset = {'medicine' : Medicine.objects.filter(status=1).order_by("-created_on"),
'category' : Category.objects.all()
}
#queryset = Medicine.objects.filter(status=1).order_by("-created_on")
print(queryset)
template_name = "medicine.html"
context_object_name = 'element'
#paginate_by = 10
Here is my medicine.html file,
<div class="container">
<div class="row">
<div class="col-md-8 mt-3 left">
<nav>
<div class="nav nav-tabs nav-fill" id="nav-tab" role="tablist">
{% for item in element.category %}
<a class="nav-item nav-link active" id="{{ item.id }}" data-toggle="tab" href="#{{ item }}" role="tab" aria-controls="nav-home" aria-selected="true">{{ item }}</a>
{% endfor %}
</div>
</nav>
{% for item in element.category %}
<div class="tab-content py-3 px-3 px-sm-0" id="nav-tabContent">
<div class="tab-pane fade show active" id="{{ item }}" role="tabpanel" aria-labelledby="{{ item.id}}">
<table class="col-md-8 mt-3 left">
{% for post in element.medicine %}
{% cycle 'row' '' as row silent %}
{% if row %}<tr>{% endif %}
<td style="padding: 10px;">
<div class="card mb-4">
<div class="card-body">
<h6 class="card-title text-center"> {{ post.display_name }}</h6>
</div>
</div>
</td>
{% if not row %}</tr>{% endif %}
{% endfor %}
</table>
</div>
</div>
{% endfor %}
</div>
{% block sidebar %}
{% include 'sidebar.html' %}
{% endblock sidebar %}
</div>
</div>
Please help me out with this code, it;s not working.
Your queryset should not be a dictionary, Django expects a queryset instance here.
Try:
class MedicineList(generic.ListView):
queryset = Category.objects.all()
# or: model = Category
template_name = "medicine.html"
context_object_name = 'element'

In django, getting the following usernames in user profile

i'm building a following model. I have created a following model as shown below and it is working fine in the admin. I did not create a view for the following because i'm in primary stage of building i'm testing in templates to bring that usernames in userspostlist, but it's not working.
my models.py for following:
class UserProfile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, related_name='owner', on_delete=models.CASCADE)
following = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, related_name='followed_by')
def __str__(self):
return str(self.following.all().count())
class post(models.Model):
parent = models.ForeignKey("self", on_delete=models.CASCADE, blank=True, null=True)
title = models.CharField(max_length=100)
image = models.ImageField(upload_to='post_pics', null=True, blank=True)
video = models.FileField(upload_to='post_videos', null=True, blank=True)
content = models.TextField()
likes = models.ManyToManyField(User, related_name='likes', blank=True)
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
objects = postManager()
def __str__(self):
return self.title
my views.py for userpostlist:
class UserPostListView(ListView):
model = post
template_name = 'blog/user_post.html' #<app>/<model>_<viewtype>.html
context_object_name = 'posts'
def get_queryset(self):
user = get_object_or_404(User, username=self.kwargs.get('username'))
return post.objects.filter(author=user).order_by('-date_posted')
and my userpostlist.html:
{% extends "blog/base.html" %}
{% load crispy_forms_tags %}
{% block content %}
<h1 class="mb-3">posts by {{view.kwargs.username}}</h1>
{% for user in username.owner.following.all %}
{{ user.username }}
{% endfor %}
{% for post in posts %}
<article class="content-section">
<div class="article-metadata">
<div class="img">
<img class="rounded-circle article-img" data-toggle="modal" data-target="#mymodal" src="{{ post.author.profile.image.url }}">
</div>
<div class="profile-info">
<a class="h2" href="{% url 'user-posts' post.author.username %}">{{ post.author }}</a>
<div class="text-muted">{{ post.date_posted }}</div>
</div>
</div>
{% endfor %}
{% endblock content %}
Is there any problem with the userpostlist view in views.py? do i need to add some code there?
You have some options here, where one is to pass users into context:
class UserPostListView(ListView):
...
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['author'] = get_object_or_404(User, username=self.kwargs.get('username')
return context
And then instead of this:
{% for user in username.owner.following.all %}
{{ user.username }}
{% endfor %}
Use this:
{{ author.username }}

Django unrecognized token: "#" while query

I simply want to implement a search view into my Django app. But when i try to search something on my App i get the following error:
'unrecognized token: "#"'
In the end i want that my Query is a combination of category and searchword. So that the user can filter specific categories (Just like Amazon.com searchfield) e.g.: http://127.0.0.1:8000/search/?category=1&q=hallo
base.html
...
<div class="globalsearch">
<form id="searchform" action="{% url 'search' %}" method="get" accept-charset="utf-8">
<label for="{{ categorysearch_form.category.id_for_label }}">In category: </label> {{ categorysearch_form.category }}
<input class="searchfield" id="searchbox" name="q" type="text" placeholder="Search for ...">
<button class="searchbutton" type="submit">
<i class="fa fa-search"></i>
</button>
</form>
</div>
</div>
...
categorysearch_form is a dropdown selector that gets his ID from the Database.
views.py
...
from django.contrib.postgres.search import SearchQuery, SearchRank, SearchVector
from django.views.generic import ListView
class globalsearch(ListView):
"""
Display a Post List page filtered by the search query.
"""
model = Post
paginate_by = 10
def get_queryset(self):
qs = Post.objects.all()
keywords = self.request.GET.get('q')
if keywords:
query = SearchQuery(keywords)
title_vector = SearchVector('title', weight='A')
content_vector = SearchVector('content', weight='B')
tag_vector = SearchVector('tag', weight='C')
vectors = title_vector + content_vector + tag_vector
qs = qs.annotate(search=vectors).filter(search=query)
qs = qs.annotate(rank=SearchRank(vectors, query)).order_by('-rank')
return qs
...
urls.py
...
url(r'^search/$', views.globalsearch.as_view(), name='search'),
...
Search.html results are getting displayd here:
{% extends 'quickblog/base.html' %}
{% block content %}
{% for post in object_list %}
<div class="post">
<h1><u>{{ post.title }}</u></h1>
<p>{{ post.content|linebreaksbr }}</p>
<div class="date">
<a>Published by: {{ post.author }}</a><br>
<a>Published at: {{ post.published_date }}</a><br>
<a>Category: {{ post.category }}</a><br>
<a>Tag(s): {{ post.tag }}</a>
</div>
</div>
{% endfor %}
Post Model
...
#Post Model
class Post(models.Model):
author = models.ForeignKey('auth.User', on_delete=models.CASCADE)
title = models.CharField(max_length=75)
content = models.TextField(max_length=10000)
tag = models.CharField(max_length=50, blank=True)
category = models.ForeignKey(Category, verbose_name="Category", on_delete=models.CASCADE, null=True)
postattachment = fields.FileField(upload_to='postattachment/%Y/%m/%d/', blank=True ,null=True)
postcover = fields.ImageField(upload_to='postcover/%Y/%m/%d/', null=True, dependencies=[
FileDependency(processor=ImageProcessor(
format='JPEG', scale={'max_width': 200, 'max_height': 200}))
])
created_date = models.DateField(auto_now_add=True)
published_date = models.DateField(blank=True, null=True)
def publish(self):
self.published_date = timezone.now()
self.save()
class Meta:
ordering = ["-title"]
def __str__(self):
return self.title
...
i guess im simply missing something
at that point...
I already read that this issue comes from local SQL database aka. SQLite, could that be true?
Smb. has a solution?
Thanks
After a bit of tinkering with a friend i found a solution, the Django Documentation according to vector searching is really not that good...
views.py
class globalsearch(ListView):
"""
Display a Post List page filtered by the search query.
"""
model = Post
paginate_by = 10
template_name = 'quickblog/search.html'
def get_queryset(self):
keywords = self.request.GET.get('q')
if keywords:
query = SearchQuery(keywords)
title_vector = SearchVector('title', weight='A')
content_vector = SearchVector('content', weight='B')
tag_vector = SearchVector('tag', weight='C')
vectors = title_vector + content_vector + tag_vector
qs = Post.objects.annotate(rank=SearchRank(vectors, query)).filter(rank__gte=0.1).order_by('-rank')
return qs
models.py
#Post Model
class Post(models.Model):
author = models.ForeignKey('auth.User', on_delete=models.CASCADE)
title = models.CharField(max_length=75)
content = models.TextField(max_length=10000)
tag = models.CharField(max_length=50, blank=True)
category = models.ForeignKey(Category, verbose_name="Category", on_delete=models.CASCADE, null=True)
postattachment = fields.FileField(upload_to='postattachment/%Y/%m/%d/', blank=True ,null=True)
postcover = fields.ImageField(upload_to='postcover/%Y/%m/%d/', null=True, dependencies=[
FileDependency(processor=ImageProcessor(
format='JPEG', scale={'max_width': 200, 'max_height': 200}))
])
created_date = models.DateField(auto_now_add=True)
published_date = models.DateField(blank=True, null=True)
def publish(self):
self.published_date = timezone.now()
self.save()
class Meta:
ordering = ["-title"]
def __str__(self):
return self.title
search.html
{% extends 'quickblog/base.html' %}
{% block content %}
{% for post in object_list %}
<div class="post">
<h1><u>{{ post.title }}</u></h1>
<p>{{ post.content|linebreaksbr }}</p>
<div class="date">
<a>Published by: {{ post.author }}</a><br>
<a>Published at: {{ post.published_date }}</a><br>
<a>Category: {{ post.category }}</a><br>
<a>Tag(s): {{ post.tag }}</a>
</div>
</div>
{% endfor %}
{% if is_paginated %}
<ul class="pagination">
{% if page_obj.has_previous %}
<li>«</li>
{% else %}
<li class="disabled"><span>«</span></li>
{% endif %}
{% for i in paginator.page_range %}
{% if page_obj.number == i %}
<li class="active"><span>{{ i }} <span class="sr-only">(current)</span></span></li>
{% else %}
<li>{{ i }}</li>
{% endif %}
{% endfor %}
{% if page_obj.has_next %}
<li>»</li>
{% else %}
<li class="disabled"><span>»</span></li>
{% endif %}
</ul>
{% endif %}
{% endblock %}
urls.py
url(r'^search/$', views.globalsearch.as_view(), name='search'),
Hope that i was able to help the next one with that Post :D