Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - decorators restrict "staff"
My goal is to restrict the access the the "staff Group" I am trying to do that with the decorators.py but when I do that, it restricts every user I have registered and not only the staff. When I log in with admin it gives me " you are not authorized" that should be only for the "staff" that should see only one template of the platform. Here the picture also of my admin page. core/decorators.py from django.http import HttpResponse from django.shortcuts import redirect def allowed_user(allowed_roles=[]): def decorator(view_func): def wrapper_func(request, *args, **kwargs): group = None if request.user.groups.exists(): group = request.user.groups.all() if group in allowed_roles: return view_func(request, *args, **kwargs) else: return HttpResponse(' You are not Authorized!') return wrapper_func return decorator core/views.py from django.shortcuts import render, get_object_or_404 from django.contrib.auth.models import User from django.contrib.auth.mixins import LoginRequiredMixin from django.views.generic.list import ListView from .decorators import allowed_user # Create your views here. from quiz.models import Questions from jobs.models import post_job @allowed_user(allowed_roles=['Admin, Students']) def homepage(request): return render(request, 'core/homepage.html') @allowed_user(allowed_roles=['Admin, Students']) def userProfileView(request, username): user= get_object_or_404(User, username=username) jobs = post_job.objects.all() categories = Questions.CAT_CHOICES scores = [] for category in categories: score = Questions.objects.filter(catagory=category[0], student= user).count() scores.append(score) context = { 'user' : user, 'categories_scores' : zip( categories,scores), 'jobs': jobs … -
Display video Django application
I'm trying to display a test video at my Django app, this is how the .html file looked like {% extends "blog/base.html" %} {% load static %} {% block content %} <video oncontextmenu="return false;" width='320' height= '240' autoplay controls controlsList="nodownload"> <source src="{% static 'videos/test.mp4' type='video/mp4' %}"> Your browser does not support the video tag. </video> {% endblock content %} after setting the settings.py for defining the static root STATIC_URL = '/static/' MEDIA_ROOT=os.path.join(BASE_DIR, 'media') MEDIA_URL='/media/' also the URL patterns were adjusted: if settings.DEBUG: # urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Now the problem is that I can display the video only using local host, and I can't display it in production using a public IP or vistual one, where I can see a video fram that can not be displayed! I think something is missing in the settings.py for defining the URL pattern being accessed publicly during calling from a foreign router. but I can't figure it out! I need help in amending the code! thanks a lot! -
Exception Value: local variable 'other_user' referenced before assignment
So, this is probably just something simple I'm doing wrong here. But basically, I am attempting to simply pass in the pk of the other_user. I tested that the query works correctly, and am indeed printing the other user. Just don't know where to place it correctly in my code so I can pass it to the render part. local variable 'other_user' referenced before assignment def message (request, profile_id): if request.method == 'POST': form = MessageForm(request.POST, other_user.id) if form.is_valid(): form.save() return redirect('dating_app:messages', other_user.id) else: conversation, created = Conversation.objects.filter(members = request.user).filter(members= profile_id).get_or_create() print(conversation) other_user = conversation.members.filter(id=profile_id).get() print(other_user) form = MessageForm({'sender': request.user, 'conversation': conversation}) context = {'form' : form } return render(request, 'dating_app/message.html', context) -
'The requested URL / was not found on this server' Django Deployment issue
I'm developing a django website and am currently working on deploying. I'm following this tutorial. And im in the last stage of the tutorial (1:08:00 in the video). After he finished configuration th django-project.conf file he saves and everything is working, but me on the other hand, i get an: Not Found The requested URL / was not found on this server. Apache/2.4.34 (Ubuntu) Server at **** Port 80 This is my projects .conf file: <VirtualHost *:80> ServerName _ Redirect 404 / Alias /static /home/user/project/static <Directory /home/user/project/static> Require all granted </Directory> <Directory /home/user/project/project> <Files wsgi.py> Require all granted </Files> </Directory> WSGIScriptAlias / /home/user/project/project/wsgi.py WSGIDaemonProcess project_app python-path=/home/user/project python-home=/home/user/project/venv WSGIProcessGroup project_app </VirtualHost> This is my urls.py: from django.contrib import admin from django.urls import path, include from . import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.homepage), path('rh/', views.rh, name="rh"), path('gvt/', views.gvt, name="gvt"), path('fth/', views.fth, name="fth"), path('pages/', include('pages.urls')), ] This is my wsgi.py from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'excelsite.settings') application = get_wsgi_application() sys.path.append('/home/alexholst/excelsite') -
Django Rest API Djoser Refresh and Access Token Problem
I am trying to get access and refresh tokens when the user registers using the /auth/users/ endpoint. I have already extended the serializer and it is showing all custom fields. It registers the user successfully and returns the result as follows: { "mobile": "12345", "driving_id": "478161839", "full_name": "John Doe", } This is where I would want to have an access and refresh token. I read that djoser uses django simple jwt library to provide access and refresh tokens. This is the function to create the tokens manually which I am able to do but the only thing I am not understanding is where to return the data with other details. from rest_framework_simplejwt.tokens import RefreshToken def get_tokens_for_user(user): refresh = RefreshToken.for_user(user) return { 'refresh': str(refresh), 'access': str(refresh.access_token), } -
What is similar to PrimeNG for Django?
I know that Django makes use of html templating system to make the UI development easy. But no one can start building a table ( like in https://primefaces.org/primeng/showcase/#/table) with html templating system from scratch right? (I assume that will be time taking and will require more resources) Is there a library that provides rich UI components like in PrimeNG for Django? -
Djnago, how to figure out in template a list value from my Manager?
I have the following models.py: class MaterialeManager(models.Manager): def get_queryset(self, *args, **kwargs): return super().get_queryset(*args, **kwargs).annotate( total=F('quantity')*F('price'), ) def get_monthly_totals(self): products = dict((p.id, p) for p in Products.objects.all()) return list( (product, datetime.date(year, month, 1), totale) for product_id, year, month, totale in ( self.values_list('product__nome', 'date__year', 'date__month') .annotate(totale=Sum(F('quantity') * F('price'))) .values_list('product__nome', 'date__year', 'date__month', 'totale') ) class Materiale(models.Model): product= models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) quantity=models.DecimalField() price=models.DecimalField() date=models.DateField() obejcts=MaterialManager() Could I figure out in my template the .values_list('product__nome', 'date__year', 'date__month', 'totale'). I try with Materiale.objects.all() but does not work. -
if field.choices change in a model, what happens to older records that have selections that are no longer in the list?
Would the data for these records be deleted automatically or left as they were? I'm wondering whether to use a seperate model to list these or if this is even an issue. -
CORS HEADERS IN ANGULAR AND DJANGO
I'm working on a personal project and curenttly int the authentication part, now I have enabled CORS ORIGIN WHITE TO ONE SPECIFIC port that im using for the angular. however when I enable use withCredentials int he headers, there is no set cookies section int he console to ebsure that a user maintains the state of signed in when I refresh, I even used interceptors but still i get this error with no set cookies. this is the error: has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' the following is my code so far: export class AuthService { signedin$ = new BehaviorSubject(false); httpHeaders = new HttpHeaders({ 'Content-Type': 'application/json', observe: 'response' as 'response' //Authorization: 'Token 9e16a8fba7d0fe6e70a0b417d70660c3eb487be0' }); baseurl = "http://localhost:8000/"; constructor(private http: HttpClient) { } usernameAvailable(username: string){ return this.http.post<usernameResponse>(this.baseurl + 'users/', {headers:this.httpHeaders, username:username}) } signUp(credentials:signupcredentials){ return this.http.post<signupresponse>(this.baseurl + 'users/', credentials, {headers:this.httpHeaders}).pipe( tap( ()=>{ this.signedin$.next(true); }) ); } checkAuth(){ return this.http.get('http://localhost:8000/users/', {headers: this.httpHeaders}).pipe( tap( response=>{ console.log(response) }) ); } } my interceptor is also as follows: import {Injectable} from '@angular/core'; import {Observable} from 'rxjs'; import { HttpEvent, HttpHandler, HttpRequest, HttpInterceptor} … -
Django reached maximum value of sequence
I am running a program that creates millions of records daily, after running this program for over a year it seems like I have reached the id limit on my postgres database. The error I am receiving is django.db.utils.DataError: nextval: reached maximum value of sequence "main_records_id_seq" (2147483647) Is there a way to extend the maximum id using SQL or the django ORM? Or is there a better solution? -
How can I find the view mapped to certain url in django with pycharm?
I'm debugging multiple apis built with django rest framework , How can I find the views mapped to a certain URL?. I'm currenty using pycharm so is there any plugin than can help EX: in url : /api/users/business-segment/ how can I know the view that maps to this url ? -
is it possible to override a foreign key relation with a custom method/property
Context I'm working on refactoring a Django 2.X app, particularly the core model, CoreModel. There's a single database (Postgres) containing all related tables. Instances of CoreModel will no longer live in Postgres after this refactor, they will live somewhere else but outside the scope of the Django project, let's say some AWS No-SQL database service. There also several satellites models SateliteModel to CoreModel which will continue to live on Postgres, but CoreModelis currently modelled as a foreign key field. class CordeModel(models.Model): pass class SatelliteModel(models.Model): core = models.ForeignKey(CoreModel) def some_instance_method(self): return self.core.calculate_stuff() # <- override self.core! Problem The code is filled with mentions to the CoreModel relation, and I haven't been able to successfully solved this issue. My first naive approach was to implement a @property getter method, that way I had enough flexibility to do something like: @property def core(self): try: # ORM return self.core except CoreNotFound: # External datastore return aws_client.fetch_core() With this snippet I have a circular dependency on the core name, so the idea is out. I could rename the foreign key: but I would much rather not touch the database schema. After all I'm already refactoring the central part of the app, and that's an very … -
HOW TO ISSUE Roll no. slips to SCHOOLS
I am beginner.Learning Django. In project, i taken students data from some schools to take a special exam.NOW HOW TO ISSUE Roll no. slips to SCHOOLS. my School model is onetooneField link with User. And School is parent class of Student Model. Please suggest me what to learn next to achieve it. -
Handling input from an input field or form field with Django
So I'm trying to learn Django by building a very simple single-page site that just takes emails for subscriptions and stores it into djangos backend. I made an html page for the site that has form and input elements, and I've successfully rendered the page by following the documentation. I even built a model called 'subscriptions', to take email strings, but now i'm unsure about how to handle the input from the html page and store the emails in the backend. All the documentation is kind of confusing cause it instructs me to build a separate .html file for the form, and handle it in another views and model page, which just seems unnecessary. Does django necessitate handling input in a separate forms.html file? Or can i just use the index.html, and add views to 'views.py' or revise 'models.py'? I'm pretty confused, all help and examples are very appreciated! -
I'm trying to use data pulled from CoinMarketCap API, I can't access all the information from the dictionary
It looks like the information is a List with embedded dictionary. I'm a beginner and don't fully understand how to pull the information from lists/dictionaries. EXP: 'data': [{'id': 1, 'name': 'Bitcoin', 'symbol': 'BTC', 'slug': 'bitcoin', 'num_market_pairs': 7956, 'date_added': '2013-04-28T00:00:00.000Z', 'tags': ['mineable'], 'max_supply': 21000000, 'circulating_supply': 18344737, 'total_supply': 18344737, 'platform': None, 'cmc_rank': 1, 'last_updated': '2020-04-25T16:09:51.000Z', 'quote': {'USD': {'price': 7582.532132, 'volume_24h': 33998463530.3441, 'percent_change_1h': -0.102004, 'percent_change_24h': 0.497048, 'percent_change_7d': 5.20237, 'market_cap': 139099557755.5893, 'last_updated': '2020-04-25T16:09:51.000Z'}}} I can pull the information in 'data', but I can't pull the information in the 'quote':{'USD'} portion of the dictionary. My code in my template is: {% for coin_Key in cmc_Data.data %} {{ coin_Key }} <tr> <td>{{ coin_Key.cmc_rank }}</td> <td>{{ coin_Key.name }}</td> <td>{{ coin_Key.symbol }}</td> <td>{{ coin_Key.quote.price }}</td> <td>{{ coin_Key.quote.market_cap }}</td> <td>{{ coin_Key.total_supply }}</td> <td>{{ coin_Key.max_supply }}</td> </tr> {% endfor %} the {{ coin_Key }} lists all the information, so I know it's pulling from the API properly. I'm not sure I explained this properly, hit me up with any questions and I'll do my best to clarify. -
Django: Create object with ForeignKey from url
I am working on a Django project with two models linked by a ForeignKey. The parent model, Composition, is linked to the child model, NoteObject, by the id of Composition. in models.py class Composition(models.Model): id = models.AutoField(primary_key=True) ... class NoteObject(models.Model): id = models.AutoField(primary_key=True) composition = models.ForeignKey(Composition, on_delete=models.CASCADE) ... Once a composition is created, the user needs to be able to create NoteObjects that belong to that composition. The notes are created with the following method: in views.py class NoteCreateView(CreateView): model = NoteObject template_name = 'entry.html' fields = ['duration', 'pitch', 'accidental', 'octave'] success_url = reverse_lazy('compositions') def get_context_data(self, **kwargs): kwargs['notes'] = NoteObject.objects.filter( composition=self.kwargs['composition']) return super(NoteCreateView, self).get_context_data(**kwargs) The get_context_data method is there to display only the notes for the current composition. The current composition comes from the id of the composition that is part of the url where <composition> is the id of the composition. in urls.py path('entry/<composition>/', views.NoteCreateView.as_view(), name='entry') When I save a NoteObject, what do I need to do in order to set the value of the ForeignKey to be the value within <composition>? in models.py def save(self, *args, **kwargs): composition_id = ???????? self.composition_id = composition_id super(NoteObject, self).save(*args, **kwargs) How do I get the value of kwarg in the CreateView to … -
Unknown Indentation Error in the following code
this is the code: 3nd line is giving error. class RawMassegeForm(forms.Form): subject = forms.CharField(widget= forms.TextInput(attrs={'placeholder':'Enter your Subject'})) name = forms.CharField(widget= forms.TextInput(attrs={'placeholder':'Enter your Name'})) email = forms.EmailField(widget= forms.EmailInput(attrs={'placeholder':'Enter your email'})) message = forms.TextField(widget= forms.Textarea(attrs={'placeholder':'Enter Your Message here...'})) -
i want to create a MY ACCOUNT or MY PROFILE page on my django website. but my "account.html" template doesnt render
below is the VIEWS.PY code from django.shortcuts import render, redirect from django.http import HttpResponse from .models import Tutorial from django.contrib.auth.forms import AuthenticationForm from django.contrib.auth import login, logout, authenticate from django.contrib import messages from .forms import NewUserForm from .models import Tutorial, TutorialCategory, TutorialSeries from django.http import HttpResponse from django.contrib.auth.decorators import login_required def single_slug(request, single_slug): # first check to see if the url is in categories. categories = [c.category_slug for c in TutorialCategory.objects.all()] if single_slug in categories: matching_series = TutorialSeries.objects.filter(tutorial_category__category_slug=single_slug) series_urls = {} for m in matching_series.all(): part_one = Tutorial.objects.filter(tutorial_series__tutorial_series=m.tutorial_series).earliest("tutorial_published") series_urls[m] = part_one.tutorial_slug return render(request=request, template_name='main/category.html', context={"tutorial_series": matching_series, "part_ones": series_urls}) tutorials = [t.tutorial_slug for t in Tutorial.objects.all()] if single_slug in tutorials: this_tutorial = Tutorial.objects.get(tutorial_slug=single_slug) tutorials_from_series = Tutorial.objects.filter(tutorial_series__tutorial_series=this_tutorial.tutorial_series).order_by('tutorial_published') this_tutorial_idx = list(tutorials_from_series).index(this_tutorial) return render(request=request, template_name='main/tutorial.html', context={"tutorial": this_tutorial, "sidebar": tutorials_from_series, "this_tut_idx": this_tutorial_idx}) return HttpResponse(f"'{single_slug}' does not correspond to anything we know of!") #homepage def homepage(request): return render(request=request, template_name='main/categories.html', context={"categories": TutorialCategory.objects.all}) #register function def register(request): if request.method == "POST": form = NewUserForm(request.POST) if form.is_valid(): user = form.save() username = form.cleaned_data.get('username') messages.success(request, f"New Account Created: {username}") login(request, user) messages.info(request, f"You are now logged in as {username}") return redirect("main:homepage") else: for msg in form.error_messages: messages.error(request, f"{msg}: {form.error_messages[msg]}") form = NewUserForm return render(request, "main/register.html", context={"form":form}) #logout def logout_request(request): logout(request) … -
Retrieve data from queryset and pass to template in django
I have a model as bellow: class Artwork(models.Model): title = models.CharField(max_length=120) collection = models.CharField(max_length=120,null=True) slug = models.SlugField(blank=True, unique=True) description = models.TextField() price = models.DecimalField(decimal_places=2, max_digits=20, default=0) image = models.ImageField(upload_to=upload_image_path, null=True, blank=True) banner = models.ImageField(upload_to='artworks/banner') video = models.FileField(upload_to='artworks/video',blank=True,null=True) category = models.CharField(choices=CATEGORY_CHOICES, max_length=15) views_count = models.IntegerField(default=150) featured = models.BooleanField(default=False) active = models.BooleanField(default=True) created = models.DateTimeField(default=timezone.now) and The view as bellow: def artwork_list_view(request): queryset = Artwork.objects.all() context = { 'objet_list':queryset, } return render(request, "artworks/list.html", context) I use the queryset in template as bellow: <div style='min-height:80px;'><p >First Collection</p></div> {% for obj in object_list %} <div class="workSeriesThumbnailStrip"> {% if obj.image %} <a href="{{ obj.get_absolute_url }}"><img src="{{ obj.image.url }}" style="float:left;width:67px;height:87px;margin:10px;" ></a> {% endif %} </div> {% endfor %} </div> know I have more than one collection and want to place a for loop in collections to show items of each collection in one row. But as I'm new in django, I don't know how to retrieve the list of collections and pass them to template. please help me. -
Django, Docker and SMTP - messages don't send
I'm trying to send an email through Django and a namshi/smtp Docker image. Code: settings.py: EMAIL_HOST = 'smtp' EMAIL_PORT = '25' DEFAULT_FROM_EMAIL = 'noreply@<domain name here>' # obviously, domain name is set here docker-compose.yml: smtp: image: namshi/smtp restart: always ports: - '25:25' volumes: - ./:/web environment: - KEY_PATH=/web/config/ssl_keys/privkey.pem - CERTIFICATE_PATH=/web/config/ssl_keys/fullchain.pem I'm using django-allauth to send a password reset email. This is the console output when I request for password reset for my account with a valid Yandex email address: smtp_1 | 282 LOG: MAIN smtp_1 | 282 <= noreply@<domain> H=<project name>_web_1.<project name>_default (<some sort of id>) [<some ip here>] P=esmtp S=8248 id=<i feel like it's better if i remove this>@<some sort of id> smtp_1 | 282 LOG: smtp_connection MAIN smtp_1 | 282 SMTP connection from shpplace_web_1.shpplace_default (<some sort of id>) [<some ip>] closed by QUIT web_1 | <my ip?>:34856 - - [25/Apr/2020:21:09:33] "POST /accounts/password/reset/" 302 - smtp_1 | 283 Exim version 4.92 uid=101 gid=101 pid=283 D=80001 smtp_1 | Berkeley DB: Berkeley DB 5.3.28: (September 9, 2013) smtp_1 | Support for: crypteq iconv() IPv6 GnuTLS move_frozen_messages DANE DKIM DNSSEC Event OCSP PRDR SOCKS TCP_Fast_Open smtp_1 | Lookups (built-in): lsearch wildlsearch nwildlsearch iplsearch cdb dbm dbmjz dbmnz dnsdb dsearch nis nis0 passwd … -
How to change title for the tab of User Change Page of Django admin?
I'm working on Django and wanted to change the default title for the tab of User Change Page of Django admin as marked in the pic : my admin.py file is: from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .models import CustomUser class CustomUserAdmin(UserAdmin): change_list_template='change_list_form.html' change_form_template = 'change_form.html' add_form_template='add_form.html' list_display = ('first_name','last_name','email','is_staff', 'is_active',) list_filter = ('first_name','email', 'is_staff', 'is_active',) search_fields = ('email','first_name','last_name','a1','a2','city','state','pincode') ordering = ('first_name',) add_fieldsets = ( ('Personal Information', { # To create a section with name 'Personal Information' with mentioned fields 'description': "", 'classes': ('wide',), # To make char fields and text fields of a specific size 'fields': (('first_name','last_name'),'email','a1','a2','city','state','pincode','check', 'password1', 'password2',)} ), ('Permissions',{ 'description': "", 'classes': ('wide', 'collapse'), 'fields':( 'is_staff', 'is_active','date_joined')}), ) So can we change it?? If yes then how?? Thanks in advance!! -
Django : How to show logged in users data from database
I am working on invoice management system having in which user can add invoice data and it will save in database and whenever user logged in the data will appear on home page.but the problem if whenever any user logged in the home page showing other users data also but i want active users data only. could you guys help me. here is my home page,you can see i am logged in through user 1 but at home page user 2 data also appear here is my code views.py from django.shortcuts import render from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from django.views.generic import ( ListView, DetailView, CreateView, UpdateView, DeleteView ) from .models import Invoicelist def home(request): context = { 'invoices': Invoicelist.objects.all() } return render(request, 'invoicedata/home.html', context) class InvoiceListView(ListView): model = Invoicelist template_name = 'invoicedata/home.html' # <app>/<model>_<viewtype>.html context_object_name = 'invoices' class InvoiceDetailView(DetailView): model = Invoicelist class InvoiceCreateView(LoginRequiredMixin, CreateView): model = Invoicelist fields = ['issuer','invoice_number','date','amount','currency','other'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) class InvoiceUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = Invoicelist fields = ['issuer','invoice_number','date','amount','currency','other'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def test_func(self): invoice = self.get_object() if self.request.user == invoice.author: return True return False class InvoiceDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView): model = Invoicelist success_url = '/' … -
coveralls doesn't recognize token when dockerized django app is run in TravisCI, but only from pull requests
I'm getting this error from TravisCI when it tries to run a Pull Request coveralls.exception.CoverallsException: Not on TravisCI. You have to provide either repo_token in .coveralls.yml or set the COVERALLS_REPO_TOKEN env var. The command "docker-compose -f docker-compose.yml -f docker-compose.override.yml run -e COVERALLS_REPO_TOKEN web sh -c "coverage run ./src/manage.py test src && flake8 src && coveralls"" exited with 1. However, I do have both COVERALLS_REPO_TOKEN and repo_token set as environment variables in my TravisCI, and I know they're correct because TravisCI passes my develop branch and successfully sends the results to coveralls.io: OK Destroying test database for alias 'default'... Submitting coverage to coveralls.io... Coverage submitted! Job ##40.1 https://coveralls.io/jobs/61852774 The command "docker-compose -f docker-compose.yml -f docker-compose.override.yml run -e COVERALLS_REPO_TOKEN web sh -c "coverage run ./src/manage.py test src && flake8 src && coveralls"" exited with 0. How do I get TravisCI to recognize my COVERALLS_REPO_TOKEN for the pull requests it runs? -
Writing to txt file in UTF-8 - Python
My django application gets document from user, created some report about it, and write to txt file. The interesting problem is that everything works very well on my Mac OS. But on Windows, it can not read some letters, converts it to symbols like é™, ä±. Here are my codes: views.py: def result(request): last_uploaded = OriginalDocument.objects.latest('id') original = open(str(last_uploaded.document), 'r') original_words = original.read().lower().split() words_count = len(original_words) open_original = open(str(last_uploaded.document), "r") read_original = open_original.read() characters_count = len(read_original) report_fives = open("static/report_documents/" + str(last_uploaded.student_name) + "-" + str(last_uploaded.document_title) + "-5.txt", 'w', encoding="utf-8") # Path to the documents with which original doc is comparing path = 'static/other_documents/doc*.txt' files = glob.glob(path) #endregion rows, found_count, fives_count, rounded_percentage_five, percentage_for_chart_five, fives_for_report, founded_docs_for_report = search_by_five(last_uploaded, 5, original_words, report_fives, files) context = { ... } return render(request, 'result.html', context) report txt file: ['universitetindé™', 'té™hsili', 'alä±ram.', 'mé™n'] was found in static/other_documents\doc1.txt. ... -
How to get two distinct objects from the same view function in django according to the requirements?
I have 3 models in Django which are like: class Category(models.Model): name = models.CharField(max_length=100, unique=True) slug = models.SlugField(max_length=100, unique=True) class Subcategory(models.Model): name = models.CharField(max_length=100) slug = models.SlugField(max_length=100, unique=True) class Product(models.Model): name = models.CharField(max_length=200, unique=True) category = models.ForeignKey(Subcategory, on_delete=models.CASCADE, related_name='products') slug = models.SlugField(max_length=150, unique=True) The view function which I want to modify currently looks like this: def product_list(request, category_name): subcategory = get_object_or_404(Subcategory, slug=category_name) subcategory_name = subcategory.name product_list = subcategory.products.all() context = { 'name':subcategory_name, 'product_list':product_list, } return render(request, 'products/product_list.html', context) In one of my html templates each category is displayed along with the subcategories under it. If anyone clicks on the category name instead of the subcategory under that category name, I want the views function to display all the products which come under that category and not just one subcategory under that given category. I can create a separate view to do that but I want to know if there's a way to do that in the same view function.