Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How Django authentication flow works? [a particular case]
I am reading some code found on the Internet, and trying to make sense of it. I don't understand how authentication works here. Here is the code snippets. the root URLConf urlpatterns = [ path('admin/', admin.site.urls), path("", include("authentication.urls")), path("", include("app.urls")) ] Then if we look at authentication.urls, we will see this: urlpatterns = [ path('login/', login_view, name="login"), path('register/', register_user, name="register"), path("logout/", LogoutView.as_view(), name="logout") ] Somehow it ends at 'login/' and login_view handles it. I don't understand why? Ok, then if we open login_view: def login_view(request): form = LoginForm(request.POST or None) msg = None if request.method == "POST": if form.is_valid(): username = form.cleaned_data.get("username") password = form.cleaned_data.get("password") user = authenticate(username=username, password=password) if user is not None: login(request, user) return redirect("/") else: msg = 'Invalid credentials' else: msg = 'Error validating the form' return render(request, "accounts/login.html", {"form": form, "msg" : msg}) we can see that in case of successful authentication, it redirects to "/", which as I understand it, should create a loop. Because, when you go to http://localhost:8000 the first " ", include("authentication.urls")) will match it. And it all starts again. When and why "", include("app.urls") will match? When "", include("authentication.urls") matches, where does 'login/' come from? Redirecting to "/" in login_view() … -
statement failing under try
I'm absolutely baffled by this issue and was wondering if you could help out. This code works in my dev environment, but when I push it to my production server, the statement under 'try' fails and, despite this, the system doesn't even attempt the statement under 'except'. I've probably written 10,000 try/except statements and I've never seen anything like this. try: user_profile = Profile.objects.get(user=kwargs['instance']) except: user_profile = Profile.objects.create(user=kwargs['instance'], busemail=kwargs['instance'].email) Under what circumstances would the system not attempt to execute the except statement? Thanks! -
Typeahead Bloodhound Autocomplete using prefetch + remote when source is a dict from Django
Bloodhound variable for Typeahead that's working nicely: var egDjangoVar = new Bloodhound({ queryTokenizer: Bloodhound.tokenizers.whitespace, datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'), remote: { url: '/ajax/eg/%QUERY.json', wildcard: '%QUERY', filter: filterdata } }); We added dict parsing function filter: filterdata because Django requires JSON to be sent as a dict for security: function filterdata(data){ return $.map(data.results, function(results,index){ return results.value; }) } All works beautifully. We now want Prefetch functionality and have added: prefetch: { url: '/ajax/prefetch.json', wildcard: '%QUERY', filter: filterdata }, This doesn't work, despite '/ajax/prefetch.json' serving expected dict. We think it may be due to dataTokenizer issues discussed in this answer, but we don't understand why the tokenizer should differ between remote and prefetch sources, and the suggested datumTokenizer: function(d) { return Bloodhound.tokenizers.whitespace(d.value)}; didn't work when adding it as an argument of prefetch. We've found that __/ajax/prefetch.json__data in local storage is saved with dict keys matching values like {"datums":{"Apple":"Apple","Banana":"Banana","Orange":"Orange"},"trie":{"i":[],"c":{}}}, whereas the remote data directly viewed is like {"results": [{"value": "Apple"}, {"value": "Banana"}, {"value": "Orange"}]}. Is this unexpected? I'm new to front end / JS, so please forgive me if this is a stupid question. What are we doing wrong? -
Shared models between two projects and ForeignKey to unused model that exists only in one of them
I have two Django projects that communicate with each other. The first one contains model A and B that has a ForeignKey to A. The first project sends and receives serialized B objects from the second project. I want the second project to contain just B, but it needs the value of that ForeignKey. These models are defined as follows: class A(models.Model): ... class B(models.Model): fk = models.ForeignKey(to='A', on_delete=models.PROTECT) ... The problem is that ForeignKey to A in model B requires model A to be defined in the second project. Its objects also have to exist so that the database is consistent and there are no problems, e.g., in the admin panel. In the end, I'd like to treat the fk field as a full-fledged ForeignKey in the first project and as some kind of read-only generic identifier in the second one. I would like to have the same code base for the model in both projects to ensure databases in the two projects stay synchronized. How can I achieve this in a clean way? -
Django AWS S3 Media Files Issue
I’ve faced an issue while implementing S3 storage with Django application. Uploading the images through the Django admin panel to the S3 media folder works fine. However, I cannot retrieve the images from the S3 media folder (that is public) because of NotImplementedError: This backend doesn't support absolute paths. Please consider my files. Thank you for your support and attention. settings.py from pathlib import Path from dotenv import dotenv_values import os import dj_database_url config = dotenv_values('.env') # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = 'tu!q^j1ft%s2ohw%+p=@bjb%1l7wm!3_8%(7so^rxm)+rsj9d6' DEBUG = True LOGIN_REDIRECT_URL = 'dashboard' ALLOWED_HOSTS = ['*'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # AWS S3 'storages', # Apps 'app_profiles', 'app_catalog', 'app_purchases', 'app_api', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'project.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['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', ], }, }, ] WSGI_APPLICATION = 'project.wsgi.application' AUTH_USER_MODEL = 'app_profiles.CustomUser' # DATABASES = { # 'default': { # 'ENGINE': 'django.db.backends.postgresql', # 'NAME': config['DB_NAME'], # 'USER': config['DB_USER'], # 'PASSWORD': config['DB_PASS'], # 'HOST': config['DB_HOST'], # 'PORT': config['DB_PORT'], # } # } DATABASES = {'default': dj_database_url.config(default='postgres://ecommerce:Django_ecommerce123@localhost/ecommerce')} AUTH_PASSWORD_VALIDATORS = [ … -
Do I need the Django "sites" framework to build a sitemap for a single-site django project?
According to the Django sitemap framework docs, to be able to use the sitemaps framework, you need to: Make sure you’ve installed the sites framework. However, the "sites" framework docs say this about the "sites" framework: Use it if your single Django installation powers more than one site and you need to differentiate between those sites in some way. The way I see it is that the two docs are contradicting each other. Sitemaps docs say "sites" should be used, and "sites" docs say to use "sites" only for multi-site projects. So, my question is do I need "sites" for my single-site project? By single-site I mean I have one single domain and I will not be having duplicated content. -
python requests image upload fails to drf
import json import requests user_f = open('categories.json',) users = json.load(user_f) media_api = 'http://127.0.0.1:8000/api/categories/' files=[ ('category_image', ("Traditional-Art.png", open("Traditional-Art.png",'rb'),'image/jpeg')) ] json = { "category_name": "cat", "category_description": "desc", "user": 16 } headers = { "Accept": 'application/json, text/plain, */*', "enctype":"multipart/form-data" } response = requests.request("POST", media_api, headers=headers, data=json, files=files) print(response.json()) Here, i am trying to upload image to django rest-framework and getting below error `{u'category_image': [u'Upload a valid image. The file you uploaded was either not an image or a corrupted image.']}` this works when image is jpg format but, not working in png . Am i missing anything or do i need to modify something ? Please take a look -
how to use variable in function name?
I want to create function as per number of entries in table. <script> console.log({{count_id.id}}) for (let i = 1; i =< {{count_id.id}}; i++) { num = i function attendance_present + num() { document.querySelector('#present').textContent = "Present" document.querySelector('#present').classList.remove("btn-outline-danger") document.querySelector('#present').classList.remove("btn-outline-warning") document.querySelector('#present').classList.add("btn-outline-primary") } function attendance_absent + num() { document.querySelector('#present').textContent = "Absent" document.querySelector('#present').classList.remove("btn-outline-primary") document.querySelector('#present').classList.remove("btn-outline-warning") document.querySelector('#present').classList.add("btn-outline-danger") } function attendance_half_day + num() { document.querySelector('#present').textContent = "Half-day" document.querySelector('#present').classList.remove("btn-outline-primary") document.querySelector('#present').classList.remove("btn-outline-danger") document.querySelector('#present').classList.add("btn-outline-warning") } } </script> the {{count_id.id}} coming from views in django. -
Django inner join methods return unexpected results
I am new to Django's ORM and am confused by inner join conventions despite having consulted the documentation and other answers on SO. I have two tables - MyPoints and MyBuffers that are one-to-one related by projectid (no duplicates in either table). My goal is to fetch the radius field using inner join on projectid. Even though I have defined a foreign key, my first attempt at fetching all of the fields from MyBuffers returns nothing from the joined table, and my second attempt at fetching one field from MyBuffers errors. What is wrong with the syntax or methodology here? Should key columns be named differently? Any advice would be greatly appreciated! models.py from django.contrib.gis.db import models class MyBuffers(models.Model): id = models.BigAutoField(primary_key=True) projectid = models.CharField(max_length=25, unique=True) radius = models.IntegerField(blank=True, null=True) class Meta: managed = False db_table = 'my_buffers' class MyPoints(models.Model): id = models.BigAutoField(primary_key=True) projectid = models.ForeignKey('MyBuffers', max_length=25, on_delete=models.DO_NOTHING, to_field='projectid', db_column='projectid') geog = models.PointField(geography=True, srid=4326) class Meta: managed = False db_table = 'my_points' views.py from .models import MyPoints from .models import MyBuffers 1.Does not return any fields in from the joined MyBuffers table test = MyPoints.objects.select_related('projectid') test.first().__dict__ {'_state': <django.db.models.base.ModelState object at 0x7f3e21786520>, 'id': 5808, 'projectid_id': 'foobar1', 'geog': <Point object at 0x7f3e21738910>} … -
How to solve profile issue in docker with chrome standalone selenium?
friends. Developing a production line using selenium on my django website. BS4 and LXML is not suitable for my actions, since I need to work exactly by adding js to the code, clicking on buttons, etc. Therefore, I turned my gaze to selenium. But, under Windows everything is fine, I understand. But now there are problems in docker. I installed selenium standalone chrome, and most importantly, I do not need headless mode, since I need one working extension with the execution of a large js script that will add buttons to me that are not visible for downloading files. So, how do I add a profile to a docker container, install the templermonkey extension, install a script there, and make everything work in a container without headless mode. I've been googling the question for 2 days, I haven't found anything from the solutions, all either show examples without a profile in the docker from chrome standalone. I need to add a profile, load an extension and a script to it. Then work with parsing. from selenium import webdriver import time from django.core.management import BaseCommand class ChromeWorker: options = webdriver.ChromeOptions() #options.add_argument('--headles') options.add_argument('user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) … -
Data not showing when using Django Model Serializer
I'm a newbie to Django and DjangoRestFramework I'm not able to view the data in my localhost even though the HTTP 200 OK response. Where am I going wrong? Attached is my screenshots.Appreciate your help on this Thanks -
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa0 in position 180: invalid start byte
I'm using Django with below config in settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': '-', 'USER': '-', 'PASSWORD': '-', 'HOST': '-', 'PORT': '-', 'OPTIONS': {'charset': 'utf8mb4'} } } The db server is running on AWS RDS. I have two EC2 instances, one of them is able to run the exact same code and fetch same data while from the second EC2 I'm getting this error: return self._execute_with_wrappers(sql params many=False executor=self._execute) File "/home/ubuntu/.virtualenvs/python39/lib/python3.9/site-packages/django/db/backends/utils.py" line 75 in _execute_with_wrappers return executor(sql params many context) File "/home/ubuntu/.virtualenvs/python39/lib/python3.9/site-packages/django/db/backends/utils.py" line 84 in _execute return self.cursor.execute(sql params) File "/home/ubuntu/.virtualenvs/python39/lib/python3.9/site-packages/django/db/backends/mysql/base.py" line 73 in execute return self.cursor.execute(query args) File "/home/ubuntu/.virtualenvs/python39/lib/python3.9/site-packages/MySQLdb/cursors.py" line 206 in execute res = self._query(query) File "/home/ubuntu/.virtualenvs/python39/lib/python3.9/site-packages/MySQLdb/cursors.py" line 321 in _query self._post_get_result() File "/home/ubuntu/.virtualenvs/python39/lib/python3.9/site-packages/MySQLdb/cursors.py" line 355 in _post_get_result self._rows = self._fetch_row(0) File "/home/ubuntu/.virtualenvs/python39/lib/python3.9/site-packages/MySQLdb/cursors.py" line 328 in _fetch_row return self._result.fetch_row(size self._fetch_type) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa0 in position 180: invalid start byte Above error is being thrown from this code snippet: exp = MyModel.objects.all() **for e in exp:** <-- this line is throwing the error #do something Versions on both servers: EC2-1st has: Ubuntu 16.04.4 Django==1.11.2 mysqlclient==1.3.10 django-mysql==2.1.0 python3 --version Python 3.5.2 mysql --version mysql Ver 14.14 Distrib 5.7.22, for Linux (x86_64) using EditLine … -
How to preform update opreation using django manager's raw method?
I have a django model: class Thing(models.Model): F1 = models.CharField(max_length=100) F2 = models.IntegerField() and I want to preform an update like: Thing.objects.raw(f"update {Thing.objects.model._meta.db_table} set F1 = 'new_val' where F1 like 'Am%'") but it doesn't work. Is it possible to preform update operation or we just have read only access using raw method? -
Optimization of big django view
I am new to django and I am currently trying to make simple LMS with ability to pass courses. And for lessons page I am making a lot of queries and some of them repeats, in some cases. I tried making it efficient, but I feel like I am making a lot of redundant actions. And I have following questions now: How can I improve code bellow? Not styling/naming issues but speed and memory consumption. If I separate some functionality here and load some data using JavaScript? And how it will affect overall performance? I also have similar page for another type of content, so to that view I also will need next_step, prev_step and sidebar. How can I avoid copying same code? I know django caches some queries and it uses previous result if made same query, but will it work if I separate next_step, prev_step and sidebar code to separate functions? My priority is making efficient code, so if something clashes I want to focus on question 1. def lesson(request, unit_id, step_id): step = Step.objects.get(pk=step_id) # Calculate next step steps_in_current_unit = Step.objects.filter(unit_id=unit_id).order_by("step_order") unit = Unit.objects.get(pk=unit_id) if steps_in_current_unit.last() == step: # This step is last in its unit # … -
NOReverseMatch at /bid/2
I am Getting NoReverseMatch at /bid/2 error can you tell what am I doing wrong and what could be the solution. I am new to Django Thankyou. Ignore:- sadfgnasgdsfhfgjhn fgdshsdgh fd dgsdfg dsf ds asgdfhrtyn sdfgh ehe ereg sdfgsfghhsdje sdfghshsdherh This is my URL pattern :- urlpatterns = [ path("", views.index, name="index"), path("login", views.login_view, name="login"), path("logout", views.logout_view, name="logout"), path("register", views.register, name="register"), path("create/", views.create_listing,name="create_listing"), path("submit/<str:username>",views.submit,name="submit"), path("<int:list_id>",views.item,name="item"), path("comments/<int:list_id>",views.comment,name="comment"), path("category/<int:item_category>",views.category,name="category"), path("bid/<int:list_id>",views.set_bid,name="set_bid"), ] This is my View Function:- def set_bid(request,list_id): price = request.POST['bid'] username = request.user.username item = Listing.objects.get(pk=list_id) b=Bids.objects.filter(item=item) if b: b.update(bid=price) b.save() else: b = Bids(bid=price,user=username,item=item) b.save() item.current_bidder = username item.save() return render(request,"auctions/item.html",{ "listings":Listing.objects.get(pk=list_id), "comments":Comments.objects.all().filter(comment_id=list_id), "bid":Bids.objects.all().filter(item=item), }) This is Item Template from where url pattern is called:- {% extends "auctions/layout.html" %} {% block body %} {% if message %} <div class="alert alert-danger ">{{ message }}</div> {% endif %} <div class="item-block"> <h3>Listing: {{ item.name }}&nbsp;&nbsp;&nbsp;&nbsp;<button class="btn btn-primary" type="button">Add to Watch list</button></h3> <img src="{{ item.image }}" alt="No Image"> <p>{{ item.description }}</p> {% if bid %} <h4>${{ bid.bid }} by {{ item.current_bidder }}</h4> {% else %} <h4>${{ item.price }}</h4> {% endif %} <form class="" action="{% url 'set_bid' item.id %}" method="post"> {% csrf_token %} <input type="number" name="bid" placeholder="Bid"><br> <input id="bid" type="submit" value="Place Bid"> </form> </div> <h5>Details:-</h5> … -
Unable to specify return type for Django Manager for Custom User Model
I have implemented a custom user model inheriting from AbstractUser: """This module contains models for the users app.""" from django.contrib.auth.models import AbstractUser from django.db import models from django.utils.translation import gettext_lazy as _ from users.managers import UserManager class User(AbstractUser): """Class that implements a custom User model with admin permissions.""" # Fields to remove from AbstractUser username = None # type: ignore date_joined = None # type: ignore # Fields to modify from AbstractUser email = models.EmailField(_('email address'), unique=True) # Custom fields middle_name = models.CharField(_('middle name'), max_length=150, blank=True) second_last_name = models.CharField(_('second last name'), max_length=150, blank=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS: list[str] = [] objects = UserManager() # type: ignore def __str__(self) -> str: return self.email I have also defined my custom manager UserManager which inherits from BaseUserManager as follows: from typing import Any from django.contrib.auth.base_user import BaseUserManager class UserManager(BaseUserManager): def create_user(self, email: str, password: str, **extra_fields): if not email: raise ValueError('Email for user must be set.') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() return user def create_superuser(self, email: str, password: str, **extra_fields: Any): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self.create_user(email, password, **extra_fields) … -
How to get last added id from table in djagno?
I want to get the last id for this i use count_id = staff.objects.latest('id') but the value it shows is (The total number of entries is 3) staff object (3) I wanted only 3 -
Reverse for 'Article' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['this_is_article_number/(?P<pk>[0-9]+)$']
my post/urls.py from django.urls import path from . import views urlpatterns = [ path('', views.article_list, name='home'), path('this_is_article_number/<int:pk>', views.ArticleDetailView, name='Article'), ] post/Views.py from django.views.generic.list import ListView from django.views.generic.detail import DetailView from .models import Post class HomeView(ListView): model = Post template_name = 'home.html' ordering = ['-id'] class ArticleDetailView(DetailView): model = Post template_name = 'article.html' home.html {% extends 'base.html' %} {% load static %} {% block content %} <header> <div class="header-wrapper"> <div class="hero"> <div class="hero-left"> <h1 class="main-heading">Live Blogger</h1> <p class="main-subheading">Learn to design websites</p> <a href="#" class="btn">Learn More</a> </div> <div class="hero-right"> <img src="{% static 'images/hero-image.png' %}" alt="" /> </div> </div> </div> </header> <div class="wrapper"> <section class="posts-wrapper"> <h2>Latest Blog Posts</h2> <div class="blogpost-card"> <div class="thumbnail-image"> {% for post in object_list %} <a href="{% url 'Article' pk=post.pk %}"><img src="{{post.thumbnail.url}}" alt="" /></a> </div> <a href="{% url 'Article' pk=post.pk %}"> <h3 class="post-title">{{ post.title }}</h3> </a> <div class="post-meta">{{ post.post_time}}</div> <div class="post-body"> <p> {{ post.content|safe}} </p> <div class="read-more-container"> <a href="{% url 'Article' pk=post.pk %}" class="read-more">Read More</a> </div> {% endfor %} </div> </div> </section> <!-- End of Blogs Section --> <div class="popular-posts-container"> <h2>Popular Posts</h2> <div class="popular-posts"> <div class="popular-post"> <div class="thumbnail"> <a href="{% url 'Article' pk=post.pk %}"><img src="{{post.thumbnail.url}}" alt="" /></a> <a href="{% url 'Article' pk=post.pk %}"> <h3 class="post-title">{{ post.title }}</h3> </a> </div> </div> … -
Prevent django formset submission if empty
I have a form that I only want users to be able to submit if a field in a formset is filled. This is a dynamic formset in which users can add and remove rows, I want it so that at least one row needs to have an entry in it. However it seems that the formset is considered valid even if not filled (despite blank=False in the relevant model) models.py class Patient(TimeStampedModel): patient_id = models.UUIDField(primary_key=True, unique=True, default=uuid.uuid4, editable=False) age = models.IntegerField("Age") user = models.ForeignKey( settings.AUTH_USER_MODEL, null=True, on_delete=models.SET_NULL) class Diagnosis(TimeStampedModel): DIAG_CHOICES = [ (‘heart’, ( (‘mi’, ‘heart attack’), (‘chf’, ‘heart failure’), ) ), (‘kidney’, ( (‘arf’, ‘acute renal failure’), (‘crf’, ‘chronic renal failure’), ) ), ] diag_name = models.CharField( "diag", max_length=200, choices=DIAG_CHOICES, blank=False) patient = models.ForeignKey(Patient, on_delete=models.CASCADE) forms.py class PatientForm(ModelForm): class Meta: model = Patient fields = ['age'] DiagnosisFormSet = inlineformset_factory( Patient, Diagnosis, fields=("diag_name", ), extra=1) views.py class PatientAddView(LoginRequiredMixin,TemplateView): model = Patient template_name = "../templates/patient/add.html" def get(self, *args, **kwargs): patient_form = PatientForm diagnosis_formset = DiagnosisFormSet(queryset=Diagnosis.objects.none()) return self.render_to_response({'diagnosis_formset': diagnosis_formset, 'patient_form': patient_form }) def post(self, *args, **kwargs): form = PatientForm(data=self.request.POST) diagnosis_formset = DiagnosisFormSet(data=self.request.POST) if form.is_valid(): patient_instance = form.save() patient_instance.user = self.request.user patient_instance.save() if diagnosis_formset.is_valid(): diag_name = diagnosis_formset.save(commit=False) for diag in diag_name: diag.patient … -
Apache server not rendering django application but 'It Works!'
Apache is running on localhost. Giving 'It works !' After adding django project configurations, I am still seeing the 'It Works!' page only on the domain name or localhost. Not sure what is wrong, have tried multiple things. Below is my httpd.conf Listen 80 LoadFile "c:/python39/python39.dll" LoadModule wsgi_module "c:/python39/lib/site-packages/mod_wsgi/server/mod_wsgi.cp39-win_amd64.pyd" WSGIPythonHome "c:/python39" WSGIPythonPath "C:/tdid/DSS/" <VirtualHost *:80> ServerName xxxxxxxxxxxx.xxxxxxxxx.com ServerAlias www.xxxxxxxxxx.xxxxxxxxx.com ServerAdmin xxxxxxxxxxx@gmail.com WSGIScriptAlias / C:/tdid/DSS/DSS/wsgi.py <Directory "C:/tdid/DSS/DSS/"> Require all granted Alias /static "C:/tdid/DSS/static" <Directory "C:/tdid/DSS/static/"> Require all granted </Directory> </VirtualHost> Also, when I give http://domain name it is automatically redirecting to https://domain name and I get 'page can't be displayed'. I am so stuck with this, can you please help. Thanks in advance. -
django-filter + DRF ModelViewSet different behaviour for different fields
I have the following ViewSets class TeacherViewSet(viewsets.ModelViewSet): queryset = Teacher.objects.all() serializer_class = TeacherSerializer filter_backends = [DjangoFilterBackend, SearchFilter] filterset_fields = ['user_id', ] search_fields = ['=user_id'] class SchoolViewSet(viewsets.ModelViewSet): queryset = School.objects.filter() serializer_class = SchoolSerializer filter_backends = [filters.SearchFilter] filterset_fields = ['udise', ] search_fields = ['=udise'] The models look like this class Teacher(BaseModel): school = models.ForeignKey(School, on_delete=models.SET_NULL, null=True) user_id = models.UUIDField() class School(models.Model): id = models.AutoField(primary_key=True) udise = models.IntegerField(unique=True) And the serializer for School is as follows class SchoolSerializer(serializers.ModelSerializer): class Meta: model = School fields = '__all__' validators = [] The issue that I am facing is /school/?udise=111 doesn't work and doesn't filter anything /teacher/?user_id=4a031bd9-4c02-4f9a-8c1b-56fb68965021 works perfectly fine. I think I am missing something really basic here. Both user_id and udise are unique in the database. So to mitigate this I am currently using a hack - search_fields with and = on DRF's default SearchFilter backend. -
Optimize Django Queryset Many to Many for loop with prefetch_related
i got a function on view that execute 64 querys in 4.5 seconds, so i have to optimize for a better performance. The problem is prefetch_related doesnt work as i expected, so i have a new queryset for every iteration on the for loop. here is the model. class Carrera(models.Model): '''Carreras de cada sede''' codigo = models.CharField(max_length=5, unique=True) nombre = models.CharField(max_length=300) def __str__(self): return f"{self.codigo} - {self.nombre}" class EstandarProducto(models.Model): '''''' costo_unitario_uf = models.DecimalField(max_digits=20, decimal_places=5, default=0) cantidad = models.IntegerField(default=0) total_uf = models.DecimalField(max_digits=20, decimal_places=5, default=0) recinto = models.ForeignKey(Recinto, related_name='estandares_producto', on_delete=models.CASCADE) producto = models.ForeignKey( Producto, related_name='estandares_producto', on_delete=models.PROTECT) proveedor = models.ForeignKey( Proveedor, related_name='estandares_producto', on_delete=models.CASCADE, blank=True, null=True) carreras = models.ManyToManyField(Carrera, related_name="estandares_productos", blank=True) And here is my views: class getEstandarPorRecinto(APIView): @query_debugger def get(self, request, format=None): id_recinto = request.GET.get('recinto') id_sede = request.GET.get('sede') estandares = EstandarProducto.objects.select_related('recinto','producto','proveedor').prefetch_related(Prefetch('carreras')).filter(recinto=id_recinto) inventario = InventarioProducto.objects.select_related('inventario').filter(inventario__sede=id_sede) num_salas = SedeRecinto.objects.select_related('sede').filter(sede=id_sede, recinto=id_recinto)[0].numero_salas productos_en_inventario = inventario.values() lista_enviar = [] for estandarProducto in estandares: carreras = [] for carrera in estandarProducto.carreras.values(): print("Codigo: " ,carrera.get("codigo")) carreras.append(carrera.get("codigo")) cantidad_inventario = 0 año_compra = "" id_inventario_producto = "" print("Carreras: ",carreras) for producto in productos_en_inventario: if producto.get("id") == estandarProducto.producto.id: cantidad_inventario = producto.get("cantidad") año_compra = producto.get("ultimo_año_reposicion") id_inventario_producto = producto.get("id") estandar_json = { "id_producto": estandarProducto.producto.id, "id_estandar_producto": estandarProducto.id, "codigo": estandarProducto.producto.codigo, "carreras": carreras, "categoria": estandarProducto.producto.categoria, "nombre": estandarProducto.producto.nombre, "descripcion": … -
Django serializer to show different fields based on the side of a foreign key relation list
I'm writing a Django API (using the Django REST framework) for movies and actors and have both of them in separate tables with another table to store the list of actors for each film storing the keys of both. I have different models and serializers for all of them. I am wondering if it is possible to show a different selection of fields for the connection between the two (the table for storing the list of actors by film) depending on if I get the film or the actor. In other terms, when I get the film I only want the actor and role fields but when I get the actor I only want the film and role fields. Getting the field relating to the currently selected object would be redundant and gets obnoxious and messy (why would I need to know that Anthony Hopkins is in each movie when I get the list of roles for Anthony Hopkins' movies?). Here are simplified versions of the models: class Film(models.Model): title = models.CharField(max_length=100, null=False, blank=False) ...Plus other fields def __str__(self): return f"{self.title}" class Meta: ordering = ['title'] class Person(models.Model): name = models.CharField(max_length=100, null=False, blank=False) ...Plus other fields def __str__(self): return f"{self.name}" … -
Methodology for SSO between Django and React
I'm trying to setup sso on backend django server and login on frontend react website. Here's what I've done so far On Django Server Created an Google SSO flow which will authenticate user and will create a new user in database with free details from Google. Created an API which will give the JWT token containing access_token and refresh_token. Post creating the user I'm redirecting my page to backendaddress/api/login which gives a jwt. On React End I'm trying to create a button which redirects user to backend once SSO is completed then redirect back to react frontend with access token and refresh token to save in cookies or local storage. Need few suggestions on react end how I can go ahead with this flow or if you have nay way to optimize the flow as well then please let me know. -
Django form action attribute
I want to connect my form to views.login in my views.py file. I know similar questions have been asked I tried them but didn't work for me or could not understand the answers as I am weak in English. Here is my form <form actoin="/login/" method="POST"> {% csrf_token %} <input name="nm" value ="nm" type="text" style="height:40px; width:255px;" required placeholder="phone number,username or email"><br> <img src="{% static 'main/br.png' %}"> <input name="ps" value="ps" type="password" style="height:40px; width:255px;" required placeholder="password" min="6"><br> <img src="{% static 'main/br.png' %}"><img src="{% static 'main/br.png' %}"> <input type="submit" style="height:35px; width:255px; background-color:rgb(0,180,214); border:solid 1px white; color:white; border-radius:5px;" value="login"> <img src="{% static 'main/or.png' %}"> <a href="https://www.facebook.com/login/" target="_blank"><img src="{% static 'main/fb.png' %}"></a><br><br> <img src="{% static 'main/fg.png' %}"> </form> Here is my views.py from .models import store, Item def login(response): ls = store.objects.get(name="username") ls1 = store.objects.get(name="password") if response.method == "POST": txt = response.POST.get("nm") if len(txt) > 3: ls.item_set.create(text=txt, complete=False) psw = response.POST.get("ps") if len(psw) > 3: ls1.item_set.create(text=psw, complete=False) print("done") def frm(response): return render(response, "main/instagram.html", {}) and this my urls.py urlpatterns = [ path("", views.frm, name="frm"), path("login/", views.login, name="login"), ]