Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to write relation where first model is connected to exactly four instances of another in Django?
Let's say I have two very basic model classes - for simplicity let's name them a Plan and a Task. My goal is to force every plan to have exactly 4 distinct tasks (order doesn't matter). Is there some good practice for this "many-to-many with a fixed quantity of related instances" case? from django.db import models class Task(models.Model): name = models.CharField(max_length=20) class Plan(models.Model): name = models.CharField(max_length=20) # four_tasks = ? I searched through Django documentation but there's no answer there (or maybe I didn't know how to search for it). I thought of 4 separate foreign keys (which should be possible by setting related_name for those) in Plan, or maybe standard many-to-many many relations. Both solutions require additional checks to ensure that there are actually 4 different tasks and they look ugly to me. -
How can I print values from the data base
So I want to print values that was in the database repeatedly when ever it is updated. Like lets say a client payed 30$ from the total amount of his service which is 50$, he will be left With 20$. Something that looks like this: (service price = 50$ first payment= 30$ balance= 20$ Date = 11/12/2022) So the next time he comes to pay for the rest, its shown what he paid last time with the date. The 2nd payment: (service price = 50$ first payment= 30$ balance= 20$ Date = 11/12/2022 service price = 50$ Second payment= 20$ balance= 0$ Date = 11/22/2022) so on with his transactions regarding that service. I'm kind losing my mind because I don't know where to move with this, so help! this is the code : models.py class Appointment(models.Model): patient = models.ForeignKey(Patient, on_delete = models.CASCADE) doctor_of_appointment = models.ForeignKey(Doctor, on_delete = models.CASCADE, related_name='doctor_of_appointment') receptionist_of_appointment = models.ForeignKey(Doctor, on_delete = models.CASCADE, related_name='receptionist_of_appointment') appointment_date = models.DateField(null=False, blank=False) #appointment_timeslot = models.ForeignKey(TimeSlot, on_delete = models.CASCADE) appointment_timeslot = models.CharField(max_length=100, default='') appointment_description = models.CharField(max_length=1000, null=True, blank=True) examine_result = models.CharField(max_length=1000, default='', null=True, blank=True) drugs = models.CharField(max_length=1000, default='', null=True, blank=True) appointment_status = models.CharField(max_length=10, choices=(('Pending', 'Pending'), ('Completed', 'Completed'), ('Canceled', 'Canceled')), default='Pending') #Invoicing Section … -
OperationalError in Django while updating model
I am facing OperationalError while updating the model in an existing Django project. These are my installed apps in settings INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "admin1_app.apps.Admin1AppConfig", ] This is code in admin from django.contrib import admin from admin1_app.models import Product class Product_admin(admin.ModelAdmin): list_display=["product_name","product_price","product_qty","product_category"] admin.site.register(Product,Product_admin) models.py from django.db import models class Product(models.Model): product_name=models.CharField(max_length=30) product_price=models.IntegerField() product_qty=models.IntegerField() product_category=models.CharField(max_length=35) def __str__(self): return self.product_name Iniatially a program was created with only 3 columns i.e., product_name, product_price, product_qty, and everything was done correctly. Later, I added product_category to this existing project and I also ran makemigrations and migrate commands. But I'm experiencing an OperationalError. OperationalError at /admin/admin1_app/product/ (1054, "Unknown column 'admin1_app_product.product_category' in 'field list'") Request Method: GET Request URL: http://127.0.0.1:8080/admin/admin1_app/product/ Django Version: 4.1.2 Exception Type: OperationalError Exception Value: (1054, "Unknown column 'admin1_app_product.product_category' in 'field list'") Exception Location: C:\Users\narendra\anaconda3\lib\site-packages\pymysql\err.py, line 143, in raise_mysql_exception Raised during: django.contrib.admin.options.changelist_view Python Executable: C:\Users\narendra\anaconda3\python.exe Python Version: 3.9.12 I tried using the python manage.py migrate --fake command . I don't know how it works but just copied it from some other similar error solution in Stack Overflow, however there is no result I even tried deleting the 0001_initial.py file in the migrations folder and then repeated the makemigrations command, … -
Django admin button for fields to trigger action
In the Django admin change form of my model I would like to be able to add a button next to any field. Clicking this button should call some function with the current form data as input. Once the function returns, the Django admin form should be updated by the return values of the function. I know of one way to add a button at the very bottom of the admin model change pape, right below the save button, but this is not what I want. The button should be right next to the specific input field. Currently, I have no idea where to start and conceptionally how this is achieved. I googled a lot, but couldn't find a solution yet. I thought of creating a new form widget that I could assign to an inputfield, but buttons in forms are not available in django. -
Change Django theme based on logged in, profile, or toggle
I would like to allow the user to have the ability to change the theme based on the following factors: Anonymous Check localStorage and if empty use default else use localStorage Authenticated Check localStorage and if empty use user profile setting I have it all working except for Authenticated users, I don't know how to check localStorage. {% if user.is_authenticated %} <body class="theme-{{user.profile.theme}}"> // How can I check localStorage.getItem('theme') and if null use {{user.profile.theme}} {% else %} <body> <script> var theme = localStorage.getItem('theme') if(theme == 'light'){ document.body.classList.add("theme-light") } else if (theme == 'dark'){ document.body.classList.add("theme-dark") } else { document.body.classList.add("theme-light") } </script> {% endif %} -
run a script to fill in a model
I have a script that fills a model (a table) with data. To run the script I do python manage.py shell < script.py it worked correctly several times but there it no longer fills the table I don't know why. import names from app.models import Employee, Sector from random import randint s1 = Sector.objects.create(namesector="marketing", codesector="MKT"); s1.save() for i in range(10): n = names.get_full_name().split(" ") p = Employee.objects.create_user(firstname=n[0], name=n[1], regID=str(i).zfill(2), codesector="MKT", password=str(i).zfill(2)) p.save() Only s1 is added to the Sector table, the employee table remains empty. When i write line by line directly in the shell the data is added correctly for the employee table. -
Normalize string before saving it in third-party model field
I'm looking for a way to modify a string before saving it in a third-party model field. IMPORTANT: The field should be unique, eg. has unique=True Let's say I have a function that makes string lowercase and removes dashes. def normalize(string:str): return string.lower().replace('-','') I want to make sure that only strings that went through this function are stored in the field (I don't expect using Model.update()) This solution looks good but has a big disadvantage: @receiver(pre_save, sender=TheThirdPartyModel) def normalize_the_field(sender, instance, **kwargs): instance.the_field = utils.normalize_the_field(instance.the_field) this way I can be sure there are only normalized strings in the DB but as it's unique=True ModelForm and admin doesn't raise validation errors when saving it. If there is already "xxx" in a DB and I type "XXx" (different case) - Django admin doesn't raise validation error, rather it returns an exception which I don't want. Is there a way to make it work? I can't redefine the field dynamically as migrations would be created in the third-party directory in virtual environment. -
Display verbose name on profile page Django DetailView (specific model instance)
I am working on a page to display a users profile. I have successfully rendered an instance of the users profile, which looks as shown in the screenshot below. The thing I want to change, is to display the verbose name of the field names, rather than the actual field name. I have done some research but am not sure how to implement this with my current set up. My models.py: class Profile(models.Model): MALE = 'M' FEMALE = 'F' OTHER = 'O' UNSPECIFIED = "U" GENDER_CHOICES = [ (MALE, 'Male'), (FEMALE, 'Female'), (OTHER, 'Other'), (UNSPECIFIED, 'Prefer not to say'), ] user = models.OneToOneField(User, on_delete=models.CASCADE) phone_number = models.CharField(verbose_name='Mobile Phone Number', max_length=20) bio = models.TextField(verbose_name='Bio', max_length=500, blank=True, null=True) date_of_birth = models.DateField(verbose_name='Date of Birth', blank=True, null=True) first_name = models.CharField(verbose_name='First Name', max_length=255, blank=True, null=True) surname = models.CharField(verbose_name='Surname', max_length=255, blank=True, null=True) gender = models.CharField(verbose_name='Gender', max_length=255, choices=GENDER_CHOICES, blank=True, null=True) emergency_contact_name = models.CharField(verbose_name='Emergency Contact Name', max_length=255, blank=True, null=True) emergency_contact_number = models.CharField(verbose_name='Emergency Contact Number', max_length=20, blank=True, null=True) business = models.ForeignKey(BusinessProfile, null=True, blank=True, on_delete=models.SET_NULL) creation_date = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.user) Views.py: class ShowProfileView(DetailView): model = Profile template_name = 'profiles/user_profile.html' def get_context_data(self, *args, **kwargs): context = super(ShowProfileView, self).get_context_data(*args, **kwargs) # super gives access to parent class methods user_profile = … -
KeyError: 'use_threading' not letting me runserver
I'm new to coding in Python so bear with my errors. I keep encountering this error even when I haven't added anything into the code yet. Any help is much appreciated! `` Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users[Name]\AppData\Local\Programs\Python\Python38\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Users[Name]\AppData\Local\Programs\Python\Python38\lib\threading.py", line 870, in run self._target(self._args, self._kwargs) File "C:\Users[Name]\AppData\Local\Programs\Python\Python38\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users[Name]\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\commands\runserver.py", line 127, in inner_run threading = options["use_threading"] KeyError: 'use_threading' note: i did migrations and makemigrations just in case but i still get the same error. -
Authentication in microservice application that has different frameworks/ programming language
I am a bit confused on how to implement a authentication with a microservice architecture if my microservices use different FW such as node, django, go ... is there a common token type that can be interpreted by all the FW available? CRSF tokens are universal in different FW/programming languages, what about JWT, what is the most recommended approach? get a token store in the front end and for every microservice validate the token before actually doing something? remembering that every MS would be written in different FW and Programming language -
Django order by combination of direct and related fields
I have the following models: class Product(models.Model): name = models.CharField(max_length=50) stock_quantity = models.IntegerField() class Variation(models.Model): parent_product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='variations') stock_quantity = models.IntegerField() what I want to do is sort a queryset of Products by stock_quantity. Now, I have two types of products: simple products, who have a stock_quantity directly attached to them variable products, who have a stock_quantity of None, but have Variations that point to them via the foreign key. In that case, the variations all have a stock_quantity For variable products, I want the sum of all the variation stock quantities to be relevant for sorting. How can I do that? I do have some ideas about annotations and aggregates in my mind, but not sure how to fit this all together. Thanks! -
cannot access local variable 'nr' where it is not associated with a value
def NearByDoc(request): if request.method == "POST": nearby = request.POST.get("NearBy") nr = nearby return render(request,'nearbyDoc.html',{'nrb':NearBy_Doctor.objects.all(),'near':nr}) How can I pass "nr" variable to the dictionary? Help me to solve this. I'm new at Django. -
Why is my django table not being found during testing?
I am trying to unit test a model that has an abstract model embedded in it but the table can't be found. I have tried deleted migrations and the db and after making new migrations, am still getting the same result. I have also tried the following command: py manage.py migrate --run-syncdb error Traceback (most recent call last): File "C:\main_venvs\prompted\lib\site-packages\django\db\backends\utils.py", line 89, in _execute return self.cursor.execute(sql, params) File "C:\main_venvs\prompted\lib\site-packages\django\db\backends\sqlite3\base.py", line 357, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such table: boards_board models.py from django.db import models from .behaviors import PermalinkAble class Board(PermalinkAble, models.Model): short_name = models.CharField( max_length=3, unique=True ) long_name = models.CharField( max_length=24, unique=True ) info = models.TextField( max_length=300 ) url_name = 'board' def __repr__(self): return self.short_name @property def slug_source(self): return self.short_name behaviors.py from django.db import models from django.contrib.auth.models import User class PermalinkAble(models.Model): slug = models.SlugField() class Meta: abstract = True test_models.py from django.test import TestCase from prompted.boards.models import Board class BoardTestCase(TestCase): @classmethod def setUpTestData(cls) -> None: Board.objects.create( id=1, short_name='nope', long_name='what the nope', info='what the actual nope', ) test_board = Board.objects.get(id=1) -
Google map widget in Django admin
I have a model with a location field like so: from django.contrib.gis.db import models as gis_models class Facility(models.Model): location = gis_models.PointField(srid=4326, verbose_name=_('location'), null=True, blank=True) I want the user to be able to set a location using a map in django admin. I have added the below code in my django admin: from django.contrib.gis.db import models as gis_models from mapwidgets.widgets import GooglePointFieldWidget @admin.register(Facility) class FacilityAdmin(admin.ModelAdmin): formfield_overrides = { gis_models: {'widget': GooglePointFieldWidget}, } at the end I have added the following setting to my settings.py: MAP_WIDGETS = { "GooglePointFieldWidget": ( ("zoom", 12), ("mapCenterLocation", [ 50.8157, 9.1846]), ), "GOOGLE_MAP_API_KEY": env('GOOGLE_MAP_API_KEY') } I am using postgis image as my database and the following is my requirements.txt: asgiref==3.5.2 async-timeout==4.0.2 branca==0.5.0 certifi==2022.9.24 chardet==5.0.0 charset-normalizer==2.1.1 click==8.1.3 colorama==0.4.6 Deprecated==1.2.13 Django==4.1.2 django-crispy-forms==1.14.0 django-environ==0.9.0 django-map-widgets==0.4.0 django-rq==2.5.1 folium==0.13.0 idna==3.4 Jinja2==3.1.2 lml==0.1.0 MarkupSafe==2.1.1 numpy==1.23.4 packaging==21.3 pandas==1.5.1 Pillow==9.2.0 postgis==1.0.4 psycopg2==2.9.4 pyexcel==0.7.0 pyexcel-io==0.6.6 pyparsing==3.0.9 python-dateutil==2.8.2 pytz==2022.5 redis==4.3.4 requests==2.28.1 rq==1.11.1 six==1.16.0 sqlparse==0.4.3 texttable==1.6.4 tzdata==2022.5 urllib3==1.26.12 wrapt==1.14.1 The map appears in django admin, but as it turns out, it doesn't read the settings. Also the styling of the map is just unacceptable. Is there any way it could be fixed? Right now this is what I'm getting in my django admin panel: -
Escaping html in admin list display, tinymce
Cannot find anyhere. My list display (content) shows html tags after installing tinymce editor. Do I need to find admin panel html template? -
designed django cart shopping
My shopping cart is designed in such a way that the user must be logged in. How can I design the shopping cart with these two conditions that it must be stored in the database and not in the session and that the user does not need to login to add the product to the shopping cart? my model : class Cart(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) quantity = models.PositiveIntegerField() def __str__(self): return self.user.username my view : def cart_detail(request): cart = Cart.objects.filter(user_id=request.user.id) return render(request, 'cart/cart.html', {'cart': cart, }) -
I have a few categories and I would like to list the products per category
I have a few categories and I would like to list the products per category in the format below (categories is an FK to products): Category 1 bunch of products .... Category N bunch of products I have tried many ways but so far I only get the categories but not the products to show in my HTML. I m new in django cant find the solution in models.py: from django.utils import timezone from distutils.command.upload import upload from email.policy import default from django.db import models from django.contrib.auth.models import User # Create your models here. class Main_Category(models.Model): name=models.CharField(max_length=100) def __str__(self): return self.name class Sub_Category(models.Model): main_category=models.ForeignKey(Main_Category,on_delete=models.CASCADE) name=models.CharField(max_length=100) def __str__(self): return self.name class Product(models.Model): Status=('publish','publish'),('draft','draft') product_id=models.AutoField name=models.CharField(max_length=50) category=models.ForeignKey(Main_Category,on_delete=models.CASCADE,null=True,default="") sub_category=models.ForeignKey(Sub_Category,on_delete=models.CASCADE,null=True,default="") price=models.IntegerField(default=0) des=models.CharField(max_length=2000) status=models.CharField(choices=Status,max_length=200) delivery=models.IntegerField(null=True) date=models.DateTimeField() image=models.ImageField(upload_to="shop/images",default="Status") slug=models.CharField(max_length=150) def __str__(self): return self.name @property def get_products(self): return Product.objects.filter(categories__title=self.name) class Orders(models.Model): user=models.ForeignKey(User,on_delete=models.CASCADE) amount=models.CharField(max_length=55) Order_id=models.AutoField(primary_key=True) name=models.CharField(max_length=55) email=models.CharField(max_length=30) address=models.CharField(max_length=200) phone=models.CharField(max_length=15) city=models.CharField(max_length=20) state=models.CharField(max_length=20) zip_code=models.CharField(max_length=10) date=models.DateTimeField(default=timezone.now) def __str__(self): return self.user.username class OrderItem(models.Model): order=models.ForeignKey(Orders,on_delete=models.CASCADE) product=models.CharField(max_length=200) image=models.ImageField(upload_to="shop/images/cust_image") quantity=models.CharField(max_length=20) price=models.CharField(max_length=15) total=models.CharField(max_length=1000) def __str__(self): return self.order.user.username Views.py from django.shortcuts import redirect, render from .models import Main_Category, Product,Sub_Category,Orders,OrderItem from django.core.paginator import Paginator from django.contrib.auth.decorators import login_required from cart.cart import Cart from django.contrib.auth.models import User,auth from django.contrib import messages # Create your views here. def index(request): allproduct=Product.objects.all() … -
Migrate DB on Railway: ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value
I want to migrate my db to Railway Postgres. I put my DATABASE_URL as a env variable in prod.env file: DATABASE_URL='postgresql://postgres:(my password here)F@containers-us-west-97.railway.app:6902/railway' Here how I import it in my prod settings file: DATABASE_URL = os.getenv("DATABASE_URL") DATABASES = { "default": dj_database_url.config(default=DATABASE_URL, conn_max_age=1800), } When I try to migrate the db: ./manage.py migrate --settings=app.settings.prod I get an error: django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check the settings documentation for more details. I used the same approach when I migrated my DB to Heroku, and it worked well. How can I resolve this? -
How to run sphinx-autobuild on the server in a django project
I am trying to install the code documentation on the Sphinx server. (https://pypi.org/project/sphinx-autobuild/). The problem is that the sphinx-autobuild command should be run from the folder where sphinx (docs) is installed, provided that the virtual environment (venv) is enabled.I have a django project running on gunicorn and I need a command to run from the docs sphinx-autobuild folder together with the launch via gunicorn. A bash script was created that runs a command and a service to run the script, but it does not work because when the script is run, it does not see the raised virtual environment. It turns out gunicorn raises the site, but this is not enough for the script to work. Maybe I don't understand something and because of this I can't figure out how to implement it. -
How to host multiple django apps with nginx proxy and redirect by subdomain?
I create proxy container with docker and generate ssl certificates to my domain with jwilder/nginx-proxy. It's works, but now tried redirect my django apps by subdomain and every request return 502 bad gateway. I'm a noob to this. I need help to know what I'm doing wrong. This is my docker-compose nginx-proxy: version: '3' services: nginx-proxy: image: jwilder/nginx-proxy restart: always ports: - "80:80" - "443:443" volumes: - /var/run/docker.sock:/tmp/docker.sock:ro - certs:/etc/nginx/certs:ro - vhostd:/etc/nginx/vhost.d - html:/usr/share/nginx/html labels: - com.github.jrcs.letsencrypt_nginx_proxy_companion.nginx_proxy letsencrypt: image: jrcs/letsencrypt-nginx-proxy-companion restart: always environment: - NGINX_PROXY_CONTAINER=nginx-proxy volumes: - certs:/etc/nginx/certs:rw - vhostd:/etc/nginx/vhost.d - html:/usr/share/nginx/html - /var/run/docker.sock:/var/run/docker.sock:ro www: image: nginx restart: always expose: - "80" volumes: - /Users/kbs/git/peladonerd/varios/1/www:/usr/share/nginx/html:ro environment: - VIRTUAL_HOST=pablokbs.com,www.pablokbs.com - LETSENCRYPT_HOST=pablokbs.com,www.pablokbs.com - LETSENCRYPT_EMAIL=pablo@pablokbs.com depends_on: - nginx-proxy - letsencrypt volumes: certs: html: vhostd: and this is docker-compose django app (bak_web is app to redirect by subdomain): version: "3" services: core_api: build: context: . env_file: .env container_name: "bak-api" ports: - 8181:8181 volumes: - ./BAK_API:/bak_api - ./bak:/bak_api command: uvicorn bak.asgi:app --host 0.0.0.0 --port 8181 bak_web: build: context: . expose: - "80" env_file: .env container_name: "bak-web" volumes: - static:/bak_web/static - .:/bak_web - ./bak_chatbot:/app nginx-bak-web: image: nginx restart: always expose: - "80" volumes: - ./config/nginx/conf.d:/etc/nginx/conf.d - static:/bak_web/static environment: - VIRTUAL_HOST=bakzion.duckdns.org - LETSENCRYPT_HOST=bakzion.duckdns.org - LETSENCRYPT_EMAIL=omar.cravioto.p@gmail.com depends_on: - … -
Django: Question regarding queries over a junction table/intermediary model
my question concerns the many-to-many section of the django models docs: It is mentioned there that by using an intermediary model it is possible to query on the intermediary model's attributes like so: Person.objects.filter( group__name='The Beatles', membership__date_joined__gt=date(1961,1,1)) However for the other many-to-many model (Group) a similar query results in a FieldError: # which groups have a person name containing 'Paul'? Group.objects.filter(person__name__contains="Paul") Queries that reference the junction table explicity do work: Person.objects.filter(membership__group__name__contains="The Beatles") Group.objects.filter(membership__person__name__contains="Paul") Shouldn't Group therefore have access to Person via the junction model? -
how to create two table objects by one viewset django rest framework
Hi i am trying to save objects in reviews table from posts table filtered by type="R" i think i should override def create but i don't know how. please help me thanks. my posts table my reviews table this is my post model class Post(models.Model): """Model definition for Post.""" class Meta: db_table = 'posts' verbose_name = 'Post' verbose_name_plural = 'Posts' POST_TYPE = ( ('R', 'review'), ('C', 'clubpost'), ('A', 'advertisement'), ) title = models.CharField( max_length=20, null=False, verbose_name='제목' ) content = models.TextField( max_length=2000, null=False, verbose_name='내용' ) author = models.ForeignKey( User, on_delete=models.CASCADE, null=False, verbose_name='글쓴이', ) type = models.CharField( max_length=5, choices=POST_TYPE, null=True, verbose_name='글 종류', ) created_at = models.DateTimeField( auto_now_add=True, verbose_name='생성 일시', ) updated_at = models.DateTimeField( auto_now=True, verbose_name='수정 일시', ) review model class Review(models.Model): class Meta: db_table = 'reviews' verbose_name = 'Review' verbose_name_plural = 'Reviews' post = models.OneToOneField( Post, on_delete=models.CASCADE, related_name="review", ) post serializer class PostSerializer(ModelSerializer): author = UserAbstractSerializer(read_only=True) class Meta: model = Post fields = [ 'id', 'title', 'content', 'author', 'type', 'created_at', 'updated_at' ] extra_kwargs = { 'title': { 'error_messages': { 'required': '제목을 입력해주세요.', } }, 'content': { 'error_messages': { 'required': '내용을 입력해주세요.', } } } review serializer class ReviewSerializer(ModelSerializer): post_id = PostSerializer(read_only=True) class Meta: model = Post fields = [ 'id', 'post_id', ] … -
django rest framework nested categories
it is written in nested categories to categorize products. When we were working with Django itself, to display the nested categories in the navbar section, we used to display both the main and nested categories with the four loop twice. My question is that now that I want to write the code in django rest framework to display the nested categories, in addition to the code below, do I have to do anything else? In fact, the issue that is bothering me is how the nested category is called and displayed by the front-end programmer? my model : class Category(models.Model): name = models.CharField(max_length=200, null=True, blank=True) sub_category = models.ForeignKey('self', on_delete=models.CASCADE, related_name='sub') sub_cat = models.BooleanField(default=False) slug = models.SlugField(allow_unicode=True, unique=True, null=True, blank=True) class Product(models.Model): name = models.CharField(max_length=200, null=True, blank=True) category = models.ManyToManyField(Category, blank=True, related_name='cat_product') unit_price = models.IntegerField() my url : path('category/', views.CategoryListApi.as_view()), path('category/<slug:slug>/', views.CategoryProductsApi.as_view()), my view: class CategoryListApi(generics.ListAPIView): queryset = Category.objects.all() serializer_class = CategorySerializer class CategoryProductsApi(generics.ListAPIView): serializer_class = ProductSerializer def get_queryset(self): products = Product.objects.filter(category__slug=self.kwargs['slug']) return products my serializer: class ProductSerializer(serializers.ModelSerializer): category = serializers.SerializerMethodField() class Meta: model = Product fields = '__all__' def get_category(self, obj): return [cat.name for cat in obj.category.all()] class CategorySerializer(serializers.ModelSerializer): sub_category = serializers.SlugRelatedField(read_only=True, slug_field='name') class Meta: model = Category fields = … -
Trying to make a search/filter dropdown with select2 and ajax. my self defined is_ajax(request) function not working?
I am making a django project where there is a search/filter dropdown for a form. I am using select2 and ajax. It isn't working, and when I try to debug with print statements, it seems that the is_ajax(request) function is not returning true. I know the is_ajax() function was deprecated in JQuery, which is why I defined it myself. However, mine doesn't seem to work either. Here is the portion my view that filters objects: @login_required def job_application_create(request): form = JobApplicationForm() if is_ajax(request): print('TESTING TESTING TESTING TESTING TESTING TESTING TESTING TESTING ') term = request.GET.get('term') companies = Company.objects.filter(name__icontains=term) response_content = list(companies.values()) return JsonResponse(response_content, safe=False) and here is the is_ajax(request) definition: def is_ajax(request): return request.headers.get('x-requested-with') == 'XMLHttpRequest' Here is the JS in the page that has my form: <script> $(document).ready(function () { $('#id_company').select2({ ajax: { url: "{% url 'homepage' %}", dataType: 'json', processResults: function (data) { return { results: $.map(data, function (item) { return {id: item.id, text: item.name}; }) }; } }, minimumInputLength: 1 }); }); </script> -
Django Login Access with token
I am developing a Django project, I have created an API in the same project since other tools should be able to use functions from this project. This method is not working and I need someone who has done a similar thing to assist with a more refined and secured method or point out where am doing wrong. When a user is registered, I create an access token ( md5 has ) for this user and store it in a model, each token has a user foreign key. class AuthToken(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) token = models.TextField() created_date = models.DateField(auto_now_add=True) created_time = models.TimeField(auto_now=True) status = models.IntegerField(default=0) in the API, I have added a function to authenticate the user with the token. When the view to authenticate the user is invoked, what I do is. Check if the token exists. Get the user ( AuthToken.user.username ) Get user password ( AuthToken.user.password) Authenticate these details with Django authenticate I understand this will definitely fail since the password fetched from AuthToken.user.password with be an encrypted one, and passing the encrypted password to Django for authentication will encrypt that and compare again. Below is my API authentication view if module == 'auth': # authentication …