Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ignore user_permissions
In my django project I use only group permissions. The debug-toolbar shows me that a request is made against user_user_permissions as well as against auth_group_permissions. Even if the model user_user_permissions is not populated, is it possible to avoid this query? Regards -
Database graphic display using Django or Sqlite
Is there any software or package that can help me get a graphical representation of my database. I want something that can take as input my Django models or my sqlite database and provide me with a graphical representation of tables and relationships. -
How do i really move forward with Django, exploring and covering more advanced topics like docker implemetation and postgresql?
I feel like I am stuck in the middle of moving from basic Django to Django for professionals. i can't just move on. I need your advice. How do i begin to work with Docker implementation and PostgreSQL? -
cant access the admin panel of my django project [closed]
: return debug, technical_500_response(request, *exc_info) File "/data/user/0/ru.iec.pydroid3/files/aarch64-linux-android/lib/py thon3.9/site-packages/django/views/debug.py", line 66, in technical 500 html reporter.get_traceback_html() = File "/data/user/0/ru.iec.pydroid3/files/aarch64-linux-android/lib/py thon3.9/site-packages/django/views/debug.py", line 386, in get traceback html return trender(c) File "/data/user/0/ru.ilec.pydroid3/files/aarch64-linux-android/lib/py thon3.9/site-packages/django/template/base.py", line 175, in render return self._render(context) File "/data/user/0/ru.iec.pydroid3/files/aarch64-linux-android/lib/py thon3.9/site-packages/django/template/base.py", line 167, in _render return self, nodelist, render(context) File "/data/user/0/ru. iiec.pydroid3/files/aarch64-linux-android/lib/py thon3.9/site-packages/django/template/base.py", line 1000, in render return SafeString("join([node render_annotated(context) for node i self) File "/data/user/0/ru.iec.pydroid3/files/aarch64-linux-android/lib/py thon3.9/site-packages/django/template/base.py", line 1000, in return SafeString( .join([node render annotated(context) for node i self))) File "/data/user/0/ru, ilec.pydroid3/files/aarch64-linux-android/lib/py thon3.9/site-packages/django/template/base.py", line 958, in render anno tated return self.render(context) File "/data/user/0/ru.iec.pydroid3/files/aarch64-linux-android/lib/py thon3.9/site-packages/django/template/base.py", line 1059, in render output = self, filter_expression, resolve(context) File "/data/user/0/ru. iiec.pydroid3/files/aarch64-linux-android/lib/py thon3.9/site-packages/django/template/base.py", line 735, in resolve obj = template_localtime(obj, context, use_tz) File "/data/user/0/ru.iec.pydroid3/files/aarch64-linux-android/lib/py thon3.9/site-packages/django/utils/timezone.py", line 184, in template I ocaltime return localtime(value) if should convert else value File "/data/user/0/ru.iec.pydroid3/files/aarch64-linux-android/lib/py thon3.9/site-packages/django/utils/timezone.py", line 203, in localtime timezone get_current_timezone() = File "/data/user/0/ru.iec.pydroid3/files/aarch64-linux-android/lib/py thon3.9/site-packages/django/utils/timezone.py", line 84, in get_current timezone return getattractive, "value", get_default_timezone()) File "/data/user/0/ru.lec.pydroid3/files/aarch64-linux-android/lib/py thon3.9/site-packages/django/utils/timezone.py", line 70, in get_default timezone return zoneinfo. ZoneInfo(settings. TIME ZONE) File "/data/user/0/ru.iec.pydroid3/files/aarch64-linux-android/lib/py thon3.9/zoneinfo/common.py", line 24, in load tzdata raise ZoneInfoNotFoundError("No time zone found with key (key}") zoneinfo, common, ZoneInfoNotFoundError: 'No time zone found with key UTC ་ [26/Jul/2022 13:41:38] "GET /admin/login/?next=/admin/ HTTP/1.1" 500 59 -
Django user authentication with Azure AD and app roles
Outline I want to integrate Azure Active Directory for authentication and authorization. Question How do I integrate the msal library into a Django web app, because the official Azure examples are using Flask? And how to map the AppRoles I have defined in the Azure AD app registration to Django groups defined in the Django backend? -
celery_beat relations not found by postgres using docker
I have a Django app with Nginx, Gunicorn, PostgreSQL and Celery that I've been dockerizing. When trying to add celery_beat in my docker-compose.yml, I get a django.db.utils.ProgrammingError: relation "django_celery_beat_periodictask" does not exist even though the migrations have been ran successfully. Locally, starting celery_beat works fine, but here it returns this error and I have no idea where it could be coming from. Postgres doesn't seem to find the relation django_celery_beat_periodictask but it should since the migrations were done. Is there something I misunderstood ? Here is my docker-compose.yml: version: '3.8' services: rabbitmq3: container_name: rabbitmq image: rabbitmq:3-alpine ports: - 5672:5672 postgres: container_name: postgres hostname: postgres image: postgres:latest env_file: - env environment: - POSTGRES_USER=user - POSTGRES_PASSWORD=password - POSTGRES_DB=db ports: - "5432:5432" restart: on-failure volumes: - postgresql-data:/var/lib/postgresql/data django_gunicorn: container_name: django_gunicorn volumes: - static:/app/static - media:/app/media env_file: - env build: context: . ports: - "8000:8000" command: sh -c "python manage.py migrate && python manage.py collectstatic --no-input && gunicorn main.wsgi:application --bind 0.0.0.0:8000" depends_on: - postgres nginx: container_name: nginx build: ./nginx volumes: - .:/code - static:/static ports: - "80:80" depends_on: - django_gunicorn celery: container_name: celery volumes: - media:/app/media build: context: . command: celery -A main worker -P eventlet -c 100 -l INFO env_file: - env restart: … -
what's the equivalent of django orm's values_list in sqlalchemy?
I want to extract all the ids of the first query old_devices_or_user_tokens = DeviceDAO(session=session).filter__or(user_id=user.id,device_id=token_obj.device_id) DeviceDAO(session=session).delete(synchronize_session=False, ) so that i can pass the list of ids in the delete statement with something like DeviceDAO(session=session).delete(synchronize_session=False, id__in=old_devices_or_user_tokens) In django ORM i could have just done old_devices_or_user_tokens.values_list('id', flat=True) -
How do I loop a intergerFIeld in django templates?
I have to loop an element according to the dynamic data. I have an INTeger Field. Here's what I want to loop: <li class="list-inline-item"><i class="fas fa-star text-warning"></i></li> about 5 times max and 1 min. Thanks -
Django not finding database object when trying to render view
I'm getting the following error when I go to the /val/4/13/bs url: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/val/4/13/bs Raised by: valapp.views.BSDetail No balance sheet found matching the query Here is the views.py code: class BSDetail(generic.View): def get(self, request, *args, **kwargs): view = BSDisplay.as_view() return view(request, *args, **kwargs) def post(self, request, *args, **kwargs): view = PostEvent.as_view() return view(request, *args, **kwargs) class BSDisplay(generic.DetailView): template_name = 'valapp/balsheet.jinja' model = BalanceSheet def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) entityobject = get_object_or_404(Entity, pk=self.kwargs['pkent']) context['bsinfo'] = BalanceSheet.objects.filter(company = entityobject) return context class EntityDetail(generic.View): def get(self, request, *args, **kwargs): view = EntityDetailDisplay.as_view() return view(request, *args, **kwargs) class EntityDetailDisplay(generic.DetailView): model = Entity template_name = 'valapp/entitydetail.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) engobject = get_object_or_404(Engagement, pk=self.kwargs['pk']) entobject = get_object_or_404(Entity, pk=self.kwargs['pkent']) context['engagement'] = engobject context['entity'] = entobject return context The urls.py code is: app_name = 'valapp' urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('<int:pk>/', views.ValDetailView.as_view(), name='engagement'), path('<int:pk>/<int:pkent>/', views.EntityDetail.as_view(), name='entitydetail'), path('<int:pk>/<int:pkent>/bs', views.BSDetail.as_view(), name='bs'), path('newval/', views.newval, name="newval"), path('<int:pk>/newentity/', views.NewEntity.as_view(), name="newentity"), ] Here is the models.py: class BalanceSheet(models.Model): company = models.ForeignKey(Entity, on_delete=models.CASCADE) account_type = models.CharField(max_length=50, choices = BS_ACT_CHOICES) value = models.DecimalField(max_digits=20, decimal_places=2) name = models.CharField(max_length=100) year = models.IntegerField(choices=YEAR_CHOICES, default=2022) tab_abv = models.DecimalField(max_digits=20, decimal_places=2, default=0) tab_rdt = models.DecimalField(max_digits=20, decimal_places=2, default=0) tab_debt = … -
How to upload images to wagtail images using django rest framework?
I have a bit of a problem, any help would be appreciated: I have a model which has an icon field, which is related to wagtailimages.Image How do I upload images to that field which is ForeignKey related to wagtailimages.Image This is the serializer of my model: class CommunitySerializer(serializers.ModelSerializer): class Meta: model = Community fields = [ "id", "icon", "name", "description", "short_description", "website", ] And this is my models.py: class Community(ClusterableModel): ............ icon = models.ForeignKey( "wagtailimages.Image", null=True, blank=True, on_delete=models.SET_NULL, related_name="+", ) .......... So, how should i go about uploading images to the "icon" field using DRF? I have tried to use both the DRF's FileField and ImageField but without success, maybe I am missing something? -
How can I get a size of SVG in Python?
From Django CMS admin I upload a SVG image and I need to validate its size For some other formats (jpeg, png) it works just fine def validate_social_icon(fieldfile_obj): w, h = get_image_dimensions(fieldfile_obj) if w > 100: raise ValidationError("The icon width must be <= 100 pixels. Yours is %i pixels." % w) if h > 100: raise ValidationError("The icon height must be <= 100 pixels. Yours is %i pixels." % h) But if I upload a SVG file, it says h and w are None, so there is an exception bc Python can't compare None to int. Is there a similar way to do that for SVG? -
Placing functions in vue.js that accept parameters and do not operate on variables in the component
I've been trying to wrap my head around best practices in vue.js (+ pinia as store). I'm coming from using Django templates where one can use template functions on variables to massage data for displaying. However, I'm not sure where to put such functions in vue.js. Suppose I have a variable holding a string and I want to cut off trailing digits. The variable is coming from a vue.js for-loop over a dict variable present in the store. I would create some function to do so: displayString(s) { const re = /\d+$/; return s.replace(re, ""); } I would use it in the template in some way: <th v-for="(item, index) in store.myDict" :key="index"> {{ displayString(item) }} </th> To me, neither place for putting the function (methods/computed or actions/getters in pinia) would be right as they are all intended to use data from the store or component (and not all of them accept parameters anyway). Conceptually, where would a function go that does not return data from the component or store but accepts a parameter and returns a modified version of it? Or should I design things differently, writing getters/computed functions that massage the dict in some way for displaying the data? … -
invalid connection option "ssl" when connecting to postgres using sqlalchemy
I used this code to connect my django application with postgresql using sqlalchemy ORM: DB_CONN_STRING = "{driver}://{user}:{password}@{host}:{port}/{dbname}?options='-c client_encoding=utf8&sslmode=require".format( driver=settings.DATABASES['db']['ENGINE'].split('.', -1)[-1], user=settings.DATABASES['db']['USER'], password=settings.DATABASES['db']['PASSWORD'], host=settings.DATABASES['db']['HOST'], port=settings.DATABASES['db']['PORT'], dbname=settings.DATABASES['db']['NAME']) db_engine = sqlalchemy.create_engine(DB_CONN_STRING, echo=settings.SQLALCHEMY_ECHO, pool_recycle=1800, pool_size=1, max_overflow=9, pool_use_lifo=True, pool_pre_ping=True, connect_args=ssl_args) db_session = scoped_session(sqlalchemy.orm.sessionmaker(bind=db_engine), scopefunc=get_current_request_id) But it raises this error when I run select query: (psycopg2.ProgrammingError) invalid dsn: invalid connection option "ssl" Is there a wrong with my connection string? -
Django TabularInline and field from related models
using django admin on an existing database i set up a many to many relation between "Contact" and "Groupe" based on a intermediate model "Contactgroup". In the "Group" Admin form i add a tabular in line to show all Contactgroup. It's OK but i get on error while adding fields from related Contact. model.py class Contact(models.Model): id = models.IntegerField(primary_key=True) e_mail = models.TextField() ... class Contactgroup(models.Model): id = models.IntegerField(primary_key=True) id_contact = models.ForeignKey(Contact, on_delete=models.CASCADE,db_column="id_contact", blank=False, null=False, verbose_name='Contact') id_groupe = models.ForeignKey(Groupe, on_delete=models.CASCADE,db_column="id_groupe", blank=False, null=False, verbose_name='Groupe') admin.py class MyContactgroupInline(admin.TabularInline): model = Contactgroup fields = ['id','id_contact'] MyGroupeModelAdmin.inlines = [MyContactgroupInline,] Then i try to add the Contact e_mail field : class MyContactgroupInline(admin.TabularInline): model = Contactgroup fields = ['id','id_contact', 'id_contact__e_mail'] MyGroupeModelAdmin.inlines = [MyContactgroupInline,] I get : Unknown field(s) (id_contact__e_mail) specified for Contactgroup -
Django path in pycharm
PS C:\Users\rajla> django-admin startproject mymall . django-admin : The term 'django-admin' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 django-admin startproject mymall . + CategoryInfo : ObjectNotFound: (django-admin:String) [], CommandNotFoun dException + FullyQualifiedErrorId : CommandNotFoundException this is the issue i am facing i am totally confused and i am getting headache so please help me -
TypeError: all() missing 1 required positional argument: 'self' while using AbstractUser model
class User(AbstractUser): nickname = models.CharField(max_length=32) birthday = models.DateField() objects = MyUserManager class Meta: ordering = ('-id',) I created an custom user model and defined the MyUserManager class to manage the model. class MyUserManager(UserManager): def _create_user(self, username, email, password, **kwargs): if not username: raise ValueError('id는 필수입니다.') user = self.model(email=self.normalize_email(email), **kwargs) user.set_password(password) user.save() return user def create_user(self, username, email=None, password=None, **kwargs): kwargs.setdefault('is_admin', False) return self._create_user(username, email, password, **kwargs) def create_superuser(self, username, email=None, password=None, **kwargs): kwargs.setdefault("is_staff", True) kwargs.setdefault('is_admin', True) return self._create_user(username, email, password, **kwargs) I was going to create a createuse function that receives values for the custom fields as parameters. However, first of all, I would like to resolve the errors that have occurred now. class UserViewSet(ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializers This is views.py in account app and error have occured this code. Why can't I find a self instance? What instance does the original User.objects return? Is there a problem with the MyUserManager class? -
How to order a queryset using related_name in django
I've got a User model which is related to the DriverCar model using related_name='driver'. Each user could be related to multiple drivercars. DriverCar model has a field "reference_number" of type integer. I want to show a list of all users ordered by thereference_number of the last DriverCar object related to the user. Using a query like User.objects.filter(archive=False).order_by('-driver__reference_number') gives me the wrong answer. But if I use order_by('-pk') everything works perfectly. Is there any way to do this correctly? class User(AbstractUser): archive = models.BooleanField(default=False) class DriverCar(models.Model): user = models.ForeignKey(User , on_delete=models.CASCADE , related_name='driver') reference_number = models.BigIntegerField(default=0, null=True, blank=True) -
How to update db setting in django at runtime?
To be more specific, I want to retrieve db setting from a config server when django project starts, and use it to setup django db connection Someday in the future, the setting in the config server may be changed (for example, change the user password) and pushed to django project then reset the db connection, so I can use new setting without restarting django project or updating project code Is there a way to do that? Or what's the right way to hide the db sensitive information (password, etc) from django project code? Any helps will be grateful, thanks~ -
How To Add UPI method in Django or DJANGO REST FRAMEWORK [closed]
How To Add UPI method in Django or DJANGO REST FRAMEWORK lIKE THIS IN BELOW Image -
Python Sendgrid send email with all extension file attachment django
I want to send an email with an attachment using SendGrid API with all extensions in Django. Here is my code for mail sending. views.py def submitTicket(request): try: if request.method == 'POST': name = request.POST.get('name') email = request.POST.get('email') subject = request.POST.get('subject') comment = request.POST.get('comment') atchfile = request.FILES['fileinput'] allinfo = " Name : " + name + "\n E-Mail : " + email + "\n Comment : " + comment recipients_list = ['abc@gmail.com'] if allinfo: message = Mail(from_email='xxx@gmail.com', to_emails=recipients_list, subject=subject, html_content=allinfo) with open(atchfile, 'rb') as f: data = f.read() f.close() encoded_file = base64.b64encode(data).decode() attachedFile = Attachment( FileContent(encoded_file), FileName(atchfile), FileType(atchfile), Disposition(atchfile) ) message.attachment = attachedFile sg = SendGridAPIClient('0000000000000000000000000000000') sg.send(message) return HttpResponseRedirect('submitTicket') except Exception as e: print("Exception = ", e) return render(request, 'submitTicket.html') I am getting below error while trying to perform this. TypeError at /submitTicket expected str, bytes or os.PathLike object, not InMemoryUploadedFile -
Django Admin site with different Superuser permissions and roles
In addition to default superuser " that has access to all apps in the project and all permissions " I want to create two more types of superuser, The maker has able to do All operations Of CRUD on all apps without executing in database in django admin , And the checker has to view one table " operations " to Approve or reject these operations. is superuser = True is_superuser with is_maker = True is_superuser with is_checker = True How could I check the user login in admin.py Django admin site panel to control other stuff ? models.py class User(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) is_maker = models.BooleanField(blank=True, null=True, default=False) is_checker = models.BooleanField(blank=True, null=True, default=False) class Operation(models.Model): name = models.CharField(max_length=255, blank=True, null=True) model_name = models.ForeignKey(ContentType, blank=True, null=True, on_delete=models.SET_NULL) old_value = models.TextField(default='', null=True, blank=True) new_value = models.TextField(default='', null=True, blank=True) rejection_reason = models.TextField(null=True, blank=True, default='') status = models.CharField(choices=STATUS_CHOICES, max_length=50, blank=True, null=True, default=STATUS_PENDING) created_by = models.ForeignKey(User, blank=True, null=True, db_column='created_by', on_delete=models.CASCADE) -
Can't import youtubesearchpython into my code
Pip install youtube-search-python And than when i try : from youtubesearchpython import * I see an error tells me that the module not found What is the problem -
Django won't load admin dashboard css with ngnix
I have a problem that has been holding me up in development for 1 week and I can't get out of it by seeing other users' answers. My project consists of a backend in Django and a frontend in React, the whole application is Dockerized and is served using ngnix. Now with the current configuration the Django css is not loading, what am I doing wrong? I thank everyone for the help. settings.py # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/4.0/howto/static-files/ BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static', 'static') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'static', 'media') urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', include('DigitalMapping.urls')), path('test', test, name='test'), path('notificationCompletedOperation', NotificationCompletedOperation, name='notificationCompletedOperation'), path('notificationErrorOperation', NotificationErrorOperation, name='notificationErrorOperation'), path('', include('notifications.urls')), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) Dockerfile FROM python:3.8.5 WORKDIR /backend COPY ./ ./ RUN pip install --upgrade pip RUN pip install -r requirements.txt RUN python manage.py collectstatic ENV PYTHONPATH ./backend default.conf upstream django { server django:8002; } server { listen 8080; location / { root /var/www/react; } location ~ ^/(api|admin)/ { proxy_pass http://django; proxy_set_header Host $http_host; if ($request_method = 'OPTIONS') { add_header 'Access-Control-Allow-Origin' '*'; # # Om nom nom cookies # add_header 'Access-Control-Allow-Credentials' 'true'; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS'; # # Custom … -
TailwindCSS infinite reloading bug in Django-app on Heroku
I'm running a Django-app on Heroku and use TailwindCSS. When I deploy, the app ends up endlessly loading. Looking at Network in Chrome's dev-tool, I noticed that the endless loading originates from my app trying to load browser-sync-client.js. Basically, it waits for ~4 minutes for that script to load, doesn't get a response, and then stops loading. The app works perfectly fine, it's just annoying to have something loading in the back all the time. What I've tried so far is following the answer to this question. So I've edited the tailwind.config.js file's purge settings to include the right HTML/js files. But this still won't fix the endless loading bug. Has anybody experienced something similar? Any ideas on how to fix this? -
How to use Group by clause without model's id in Django ORM?
This is my Model class Model1(models.Model): category = models.CharField() name = models.CharField() I want to get count of category. So I wrote ORM like below: from django.db.models import Count result = Model1.objects.values('category').annotate(Count('sns_type')) but the result shown like below <QuerySet [{'category': 'A', 'category__count': 1}, {'category': 'B', 'category__count': 1},...]> I felt so weird, so I printed a query of this result. query shown like below SELECT "example_table"."category", COUNT("example_table"."category") AS "category__count" FROM "example_table" GROUP BY "example_table"."category", "example_table"."id" I don't know Why id is included in this query. Query I want to use is like below: SELECT "example_table"."category", COUNT("example_table"."category") AS "category__count" FROM "example_table" GROUP BY "example_table"."category"