Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Displaying Objects based on Authenticated User/ UserID
I am trying to limit the number of objects the user can see based on his/her user id. I am getting an the object Usergame where it's a linked table for User and Games. So based on the games the user is assigned to, they will only be able to add, edit, or delete the games they are assigned to in this linked table. my code is: def Flag_List(request): if request.user.groups == "Referee": games = [] for g in Usergame.objects.filter(user_id): games.append(g.game_id) flags = Flag.object.filter(game_id__in = games) return render(request, 'MSAapp/flag_list.html', {'flags': flags}) else: return render(request, 'MSAapp/Invalid_Permission.html') -
Hashing + salting emails used in authentication - good or bad practice?
Is hashing + salting of emails not a normal thing to do? Like in a data breach you wouldn't be able to know who is registrered to the service since every field is hashed + salted? Is there any cons to this since there isnt much about it on the internet? -
How to Fix: Cannot resolve keyword 'user' into field. Choices are: description, end_time, id, start_time, title Django Error
I'm a beginner to Django and I'm trying to implement a login system into my django planner. The error: FieldError at /login_user/ Cannot resolve keyword 'user' into field. Choices are: description, end_time, id, start_time, title I've tried adding the user field into my event model on model.py and migrating it but it just makes the whole application crash. views.py def event(request, event_id=None): instance = Event() if event_id: instance = get_object_or_404(Event, pk=event_id) else: instance = Event() form = EventForm(request.POST or None, instance=instance) if request.POST and form.is_valid(): form.save() return HttpResponseRedirect(reverse('cal:calendar')) return render(request, 'cal/event.html', {'form': form}) def login_user(request): if request.method == "POST": username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) if user is not None: if user.is_active: events = Event.objects.filter(user=request.user) login(request, user) return render(request, 'cal/calendar.html', {'calendar': calendar}) else: return render(request, 'cal/login.html', {'error_message': 'Your account has been disabled'}) else: return render(request, 'cal/login.html', {'error_message': 'Invalid login'}) return render(request, 'cal/login.html') forms.py class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) class Meta: model = User fields = ['username', 'email', 'password',] models.py class Event(models.Model): title = models.CharField(max_length=200) description = models.TextField() start_time = models.DateTimeField() end_time = models.DateTimeField() @property def get_html_url(self): url = reverse('cal:event_edit', args=(self.id,)) return f'<a href="{url}"> {self.title} </a>' calendar.html {% extends 'cal/base.html' %} {% block title %} Calendar {% … -
Django form without model not appearing in template when rendered
I have a form without an associated model, just a contact form for sending a message. I have some experience with django forms by now, so I thought I had done everything correctly, but nothing ends up rendering when the page is viewed in a browser at all, nor are there any errors to troubleshoot. My forms.py: from django import forms class ContactForm(forms.Form): class Meta: fields = ['full_name', 'phone', 'email', 'message'] full_name = forms.CharField(max_length=20) phone = forms.CharField(max_length=20) email = forms.CharField(max_length=30) message = forms.CharField(max_length=400) And my view that turns the form into something useful: def contact_view(request): full_name = request.POST.get('full_name', False) phone = request.POST.get('phone', False) email = request.POST.get('email', False) message = request.POST.get('message', False) form = ContactForm() if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): # send_emails(first_name, last_name, email) template = loader.get_template('/myapp/mysite/main_page/templates/main_page/thankyoumsg.html') return HttpResponse(template.render({}, request)) template = loader.get_template('/myapp/mysite/main_page/templates/main_page/contact.html') return HttpResponse(template.render({}, request)) And my template: <form class="leave-comment" action="." method="post"> {% csrf_token %} {{form.as_p}} <button type="submit">Submit</button> </form> But nothing is displaying, and I am unsure why. How can I troubleshoot this? -
Any Class Based Views or Package for Auth with related model?
Currently I have two styles of templates: User + Client, and User + Company. And I want to create a view to create a User + account from either of these two related templates. Currently I have achieved this, but there is a problem: the code seems to be very bloated, and I also do not know if there is CBV to edit model with related models, then it will result in other views also bloated. Is there any way to improve this? models.py: https://pastebin.com/9Fp0F6CG my views.py: from django.shortcuts import render, redirect from django.contrib.auth import login, authenticate from django.views import generic from .forms import UserForm, ClientForm, CompanyForm class ClientFormView(generic.View): def get(self, request, *args, **kwargs): template_name = "users/registration/form_client.html" context = {"form_user": UserForm, "form_client": ClientForm} return render(request, template_name, context) def post(self, request, *args, **kwargs): template_name = "users/registration/form_client.html" context = {"form_user": UserForm, "form_client": ClientForm} form_user = UserForm(request.POST) form_client = ClientForm(request.POST) if form_user.is_valid() and form_client.is_valid(): # get data for auth and login email = form_user.cleaned_data["email"] password_raw = form_user.cleaned_data["password1"] # add user_type = client instance_user = form_user.save(commit=False) instance_user.user_type = "cl" instance_user.save() instance_client = form_client.save(commit=False) user = authenticate(email=email, password=password_raw) if user is not None: # add the user in related user field instance_client.user = user instance_client.save() … -
How to load Django ListView via Ajax
Basically code works as I expected, but my ListView is not refreshing. Everything works fine, but template does not load itself, I must push reload button (all data are loaded correctly then). I done simple form/input for testing and there is no problem with views. My project requires calendar widget for picking months, and simplest way to do this I found on the internet was Ajax approach. Ajax function: $(document).ready(function () { $(function () { $("#datetimepicker1").datetimepicker({ viewMode: 'months', format: 'MM/YYYY', }).on('dp.change', function (e) { var url = "/booking/update_months/{{hotel_id}}"; $.ajax({ type: 'GET', url: url, dataType: 'json', data: { month: e.date.month(), }, success: function (data) { }, error: function (data) { } }); }) }); }); Url "/booking/update_months/{{hotel_id}}" refers to first View function I'm using for this functionality: @csrf_exempt def update_months(request, hotel_id): if request.GET.get('month'): month = request.GET.get('month') request.session['month'] = int(month) + 1 return HttpResponseRedirect(reverse('booking:hotel_statistics', args=(hotel_id,))) else: return render_to_response(request, 'booking/hotel_statistics.html') Then in HotelStatistics ListView I'm doing some stuff in get_context_data function, nothing special here. Just by some "prints" I've tested that the code is being executed until the end of the class. class HotelStatistics(ListView): model = Reservation context_object_name = 'reservations' template_name = 'booking/hotel_statistics.html' def get_context_data(self, **kwargs): . . . return context I'm pretty … -
improve performance of python django models.py query
I am loading the website data into Postgres using Python-Django, there are around 9 csv files that i am loading to database but its taking so long ~10 hrs to fetch the data from website, and load it to Postgres. I wanted to increase the performance of the query. Can you guys please help with that? from django.db import models from django_pandas.managers import DataFrameManager import pandas as pd from sqlalchemy import create_engine import zipfile import os from urllib.request import urlopen import urllib.request import io from io import BytesIO class mf(models.Model): pg_engine=create_engine('postgresql://First.csv zipped file. zf = zipfile.ZipFile(BytesIO(urllib.request.urlopen('http://md_file.zip').read())) df1 = pd.read_csv(zf.open('nm.dat'),header=None,delimiter='|', index_col=0, names=['aaa', 'xxxx', 'yyy','zzz']) df1.to_sql('nm',pg_engine,if_exists='replace') -
Django redirect after search using a queryset
When I click search on the homepage, I want it to take that query set e.g (http://127.0.0.1:8000/?q=car) and then use the same url, but in the search view. I have tried searching around but couldn't find anything that was working. Views: class IndexView(ListView): model = Post # queryset = Post.objects.filter(live=True) template_name = "public/index.html" def get_queryset(self): queryset = super().get_queryset().filter(live=True) query = self.request.GET.get("q") if query: queryset = queryset.filter(title__icontains=query) return redirect(reverse('search-view'), queryset) def get_context_data(self, **kwargs): context = super(IndexView, self).get_context_data(**kwargs) context['queryset'] = self.get_queryset() context['category'] = Category.objects.all() return context URLS: urlpatterns = [ path('', views.IndexView.as_view(), name="index-view"), path('post/create/', views.PostCreateView.as_view(), name="post-create"), path('post/<slug>/update/', views.PostUpdateView.as_view(), name="post-update"), path('post/<slug>/', views.PostDetailView.as_view(), name="post-detail"), path('category/', views.CategoryView.as_view(), name="category"), path('category/<int:pk>/', views.CategoryDetailView.as_view(), name="category-detail"), path('search/', views.SearchListView.as_view(), name="search-view") ] I have tried doing it using a redirect and reverse but it is not working at all. I have 2 templates/views. When I click search on the homepage, I want it to carry on over to the search view and then run the search query on there. Thanks. -
Django DRF field display verbose_name in error message
When model field validation fail, I would like DRF to return the field verbose_name in the error message. example : models.py : class MyClass(models.Model): myfield = model.CharField(max_length=20,\ verbose_name="This is the field",\ default="blabla") serialiers.py : class MyClassSerializer(serializers.ModelSerializer): class Meta: model = MyClass fields = ('myfield',) If, POSTED data for this field is more than 20 characters, response payload is: {"myfield":["the error message..........."]} To make a friendlier message for the users (... and easily manage the errors :-) ) , I'd like to use the model field's verbose_name, so the response payload would be : {"This is the field":["the error message..........."]} Do you have any idea? Thanks! -
Extra fields not in cleaned data of Django Modelform
I have a modelform with some extra fields. I have the clean() function of this form overwritten but can't access these extra fields in the cleaned_data. When validating the form below, on the second last line "data.get('startDate')" returns None as it did not found 'startDate' in the cleaned data. ## Model ## class Reservation(models.Model): groupName = models.CharField(max_length=64) email = models.EmailField() comments = models.TextField(null=True, blank=True) ## Form ### class ReservationForm(forms.ModelForm): startDate = forms.DateField(widget=forms.SelectDateWidget) endDate = forms.DateField(widget=forms.SelectDateWidget) class Meta: model = Reservation fields = [ 'groupName', 'email', 'startDate', 'endDate', 'comments' ] def clean_startDate(self): data = self.cleaned_data['endDate'] if data < datetime.date.today(): raise forms.ValidationError('Pick a date in the future') return data def clean(self): data = super().clean() if data.get('startDate') > data.get('endDate') raise forms.ValidationError('End date must be after start date.') -
Why is the value of my many to many field zero even though it contains users?
I am currently creating a debate website but I'm having a problem with the liking system. In my models I have a class called Debate which has likes, which likes being a many-to-many field. On my admin page it says that the likes field has a certain amount of users - yet when I print the count of likes out - it shows 0. I have already tried to change the parameters on my likes model, manually set the users value in the model, and checked if I was printing the value out incorrectly, but none of them seemed to help my problem. IN MODELS FILE class Debate(models.Model): username = models.CharField(max_length =20 , blank=True, default='') title = models.CharField(max_length = 200, blank=True, default='') likes = models.ManyToManyField(UserProfile, related_name='likes', blank=True) IN ADMIN FILE from django.contrib import admin from .models import Debate, Comments class InfoAdmin(admin.ModelAdmin): list_display = ('id', 'title', 'like_count',) def like_count(self,obj): return obj.likes.all().count() admin.site.register(Debate, InfoAdmin) ADMIN PAGE IN A SINGLE DEBATE'S LIKES SECTION(debate title is h) Likes: UserProfile object(5) UserProfile object(9) ADMIN PAGE DEBATES LIST ID TITLE LIKE COUNT 13 h 0 This is the like output when a debate is just created. You would expect the like count to print 2 since … -
Update queryset on view without actually updating on database
I'm trying to add a field "grade" to my users queryset. I have 3 models: Users, Subject and Exam. I don't think there is a way to calculate a user grade on the initial query like: Users.objects.get(pk=x).annotate(grade=z) because I have to call a method of the Subject model to calculate the total grade of that user for the subject, not only the grade for 1 exam (see the method below in the models description). In my view I did: user_obj = Users.object.get(pk=x).annotate(grade=Value(0, IntegerField())) calculated_grade = subject.calculate_user_grade(user_obj) user_obj.grade = calculated_grade And then passed the user_obj to the template. But once it gets there the grade field I modified is already gone. I print "user_obj.grade" on view and it gives the correct value, then I print it on the template and it gives me 0, the initial value of the "annotate". The models I use are the default user model in django and then class Subject(models.Model): name = models.CharField() def calculate_user_grade(self, user): points = 0 exams = Exam.objects.filter(subject=self) for exam in exams: user_answer = ExamUser.objects.get(user=user, exam=exam) points += user_answer.points return points class Exam(models.Model): subject = models.ForeignKey(Subject) question = models.CharField() class ExamUser(models.Model): exam = models.ForeignKey(Exam) user = models.ForeignKey(User) points = models.PositiveIntegerField(default=0) -
How to get emailAddress from Linkedin using allauth in django?
I want to register users using Linkedin, to retrieve their name, last name and email. For that I'm using allauth on django. I can register the first and last name but I cannot automatically save the email from the data. Looking in Home › Social Accounts › Social accounts › "the_user" on Extra data: {"elements": [{"handle": "urn:li:emailAddress:152954186", "handle~": {"emailAddress": "example@example.com"}}], "firstName": { ... . I can see that the code do retrieve the email, but it doesn't store it. Checking in select * from auth_user;(from database) or in Home › Authentication and Authorization › Users, I see that the code does not store the email automatically. I suppose that the code retrieve first and last name as those items are not inside Arrays. My linkedin app has r_emailaddress, r_liteprofile and w_member_social permissions, and I am using OAuth 2.0. On settings.py : ALLOWED_HOSTS = ['localhost'] INSTALLED_APPS = [ ... 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.facebook', 'allauth.socialaccount.providers.linkedin_oauth2', ] SOCIALACCOUNT_QUERY_EMAIL = True SOCIALACCOUNT_PROVIDERS = \ { 'linkedin_oauth2': { 'SCOPE': [ 'r_liteprofile', 'r_emailaddress', 'w_member_social', ], 'PROFILE_FIELDS': [ 'id', 'firstName', 'lastName', 'emailAddress', 'email-address', 'profilePicture', 'public-profile-url', ], 'LOCATION_FIELDS': [ 'location', ], 'POSITION_FIELDS': [ 'company', ] } } SOCIAL_AUTH_LINKEDIN_OAUTH2_KEY = 'secret' # App ID SOCIAL_AUTH_LINKEDIN_OAUTH2_SECRET ='secret' #app key … -
Django jinja2 template, extends another template. Django renders base template without jinja2
I'm using jinja2 to render a template in django: TEMPLATES = [ { "BACKEND": "django.template.backends.jinja2.Jinja2", "DIRS": [os.path.join(BASE_DIR, "templates/jinja2/")], "APP_DIRS": True, "OPTIONS": {"environment": "management.jinja2_conf.environment"}, }, { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [], "APP_DIRS": True, "OPTIONS": { "context_processors": [ "django.template.context_processors.debug", "django.template.context_processors.request", "django.contrib.auth.context_processors.auth", "django.contrib.messages.context_processors.messages", ] }, }, ] The initial template is in myproject/foo/templates/jinja2/.... Jinja seems to find this fine. This template extends a base template, which is in myproject/templates/jinja2/.... This one cannot be found. Strangely, according to the template loader post-mortem, when django searches for the base template, it does not use jinja2 - it just uses the usual django backend. I have no idea why this is... -
Angular not sending emails when connecting with api of django rest framework
I have made an api in Django that ask for the email, subject and message and send the following data to the email provided. My serializer class is as follows: class EmailUser(serializers.ModelSerializer): class Meta: model = Email fields = ('id', 'email', 'subject', 'message') and views.py and url.py is as follows: class EmailAPIView(mixins.CreateModelMixin, generics.ListAPIView): serializer_class = EmailUser def get_queryset(self): queryset = Email.objects.all() return queryset def post(self, request, *args, **kwargs): subject = request.POST.get('subject') message = request.POST.get('message') from_email = request.POST.get('from_email') email = request.POST.get('email') send_mail(subject, message, from_email, [email], **kwargs) return self.create(request, *args, **kwargs) def get_serializer_context(self, *args, **kwargs): return {'request': self.request} url(r'email-user/', EmailAPIView.as_view()) this api is working fine taking the input and sending the subject and message to the email provided but when I connect the following api to Angular front end it isn't sending email although it stores the information in the database without any error. I am not getting what I am doing wrong. my .html file is: <div class="container-fluid px-xl-5"> <section class="py-5"> <div class="row"> <div class="col-lg-12 mb-5"> <div class="card"> <div class="card-header" style="text-align: center;"> <h3 class="h6 text-uppercase mb-0">EMAIL APPLICANTS</h3> </div> <div class="card-body"> <form class="form-horizontal" #emailForm="ngForm"> <div class="form-group row"> <label class="col-md-3 form-control-label">Email Address</label> <div class="col-md-6"> <input class="validate" #email="ngModel" [(ngModel)]="input.email" name= "email" type="email" placeholder="Email Address" … -
how to fix "IntegrityError at /prog UNIQUE constraint failed: grading_program_of_study.student_id" in django
i am setting up a django applcation in which am using one to one field when i add student detial from the backend it works well but form a frontend form it gives the following error "IntegrityError at /prog UNIQUE constraint failed: grading_program_of_study.student_id " //////////////my view code//////////////// def prog(request): if request.method == 'POST': if request.POST['program_name'] and request.POST['date_of_entry'] and request.POST['faculty']and request.POST['department'] and request.POST['program_type'] and request.POST['date_of_complition']: Program_of_study = program_of_study() Program_of_study.program_name = request.POST['program_name'] Program_of_study.date_of_entry = request.POST['date_of_entry'] Program_of_study.faculty = request.POST['faculty'] Program_of_study.department = request.POST['department'] Program_of_study.department = request.POST['program_type'] Program_of_study.date_of_complition = request.POST['date_of_complition'] Program_of_study.save() return redirect('home',{'sucess':'Program added sucessfully'}) else: return render(request,'grading/home.html') else: return render(request,'grading/home.html') ##### my model code class program_of_study(models.Model): student = models.OneToOneField(student_details, on_delete=models.CASCADE,default = 1) program_name = models.CharField(max_length=50) date_of_entry = models.DateField() faculty = models.CharField(max_length=50) department = models.CharField(max_length=50) program_type = models.CharField(max_length=50) date_of_complition = models.DateField() def __str__(self): return self.program_name -
How to translate validations from AUTH_PASSWORD_VALIDATORS in UserCreationForm
I have a multiple language app (Django 1.11) with a form to create new users. In this form, the error messages when the user send invalid input must come in Portuguese (pt-BR) or English (en-US) based on the selected language. The custom validations and some of the automatic Django messages for validations are well translated, but not the following: "The password is too similar to the username."; "This password is too short. It must contain at least 8 characters." and "This password is too common.". Actually, they are shown in Portuguese, since the LANGUAGE_CODE from settings.py is 'pt-BR'. I was able to translate some of the automatic messages such "A user with that username already exists." with django.utils.translation.activate as in the following code. from django.utils.translation import activate activate(curr_lang) But this wasn't enough to translate the validations from settings.AUTH_PASSWORD_VALIDATORS. I manually changed the LANGUAGE_CODE from 'pt-BR' to 'en-US' and was able to see the messages only in English. What is the best strategy to translate these messages? As far as I researched, setting LANGUAGE_CODE is not a option, since the results I find suggest the use of django.utils.translation.activate. Thanks in advance -
Django Annonate Boolean field depending if item is in a python list
I have an app for a Restaurant. And I have this model: class Product(models.Model): name = models.CharField(max_length=50) price = models.PositiveIntegerField() I have a list called TopSelled like this: ['Beer', 'Burger', ...] I want to aggregate a boolean field called 'Hot', depending if product item is "top-sell" or not. So my annonate should be something like this: Product.objects.all().annotate(if Product.Name in List: HOT = True ELSE Hot = False) How can I achieve this? Thx! -
How to fix timeout when authenticating with Twitch?
When trying to authenticate with Twitch, using Django-allauth, my request times out. I'm currently testing it locally and I don't have any of my ports open. I have the callback url set to the following "http://127.0.0.1:8000/accounts/twitch/login/callback/" on both the twitch app and in the allauth site. I end up at the following URL: "http://id.twitch.tv/accounts/twitch/login/callback/?code=[SOMECODE]&scope=user_read&state=[SOMESTATE]" Any help will be greatly appreciated! -
How to get substring of json parameter [HTML]
I have an img element with an src attribute I am trying to format. An example url for would be https://myurl/45/457698373.png, where the 45 is the first 2 characters of the full item.image attribute. My issue is with the item.image.substring(0,2) part. How do I get the first 2 characters of this item.image ?? <img src='https://myurl/{{item.image.substring(0,2)}}/{{item.image}}.png'> -
Static files not updating on prod
I am new to production stuff. I deployed my first Django app on digital ocean . It's working. The code is updating fine but the problem is with the static files which are serving through nginx. I updated the static files and restart nginx and gunicorn but they are not present in my prod website. I checked with chrome dev tools and it's serving old static files. I checked these changes are present in the prod repo but somehow nginx don't seem to be using the latest static files . The steps I took Run collectstatic command Restart the nginx Restart the gunicorn The nginx config for static files location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/djangoadmin/pyapps/hkc_project; } Is there anything else I have to do for this to work? Thanks in advance -
How to properly add padding using JS to display template content as PDF sheets? (Django project)
I'm working on PDF generation from html template (e.g. to let user be able to download projects portfolio pages). The task is to render each project page content one by one into a single html template and convert this template to PDF document. Suppose that we are using A4 page format for our PDF document, and let's specify a constant template body size - width: 793px; height: 1123px;. Each project page has different content length, so I've tried to use JS to properly split html elements between A4 pages and to ensure that each new project page will rendered on top of the next A4 sheet to be more "pretty-rendered". The problem is that the script runs only once, while the number of pages in for loop is 4. Here is what I already tried: function onLoad() { function getFullHeight(elem) { try { return elem.nextElementSibling.offsetTop; } catch (e) { return elem.offsetTop; } } function addGreatPaddingClass(elem) { if (elem.className.indexOf('footer') === -1 && elem.id.indexOf('footer') === -1 && elem.id !== 'last-element') elem.className += ' great-padding'; } var pageHeight = 1123; var paddingBottom = 50; var body = document.getElementsByTagName('body')[0]; var lastElement = document.getElementById('last-element'); if (lastElement.offsetTop + paddingBottom - 15 > pageHeight) { body.style.height = … -
Django: Why are some templates not detected?
Django newbie here. I'm working on a project with a couple of apps and, thus, have kept my templates at my project's level. Now, the issue here is some templates are not being detected at the corresponding urls. For instance, the template (property_list.html) corresponding to properties list is detected just fine at the relevant url (/properties), while neither property_detail.html nor property_new.html corresponding to properties/new and properties/[insert property ID] respectively are. Just for the record, Home, Sign up, Log in work just fine. I have looked up similar instances, both here as well as at other places, but nothing seems to be pointing me in the direction I want. So, what gives? A screenshot of the template structure is in the linked image below. Again, the folder is at root/project level. Template Structure Project Settings (Template Section) # ... BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # ... TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] # ... Project Urls from django.contrib import admin from django.urls import path, include from .views import HomePageView urlpatterns = [ path('', HomePageView.as_view(), name='home'), path('admin/', admin.site.urls), path('accounts/', include('allauth.urls')), path('agencies/', include('agencies.urls')), path('properties/', include('properties.urls')), ] Properties Urls … -
Django self.request not filtering though query
I am trying to achive some basic search in my search template, but when I search, it works in the URL, but doesn't change any of the posts in the template. Views: class SearchListView(ListView): model = Post template_name = "public/search.html" def get_context_data(self, **kwargs): context = super(SearchListView, self).get_context_data(**kwargs) context['queryset'] = Post.objects.filter(live=True) context['category'] = Category.objects.all() return context def SearchListView(request): query = self.request.GET.get("q") if query: queryset = queryset.filter(title_icontains=query) I am not sure if this is the right way to set things up as the tutorial I was watching was not using class based views. HTML: <div class="container mt-5 mb-5"> <div class="banner-search-main mb-5"> <form method='GET' action=''> <p class="text-muted">Keywords:</p> <input type="text" name='q' class="homebanner-search" placeholder="Enter your keywords" value='{{ request.get.q }}'> <input type="submit" value="search"> </form> </div> <div class="detail-container"> {% for post in queryset %} <div class="col-sm card-container"> <a href="{% url 'post-detail' post.slug %}"> <div class="main-card"> <div class="main-card-img"> <img src="https://via.placeholder.com/270x150" class="card-img-top" alt="#"> </div> <div class="main-card-body"> <p class="featured-category category-{{ post.category.colorcode }}">{{ post.category }}</p> <p class="featured-title">{{ post.title }}</p> <div class="featured-authcat"> <p class="featured-author mr-3"><i class="fas fa-user mr-1"></i>{{ post.author|title }}</p> </div> <p class="featured-subtitle">{{ post.sub_description|truncatewords:25 }}</p> </div> </div> </a> </div> {% endfor %} </div> </div> EXAMPLE: -
Using Django web application to be submitted as a project
I have my main project created in Django as a web application, I have completed my coding. So now that I have to submit the project and have to present it. Is there any way I can render it as an application so that my tutor could just click on an icon or link and just directly open the application instead of starting a server and multiple other things before using the app. Any advice that would help the application to dodge this complicated process would be much appreciated. I even tried looking up information on this but couldn't find anything ueful.