Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Replace or extend User model in Django 3 in custom model
I am trying to replace User model or Extend (not sure what indeed), in Django for being able to use authenticate() and decorators as @login_required and/or permissions in my methods. Why I am doing this? may you ask. Is because the Django project is not following the best practices or orthodox ways of the framework. Before me was another developer taking this kind of desicions. The project is in an advanced stage. Ok, my model is this (only this no Meta or anything more in this class): class UsuarioDiplomado(models.Model): nombres = models.CharField(max_length=50) apellidos = models.CharField(max_length=50) telefono = models.CharField(max_length=20) celular = models.CharField(max_length=20) correo = models.CharField(max_length=70) fecha_nacimiento = models.DateField() rol = models.ForeignKey("core.Rol", on_delete=models.PROTECT) activo = models.BooleanField(default=True) eliminado = models.BooleanField(default=False) password = models.CharField(max_length=20, default='123') hashusuario = models.CharField(max_length=100, default='') sucursal = models.ForeignKey("core.Sucursal", on_delete=models.PROTECT, default=1) this is the class that I want to use as extension of User class specifically the fields correo (email), and password in the settings.py I setup AUTH_USER_MODEL = 'colposcopia.UsuarioDiplomado', but as expected not working because lacks of the REQUIRED_FIELDS AttributeError: type object 'UsuarioDiplomado' has no attribute 'REQUIRED_FIELDS' I am not sure how can achive this? or what I need to do this. Can you shine some light please? -
Javascript Date unnecessarily adjusts for timezone
I am storing a date as a django DateField in my database. It simply looks like "2020-06-25" in the database. This string is returned from my api, and passed into a javascript "Date" as such: date = new Date(due_date) logging this date results in: Wed Jun 24 2020 17:00:00 GMT-0700 (Pacific Daylight Time) I don't care about the time, only the date. How do I get javascript Date to ignore the time, and not adjust for the difference in timezone between the DB and the local user? If a user sets the due date for a project in one timezone, I want every person to see the same due date. -
trying to make django load environment vars from a .env.local file using django-environ from within a venv
I keep getting this traceback (pythonApp) D:\task_trackv2>python manage.py makemigrations D:\task_trackv2\apps_config\settings.py D:\pythonApp\lib\site-packages\environ\environ.py:637: UserWarning: Error reading .env.local - if you're not configuring your environment separately, check this. warnings.warn( D:\task_trackv2\apps_config\settings.py D:\task_trackv2\apps_config\settings.py Traceback (most recent call last): File "D:\pythonApp\lib\site-packages\environ\environ.py", line 273, in get_value value = self.ENVIRON[var] File "c:\users\belkin\appdata\local\programs\python\python38-32\lib\os.py", line 675, in __getitem__ raise KeyError(key) from None KeyError: 'SECRET_KEY' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "D:\pythonApp\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "D:\pythonApp\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "D:\pythonApp\lib\site-packages\django\core\management\base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "D:\pythonApp\lib\site-packages\django\core\management\base.py", line 366, in execute self.check() File "D:\pythonApp\lib\site-packages\django\core\management\base.py", line 392, in check all_issues = self._run_checks( File "D:\pythonApp\lib\site-packages\django\core\management\base.py", line 382, in _run_checks return checks.run_checks(**kwargs) File "D:\pythonApp\lib\site-packages\django\core\checks\registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "D:\pythonApp\lib\site-packages\django\core\checks\translation.py", line 60, in check_language_settings_consistent get_supported_language_variant(settings.LANGUAGE_CODE) File "D:\pythonApp\lib\site-packages\django\conf\__init__.py", line 76, in __getattr__ self._setup(name) File "D:\pythonApp\lib\site-packages\django\conf\__init__.py", line 63, in _setup self._wrapped = Settings(settings_module) File "D:\pythonApp\lib\site-packages\django\conf\__init__.py", line 142, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "c:\users\belkin\appdata\local\programs\python\python38-32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked … -
Django day and time picker
I'm trying to build my first website with django,I've accomplished user registration and login so far but now I'm stuck: I want to show to the users a weekly calendar where they can pick a day and book a gym class. I tried to handle every week day like a form field but it didn't work. Any advice on how I should tackle this? I'm looking for something like an explanation/a tutorial and would avoid a github project, if possible. Thank you! -
Cannot modify/override templates for django-allauth and django-comments-xtd
I have a Django project using Wagtail CMS. I'm using django-allauth for user accounts and django-comments-xtd for handling comments on the blog. I want to modify the templates for both of these apps. I've followed directions for doing so from their respective documentation, tutorials, and answers here on SO, but nothing I've tried works. (For reference, these SO answers have not helped.): override templates in django-allauth How to override template in django-allauth? Unable to override django-allauth templates What I've done is copied the templates I wanted to modify from site-packages/allauth/templates/account and site-packages/django_comments_xtd/templates/comments and into my project's templates directory (project/mysite/templates/account and project/mysite/templates/comments, respectively). However, when I modify the copied templates in my project's templates directory, the changes are not reflected. For fun, if I delete the templates in the site packages directory, then I get an error saying the templates do not exist. What's strange is that the first place Django looks for the templates is in my project's templates directory (and they are there), yet I get the error. Also, if I modify the templates under site packages directory, the changes ARE reflected, but I know this is bad practice because if I update these packages, my changes will be … -
Why is Django adding an extra character to the table name of a legacy database?
I am following this_site for onboarding a legacy database. Though, irregardless of the method used Django is adding an extra character (an s) to the only table within a legacy sqlite database (table: Dogs). Screenshot below of the extra character: And my entire models.py below. Accessing the database through python's sqlite library I can query the table 'dogs' and get expected results where as querying 'dogss' yields the error "no such table: dogss". from django.db import models from datetime import datetime # Create your models here. class Tutorial(models.Model): tutorial_title = models.CharField(max_length=200) tutorial_content = models.TextField() tutorial_published = models.DateTimeField('date published', default=datetime.now()) def __str__(self): return self.tutorial_title class Dogs(models.Model): #id = models.AutoField(primary_key=True) date_of_death = models.TextField(db_column='Date of Death', blank=True, null=True) # Field name made lowercase. Field renamed to remove unsuitable characters. land_of_birth = models.TextField(db_column='Land of Birth', blank=True, null=True) # Field name made lowercase. Field renamed to remove unsuitable characters. registered_name = models.TextField(db_column='Registered Name', blank=True, null=True) # Field name made lowercase. Field renamed to remove unsuitable characters. call_name = models.TextField(db_column='Call Name', blank=True, null=True) # Field name made lowercase. Field renamed to remove unsuitable characters. breeder_name = models.TextField(db_column='Breeder_name', blank=True, null=True) # Field name made lowercase. registration_field = models.TextField(db_column='Registration#', blank=True, null=True) # Field name made lowercase. Field renamed … -
Not able to deploy Django properly on Cpanel (static part)
I tried all steps and commands to enable the static part when project deployed on Cpanel python app but I failed. Please help me out. Thanks in advance. Deployed: Deployed my codes on Cpanel on goDaddy Images which are visible are from imported from the Internet not from static file Expected: (On local machine) I'm able to open each tab in local but getting 404 error on deployed one. views.py from django.shortcuts import render, redirect from django.contrib import messages from django.http import HttpResponse from django.http import HttpResponseRedirect from .forms import ManuForm def home(request): if request.method == 'GET': return render(request, 'manufacture_page/homepage.html', {'form': ManuForm()}) else: try: form = ManuForm(request.POST) if form.is_valid(): form.save(commit=True) messages.info(request, 'Thanks! Will contact you back.') return redirect(request.META['HTTP_REFERER']) else: print("IN ERROR") errmsg= str(form.errors) print(errmsg) if "Phone already exists" in errmsg: errmsg="Error!! Entered Number already exists!" elif "Enter a valid phone number" in errmsg: errmsg="Error!! Enter number with country code. (e.g. +917529984220)." else: errmsg="Error!! Bad data passed in!" messages.error(request,errmsg) # return render(request.META['HTTP_REFERER'], 'homepage.html', {'form': ManuForm(), 'error': errmsg}) return redirect(request.META['HTTP_REFERER'], {'form': ManuForm(), 'error': errmsg}) return redirect(home) except ValueError: return render(request, 'manufacture_page/homepage.html', {'form': ManuForm(), 'error':'Bad data passed in!'}) def about(request): return render(request, 'manufacture_page/about.html') def services(request): return render(request, 'manufacture_page/services.html') settings.py import os BASE_DIR = … -
Node js vs Django vs Flask for multiple videos streaming from python
I got 6 real-time videos which are inference output from heavy deep learning calculation from python, and I've tried to display them to PyQt that lots of threading issues with ugly GUI!!. So, I want to use a framework only to display well and fancy GUI! There seem lots of frameworks based on my google search, and I have no idea which one is the best for my current project among Node js, Django, and Flask! I need to display 6 real-time videos with 10~15 FPS. Communicating well with python. Easy to build GUI, I have some features like logging, displaying real-time graph(optional) -
How to convert django.request logger time to UTC?
I have an application in another timezone, but I want to keep all logs in UTC. I already defined my own Formatter for Python logging, and all logger calls that I have throughout the app, are all using UTC, but django.request logs, are still using locale's app timezone (both logs bellow, were generated by a single request): Django Request Logger: [10/Jun/2020 16:59:52] "POST /api/v1/report/ HTTP/1.1" 200 761 Application Logger: [10/Jun/2020 23:00:02] INFO - REPORT_OK {'country': 'USA', 'ip': '127.0.0.1'} How can I apply a similar approach to django.request logger? -
NoReverseMatch at / Reverse for 'detail' with arguments '('',)' not found. 1 pattern(s) tried:
I'm following django tutorial step by step, but can't to find out why I'm getting this error: NoReverseMatch at /polls/ Reverse for 'detail' with arguments '('',)' not found. 1 pattern(s) tried: ['polls/(?P<pk>[0-9]+)/$'] My code(basically everything copied from tutorial - https://docs.djangoproject.com/en/3.0/intro/tutorial03/) views.py: class IndexView(generic.ListView): template_name = 'polls/index.html' context_object_name = 'latest_question_list' def get_queryset(self): """ Return the last five published questions (not including those set to be published in the future). """ return Question.objects.filter( pub_date__lte=timezone.now() ).order_by('-pub_date')[:5] polls/urls.py app_name = 'polls' urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('<int:pk>/', views.DetailView.as_view(), name='detail'), path('<int:pk>/results/', views.ResultsView.as_view(), name='results'), path('<int:question_id>/vote/', views.vote, name='vote'), ] polls/index.html <li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li> -
Using custom user model in Django always return anonymous user in template
I have created a custom user model since I need three information( email, institute id, password) to login to the system. I have also created an authentication backend for this purpose. when I try to login, it redirects to the correct view. But the template shows anonymous user instead of logged in user. It's not going into this condition {% if user.is_authenticated %}. However, user.is_authenticated is true in view. Can anyone please help me to figure out the problem? Any suggestion will be appreciated. I have attached my code below. Thanks in advance. model.py class UserManager(BaseUserManager): use_in_migrations = True def _create_user(self, email, center_id, password, **extra_fields): values = [email, center_id] field_value_map = dict(zip(self.model.REQUIRED_FIELDS, values)) for field_name, value in field_value_map.items(): if not value: raise ValueError('The {} value must be set'.format(field_name)) email = self.normalize_email(email) user = self.model( email=email, center_id=center_id, **extra_fields ) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, center_id, password=None, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, center_id, password, **extra_fields) def create_superuser(self, email, center_id, password=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(email, center_id, password, **extra_fields) class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField( verbose_name='email address',max_length=255,unique=True,) … -
Unable to send mail to Outlook using PasswordResetView in Django Rest Framework
My urls file looks like this : urlpatterns = [ path('', include(router.urls)), path('password-reset/', PasswordResetView.as_view( #template_name='users/password_reset.html' ), name='password_reset'), path('password-reset/done/', PasswordResetDoneView.as_view( #template_name='users/password_reset_done.html' ), name='password_reset_done'), path('password-reset-confirm/<uidb64>/<token>/', PasswordResetConfirmView.as_view( #template_name='users/password_reset_confirm.html' ), name='password_reset_confirm'), path('password-reset-complete/', PasswordResetCompleteView.as_view( #template_name='users/password_reset_complete.html' ), name='password_reset_complete'), ] My settings.py file also has EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' I have even configured the EMAIL_HOST and EMAIL_PORT in settings.py I have tried using dockerimages like https://hub.docker.com/r/mailhog/mailhog and https://hub.docker.com/r/namshi/smtp as well for setting up SMTP server since my application runs on Docker. But they say that mail sent but I do not recieve any email. I even tried using locallost SMTP server using Django - [Errno 111] Connection refused but that doesnt work. However when I use this line EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' then I can see the email body. I have no idea on how to proceed further. Please help me. -
more than one site ERROR Django uwsgi config problem
I am trying to run multiple websites with Django nginx and uwsgi services. Can you help? django project install aws ec2 amazon.using 80 port runing no problem bu using 81 port Error :502 Bad Gateway nginx/1.14.0 (Ubuntu) ngix settings : upstream app_a { server unix:///home/ubuntu/gym/gym.sock; } upstream app_b { server unix:///home/ubuntu/DemoGym/DemoGym.sock; } server { listen 80; server_name ...163; charset utf-8; client_max_body_size 20M; uwsgi_read_timeout 6000; uwsgi_send_timeout 6000; uwsgi_connect_timeout 6000; keepalive_timeout 6000; location / { include /etc/nginx/uwsgi_params; uwsgi_pass app_a; root /home/ubuntu/gym; } location /static/ { alias /home/ubuntu/gym/crm/static/; } location /media/ { alias /home/ubuntu/gym/media/; } } server { listen 81; server_name ...163; charset utf-8; client_max_body_size 20M; uwsgi_read_timeout 6000; uwsgi_send_timeout 6000; uwsgi_connect_timeout 6000; keepalive_timeout 6000; location / { include /etc/nginx/uwsgi_params; uwsgi_pass app_b; root /home/ubuntu/DemoGym; } location /static/ { alias /home/ubuntu/DemoGym/crm/static/; } location /media/ { alias /home/ubuntu/DemoGym/media/; } } uwsgi settings : [uwsgi] plugins=python3 chdir=/home/ubuntu/gym/ home=/home/ubuntu/env/ module=mdsite.wsgi:application master=True gid=ubuntu uid=ubuntu socket=/home/ubuntu/gym/gym.sock touch-reload=/home/ubuntu/.reload chmod-socket=666 chown-socket=ubuntu vacuum=True env LANG="en-US.utf8" env LC_ALL="en-US.UTF-8" env LC_LANG="en-US.UTF-8" Error :502 Bad Gateway nginx/1.14.0 (Ubuntu) -
Group data by year and month | django rest framework
I have various reports and I want to retrieve them this way: year: "2019", months: [ { month: "01", reports: [reports for jan] } { month: "02", reports: [reports for feb] } ] I've achieved something similar on a full Django project ( see below ) but I'm unable to do the same on drf. def all_reports_by_month(request): reports = Report.objects.all() total_reports = reports.count() ordered_reports = Report.objects \ .annotate(month=TruncMonth('date')) \ .values('month') \ .annotate(c=Count('id')) \ .values('month', 'c') \ .order_by('-month') context = { 'ordered_reports': ordered_reports, 'total_reports': total_reports } return render(request, 'dashboard/reports.html', context) this is the current setup for reports on my DRF back-end right now : model.py : class Report(models.Model): # each code from shop code = models.ForeignKey(Shop, to_field='code' , on_delete=models.CASCADE) clics = models.IntegerField(blank = True, null = True) rdv = models.IntegerField(blank = True, null = True) date = models.DateField(blank = True, null = True) serializers.py : class ReportSerializer(serializers.ModelSerializer): class Meta: model = Report fields = '__all__' views.py : class ReportViewSet(viewsets.ModelViewSet): queryset = Report.objects.all() serializer_class = ReportSerializer urls.py : from rest_framework.routers import SimpleRouter from .views import ReportViewSet router = SimpleRouter() router.register('', ReportViewSet, basename='reports') urlpatterns = router.urls Thanks ! -
Setting up Apache ssl returns 403 error (port 443) mod_wsgi
I'm using apache to serve a Django app using mod_wsgi on windows and it works fine on the HTTP (port 80) but whenever I use port 443 or the SSL it seems that it's trying to access another directory C:/wamp64/www/ here's how my vhosts(port 443) looks # virtual SupervisionTool <VirtualHost *:443> ServerName mydomain.com WSGIPassAuthorization On WSGIApplicationGroup %{GLOBAL} SSLEngine on SSLCertificateFile "etc/ssl/certificate.crt" SSLCertificateKeyFile "etc/ssl/private.key" SSLCertificateChainFile "etc/ssl/ca_bundle.crt" ErrorLog "logs/app.error.log" CustomLog "logs/app.access.log" combined WSGIScriptAlias / "C:\Users\administrator\app\app\wsgi_windows.py" <Directory "C:\Users\administrator\app\app"> <Files wsgi_windows.py> Require all granted </Files> </Directory> Alias /static "C:/Users/administrator/app/static_files" <Directory "C:/Users/administrator/app/static_files"> Require all granted </Directory> Alias /media "C:/Users/administrator/app/media" <Directory "C:/Users/administrator/app/media"> Require all granted </Directory> </VirtualHost> # end virtual SupervisionTool and when I access the app I get this message Apache/2.4.41 (Win64) OpenSSL/1.1.1c PHP/7.3.12 mod_wsgi/4.7.1 Python/3.6 Server at www.mydomain.com Port 80 setting the app I uncommented LoadModule ssl_module modules/mod_ssl.so only in my httpd.conf and the code mentioned above is in my httpd-vhosts.conf and my logs mention this mod_ssl/2.4.41 compiled against Server: Apache/2.4.41, Library: OpenSSL/1.1.1c Init: Session Cache is not configured [hint: SSLSessionCache] Init: Initializing (virtual) servers for SSL AH00455: Apache/2.4.41 (Win64) OpenSSL/1.1.1c PHP/7.3.12 mod_wsgi/4.7.1 Python/3.6 configured -- resuming normal operations AH00403: Child: Waiting for data for listening socket 0.0.0.0:80 client denied by server configuration: C:/wamp64/www/ … -
É possivel utilizar 2 Forengkey em um mesmo model no django?
Estou tentando fazer com que ele pegue o valor de venda do model Estoque automaticamente, assim como ele pega o nome do Produto, porém não consigo colocar 2 relacionamentos no mesmo model. É possível fazer algo do tipo no backend ou terei que fazer no front com javascript por exemplo. Python 3.7 e django 3.0 class Estoque(models.Model): nomeProduto = models.CharField(max_length=120) quantidade = models.DecimalField(max_digits=10, decimal_places=0) valorUnitario = models.DecimalField(max_digits=10, decimal_places=2) valorTotal = models.DecimalField(max_digits=10, decimal_places=2) valorVenda = models.DecimalField(max_digits=10, decimal_places=2) created_at = models.DateField(auto_now_add=True) updated_at = models.DateField(auto_now=True) def __str__(self): return self.nomeProduto class Venda(models.Model): produto = models.ForeignKey(Estoque, on_delete=models.DO_NOTHING, related_name='nomedoproduto') quantidadeProduto = models.DecimalField(max_digits=10, decimal_places=0) **precoVenda = models.ForeignKey(Estoque.valorVenda, on_delete=models.DO_NOTHING, related_name='valorcomercial')** total = models.DecimalField(max_digits=10, decimal_places=2) created_at = models.DateField(auto_now_add=True) updated_at = models.DateField(auto_now=True) -
Django DRF and XLSX binary file uploads from Postman
Hi im trying to upload an XLSX to my django application with DRF. I am getting the follow error { "detail": "Unsupported media type \"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\" in request." } My Header Content-Type is "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet". The Django DRF document tells me DRF is passing me that error when i try to print(request.FILES), but it doesn't really explain how to handle this. Can someone show me how to handle XLSX file uploads? Thanks! -
Django 3: browser doesn't display the content of a variable
I started learning Django 3 from a book. I have the following code: views.py: from django.views.generic import TemplateView class HomepageView(TemplateView): template_name = 'index.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['my_statement'] = 'Nice to see you!' return context index.html <h1>Greetings</h1> <p>Hello, world!</p> <p>{{ my_statement }}</p> The browsers (Opera and Firefox) will display fine the first 2 lines but nothing for the third in the index.html (so urls.py and settings.py should be correct?) Inspecting the page source I see for the third line the opening and closing paragraph tags with nothing in between. If I write abc or whatever before or after the {{ }}, that abc text gets displayed. I have even copy/pasted the code from the book authors, and no change. I'm sure I'm missing something obvious, but what? -
Django Pagination for Component
I'm having trouble getting pagination to work on a component template with a has-many relationship where we have a view for ModelA which has a component template for ModelB, but ModelB does not have its own url. I'm guessing that I have an error in the views.py but I'm not really sure what else I should put to get pagination working for ModelB. Any and all help would be greatly appreciated! I can also put up more code on request. Views: ModelAView(ListView): model: ModelA template_name = 'modela.html' # Model A has-many Model B ModelBView(ListView): model: ModelB template_name = 'modelb.html' # this paginate is not working paginate_by = 10 template for modela.html: {% for a in object_list %} {% include 'modelb.html' with modela=modela %} {% endfor %} template for modelb.html: {% for modelb in modela.modelb.all%} # this is displayed in a table format but not being paginated. ... {% endfor %} urls.py url(r'^modela/$', ModelA.as_view(), name='model-a') -
Django Rest Framework has_object_permission not returning specified "message"
I have created a permission class for Detail View in DRF as below class IsDealOwner(permissions.BasePermission): message = "You are Not Authorized to Access the Deal" def has_object_permission(self, request, view, obj): user_roles = view.request.STRATA_USER_ROLES user_id = view.request.STRATA_USER_ID company_id = view.request.STRATA_COMPANY_ID if settings.CRM_ROLE in user_roles: return True if obj.investor_id == user_id: return True if obj.distributor_id: if obj.distributor_id == user_id: return True if obj.partner_id: if (obj.partner_id == company_id) and (settings.PARTNER_ROLE in user_roles): return True return False But when the object level permission is not specified, I am getting the error "Authentication Credentials were not provided". Why is it not returning the message specified in message attribute (As per DRF docs)? -
Need help designing a permissions system in Django and DRF
I'm trying to design a seemingly simple permissions system in Django and DRF. Right now, I have a user model, User, a custom group model, CustomGroup, an article model, Article, and finally a source model, Source. Just for reference, I'm using Django Rest Framework and Django Guardian. The article model contains a field source. I'd like a system built such that when a user makes a query request for articles, depending on their assigned custom group, return articles that omit articles that belong to a specific source. What I was thinking of implementing was something along the lines of class Source(models.Model): name = models.CharField(max_length=255) class Article: sources = models.ManyToManyField(Source) ... class Meta: permissions = ( 'can_view_source_1', 'Can View Source 1', 'can_view_source_2', 'Can View Source 2', ... 'can_view_source_n', 'Can View Source n' ) From there I can then assign these specific permissions to my custom group model. So, when a user makes a request for a queryset containing n sources, I can then iterate over all the sources by name and check if the user's custom group has permission to view that group. Something like (pseudocode warning!) the code below in my view or serializer. for source in sources_from_queryset: if not … -
Django: Analyse Website to make it quicker
I was wondering what can we use to analyse our code in django. My website seems to show some timeout and some webpage take 2 seconds to open. I`ve attached a screenshot but I would like to know if using bootstrap could be the reason and if I should move to react. -
django elasticsearch-dsl 7.1 check connection before send data to elastic
i have some problem with integration of elasticsearch-dsl to django app this is my documents.py from django_elasticsearch_dsl import Document, fields, Index from django_elasticsearch_dsl.registries import registry from .models import CustomerTransaction, CustomUser # from django.conf import settings customerTransaction = Index('core_custrans') customerTransaction.settings( number_of_shards=1, number_of_replicas=0 ) @registry.register_document class CustomerTransactionDocument(Document): user_emet = fields.ObjectField(properties={ 'slug': fields.TextField(), 'num_cni': fields.TextField(), }) user_recep = fields.ObjectField(properties={ 'slug': fields.TextField(), 'num_cni': fields.TextField(), }) class Index: name = 'custrans' class Django: model = CustomerTransaction fields = [ 'type_trans', 'montant', 'solde_pass', 'solde_actual', 'date_trans' ] def get_instances_from_related(self, related_instance): return related_instance.customertransaction_set.all() @registry.register_document class CustomUserDocument(Document): class Django: model = CustomUser index = 'core_customUsers' fields = [ 'slug', 'num_cni', ] ignore_signals = True class Index: name = "customuser" i want to know how can i check the availability of elastic before saving data in elasticseach to avoid this exception elasticsearch.exceptions.ConnectionError: ConnectionError(<urllib3.connection.HTTPConnection object at 0x7ff6a6890a60>: Failed to establish a new connection: [Errno 111] Connection refused) caused by: NewConnectionError(<urllib3.connection.HTTPConnection object at 0x7ff6a6890a60>: Failed to establish a new connection: [Errno 111] Connection refused) i want to check availability of elastic before saving regards! -:) -
Want to create a non primary key auto field
Is it possible to create a non primary key auto-field? When the format of such order is 01010, 01011, 01012, and so on How will this look on my models.py -
to add dynamic images in django as using background-image (HTML) tag?
My template is this . you can see clickin this [enter link description here][1][1]: https://colorlib.com/wp/template/eatery/ if i show you the html code which is behind <div class="slider-item" style="background-image: url('img/hero_2.jpg');"> <div class="container"> <div class="row slider-text align-items-center justify-content-center"> <div class="col-md-8 text-center col-sm-12 element-animate"> <h1>Delecious Food</h1> <p class="mb-5">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Commodi unde impedit, necessitatibus, soluta sit quam minima expedita atque corrupti reiciendis.</p> <p><a href="#" class="btn btn-white btn-outline-white">Get Started</a></p> </div> </div> </div> </div> Not working like these ways <div class="slider-item" style="background-image: url({%static'/img/hero_1.jpg'%});"> or <div class="slider-item" style="background-image: url{%static'/img/hero_1.jpg'%}"> I don't want to add like an img tag like this way. it is not coming how i am expecting .when i am trying with <img> images are loading well.." <img src="{% static '/img/hero_2.jpg' %}" />" please help me with this thank you