Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Declaring an app label error for django oauth2_provider package
I am trying to upgrade my apps django version from 1.8 to 3.2. my root URL config is defined as: ROOT_URLCONF = 'clickwork.urls' in settings.py inside the urls file, I have this imports: from django.conf import settings import oauth2_provider.views as oauth2_views from django.contrib import admin admin.autodiscover() the ouath2provider import statement is throwing app_label error: RuntimeError: Model class django.contrib.contenttypes.models.ContentType doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. Here is what I have tried to resolve the issue: Upgrading the oauthprovider package to the latest version 1.5, it supports Django 2.2+ as per their docs. https://github.com/jazzband/django-oauth-toolkit Adding apps.py file in the root directory and adding the path to the project config in INSTALLED_APPS in settings, this is mentioned in the Django 3.2 release notes: https://docs.djangoproject.com/en/3.2/ref/applications/#configuring-applications-ref I went through the django.contrib.contenttypes.models.ContentType class code and added an app label, it was not there before: class ContentType(models.Model): app_label = models.CharField(max_length=100) model = models.CharField(_('python model class name'), max_length=100) objects = ContentTypeManager() class Meta: verbose_name = _('content type') verbose_name_plural = _('content types') db_table = 'django_content_type' unique_together = [['app_label', 'model']] Doing step3 solves the problem but obviously changing the code in the package is dumb. Can anyone guide me on what I am doing … -
Can permissions mixin be used in some other model rather than the auth user model?
In my web application, a single user can have many accounts, but user has to login only once. However, different accounts can have different permissions. Each account has its own session and the request.user will change depending on which account the user has logged in to. And there will be two types of login, the first type is when user logs into the website, and the other type is when user logs in into any of his account. I used the django auth user model to store the user's email and password and use it only for first type login and it does not inherit the permissions mixin. And for accounts, I have an account model which does inherit permissions mixin. It is used for second type log in and relating each account to its set of permissions. After doing this I am facing issues, since third party libraries like django-rules still refer to the auth user model for permissions when calling request.user.has_perm('some_perm_string') So is it a good practice to have permissions mixin used in some other model rather than the auth user model? If not then permissions is available in Django as a mixin? -
Deserialize to get an object instance
I would like to deserialize django rest framework serialized data to get back an object, i.e to do something like Modelname.objects.get(**serialized_data). However when I try the following, I get validation error because drf is attempting to create a new instance and it already exists. I only need to retrieve existing object. How can I do that without resorting to manually getting each field parameter from the dict? My code: clinic = biovardata['linkedclinic'] print("\n Deserializing clinic..") print("Clinic:", clinic) clinicserializer = ClinicSerializer(data=clinic, many=False) if clinicserializer.is_valid(): print("Clinic Serializer is valid") cl = Clinic(clinicserializer.validated_data) print("Clinic is ", clinic) else: print("Clinic Serializer is not valid") print(clinicserializer.errors) My output: Deserializing clinic.. Clinic: {'clinicid': 21, 'name': "Clinic name", 'label': 'joelper'} Clinic Serializer is not valid {'name': [ErrorDetail(string='clinic with this name already exists.', code='unique')], 'label': [ErrorDetail(string='clinic with this label already exists.', code='unique')]} -
How to inner join tables based on ManyToManyField and group by a parameter and get latest one in Django?
I have two models with ManyToManyField relationship: class Education(models.Model): title = models.CharField(default=None, max_length=100) content = models.TextField(default=None) price = models.ManyToManyField(Price) class Price(models.Model): cost = models.CharField(default=None, max_length=20) created_at = models.DateTimeField(auto_now=True, null=True, blank=True) I can fetch all rows like this: result = Education.objects.filter(price__in=Price.objects.all()).select_related('Price')/ .values_list('title', 'content', 'price__cost', 'price__created_at') But now i want to group by education.id and the cost parameter should be latest parameter that inserted(based on created_at). So i want to have list of all Education with latest cost that inserted for every education. -
How to add signals with atomic transaction?
I have some api which will create User model and I have a post_save signal which will do some database update. I want to apply transaction.atomic but is it required when using signal ? Does signals handle atomic transaction? If not how can I make it ? @receiver(post_save, sender=User) def some_signal(sender, instance, using, **kwargs): # some database transaction if instance: ..... class User(AbstractUser): .... # api User.objects.create() -
How to convert the last number of Str = (2021GC110) in Int on Python
I'm begginer in Django and i trying convert Str where the base for this is (2021(year) - CG(product name) - 1(ID product) -101 (var the product). But I need the last number for variable. exemple: product 1: 2021CG1101 product 2: 2021CG1102 this is my view.py if serialNumberForm.is_valid(): os = serialNumberForm.save(commit=False) Produto.numeroSerie = NumeroSerie.id os.numeroSerie = id lastProduct = NumeroSerie.objects.last() if lastProduct == None: prefix = datetime.date.today().year fix = product.nome[3:6] sufix = Produto.id var = 10 os.serialNumber = str(prefix) + fix + str(sufix) + str(var) elif int(lastProduct.serialNumber[0:3]) != datetime.date.today().year: prefix = datetime.date.today().year fix = product.nome[3:6] sufix = Produto.id var = 10 os.serialNumber = str(prefix) + fix + str(sufix) + str(var) else: prefix = datetime.date.today().year fix = product.nome[3:6] sufix = NumeroSerie.produto(os) var = (lastProduct.serialNumber[-1]) =+ 1 os.serialNumber = str(prefix) + fix + str(sufix) + str(var) os.save() -
Multiple table in a same Row using Python-docx?
I want to create two separate tables starting at the same line. I already tried WD_TABLE_DIRECTION, WD_TABLE_ALIGNMENT it works only for a different line or a level different line. ''' from docx.enum.table import WD_TABLE_DIRECTION table = document.add_table(3, 3) table.direction = WD_TABLE_DIRECTION.RTL or table.direction = WD_TABLE_DIRECTION.LTR ''' from docx.enum.table import WD_TABLE_ALIGNMENT table = document.add_table(3, 3) table.alignment = WD_TABLE_ALIGNMENT.CENTER or LEFT or RIGHT ''' -
How to add a custom method to a model field in Django?
I have two models that will use the same CardNumberField() to store credit card numbers. How can I add a custom method to the field to mask the card numbers? I have created the CardNumberField() which inherits from models.Charfield: # CARD NUMBER FIELD class CardNumberField(models.CharField): description = _('card number') def __init__(self, *args, **kwargs): kwargs['max_length'] = 19 super().__init__(*args, **kwargs) The CardNumberField() is then imported and used in my customers/models.py: # CARD MODEL class Card(models.Model): number = CardNumberField() ... def __str__(self): return 'Card [{number}]'.format(number=self.number) ...and in my transactions/models.py: # TRANSACTION MODEL class Transaction(models.Model): card_number = CardNumberField() ... def __str__(self): return 'Transaction ...' So, how can I add the following method to my CardNumberField() to be used by both of my models? def masked_number(self): # display masked card number number = self.number return number[-4:].rjust(len(number), '#') Also, how will I grab this field method in a DRF serializer class? -
Issue while deploying django site on AWS (TemplateSyntaxError)
I manage to deploy my site on AWS using NGINX and Gunicorn. The site was working fine but not I noticed there's an error when I visit the page. Can anyone guide me on what went wrong? here's the live site link: http://ec2-3-16-152-98.us-east-2.compute.amazonaws.com/ -
DRF-Yasg - blank page when trying to enter swagger ui view
This is my urls.py code, which is similar to the code provided in the documentation. from drf_yasg.views import get_schema_view from drf_yasg import openapi schema_view = get_schema_view( openapi.Info( title="Snippets API", default_version='v1', description="Test description", ), public=True, permission_classes=(permissions.AllowAny,), ) urlpatterns += [ url(r'^swagger(?P<format>\.json|\.yaml)$', schema_view.without_ui(cache_timeout=0), name='schema-json'), url(r'^swagger/$', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'), url(r'^redoc/$', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'), ] When I'm trying to enter /api/swagger/ I see nothing more than a blank page with two links. I'm pretty sure I should see something more... colorful. Another try: /api/swagger.json leaves me with some JSONs with endpoints, parameters, status codes, etc. -
VSCode debugger not running inside virtual environment
I'm trying to debug my Django application within VSCode, but for some reason VSCode isn't running inside my virtualenv. I've tried multiple ways for it to work, but still no luck. I've set pythonpath to the path of the Pythonfile inside my virtualenv: "python.pythonPath": "/Users/username/documents/programmering/bq/env/bin/python3" I've tried selecting the Python file inside my virtual environment as the interpreter in VScode I've added the following line to my launch.json: "env": { "PYTHONPATH": "${workspaceRoot}"} If I run the debugger and print sys.version and sys.path I'm getting the following prints: SYS VERSION: 3.9.7 (default, Oct 13 2021, 06:44:56) [Clang 12.0.0 (clang-1200.0.32.29)] SYS PATH: ['/Users/username/Documents/Programmering/bq/project/projectile', '/Users/username/Documents/Programmering/bq/project', '/usr/local/Cellar/python@3.9/3.9.7_1/Frameworks/Python.framework/Versions/3.9/lib/python39.zip', '/usr/local/Cellar/python@3.9/3.9.7_1/Frameworks/Python.framework/Versions/3.9/lib/python3.9', '/usr/local/Cellar/python@3.9/3.9.7_1/Frameworks/Python.framework/Versions/3.9/lib/python3.9/lib-dynload', '/usr/local/lib/python3.9/site-packages'] This is what my interpreters looks like, not that I've got pyenv installed and have run "pyenv global 3.9.7" to set a global version for python as well ass "pyenv local 3.6.9" inside my project folder, to have the latter python version active for my project. Interpreters in VSCode What I'm a bit puzzled about is that in the directories for the interpreter the path is to the pyenv version of python, and not the actual python version in the virtual environment, perhaps that can be the cause for the issue? How would I … -
How can I solve attempted relative import beyond top-level package
I try to integrate django with scrapy my directoly is like this djangoproj / djangoproj / settings.py / urls.py / myapp / models.py ( it has the class named DjangoModel ) / views.py / scrapyproj / myscrapyapp / google.py / pipelines.py / items.py I go to the djangoproj/scrapyproj and exec like this scrapy crawl google Now I want to access the django model from pipelines.py So, my piplines.py from itemadapter import ItemAdapter from datetime import datetime import os from ..myapp.models import DjangoModel However, error occurs attempted relative import beyond top-level package -
Django: Add result from second queryset to first queryset
I have two models from two different databases (one read-only) without ForeignKey between the two models (did not get that working, as far i found it isn't possible). In the main model I store the ID from the second model (read-only DB). I want to display multiple records/rows on one view (like al table) There for I want to get the content of the second model with the id from the main model. and combine it to one row. Normal you can get it by the ForeignKey but did won't work with 2 different databases. What i got (simplified): model.py class Overeenkomst(models.Model): park = models.IntegerField(blank=False, null=False, default='0') object = models.IntegerField(blank=False, null=False, default='0') # ID from model second database date_start = models.DateField() date_end = models.DateField() class Object(models.Model): id = models.IntegerField(db_column='ID', primary_key=True) # Field name made lowercase. nummer = models.IntegerField(db_column='NUMMER', blank=True, null=True) # Field name made lowercase. omschrijving = models.CharField(db_column='OMSCHRIJVING', max_length=50, blank=True, null=True) # Field name made lowercase. idobjectsoort = models.IntegerField(db_column='IDOBJECTSOORT', blank=True, null=True) # Field name made lowercase. idobjecttype = models.IntegerField(db_column='IDOBJECTTYPE', blank=True, null=True) # Field name made lowercase. (.....) class Meta: managed = False db_table = 'OBJECT' unique_together = (('nummer', 'idpark', 'id'), ('id', 'idpark', 'idobjecttype', 'idobjectsoort', 'dubbelboeking'), ('code', 'id'),) def __str__(self): return … -
serializing only certain fields from a queryset in django serializer class
I have a queryset which I obtain from get_queryset(). What we know is, the returns of queryset gives the list of objects which contains all the fields of the model. Now I don't want to serialize all the fields from the model and show all of them in the response. I want to serialize only few fields and show in the api response. for eg: def get_queryset(self): """"" filtering happens here on the query parameters. """ abc = self.request.GET.get('abc',None) Now I have a defualt list function where I have to call serializer class only with the specific fields. def list(self, request, *args, **kwargs): queryset = self.get_queryset() # data ={ # "name":queryset. # } # serializer = ExampleSerializer(data,many=True) #serializer = serializers.serialize("json",queryset=queryset,fields=['id','name','address']) return Response(serializer, status=status.HTTP_200_OK) When I do print queryset it gives complex queryset and when I do print(type(queryset)),it gives the following <class 'django.db.models.query.QuerySet'> Now how to serialize name and address fields only to the exampleserializer class?? I did some digging and tried to do the following #serializer = serializers.serialize("json",queryset=queryset,fields=['id','name','address']) but it does not give the output in the required format not like regular json. Also it gives model: Example in the response of every object. -
Apache + Django on Windows does not start
I am trying to set up Apache with Django on Windows but it does not seem to work. My settings.py ALLOWED_HOSTS = ['localhost', '127.0.0.1'] My wsgi.py import os import sys from django.core.wsgi import get_wsgi_application from pathlib import Path # Add project directory to the sys.path path_home = str(Path(__file__).parents[1]) if path_home not in sys.path: sys.path.append(path_home) os.environ['DJANGO_SETTINGS_MODULE'] = 'mrt.settings' application = get_wsgi_application() My httpd.conf Listen 30080 Listen 8080 LoadFile "C:/Users/user/AppData/Local/Programs/Python/Python37/python37.dll" LoadModule wsgi_module "c:/users/user/pycharmprojects/djangoapi/venv/lib/site-packages/mod_wsgi/server/mod_wsgi.cp37-win_amd64.pyd" WSGIPythonHome "c:/users/user/pycharmprojects/djangoapi/venv" WSGIPythonPath "c:/users/user/pycharmprojects/djangoapi/venv/Lib/site-packages" My httpd-vhosts.conf <VirtualHost *:30080> ServerName localhost WSGIPassAuthorization On ErrorLog "c:/users/user/pycharmprojects/djangoapi/mrt/logs/apache.error.log" CustomLog "c:/users/user/pycharmprojects/djangoapi/mrt/logs/apache.access.log" combined WSGIScriptAlias / "c:/users/user/pycharmprojects/djangoapi/mrt/mrt/wsgi.py" <Directory "c:/users/user/pycharmprojects/djangoapi/mrt/mrt"> <Files wsgi.py> Require all granted </Files> </Directory> Alias /static "c:/users/user/pycharmprojects/djangoapi/mrt/static" <Directory "c:/users/user/pycharmprojects/djangoapi/mrt/static"> Require all granted </Directory> </VirtualHost> I have tried to open http://localhost:30080/ but it says the website is not reachable. I also have tried to change Ports to *8080 but without any effect, no error appears in logs, they are empty. Without Django config Apache works. Syntax is Ok. -
Django - Difference between sessions and Cookie?
Hey every one i am trying to create user story for an website and face problem creating user story for session management and cookies management. can any one help me ? -
accessing url parameters of django template url tag in createView Class
I want to prepopulate (initial) a certain form field in the django createView class according to the url parameter passed in the {% url %} tag. I don't know ho to pick the passed url parameter in the get_initial(self) method on the createView class. When I hardcode certain value, it's working. The html is like that: {% for object in model.objects_set.all %} {% subobject in objectmodel.subobjects_set.all%} <a href="{% url 'url_name' object.id %}">Create SubObject</a> {% endfor %} {% endfor %} and the views.py is like that (i am missing the ??? part): class SubObjectCreateView(generic.CreateView): model = SubObject ... def get_initial(self): return {'object': ???} urls.py is like: path('subobject/<int:something>', views.SubObjectCreateView.as_view(), name='url_name') -
How to remove last / character in root URL API in Django
API only work with url below: http://127.0.0.1:1997/api/v1/groups/ How can I remove the last '/' so that it works like below: http://127.0.0.1:1997/api/v1/groups My config url code: import os from django.contrib import admin from django.urls import path, include from rest_framework import routers from rest_framework.schemas import get_schema_view from rest_framework_swagger.renderers import SwaggerUIRenderer, OpenAPIRenderer from groups import views as group_views API_VERSION = os.getenv('API_VERSION') API_ROOT = f"api/{API_VERSION}/" router = routers.DefaultRouter() router.register('groups', group_views.GroupViewSet) schema_view = get_schema_view( title='next_blog', renderer_classes=[OpenAPIRenderer, SwaggerUIRenderer]) urlpatterns = [ path('admin', admin.site.urls), path('api_auth', include( 'rest_framework.urls', namespace='rest_framework')), path('docs', schema_view, name='docs'), path(API_ROOT, include(router.urls)), ] Thanks everyone ! -
Environment variables are obtained in the form of "" variable "", that is, there is a pair of double quotes
I have a heroku based university platform where I am deploying django. Build runs through gitlab-ci, where environment variables are set to connect to postgres. Build succeeds: There are no log errors above either. However, in the platform logs, I see: ... 2021-11-17T09:51:11.577164000Z app[web.1]: conn = _connect(dsn, connection_factory=connection_factory, **kwasync) 2021-11-17T09:51:11.577286000Z app[web.1]: django.db.utils.OperationalError: could not translate host name ""80.87.197.6"" to address: Name or service not known 2021-11-17T09:51:12.194171000Z app[web.1]: 128 static files copied to '/app/static'. 2021-11-17T09:51:12.579783000Z app[web.1]: [2021-11-17 09:51:12 +0000] [414] [INFO] Starting gunicorn 20.1.0 2021-11-17T09:51:12.583479000Z app[web.1]: [2021-11-17 09:51:12 +0000] [414] [INFO] Listening at: http://0.0.0.0:5000 (414) 2021-11-17T09:51:12.586471000Z app[web.1]: [2021-11-17 09:51:12 +0000] [414] [INFO] Using worker: sync 2021-11-17T09:51:12.590668000Z app[web.1]: [2021-11-17 09:51:12 +0000] [415] [INFO] Booting worker with pid: 415 For some reason, variables are captured with four double quotes. I checked the variables, there are no spaces. -
How to join tables with ManyToManyField type in Django?
I have models like this: class Education(models.Model): title = models.CharField(default=None, max_length=100) content = models.TextField(default=None) price = models.ManyToManyField(Price) class Price(models.Model): cost = models.CharField(default=None, max_length=20) created_at = models.DateTimeField(auto_now=True, null=True, blank=True) And i want to inner join between two tables and access to all fields of both. -
unpacking data in django rest framework
I am confused about unpacking the data or validated data in django serializers. For eg I am reading the code snippets from the drf documentation and it is following. class UserSerializer(serializers.ModelSerializer): profile = ProfileSerializer() class Meta: model = User fields = ['username', 'email', 'profile'] def create(self, validated_data): profile_data = validated_data.pop('profile') user = User.objects.create(**validated_data) Profile.objects.create(user=user, **profile_data) return user Here what I know is if we put ** in front of the **kwargs, it will unpack the kwargs dictionary and we got the values only. But in the above line Profile.objects.create(user=user, **profile_data) profile_data will be unpacked, so that means we got the value for the fields. But what I think is, it is supposed to be like address=address,mobile=mobile etc something like that while using create function. Will **profile_data will result to that what I have mentioned?? Also, when I do print(**profile_data), it will give me an error. How does it unfold then?? -
Django auth ldap open new connection for each view
I'm using Django LDAP authentication, with django-auth-ldap library. Classic authentication with user/pwd is also supported: AUTHENTICATION_BACKENDS = ['django_auth_ldap.backend.LDAPBackend', 'django.contrib.auth.backends.ModelBackend', ] It works fine, I can log in and log out. But we noticed that when a user is logged in and change view, a new connection to LDAP server is made (checked with netstat command). Is there any setting that I could play with to either close connection or use same connection without opening a new one? I don't even understand why it needs to connect several times, since the ldap user is registered in the local database as 'classic' user, with permissions and groups. Any help on how this works would be appreciated, thanks. Django 3.2.8, Django-auth-ldap 2.1.1, Python-ldap 3.2.0, Python 3.7 -
How to implement and run the cloudguru profiler with the django-app in the server?
I have my system running in the EC2 instance. I have added the settings for cloudguru profiler. Now, i need to run in the server. How should i run it ?? -
Django queryset searching for firstname and lastname with startswith
I have one django app, In which I search for a name from first_name and last_name. Which is working for me using Q tag. from django.db.models import Q def find_user_by_name(query_name): qs = User.objects.all() for term in query_name.split(): qs = qs.filter( Q(first_name__icontains = term) | Q(last_name__icontains = term)) return qs But I'm facing one issue regarding ordering the data not coming as I want. For example: search_word = 'Kia' The result I got after the search is: { "first_name": "Katja", "last_name": "Tukiainen", }, { "first_name": "Kia", "last_name": "Reijonen", }, { "first_name": "Sanna", "last_name": "Kiander", } ] But I want a result in which first starts with Kia first, Result like: { "first_name": "Kia", "last_name": "Reijonen", }, { "first_name": "Katja", "last_name": "Tukiainen", }, { "first_name": "Sanna", "last_name": "Kiander", } ] Please help me regarding this, I try this with startswith but not working for me. Thanks in advance. -
How can I save my excel file in the file I created with BASE_DIR?
here is my code How can I save my pandas_simple file here in the file I created with BASE_DIR? (This should be with Python)