Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I can't using dynmaic loop in my django project
The problem is: The joined path (S:\cdnjs.cloudflare.com\ajax\libs\Swiper\6.4.8\swiper-bundle.min.js) is located outside of the base path component (C:\My projects - python\My_django_application\Myproject\static), i have many like this error. enter image description here I can return 4 pictures, I can also more.for example if i would return in my views, 'movies1': Movies_obj[:5], it's will show a 5 movies in home page. I uploaded 12 movies through the admin. As you can see in the link to the image, after I log in, the images appear to me, I have added Next and Previous buttons, but I can not use the loop. I worked with Boostrap Studio in the first part, to import photos and design. I tried to change things in settings, I tried almost everything, I could not use it. This is my first big project. My home HTML: </div> <div class="article-clean"></div> <script src="{% static 'MainHome/HeaderFooter/assets/bootstrap/js/bootstrap.min.js' %}"></script> <script src="{% static 'MainHome/HeaderFooter/assets/js/bs-init.js' %}"></script> <script src="{% static 'MainHome/HeaderFooter/https://cdnjs.cloudflare.com/ajax/libs/baguettebox.js/1.11.1/baguetteBox.min.js' %}"></script> <script src="{% static 'MainHome/HeaderFooter/assets/js/Simple-Slider.js' %}"></script> <script src="{% static 'MainHome/HeaderFooter/https://cdnjs.cloudflare.com/ajax/libs/Swiper/6.4.8/swiper-bundle.min.js' %}"></script> <script src="{% static 'MainHome/HeaderFooter/assets/js/Lightbox-Gallery.js' %}"></script> <script src="{% static 'MainHome/HeaderFooter/assets/js/Simple-Slider-1.js' %}"></script> <script src="{% static 'MainHome/HeaderFooter/assets/js/Swipe-Slider-7.js' %}"></script> </div> <div id ="carouselExampleControls" class="carousel slide" data-ride="carousel"> <div class="carousel-inner"> <div class="carousel-item active"> <div class="row"> {% for mv1 in movies1 %} <div … -
NGINX: Block all external IPs except the server IP where ReactJS is hosted?
Can anyone help how to configure nginx so it only accepts the server IP where ReactJS is hosted? Ive tried many options to no avail. I always see ReactJS is using the client IP where the user is currently browsing (because of I guess of its client-based nature). Unfortunately, I need to block all other request to protect my Django rest api from external requests. My Django app is having this nginx reverse proxy by the way. How do you guys do this? -
Creating MySQL views with id to work with Django
I have a mysql view that I wish to define as a self-managed Django model managed = False I don't have an id column because I am doing multiple joins and the resulting view has more rows than any of the joined tables. I get a 1054 error When I try to access the model myview.objects.all() OperationalError: (1054, "Unknown column 'myview.id' in 'field list'") [Q] How do I either add an auto-incremented id column to the view and/or tell Django not to look for the 'id' field? -
Login Button is not appearing in mobile view, working fine in PC. Using Django/python and html
I'm trying to see the login button on the upper right hand screen, its working fine on PC, but in my mobile I do not see the signup button, maybe its being overlapped by something else, not sure, please help: Im using django with bulma stylesheets. HTML Code: <!DOCTYPE html> <html> <head> <!-- Meta --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- Title--> <title>F.C. Rayados Playa del Carmen</title> <!-- Styles --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@0.9.3/css/bulma.min.css"> </head> <body> <!-- Navbar --> <nav class="navbar is-light"> <div class="navbar-brand"> <a href="{% url 'frontpage' %}" class="navbar-item"><strong>Inicio</strong></a> </div> <div class="navbar-menu"> <div class="navbar-end"> <div class="navbar-item"> <div class="buttons"> {% if request.user.is_authenticated %} <a href="{% url 'logout' %}" class="button is-danger">Log out</a> {% else %} <a href="{% url 'signup' %}" class="button is-success"><strong>Registrate</strong></a> <a href="{% url 'login' %}" class="button is-light">Log in</a> {% endif %} </div> </div> </div> </div> </nav> <!-- End Navbar --> <!-- Main content --> <section class="section"> {% block content %} {% endblock %} </section> <!-- End Main content --> </body> </html> -
How to efficiently build product model with subcomponent list in django application
I am developing a product catalog web application that consists about 100 of main products build from 15-25 subproducts. Subproduct catalog is much larger, as there are almost 500 different components to build the main products. Subproducts are also multi-layer builds. Components should be stored to sqlite database and data should be reachable by the product id to create some packaging documentation, boms and other lists. I haven't really found any good examples that I could apply to this problem as making lists like this doesn't seem to be as easy as I thought it would. Does anyone know any examples that would be helpful to case like this? -
Django debugger does not start by VS Code launch.json
Until recently my Django projects would debug fine using launch.json file. But it stopped working today and I have no idea about it. Changes made by me in system were: Clean-Installing Windows Installing python in default path just for current user and not all users Problem Description: As soon as I click F5 key the debugger starts for some milliseconds and stops automatically without any prompt. As it does not shows any error I tried to log errors by nothing in it. It does not even load terminal to run commands. The added configuration in launch.json file is as below: { "configurations": [ { "name": "Python: Django", "type": "python", "request": "launch", "program": "${workspaceFolder}\\manage.py", "args": [ "runserver" ], "django": true, "justMyCode": true, "logToFile": true, "console": "integratedTerminal", "cwd": "${workspaceFolder}", "host": "localhost" } ] } Can someone help to troubleshoot this, I have already tried: Creating new projects Reinstalling Python Creating new environment Resetting VS Code Sync Settings Run other dubug configurations {they are working fine) Changing django debug configuration My current options are: Research more (Already spent a hours would take more) Wait for solution by someone Clean Install Windows and all software's (Would be like BhramaAstra) -
Django: Reverse accessor clashed with reverse accessor
In the code below, I have a post, likes, comment models. When I try to migrate the models to activate it, I am getting a reverse accessor error. For likes, user_that_liked only like once, while user_liked_to can have many likes. For comments, both user_that_commented and user_commented_to can have many comments. How should I set up my models so I can do what I want with the models, while also getting this issue fixed. If you need more information, let me know. from django.db import models from django.contrib.auth.models import User class Post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post_question = models.CharField(max_length=200) pub_date = models.DateTimeField() class Likes(models.Model): user_that_liked = models.ForeignKey(User, on_delete=models.CASCADE) user_liked_to = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) date = models.DateTimeField() like_or_dislike = models.IntegerField(default=0) class Comment(models.Model): user_that_commented = models.ForeignKey(User, on_delete=models.CASCADE) user_commented_to = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) date = models.DateTimeField() comment = models.CharField(max_length=300) -
Skip Django Allauth " You are about to sign in using a third party account from Google" page
How can I skip the page and automatically logged in users, when they clicked on Login in With Google. -
best message broker for Django?
I'm learning Django with a book and it shows the use of rabbitmq to deal with the messaging for an online shop, but some of the commands don't work and some of the code is deprecated. Do you have any recommendation for a message broker that works well for Django? Thanks and have a nice day! -
How to filter multiple nested serializer in django rest framwork
I've Tripserializer class contain nested serializer PackageSerializer, inside it there is nested serializer PriceSerializer . class Trip_apiView(generics.ListCreateAPIView): queryset= Trip.objects.all() serializer_class=TripSerializer class PackageSerializer(serializers.ModelSerializer): price=PriceSerializer(source='trip_price', many=True, read_only=True) class Meta: model = Package exclude = ('is_active', 'create_date', 'modify_date') class PriceSerializer(serializers.ModelSerializer): class Meta: model = Price exclude = ('is_active', 'create_date', 'modify_date') this my views: class Trip_apiView(generics.ListCreateAPIView): queryset= Trip.objects.all().order_by('title') serializer_class=TripSerializer I receive list of all trips from GET method like this: [ { "id": 137, "title": "dqw", "package": { "id": 139, "price": { "id": 78, "price": 2.2, "sale_price": 2.2, "trip_package": 139 }, "package_name": "wfe", "description": "fwe", "trip": 137 }, }, {....}, {....} ] How Can I Filter this List of trips by price and by title -
How to make relation between rows in the same table in Django
Let me show an example first: Table1: id | sub_is | name ---|--------|----- 1 |null | group 1 2 |1 | group 2 3 |1 | group 3 4 |2 | group 4 5 |2 | group 5 6 |3 | group 6 7 |1 | group 7 8 |4 | group 8 It will be look like a small structure: group 1 |- group 2 | |-group 4 | | |-hroup 8 | |-group 5 |- group 3 | |-group 6 |- group 7 My question is: How can I do this in Django? How, if it is possible, I can make relation between two rows in the same table? Thanks for any suggestions and any help. -
I don’t understand how to write correct query to database by Django orm
I have two models: Class Page(models.Model): Id Class LinkedPage(models.Model): page = models.ForeignKey(Page) created_year = models.IntegerField(…) I want to get queryset of linkedPage that are group by page and have the highest created_year in the his group. For example: There is page with 3 linked page created year that are 2011, 2005, 2019. There is the second page with 3 linked page created year that are 1960, 2017, 2005. I want to get 2 records(instance with all fields) year that are 2019(from the first page) and 2017(from the second page). Thanks a lot -
how to make a user act as a seller and as a buyer at the same time in Django?
I have a scenario in which I want to sign up a user but I need the user to be signed up as a seller and as a buyer at the same time after signing up. and that user can sell and purchase the products without logging out or logging as a buyer or seller separately. I know an approach to do it by using tuples but it is not a suitable solution for my problem and it is given below: class User(models.Model): USER_ROLES = ( ('SELLER', 'Seller'), ('Buyer', 'Buyer'), ) user_type = models.CharField(max_length = 10, choices = USER_ROLES) I am also thinking to do it this way: class User(models.Model): USER_ROLES = ( ('BOTH_USERS', 'Seller Buyer'), ) user_type = models.CharField(max_length = 10, choices = USER_ROLES) I am not sure how to do it. can any of you help me, please? I hope it makes some sense that what I want as a result. -
Django support for asynchronous database engines
I can't find information about django support for asynchronous database engines. For example for postgresql django supports only psycopg2 library, that is completely synchronous and nothing more is supported, for sqlite django supports only sqlite3 library that is synchronous as well. So I'm not well orientiered in django and of course I can be mistaken, but what's the sense of django asgi if it doesn't support asynchronous database engines(I mean, then all the asynchronous code becomes synchronous) ? And the second question, is there any way to use asynchronous engines in django ? -
Django Rest Framework: TypeError - Direct assignment to the forward side of a many-to-many set is prohibited
I have a custom User model and a Group model that are linked by a UserGroup through model (Many to Many relationship): models.py class User(models.Model): username = models.CharField(primary_key=True, max_length=32, unique=True) user_email = models.EmailField(max_length=32, unique=False) # Validates an email through predefined regex which checks ‘@’ and a ‘.’ user_password = models.CharField(max_length=32) user_avatar_path = models.CharField(max_length=64) class Group(models.Model): group_id = models.AutoField(primary_key=True) group_name = models.CharField(max_length=32, unique=False) group_admin = models.ForeignKey( User, on_delete=models.CASCADE, related_name='my_groups' ) members = models.ManyToManyField( User, related_name='groups', # The name to use for the relation from the related object back to this one. through='UserGroup' # Attaches a Junction table to the Many to Many relationship. ) class UserGroup(models.Model): # Manually specified Junction table for User and Group user = models.ForeignKey( User, on_delete=models.CASCADE, related_name='user_groups' ) group = models.ForeignKey( Group, on_delete=models.CASCADE, related_name='user_groups' ) I'm trying to associate multiple users with a group, using a PATCH request to update the members attribute of a group. Using the following GroupSerializer, I'm able to associate a user as a member of the group when the group is created, by overriding the create function of the serializer: serializers.py class GroupSerializer(serializers.ModelSerializer): members = MemberSerializer(many=True, required=False) group_admin = serializers.SlugRelatedField(slug_field='username', queryset=User.objects.all()) # A Group object is related to a User object by … -
Reuse webdriver sersions?
I was following this Re-using existing browser session in selenium But when I used the following code I am not able to create new sessions (driver = webdriver.Chrome(chromedriverPath)) anymore because the seision_id always the same from selenium.webdriver.remote.webdriver import WebDriver as RemoteWebDriver # Save the original function, so we can revert our patch org_command_execute = RemoteWebDriver.execute def new_command_execute(self, command, params=None): if command == "newSession": # Mock the response return {'success': 0, 'value': None, 'sessionId': session_id} else: return org_command_execute(self, command, params) # Patch the function before creating the driver object RemoteWebDriver.execute = new_command_execute Goals in my website I have too many users, so I want to prevent using too many requests as much as possible. Hence, I am trying to lunch 3 or 4 seasons then I use one of them. Now, I have too many other things I may need to explain. For example to prevent the possibility of two users clicking the same button the same time I created a data_base where it has the driver session_id and a field called is_used and a toggle it False/True. Also, when I user need data from the website I filter the database that I have then like this DriverSesions.objects.filter(is_used=False) question How can … -
CSS doesn't connect to HTML (Django)
None of my static css files connect to html. However, all static pictures work correctly. settings.py DEBUG = True INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'main' ] import os STATIC_DIR = os.path.join(BASE_DIR,"static") STATIC_URL = '/static/' STATICFILES_DIRS = [ STATIC_DIR, ] base.html (parent) <!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="shortcut icon" type="image/png" href="{% static 'img/favico.png' %}"> <title>{% block title %}{% endblock %}</title> <link rel = 'stylesheet' href = 'https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css'> <link rel = 'stylesheey' href = "https://use.fontawesome.com/releases/v5.8.2/css/all.css"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script> <link href="/docs/5.1/dist/css/bootstrap.min.css?v=513" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"> <link rel = 'stylesheet' href = "{% static 'css/main.css' %}"> </head> index.html {% extends 'main/base.html' %} {% load static %} <head> {% block title %} {{title}} {% endblock %} <link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}"> </head> {% block content %} <main> <h1>GHBDTN</h1> <body> <div class="grid-wrapper"> <header class="grid-header"> <img class="circles" src="{% static "main/img/main8.jpg" %}" alt="main pic"> <p>Предоставим качественное образование, <br> поможем понять школьную программу, <br> улучшить оценки и <br> подготовиться к экзаменам</p> </header> </div> </body> </main> {% endblock %} style.css (relate to index.html) .grid-wrapper { display: grid; grid-template-columns: 1 fr; grid-template-rows: 1 fr; grid-template-areas: 'header … -
django table onlineshop_product has no column named name
I work on an online shopping website project with the help of Django. and I'm a beginner in Django The following code provides a table of my database. It helps to add a product ``` class Product(models.Model): category = models.ForeignKey(Category,related_name='products', on_delete=models.CASCADE) name = models.CharField(max_length=200,db_index=True) slug = models.SlugField(max_length=200,db_index=True) image = models.ImageField(upload_to='products/%y/%m/%d',blank=True) description = models.TextField(blank=True) price = models.DecimalField(max_digits=10, decimal_places=2) available = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) ``` Shows me an error in the browser. This error shows me when I add a product inside the admin panel. It helps to add a product but when I add the product the following error occurs. OperationalError at /admin/onlineshop/product/add/ table onlineshop_product has no column named name when i did migration using the command ``` python manage.py migrate ``` it will appear Operations to perform: Apply all migrations: admin, auth, contenttypes, onlineshop, sessions Running migrations: No migrations to apply. Your models in app(s): 'onlineshop' have changes that are not yet reflected in a migration, and so won't be applied. Run 'manage.py makemigrations' to make new migrations, and then re-run 'manage.py migrate' to apply them. ``` python manage.py makemigrations ``` It is impossible to add the field 'created' with 'auto_now_add=True' to product without providing a … -
after creating single_product using product models ,i am not able to fetch data in detail page
enter image description heredef product_detail(request,category_slug,product_slug): try: single_product = Product.objects.get(category__slug=category_slug, slug=product_slug,) except Product.DoesNotExist: single_product=None context={ 'single_product':single_product} return render(request,'store/product_detail.html',context) -
Showing top 5 post in django
in my project i want to show top 5 post in home section by categories.i fetch all post in home sections and if category is same i showed the post.but forloop.counter is not suitable in this situation.i need counter to break the loop or if condition.but i cant. please help me. views.py def home(request): category = Category.objects.all().filter(parent=None) post_by_category = Post.objects.filter(published=True).order_by('-category') slider = Post.objects.filter(slider=True).order_by('-created_on') context = { 'category':category, 'post_by_category':post_by_category, 'slider':slider, } return render(request,'home.html',context) home.html <div class="col-md-9"> {% for post in post_by_category %} {% if post.category.category_name == category.category_name %} <div class="d-lg-flex post-entry-2"> <a href="{{post.get_url}}" class="me-4 thumbnail mb-4 mb-lg-0 d-inline-block"> <img src="{{post.heder_image.url}}" alt="" class="img-fluid"> </a> <div> <div class="post-meta"><span class="date"><a href="{{category.get_url }}">{{category.category_name }}</a> </span> <span class="mx-1">&bullet;</span> <span>Jul 5th '22</span></div> <h3><a href="{{post.get_url}}">{{post.title}}</a></h3> <p>{{post.meta_description}}</p> <div class="d-flex align-items-center author"> <div class="photo"><img style="width:50px;height:50px;border-radius:50%" src="{{user.profile.profile_picture.url}}" alt="" class="img-fluid"></div> <div class="name"> <h3 class="m-0 p-0">{{post.author.first_name}} {{post.author.last_name}}</h3> </div> </div> </div> </div> {% endif %} {% endfor %} </div> -
Django - how to use filter to check if a string field contains a word?
my model order has a text field as: order.remark. how to filter orders with the remark field containing certain word? e.g. a reference number, a telephone number. in the order remark field the user can input anything, how to filter orders with remark containing the words "SZFPS/LCB-D2232", for instance. Please be noted that user might type in a lot of information without enter space, i.e. the words are not seperated by space or tab or any sort of delimeters. how to effectively filter the orders? -
How to give a query a list of objects or items?
my Question is that how can i give a list of objects or items to a query : for example i have an objects which has 4 user id like this : list_of_user_id = [1 , 2 ,3 ,6] and now i want to set the CreatorUserID equal to list_of_user_id to check how many of the users in list_of_user_id exist in the TblAnswerQuestionRequest table . this is my Model.py : class TblAnswerQuestionRequest(models.Model): text = TextField(verbose_name='محتویات درخواست',max_length=4000, blank=True, null=True) CreatorUserID = models.ForeignKey(Members, on_delete=models.PROTECT, null=True, blank=True) knowledge_request = models.ForeignKey(TblQuestionRequest, on_delete=models.PROTECT, null=True, blank=True) CreateDate = IntegerField('تاریخ ثبت', default=LibAPADateTime.get_persian_date_normalized(), null=True, blank=True) create_hour = models.TimeField(default=datetime.datetime.now(), null=True, blank=True) Status = IntegerField('وضعیت', default=1,choices=StatusChoices, null=True, blank=True) def __str__(self): return str(self.id) and what i want is like this : Question_Users = TblAnswerQuestionRequest.objects.filter(CreatorUserID = list_of_user_id) -
no such table using ( django-treebeard)
I am trying to view my table in the django-admin panel but i keep reciving no such table (table name) when i am sure it exists. models.py : from django.db import models from vessels.models import Vessel from treebeard.mp_tree import MP_Node # Create your models here. class Component(MP_Node): name = models.CharField(max_length=200, blank=True, null=True) manufacturer = models.CharField(max_length=200, blank=True, null=True) model = models.CharField(max_length=200, blank=True, null=True) type = models.CharField(max_length=200, blank=True, null=True) remarks = models.TextField(blank=True, null=True) vessel = models.ForeignKey( Vessel, blank=True, null=True, on_delete=models.CASCADE, related_name='vessel_components') def __str__(self): return self.name admin.py : from django.contrib import admin from .models import Component # Register your models here. admin.site.register(Component) -
SMTPConnectError: (421, b'Server busy, too many connections')
I have watched videos and practice the same thing yet I keep getting smtp connect error EMAIL_BACKEND= 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'captainleon04@gmail.com' EMAIL_HOST_PASSWORD ='ppbdhcdnj' EMAIL_PORT = 587 EMAIL_USE_TLS = True -
Django ninja api in AWS app runner deterministic=True requires SQlite 3.8.3 or higher error
I'm trying to deploy a django ninja API in aws App Runner, it works properly in local but when I do it in aws it says: "django.db.utils.NotSupportedError: deterministic=True requires SQLite 3.8.3 or higher". My requirements file is: Already tried adding pysqlite3 and pysqlite3-binary as it says here but has issues installing it in local because says that there are not versions that meet requirements. I'll appreciate your help, Thanks beforehand.