Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: related_name issue
I am trying to make a query with related_name. I need to list tenants and its domain. But I am getting this error: 'TenantManager' object has no attribute 'domains' What am I doing wrong? models.py class Tenant(TenantMixin): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=100) created_on = models.DateField(auto_now_add=True) objects = TenantManager() auto_create_schema = True auto_drop_schema = True class Domain(DomainMixin): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) domain = models.CharField(max_length=253, unique=True, db_index=True) tenant = models.ForeignKey(settings.TENANT_MODEL, db_index=True, related_name='domains', on_delete=models.CASCADE) managers.py class TenantManager(models.Manager): def list_all(self): return self.domains.all() viewsets.py class TenantViewSets(viewsets.GenericViewSet): authentication_classes = (JWTAuthentication,) permission_classes = [IsAuthenticated, IsAdminUser, IsSuperUser] def list(self, request): queryset = Tenant.objects.list_all() serializer = Tenant.Serializer(queryset, many=True) return Response(serializer.data) serializers.py class DomainSerializer(serializers.ModelSerializer): tenant = serializers.RelatedField(read_only=True) class Meta: model = Domain fields = ( "id", "domain", "tenant", ) class TenantSerializer(serializers.ModelSerializer): domain = DomainSerializer(read_only=True) class Meta: model = Tenant fields = ( "id", "name", "schema_name", "created_on", "domain", ) -
Django admin site form auto-filled with values in many-to-many relationship
class Student(models.Model): id = models.IntegerField(primary_key=True, unique=True, null=False) name = models.CharField(max_length=100, null=False) password = models.CharField(max_length=100, null=False) course = models.ManyToManyField('Course', related_name='students', blank=True) class Meta: verbose_name_plural = 'Students' def __str__(self): return self.name class Course(models.Model): id = models.IntegerField(primary_key=True, null=False) name = models.CharField(max_length=255, null=False, unique=True) class Meta: unique_together = ('id','name') verbose_name_plural = "Courses" def __str__(self): return self.name I have two models, student and courses and the relationship is many to many. From the django admin site, after adding a new course if I want to add new student the courses field in the student form is already filled with all the added courses and when I save I can't remove those courses. I want to create student without assigning courses initially. How do I do that? -
Problem with different schema relationship in Django Migrations
I have a multiple schema database with relationships between them and I have a problem migrating the database in Django. Firstly I created a BaseModel to override the meta class parameters: base_models.py: import django.db.models.options as options from django.db import models options.DEFAULT_NAMES = options.DEFAULT_NAMES + ("database",) class BaseErpModel(models.Model): class Meta: abstract = True database = "erp" models.py from django.db import models from config.base_models import BaseErpModel from teste_migrate.users.models import User class TrendUpload(BaseErpModel): trend_name = models.CharField("Tendência", max_length=255) created_at = models.DateTimeField("Data de criação", auto_now_add=True) user = models.ForeignKey(User, verbose_name="Usuário", on_delete=models.DO_NOTHING) class Meta(BaseErpModel.Meta): database = "erp" def __str__(self): return f"{self.trend_name} - {self.created_at}" dbrouter.py from django.apps import apps class BaseRouter(object): """A router to control all database operations on models in the erp schema""" def db_for_read(self, model, **hints): "Point all operations on model to 'database' meta db" if hasattr(model._meta, "database"): return model._meta.database return "default" def db_for_write(self, model, **hints): "Point all operations on model to 'database' meta db" if hasattr(model._meta, "database"): return model._meta.database return "default" def allow_relation(self, obj1, obj2, **hints): "Allow any relation in the same Database" return None def allow_migrate(self, db, app_label, model_name=None, **hints): """ Don't allow migrate to 'not_alowed_relation_models' """ try: model = apps.get_model(app_label, model_name) except: return None try: database = model._meta.database allow_migration = model._meta.allow_migration except: database … -
How to regroup blog posts with multiple categories by category in Django template
I have Blog with posts that have multiple categories class BlogDetailPage(Page): heading = models.CharField(max_length=150, blank=False, null=False) categories = ParentalManyToManyField("blog.BlogCategory", blank=False) ... class BlogCategory(models.Model): title = models.CharField(max_length=30,unique=True) slug = AutoSlugField(populate_from='title') ... My posts are as follows: Post 1: Category A Post 2: Category A, Category B Post 3: Category B I want regroup posts by category as below: Category A Post 1 Post 2 Category B Post 2 Post 3 My current solution is not giving me correct results. {% regroup posts by categories.all as posts_by_categories %} <ul> {% for category in posts_by_categories %} <li>{{ category.grouper.0 }} # first category name <ul> {% for post in category.list %} <li>{{ post.id }}, {{post.categories.all}}</li> {% endfor %} </ul> </li> {% endfor %} Amy ideas? -
How to save a bunch of many to many fileds using model to dict
I have a group of many to many fields that i am trying to save together with the other fields that are not many to many in django. def save_model(self, model_obj, model_cls): """ Get and save fields of a specific model """ kwargs = model_to_dict(model_obj, fields=[field.name for field in model_obj._meta.fields], exclude=['id', 'maternal_visit_id', 'maternal_visit']) for key in self.get_many_to_many_fields(model_obj): kwargs[key] = (self.get_many_to_many_fields(model_obj).get(key)) temp_obj = model_cls.objects.create(**kwargs, maternal_visit_id=self.id, maternal_visit=self.instance) temp_obj.save() am getting the many to many fields like def get_many_to_many_fields(self, model_obj): """ Return a dictionary of many-to-many fields in a model """ return model_to_dict(model_obj, fields=[field.name for field in model_obj._meta.get_fields() if isinstance(field, models.ManyToManyField)]) and when the script runs, it is giving me an error Internal Server Error: /admin/flourish_caregiver/maternalvisit/6128fcdc-8d39-41eb-a94d-fe839dd69a6e/change/ Traceback (most recent call last): File "/Users/mcturner/.venvs/flourish/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/Users/mcturner/.venvs/flourish/lib/python3.9/site-packages/django/core/handlers/base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/mcturner/.venvs/flourish/lib/python3.9/site-packages/django/contrib/admin/options.py", line 614, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "/Users/mcturner/.venvs/flourish/lib/python3.9/site-packages/django/utils/decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "/Users/mcturner/.venvs/flourish/lib/python3.9/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/Users/mcturner/.venvs/flourish/lib/python3.9/site-packages/django/contrib/admin/sites.py", line 233, in inner return view(request, *args, **kwargs) File "/Users/mcturner/.venvs/flourish/lib/python3.9/site-packages/edc_model_admin/model_admin_next_url_redirect_mixin.py", line 68, in change_view return super().change_view(request, object_id, form_url=form_url, extra_context=extra_context) File "/Users/mcturner/.venvs/flourish/lib/python3.9/site-packages/django_revision/modeladmin_mixin.py", line 24, in change_view return super(ModelAdminRevisionMixin, self).change_view( File … -
How can I use newspaper3k with Django-rest-framework? I want to scrap news articles through newspaper3k then save in sqlite3
I want to scrap news articles through newspaper3k then save in sqlite3. I couldn't find any code where django and newspaper3k coded together. Please help me by writing proper code. Thanks -
How i can implement Calender Schedule Event in Django?
I want to implement this calender event with django. How i can do it .....?? enter image description here -
Why am I getting `NOT NULL constraint failed` error with Django?
I am new to Django. I am to create some sort of todo app. I am having trouble setting IntegerField as optional field. As far as I can see the problem is when I try to save to save the object to the database. I get error: NOT NULL constraint failed: lista_row.quantity. I have made (and migrated) migrations. Here is my models.py: from django.db import models from django.contrib import admin class Row(models.Model): name = models.CharField(max_length=200) quantity = models.IntegerField(null=False, blank=True) -
vuejs 401 unauthorized with axios from django backend with token
im trying to fetch data from django rest backend with axios in vuejs frontend but each time i get this error. the tokens match but it is still not authorizing. {"message":"Request failed with status code 401","name":"AxiosError","config":{"transitional":{"silentJSONParsing":true,"forcedJSONParsing":true,"clarifyTimeoutError":false},"transformRequest":[null],"transformResponse":[null],"timeout":0,"xsrfCookieName":"XSRF-TOKEN","xsrfHeaderName":"X-XSRF-TOKEN","maxContentLength":-1,"maxBodyLength":-1,"env":{"FormData":null},"headers":{"Accept":"application/json, text/plain, */*","Authorization":"Token838881311c52b89dd937815066e7eb3a3221604c"},"baseURL":"http://127.0.0.1:8000","method":"get","url":"/api/v1/clients/"},"code":"ERR_BAD_REQUEST","status":401} the axios looks like this axios .get('/api/v1/clients/') .then(response => { for(let i = 0; i< response.data.length; i++){ this.clients.push(response.data[i]) } }) .catch(error => { console.log(JSON.stringify(error)) }) } the settings in my django are ALLOWED_HOSTS = ['*'] CORS_ALLOWED_ORIGINS = [ "http://localhost:8080", "http://127.0.0.1:8000", ] REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES":( 'rest_framework.authentication.TokenAuthentication', ), 'DEFAULT_PERMISSION_CLASSES':( 'rest_framework.permissions.IsAuthenticated', ) } -
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 …