Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Serializer for Players and their associated sessions
I have a model that keeps track of sessions for each player class PlayerSession(models.Model): player = models.ForeignKey(Player, on_delete=CASCADE) session = models.ForeignKey(Session, on_delete=CASCADE) Where the player model is class Player(models.Model): name = models.CharField(max_length=1024) email = models.EmailField(max_length=1024) and Session model is from from django.contrib.sessions.models import Session How can I create a serializer for PlayerSession? Right now I've got class PlayerSessionSerializer(serializers.Serializer): player = serializers.PrimaryKeyRelatedField(queryset=Player.objects.all()) session = serializers.PrimaryKeyRelatedField(queryset=Session.objects.all()) def create(self, validated_data): return PlayerSession.objects.create(**validated_data) -
How to inherit from another view in Django
I am trying to make a simple website where user can order someting to eat. So I've got a view with lots of methods - 'pizza_sizes' is only one of them: class PizzaOrderView(TemplateView): template_name = 'pizza/pizza_order.html' pizza_type = ProductType.objects.filter(name='Regular Pizza').values_list('id', flat=True)[0] def post(self, request): to_return = add_to_cart(request) return to_return def pizza_sizes(self): sizes = Product.objects.filter(type=self.pizza_type).values_list('size__name', flat=True).distinct() return sizes I also have a ListView displaying all products that user has in cart. class CartView(ListView): template_name = 'orders/cart.html' From this page user can either delete or update product. So I am using UpdateView to let him update it, but then again I need all those methods (that I use in PizzaOrderView). I could rewrite those methods to this view, but it doesn't make much sens, I tried to inherit it like this: class ProductUpdateView(UpdateView, PizzaOrderView): model = CartItem fields = '__all__' pizza_type = list(ProductType.objects.filter(name__contains='Pizza').values_list('id', flat=True)) def post(self, request, **kwargs): cart_id = self.kwargs.get('pk') to_return = update_user_cart(request, cart_id) return to_return def get_template_names(self): product_type = CartItem.objects.filter(id=self.kwargs.get('pk')).values_list('product__type', flat=True)[0] if product_type in self.pizza_type: self.template_name_suffix = '_pizza_update' else: self.template_name_suffix = '_form' return super().get_template_names() And then use it in my template, but then it throws an AttributeError: 'ProductUpdateView' object has no attribute 'object' As if it somehow lost its 'object' … -
Database configuration in Django
How do I use a database connection URL in setting up database config in Django as opposed to using a dictionary? Instead of using: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': os.getenv('DB_NAME'), 'USER': os.getenv('DB_USER'), 'PASSWORD': os.getenv('DB_PASSWORD'), 'PORT': os.getenv('DB_PORT'), 'HOST': os.getenv('DB_HOST') } } I want to use: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgresql://DB_USER:DB_PASSWORD@localhost:5432/DB_NAME' } } -
Is there a library for integrating django and AI?
i have a source code of a ai that analyze face pattern and show the feeling of people in image i want to integerate it with a django project for example a client send a image to django server and that give it to ai to analyze the image or send result of the analyze to client with the django server is there any library to do this ? if you can say this in websocket programming is better (ASGI instead of WSGI for IoT) the AI uses scikit-learn -
How to create an input field to change the parameters of the yelp fusion api?
I cannot create a POST request without interrupting how my entire page is rendered when I want to change my parameters. Currently, I am only able to change the yelp fusion api parameters manually, but I want the user to be able to change them. However, I cannot make a form to accept it. I want to go from manually putting them in, to something like this params = {'categories': user_input, 'location': Pre_set} where the user can change it and store in the database or anything along those lines views.py def yelp_query(request): business_id = secret1 YELP_API_KEY = secret YELP_SEARCH = 'https://api.yelp.com/v3/businesses/search'.format(business_id) headers = {'Authorization': 'Bearer %s' % YELP_API_KEY} params = {'categories': 'Sushi', 'location': 'Boston'} ****** #params = {'categories': user_input, 'location':'Boston}***** WHAT I WANT req = requests.get(YELP_SEARCH, headers=headers, params=params) parsedData = [] jsonList = json.loads(req.text) print(json.dumps(jsonList, indent=4)) businesses = jsonList["businesses"] for yelp in businesses: yelpData = {} yelpData['name'] = yelp["name"] yelpData['location'] = yelp["location"]["display_address"] yelpData['rating'] = yelp["rating"] yelpData['price'] = yelp["price"] yelpData['phone'] = yelp["phone"] parsedData.append(yelpData) print(yelpData) print(parsedData) context = {'parsedData' : parsedData, 'form':form} return render(request,'Trends/yelp.html', context) yelp.html {% extends 'Trends/base.html' %} {% block body %} <h2>Yelp Recommendations </h2> <form action="#" method="post"> {% csrf_token %} <input type="text" class="form-control" id="yelp" placeholder="" value="" name='yelp'> <input type="submit" … -
Python / Django - Mypy: expression has type "Type[ModelInstance]", variable has type "ModelInstance"
I'm working on a Django app that provides a GraphQL api for the frontend. I'm using mypy for typechecking and when running mypy I'm encountering errors that I do not understand When running I get the following errors: api/schema.py:50: error: Incompatible types in assignment (expression has type "Type[Academy]", variable has type "Academy") api/schema.py:57: error: Incompatible types in assignment (expression has type "Type[School]", variable has type "School") api/schema.py:64: error: Incompatible types in assignment (expression has type "Type[AcademyGroup]", variable has type "AcademyGroup") This is the code that mypy is checking class AcademyType(DjangoObjectType): class Meta: model: Academy = Academy filter_fields: List[str] = ['name', 'domain', 'slug'] interfaces: Tuple = (relay.Node,) class SchoolType(DjangoObjectType): class Meta: model: School = School filter_fields: List[str] = ['name', 'academy'] interfaces: Tuple = (relay.Node,) class AcademyGroupType(DjangoObjectType): class Meta: model: AcademyGroup = AcademyGroup filter_fields: List[str] = ['name', 'academy'] interfaces: Tuple = (relay.Node,) So the lines that keep failing are variants on model: AcademyGroup = AcademyGroup, but that is just a 'Django model as type' definition that is happening all over my code (and does not seem to be generating errors) As such I'm not really sure what I am doing wrong here, so any help would be greatly appreciated. -
django User authentication via LDAP
I'm trying to check the user login in my django project against our AD via ldap. I found a lot of tutorials online that I've tried so far. For some reason the authenticate(username, password)-function returns None. Here is my Code so far: views.py (login) def login_view(request): if not request.user.is_authenticated: if request.method == 'POST': login_form = Login_form(request.POST) if login_form.is_valid(): username = login_form.data.get('username') password = login_form.data.get('password') domain_name = "@my.domain.com" if domain_name not in username: username += domain_name try: user = authenticate(username=username, password=password) print(user) # this gives me None if user is not None: if user.is_active: login(request=request, user=user) return redirect('index') else: form = AuthenticationForm() messages.error(request, 'Try again!') return render(request, 'myapp/login.html', {'form': form}) except ldap.LDAPError as e: print(e) # no error is displayed here form = AuthenticationForm() messages.error(request, 'Try again!') return render(request, 'myapp/login.html', {'form': form}) ### Some more funcs to ### redirect to login.html ### if the login fails settings.py: AUTHENTICATION_BACKENDS = ( 'django_auth_ldap.backend.LDAPBackend', ) AUTH_LDAP_SERVER_URI = "ldap://my.domain.com:389" AUTH_LDAP_BIND_DN = "CN=Users,DC=my,DC=domain,DC=com" AUTH_LDAP_BIND_PASSWORD = "" # I tried with blank password for anonymous bind or # with "%(password)s" as template but I don't know if that's possible # and also without the AUTH_LDAP_BIND_PASSWORD setting AUTH_LDAP_CONNECTION_OPTIONS = {ldap.OPT_REFERRALS: 0} AUTH_LDAP_USER_ATTR_MAP = {'group': "memberof", "first_name": "givenName", "last_name": … -
How to create a view for details of a single post and url in django?
I am creating a website with a blog application in django 2.2. I only have a problem with the last step, which is to create a view for a single post. Unfortunately, I don't know how to finish it. I created the simplest view I can, but after entering it, I get a 500 error from the server. def single_post(request): return render(request=request, template_name="posts/single_post.html") This is my model, view and url: models.py # Post models from django.db import models from datetime import datetime from django.utils.text import slugify class Post(models.Model): title = models.CharField(max_length=150, verbose_name="Tytuł") content = models.TextField(verbose_name="Zawartość") lead = models.CharField(max_length=35, verbose_name="Skrót artykułu") published = models.DateTimeField(verbose_name="Data publikacji", default=datetime.now()) slug = models.SlugField(unique=True) cover = models.ImageField(upload_to='images/') def save(self, *args, **kwargs): self.slug = slugify(self.title) super(Post, self).save(*args, **kwargs) def __str__(self): return self.title urls.py from django.contrib import admin from django.urls import path, include from . import views app_name = "posts" urlpatterns = [ path("wpisy/", views.posts_list, name="posts_list"),] views.py from django.shortcuts import render from django.http import HttpResponse from .models import Post # Create your views here. def posts_list(request): return render(request=request, template_name="posts/posts_list.html", context={"posts": Post.objects.all}) def single_post(request): return render(request=request, template_name="posts/single_post.html") I would like visitors to the site to be able to read the entire article. Currently, I was able to create only … -
django: Ajax POST response not loading in template
In my django template, An AJAX call is being made for a POST Request (to create an object instance). Template file (making ajax call): <script> $(document).on('submit', '#xyz-form', function(){ $.ajax({ type: 'POST', url: '{% url "xyz" %}', data: $("#xyz-form").serialize(), context: this, success: function(data, status) { $('#xyz-container').html(data); }, error: function (err) { alert(err.status + " " + err.statusText); } }); return false; }); </script> Views.py file: class XYZCreateView(LoginRequiredMixin, CreateView): model = XYZ def post(self, request, *args, **kwargs): # condition returns false hence I commented it # if request.is_ajax(): xyz_form = XYZForm(request.POST) xyz_list = XYZ.objects.all() if xyz_form.is_valid(): xyz_form.save() xyz_form = XYZForm() return render(request, 'ajax_data.html', {'xyz_form': xyz_form, 'xyz_list': xyz_list}) The template invoking the AJAX call is 'xyz.html' and the response data is being sent to 'ajax_data.html' file, which should get loaded as an html content in the #xyz-container that is present in the former html file. However, while the result is getting sent, it is not getting loaded in the original template. Where am I going wrong with this. -
How to inspectdb postgresql certain table in django?
I am trying to use this command for a specific table, but django does not see it. Judging by the logs, he is trying to look into another schema(public) Command: python3 cabinet/manage.py inspectdb processing.transaction > hm.py Error: Unable to inspect table 'processing.transaction' The error was: Error: relationship "processing.transaction" does not exist How to fix this? -
How to use a button to point to an existing url
I'm new to django, here i've to point a button to an existing url <li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li><button type='submit'> Result</button> here i've created a button. how to point this button to the results in url.py urlpatterns = [ path('', views.index, name='index'), path('<int:question_id>/', views.detail, name='detail'), path('<int:question_id>/results/', views.results, name='results'), path('<int:question_id>/vote/', views.vote, name='vote'), ] -
How can we separate equation smaller separated equation in sympy
Hello I am new to Python and Sympy. i have created small project That working like sympy gamma but i want to separate my equation in to smaller sub parts.is it possible using sympy function. I am Attaching one image for more information about my Problem. -
Django: Order by Aggregate Count in ArrayField
I have a complex problem hope your helps please. I have a model named Place. In this model I have a field named address_component. This field contains array of self: Example, two objects like: Place(id=1, name="USA", types="country", address_components=[]) Place(id=2, name="San Doria", types="city", address_components=[1]) class Place(models.Model): PLACE_TYPES = ( ('country', "Country"), ('city', "City"), ('street', "Street") ) name = models.CharField(max_length=255) types = models.CharField(max_length=100, choices=PLACE_TYPES) address_components = ArrayField(models.CharField(max_length=100), size=10, default=list, blank=True) Now I want to order place queryset by counting the number of places which have the most address_component in it This is my try to get countries queryset order by number of cities in it, but not success Place.objects.filter(types='country').annotate(cities_in_count=Count('address_components')).order_by('cities_in_count') -
Using different content object passed from Views to Template depending on what button user presses
I currently have one model called Comments. After entering in a youtube Channel in a form, the user is taken to the index template that shows all the comments on that youtube channels videos that includes one of three key words (Keyword A, Keyword b , Keyword C). I would like to add a feature so there are three links/buttons on the top of the page (each for one of the keywords). The user can press that link and (without page reload (does this mean I will for sure need ajax?))just see the comments with that keyword instead of all comments with any of the three keywords. I am currently sending four content variable objects from views to the template (one with all the comments, and three other objects each that just contain the comment objects for that keyword). So the template has access to the data I need, I just need to make it so that when one of the links/buttons are clicked it only shows that content. Views def addTodo(request): new_item =Channel(channel=request.POST['channel']) #if channel exists render page with comments if Channel.objects.filter(channel=new_item.channel).exists(): channel_obj=Channel.objects.get(channel=request.POST['channel']) comments_object=Comments.objects.filter(channel=channel_obj) comments_objectA=Comments.objects.filter(channel=channel_obj, key="keywordA") comments_objectB=Comments.objects.filter(channel=channel_obj, key="keywordB") comments_objectC=Comments.objects.filter(channel=channel_obj, key="keywordC") return render(request, 'todo/index.html', {'comments_all': comments_object, 'commentsa': comments_objectA,'commentsb': comments_objectB,'commentsc': comments_objectC}) … -
Problem with creating odject after mirgation from Django1.4 to Django 1.5
After updated django version my tests are not success. Error traceback looks like ERROR:mobile.tokenapi.http:: Traceback (most recent call last): File "/home/y700/projects/otipo-upd/otipo/as_site/apps/mobile/decorators.py", line 12, in wrapped response = func(*args, **kwargs) File "/home/y700/projects/otipo-upd/otipo/as_site/apps/assignation/assignmentstats/views.py", line 75, in settings rate_settings = serializer.save(data, uws) File "/home/y700/projects/otipo-upd/otipo/as_site/apps/assignation/assignmentstats/serializers.py", line 75, in save settings = HourRateSettings.objects.get_or_create(user_settings=uws) File "/home/y700/Env/otipo_upd/local/lib/python2.7/site-packages/django/db/models/manager.py", line 146, in get_or_create return self.get_query_set().get_or_create(**kwargs) File "/home/y700/Env/otipo_upd/local/lib/python2.7/site-packages/django/db/models/query.py", line 501, in get_or_create six.reraise(*exc_info) File "/home/y700/Env/otipo_upd/local/lib/python2.7/site-packages/django/db/models/query.py", line 491, in get_or_create obj.save(force_insert=True, using=self.db) File "/home/y700/Env/otipo_upd/local/lib/python2.7/site-packages/django/db/models/base.py", line 546, in save force_update=force_update, update_fields=update_fields) File "/home/y700/Env/otipo_upd/local/lib/python2.7/site-packages/django/db/models/base.py", line 650, in save_base result = manager._insert([self], fields=fields, return_id=update_pk, using=using, raw=raw) File "/home/y700/Env/otipo_upd/local/lib/python2.7/site-packages/django/db/models/manager.py", line 215, in _insert return insert_query(self.model, objs, fields, **kwargs) File "/home/y700/Env/otipo_upd/local/lib/python2.7/site-packages/django/db/models/query.py", line 1675, in insert_query return query.get_compiler(using=using).execute_sql(return_id) File "/home/y700/Env/otipo_upd/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 943, in execute_sql cursor.execute(sql, params) File "/home/y700/Env/otipo_upd/local/lib/python2.7/site-packages/django/db/backends/mysql/base.py", line 127, in execute six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2]) File "/home/y700/Env/otipo_upd/local/lib/python2.7/site-packages/django/db/backends/mysql/base.py", line 120, in execute return self.cursor.execute(query, args) File "/home/y700/Env/otipo_upd/local/lib/python2.7/site-packages/MySQLdb/cursors.py", line 209, in execute res = self._query(query) File "/home/y700/Env/otipo_upd/local/lib/python2.7/site-packages/MySQLdb/cursors.py", line 315, in _query db.query(q) File "/home/y700/Env/otipo_upd/local/lib/python2.7/site-packages/MySQLdb/connections.py", line 226, in query _mysql.connection.query(self, query) IntegrityError: (1048, "Column 'rate' cannot be null") For some reason, the rate field value is not passed to the new instance creation function. creation function @token_required @mobile_response def settings(request, workspace_id): uws = get_object_or_404(UserWorkspaceSettings, workspace_id=workspace_id, user=request.user) serializer = RateSettingsSerializer() if … -
Does Django create useless migrations?
When I change the verbose_name attribute of a Django Model, Django will generate a related migration (running make migrations command). However, without applying the migration (migrate command), the change seems to be applied all over the Django project. I think this is because verbose_name is something used at Django level rather than at database level. This makes me wonder: what is the purpose of this migration file? -
Django across joint filter ManyToMany relationship
My models.py: from django.db import models class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField() def get_all(): return Question.objects.all() def get_detail(question_id): return Question.objects.get(pk=question_id) class Choice(models.Model): question = models.ManyToManyField(Question) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) my views: from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse import datetime from .models import Question, Choice def DetailView(request, question_id): q = Question.get_detail(question_id) choices = Choice.objects.filter(question__question_text = q.question_text) #I also try question__pk == question_id context = {"qs":q, "choices":choices} return render(request, "detail_question.html", context) My url: path('detail/<int:question_id>', views.DetailView, name = 'detail'), My templates: {% extends "base.html" %} {% block content123 %} {% if Questions %} {% for item in Questions %} <p style="color: red;"><a href="{% url 'detail' item.id %}">{{ item.question_text }}</a></p> {% endfor %} {% else %} <h3 style="color: red;">There is nothing</h3> {% endif %} {% endblock %} I try to make a page in which it will display the question and the related vote. I have succeed with ManyToOne relationship with question.choice_set_all in the template. With those code when I run the server it shows the error enter image description here I tried in django shell choice.objects.filter(question__pk = 3/or question_question_text ...) The shell states alo "no such table: polls_choice_question" -
python django url shows old image when exachanging
when running the djangoserver and calling http://127.0.0.1:8000/media/pictures/h2.jpg I get shown the requested image (jpg). Now I exchange the jpg by a file, which is also calles "h2.jpg". BUT when I call the following url again:http://127.0.0.1:8000/media/pictures/h2.jpg it still shows the old picture. How to handle that? Django version 2.1.7 -
Get image before active image in carousel
I want to always display the image before the active image. Here is my code for the carousel. <div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel"> <ul class="carousel-indicators"> {% for item in page.blogpage_images.all %} <li data-target="#carouselExampleIndicators" data-slide-to="{{ forloop.counter|add:"-1" }}" class="{% if forloop.counter == 1 %}active{% endif %}"></li> {% endfor %} </ul> <div class="blog"> <div class="carousel-inner"> {% for item in page.blogpage_images.all %} {% image item.image fill-650x650 as img %} <div class="carousel-item {% if forloop.counter == 1 %}active{% endif %}"> <img src="{{ img.url }}" class="d-block w-100" alt="{{ img.alt }}"> </div> {% endfor %} </div> </div> </div> /*Add image before here*/ Im sure I need to alter this code below. I have tried changing forloop.counter to 0,2,3 etc but is there a way to make it -1 from active? {% for item in page.blogpage_images.all %} {% image item.image fill-650x650 as img %} <div class="carousel-item {% if forloop.counter == 1 %}active{% endif %}"> <img src="{{ img.url }}" class="d-block w-25" alt="{{ img.alt }}"> </div> {% endfor %} -
How I can get chained objects in my project
I have chained models -> Category - Brand - Type. For example : Category : Light vehicle Brand : Volkswagen Type : Passat And I have an Post Model. Question : How i can get chained objects in the form? Code: class Category(models.Model): title = models.CharField(max_length=32) slug = models.SlugField(max_length=32) def __str__(self): return "%s" % self.title class Brand(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) title = models.CharField(max_length=32) def __str__(self): return "%s" % self.title class Type(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) brand = ChainedForeignKey( 'Brand', chained_field="category", chained_model_field="category", show_all=False, auto_choose=True ) title = models.CharField('Модель автомобіля', max_length=32) slug = models.SlugField(max_length=32) def __str__(self): return "%s" % self.title Post Model : class Post(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) brand = models.ForeignKey(Brand, on_delete=models.CASCADE) type = models.ForeignKey(Type, on_delete=models.CASCADE) ...... def __str__(self): return "{} {}".format(self.brand, self.type) I need to create a form with chained objects. How I can get it ? or how to edit my Post model? -
Expected view Client_view to be called with a URL keyword argument named "pk". Fix your URL conf
Error While using Generic view in Django it Showing Error while using DELETE function.Please anyone give me the syntax of generic views in model set i didnt find any problem but no Delete function **Views.py** *from django.http import Http404, HttpResponse from rest_framework import viewsets, status, generics from rest_framework.decorators import api_view from rest_framework.response import Response from .serializers import ClassSerializer from .models import Client class Client_view(viewsets.ModelViewSet, generics.RetrieveUpdateDestroyAPIView): queryset = Client.objects.all().order_by('-Name') serializer_class = ClassSerializer* *lookup_fields = ['Name', 'UserName', 'Mobile', 'Email', 'Address']* **urls.py** *from rest_framework import routers from .views import Client_view router = routers.DefaultRouter() router.register('', Client_view) urlpatterns = router.urls* **models.py** *from django.db import models class Client(models.Model): Name = models.CharField(max_length=15) UserName = models.CharField(max_length=15) Email = models.CharField(max_length=20) Mobile = models.CharField(max_length=10) Address = models.CharField(max_length=20)* **serializer.py** *from rest_framework import serializers from .models import Client class ClassSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Client fields = ['Name', 'UserName', 'Email', 'Mobile', 'Address']* -
How to connect to 3rd party snowflake database using django?
How to create an engine to connect the snowflake db? On Configuring the settings.py, it errors out with below message. Try using 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'postgresql', 'sqlite3' -
connection aborted error by Django at "...\python36-32\Lib\wsgiref\handlers.py"
During getting image data(which is in binary) from the mongodb atlas into my Django project , I am facing two kind of problems. In first situation whenever the http://127.0.0.1:8000/ is searched, the data will gets populated in the html template as required along with a long trace like shown here. In second situation whenever the a GET request is sent, the browser keeps loading infinitely by showing nothing in either cmd nor in browser. And before posting here, I googled the error and visited github's django helpdesk and from that I am unable to figure out the root of the problem. Here is a code to review views.py from django import template from django.shortcuts import render import gridfs import pymongo import random register = template.Library() client = pymongo.MongoClient('mongodb+srv://danial:1234@wearit-qyueb.mongodb.net/test?retryWrites=true&w=majority') db=client.scraped_data.all_brands fs = gridfs.GridFS(client.scraped_data) # Create your views here. def index(request): template='products/products.html' return render(request,template,{'documents': get_random()[:20], 'categories':categories(), 'brands': brands()}) def categories(): raw_data=get_random() all_categories=[] for doc in raw_data: if doc.get('cat_name') not in all_categories: all_categories.append(doc.get('cat_name')) return all_categories def query_form(request): if request.method == 'GET': query_dict=request.GET select_category= query_dict.__getitem__('category-selected') min_price=query_dict.__getitem__('min-price') max_price=query_dict.__getitem__('max-price') listOfDocumets=[] if min_price!='' or max_price!='': listOfDocumets=range(min_price,max_price, db.find({'cat_name': select_category})) else: listOfDocumets=list(db.find({'cat_name': select_category})) random.shuffle(listOfDocumets) return render(request, 'products/products.html',{"documents": listOfDocumets, 'categories':categories(), 'brands': brands()}) def search_query(request): if request.method == 'GET': query_dict=request.GET select_brands= … -
Django Jinja How to check whether the user has any rights through the template?
I have a menu whose parts are displayed depending on the rights. I configured it. I want to check if the user has any rights in principle, if they do not, then the menu will not reach the moment of drawing. Something like this: {% if perms.registration2 == NUll %} # render something {% endif %} This code returns set() not NULL or '': {{ perms.registration2 }} How can I do such a check? -
How to resolve this error 407 during login?
I tried to check by printing where could be the cause of the problem. It shows that user_id and password were there but it cannot proceed after that. def login_request(request): if request.method == 'POST': user_id = request.POST['user_id'] password = request.POST['password'] user = authenticate(user_id=user_id, password=password) if user is not None: login(request, user) return redirect("/index") else: messages.info(request, 'Invalid Credentials') return redirect('login_request') else: return render(request, 'login.html') urls.py path('login_request/', views.login_request, name='login_request'),