Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django notification system for single user
Hi I would like to create a notification system I created the badge that signals me the notification on its page to see the various notifications and through ajax with the GET method I update the number of notifications. Not being attached to a single user, the count remains the number of notifications and I would like that user who clicks the 'read' button the notification is no longer seen and the conuter decreases. But how do I do it for the single user, I can do it but it would work for each user and not for the single one and that's it. model class Notification(models.Model): date = models.DateField(auto_now_add = True) title = models.CharField(max_length = 255) text = models.TextField() active = models.BooleanField(default = False) view notification + view ajax notification def notifiche(request): if request.is_ajax() and request.method == "POST": notifica = request.POST['id_notifica'] oggetto = get_object_or_404(Notification, id = notifica) if oggetto.active == True: oggetto.active = False messaggio = "Notifica disattivata" else: oggetto.active = True messaggio = "Notifica attiva sul sito" oggetto.save() return JsonResponse({'oggetto': oggetto.active, 'messaggio': messaggio}, status=200) else: notifiche = Notification.objects.all() context = {'notifiche':notifiche, 'popup':popup} return render(request, 'notifiche.html', context) def popup(request): popup = Notification.objects.filter(active = True).count() return JsonResponse({'popup': popup}, status=200) snippets/nav.html … -
Django update content of HTML element on same page based on selected item
The title is a bit vague as I couldn't think of a way to summarise this. I have 3 django models. Let's call them root, branch leaf to make it easy. A root can have multiple branches and each branch can have multiple leaves. In my template I am displaying buttons that are populated from the root objects. When a user clicks one of these buttons I would like to update the content of another element on the same page with all the branches that are children of that root. When a branch is clicked, i'd like to update another element with all the leaves. I'm assuming the process would be the same for the two updates. I am pretty new to Django but not to programming and I can't seem to find a good explanation of how to detect which 'root' has been clicked and pass that back to django in order to populate the branch elements. Can anyone offer some guidance? I probably don't need code, just more of an idea of what the workflow is. E.G use onclick to send the name of the clicked item to a javascript function, call out to a python function that … -
How to apply the same decorator chain to multiple functions
@extend_schema( methods=['GET'], responses={(200, STYLES_MIME_TYPE): OpenApiTypes.BINARY}) @extend_schema( methods=['PUT'], request={STYLES_MIME_TYPE: OpenApiTypes.BINARY}, responses={(204, 'application/json'): OpenApiResponse( response={'type': 'array', 'items': {'type': 'integer', 'format': 'int32'}}, examples=[OpenApiExample( 'Returned style IDs example', status_codes=['204'], value=[101, 102, 103])])}) @api_view(['GET', 'PUT']) @permission_classes([IsAuthenticated|ReadOnly]) @renderer_classes([StylesRenderer, StylesJSONRenderer]) @parser_classes([StylesParser]) def styles(request: Request, pid: int) -> Response: """ Get or save styles for a project. GET - protobuf binary response POST - returnd IDs for saved styles """ try: project = Project.objects.get(pk=pid) return _handle_styles(request, project) except Project.DoesNotExist: raise Http404() @extend_schema( methods=['GET'], responses={(200, STYLES_MIME_TYPE): OpenApiTypes.BINARY}) @extend_schema( methods=['PUT'], request={STYLES_MIME_TYPE: OpenApiTypes.BINARY}, responses={(204, 'application/json'): OpenApiResponse( response={'type': 'array', 'items': {'type': 'integer', 'format': 'int32'}}, examples=[OpenApiExample( 'Returned style IDs example', status_codes=['204'], value=[101, 102, 103])])}) @api_view(['GET', 'PUT']) @permission_classes([IsAuthenticated|ReadOnly]) @renderer_classes([StylesRenderer, StylesJSONRenderer]) @parser_classes([StylesParser]) def styles_xref(request: Request, xref: uuid.UUID) -> Response: """ Get or save styles for a project. GET - protobuf binary response POST - returnd IDs for saved styles """ try: project = Project.objects.get(xref=xref) return _handle_styles(request, project) except Project.DoesNotExist: raise Http404() This is Django, and obviously I want to use the same decorators for those 2 views. The only difference is that one looks up object by int ID, and the other by UUID xref field. How can I keep this DRY? -
import views vs from . import views
I am new to Python and Django, I have an app directory called calc and inside it there are two files: views.py urls.py In urls.py, if I type in import views the server generates an error, however if I type from . import views everything works fine. Could someone explain why? I thought since the two py files are in the same directly, the import statement should match the views.py -
I created folder called Tempelates and written some code in hello_world.html. But i can.t run, how can i set path for that
Base_Dir and tempelate foldeer result -
Why this SQL sentence gets stuck and never finishes
I'm using PostgreSQL and all queries have been working fine for all our users. Except now. Some hours ago, some of the sentences are not working for some users. For instance: select comments from appointments_appointmentlog where id=102501539; If I run this sentence in the psql tool, it runs just fine. But, I use a different id (one of the problematic ones), then it gets stuck: UPDATE appointments_appointmentlog SET comments='A' WHERE id=30042047; The select command works fine though: select comments from appointments_appointmentlog where id=30042047; Any idea what may be happenning? Do you need any additional information? Also, as a side note, I can update, create and delete other rows in the same appointments_appointmentlog table. Note: not sure if relevant, but we are using Django 1.1 (I know I know, too old). The problem can also be reproduced with raw sql though, without using django. -
Adding Google's reCAPTCHA a to a class-based view in Django
I want to add recaptcha for signup view in my Django app. This below uses decorators.py to achieve that. I have tried other tutorials for adding reCAPTCHA also but does not seem working. Any idea why? views.py class signup_view(generic.CreateView): form_class = RegisterForm template_name = 'users/signup.html' success_url = reverse_lazy('users:login') def form_valid(self, form): if self.request.recaptcha_is_valid: form.save() return render(self.request, 'users/login.html', self.get_context_data()) return render(self.request, 'users/signup.html', self.get_context_data()) urls.py path("signup", check_recaptcha(signup_view.as_view()), name="signup"), decorators.py from django.conf import settings from django.contrib import messages import requests def check_recaptcha(function): def wrap(request, *args, **kwargs): request.recaptcha_is_valid = None if request.method == 'POST': recaptcha_response = request.POST.get('g-recaptcha-response') data = { 'secret': settings.GOOGLE_RECAPTCHA_SECRET_KEY, 'response': recaptcha_response } r = requests.post('https://www.google.com/recaptcha/api/siteverify', data=data) result = r.json() if result['success']: request.recaptcha_is_valid = True else: request.recaptcha_is_valid = False messages.error(request, 'Invalid reCAPTCHA. Please try again.') return function(request, *args, **kwargs) wrap.__doc__ = function.__doc__ wrap.__name__ = function.__name__ return wrap signup.html <div class="form"> <form method="POST"> {% csrf_token %} {{ form|crispy }} <br> <script src='https://www.google.com/recaptcha/api.js'></script> <div class="g-recaptcha" data-sitekey="6LfzEg8gAAAAABcVpBvOjuLjs787K8_4Fu0N2wgu"></div> <input type="submit" value="Sign Up"> </form> </div> -
RabbitMQ server not running
Application rabbitmq_prelaunch exited with reason: {{shutdown,{failed_to_start_child,prelaunch,{duplicate_node_name,"rabbit","LEON"}}},{rabbit_prelaunch_app,start,[normal,[]]}} {"Kernel pid terminated",application_controller,"{application_start_failure,rabbitmq_prelaunch,{{shutdown,{failed_to_start_child,prelaunch,{duplicate_node_name,"rabbit","LEON"}}},{rabbit_prelaunch_app,start,[normal,[]]}}}"} Kernel pid terminated (application_controller) ({application_start_failure,rabbitmq_prelaunch,{{shutdown,{failed_to_start_child,prelaunch,{duplicate_node_name,"rabbit","LEON"}}},{rabbit_prelaunch_app,start,[normal,[]]}}}) Crash dump is being written to: erl_crash.dump...done -
Count different values of user over a period of time with selecting the latest for that day
I was trying to get models value over a period of time in django. The model is used to keep kind of activity log. class Activity(models.Model): PLACE_CHOICES = (('home', 'Home'),('office', 'Office')) userId = models.IntegerField() date = models.DateField() place = models.CharField(max_length=25, choices=PLACE_CHOICES) An user can have multiple place for a day ('place' can be duplicate) but I need only the latest model for that day. I need to group data over a period of time (say 15 days) for multiple user, filtering args are something like this, Activity.objects.filter(userId__in=[1,2], date__gte='2022-01-01', date__lte='2022-01-15') This is only to show the filtering. I tried other methods,like- Activity.objects.filter( userId__in=[1,2], date__gte='2022-01-01', date__lte='2022-01-15' ).annotate( home=Count('place', distinct=True, filter=Q(place='home'), office=Count('place', distinct=True, filter=Q(place='home') ).values('userId','home','office') I need values like this [{userId:1, home:4, office:3},{userId:2, home:1, office:3}] -
Write the URL in a variable in the Django view
I want to put a link inside a variable (in View Django) But I get a error. In the slug section (slug =% slug), Python confuses % url with %u! Error: %u format: a number is required, not str I use the Folium library and want to put a link in the popup. So, I can not use the normal mode and I have to use another method. for i in range(10): slug=i url = Template( """ <!DOCTYPE html> <html> <body> <a href="{% url 'test' slug= %slug %}" target="_blank" style=" text-align: right; ">Mor Info</a> </body> </html> """%slug).render(Context({})) popup = folium.features.GeoJsonPopup( fields=["name"], aliases=[f'{url}'], labels=True, localize=True, style="background-color: yellow;") -
Annotate Fields in django_filter
I am using django_filters for search by a big query with annotates: https://django-filter.readthedocs.io/en/stable/ My question is, exist some way to filter by Annotate fields? For example, by whateverannotate? whateverquery=Whatever.objects.filter(query).values('whatever').annotate( total=Count('id'), whateverannotate=Count(Case(When(whatever_field="whateveValue", then=1),output_field=IntegerField()))).values('whateverannotate','total').order_by(order) response_form=WhateverFilter(request.GET, queryset=whateverquery) filtered_qs = response_form.qs Filter class SupplierFilter(django_filters.FilterSet): Choices_options =( ('',''), ('Si','Si'), ('No','No'), ('Todos','Todos')) whateverannotate = django_filters.ChoiceFilter(label="whateverannotate",choices=Choices_options,method='whateverannotate_order') class Meta: model = Supplier fields = { 'whateverannotate': ['lt', 'gt','exact'], } def everannotate_order(self,queryset,name,value): return queryset -
Custom Django Admin page loses URLS
I am trying to create a customised django-admin, with a separate page that is referenced in the app_list. I have used https://stackoverflow.com/a/70446680 as a basis and can obtain the custom admin page. However, when I return to the admin home, all of the apps in the app_list are lost except the custom one. I can remedy this by setting admin_urls = admin.site.get_urls() but when I do, my custom admin site no longer has a get_app_list method defined (from https://stackoverflow.com/a/56476261), so my app_list in admin, does not show the 'tcptraceroute' app. from django.contrib.admin import AdminSite class CustomAdminSite(AdminSite): def get_urls(self): admin_urls = super().get_urls() # admin.site.get_urls() works to return the previously defined app urls # but I then lose the get_app_list method from the CustomAdminSite class print(admin_urls) custom_urls = [ path('django_restic/', views.Restic.as_view(), name="restic_home"), ] return custom_urls + admin_urls # custom urls must be at the beginning def get(self): request.current_app == self.name return super().get(request) def get_app_list(self, request): app_list = super().get_app_list(request) app_list += [ { "name": "My Custom App", "app_label": "my_test_app", # "app_url": "/admin/test_view", "models": [ { "name": "tcptraceroute", "object_name": tcptraceroute, "admin_url": "/admin/test_view", "view_only": True, } ], } ] return app_list site = CustomAdminSite() I have tried rearranging my app orders in installed apps, and … -
Trying to add some fields in my models to django group
Hy everyone, am new to Django. I created this model to mimic Facebook's group functionality a bit from django.db import models from profiles.models import Profile from django.contrib.auth.models import Group # Create your models here. class Groupapp(models.Model): groups = models.ManyToManyField(Group,blank= True, related_name="group") name = models.CharField(max_length=100, null=False, blank=False) cover_photo = models.ImageField(null= True, blank=True, upload_to="images/") description = models.CharField(max_length=100, null=False, blank=False) members = models.ManyToManyField(Profile, related_name="members") admin = models.ManyToManyField(Profile, related_name="admin") videos = models.FileField(null= True, blank=True, upload_to="media/") images = models.ImageField(null= True, blank=True, upload_to="images/") text = models.TextField(null= True, blank=True) def __str__(self): return(self.name) What I want to do is to add the members field to a separate group and the admin field to a separate group via signals, so I can assign separate permissions to them, please how can I go about this? Or is there other ways I should write my model to make it possible. -
Django check is an array
I have some data to handle from a MUI autocomplete. If it is a single choice then it will post an object, if its multi choice it will post an array of chosen options. Is there a way for Django to detect if the posted value is an array or not? Something like JS isArray method? Cant seem to find a solution, at least not as simple as that. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray -
Compare Date from a database to current date and alert user if it's late
I have a database set up, I am running Django for the backend and React.js for the front. This is a project for school but I am having a hard time finding information on how to do this properly. I want to take the date put for the inspection_date and compare that to the local time, and if local time is greater than inspection_date, alert the user that they are past the inspection date. Here is my class model class Hive(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) hive_number = models.IntegerField() inspection_date = models.DateField() My Serializer class HiveSerializer(serializers.ModelSerializer): class Meta: model = Hive fields = ['id', 'hive_number', 'inspection_date', 'user_id'] depth = 1 -
How save space in HTML table when exporting to PDF Django / Python
I have a very simple table that takes all employees working on one specific adress and returns me a list of names that looks like this: My question is how can i make the table fill the entire page so that instead of 3 pages or more i have 1 page with rows side by side to save space when printing. The layout right now is Page1: Name (break) Page2: Name (break) Page3: Name (break) i want something like this: Page 1: Name | Name | Name (saving as much space without breaking page.) The code i have tried using so far is this: <style type="text/css"> @page { size: letter portrait; size: Letter; margin: 1.0cm; } body { font-size: 10pt; } . { padding: 4px; } table { border-collapse: collapse; } table, th, td, tr,{ word-wrap:break-word; table-layout:fixed; border: 1px solid black; margin-top: 50%; text-align: left; padding: 8px; } .wrap { width: 50%; } .left_col { float: left; width: 48.4%; } .right_col { float: right; width: 50%; } </style> </head> <body style="margin-bottom:1px;"> <div> <h1>Jobsite: <b>{{location}}</b></h1> <h4>Date: <b>{{date}}</b></h4> </div> <table> <tr> <th>Name</th> </tr> {% for item in data %} <tr><td>{{forloop.counter}} - {{ item.LastFirst }}</tr></td> {% endfor %} <h5>Manager's Signature: _______________________________________</h5> </table> </body> … -
Can't access environment variable in django that set in the supervisor conf file
[program:program_name] command={gunicorn-path} directory={path} user={user} autostart=true autorestart=true redirect_stderr=true stderr_logfile=api_error.log stdout_logfile=api_out.log environment=ENV=my_env I use the above supervisor.conf file to set the environment for my Django, ENVIRONMENT = os.environ.get('ENV') this way I try to access the env -
How to open a django webpage from a vue js app?
I have an app that I created using django as a backend and vue js as frontend. I did all of the front end in Vue JS i.e I have no template html files in my django folder. But now I want the vue app to link to another django app(with html templates) which I had created before. I have added the app to the django folder in my project. Now how do I create a link that can route to this django app that I have just added. I am using axios. -
Setup redis-cluster with Django
Problem Statement Use django-redis with redis clustering. An error occurs when interacting with the cache. The error points to a pickle operation on an instance of the ConnectionPool class where one of it's attributes, a thread lock, cannot be serialized and results in the following error: TypeError: cannot pickle '_thread.lock' object To Reproduce Steps to reproduce the behavior: Run a redis cluster that REDIS_URL points to. Setup CACHES in Django settings file. CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": REDIS_URL, "OPTIONS": { "REDIS_CLIENT_CLASS": "redis.cluster.RedisCluster", "REDIS_CLIENT_KWARGS": { "url": REDIS_URL, }, } } } Run the Django console and try to interact with the cache e.g. cache.get("somekey") Expected behavior The value of the key from the Redis cluster. Stack trace Traceback (most recent call last): File "python3.9/site-packages/redis/cluster.py", line 1454, in initialize copy_kwargs = copy.deepcopy(kwargs) File "python3.9/copy.py", line 146, in deepcopy y = copier(x, memo) File "python3.9/copy.py", line 230, in _deepcopy_dict y[deepcopy(key, memo)] = deepcopy(value, memo) File "python3.9/copy.py", line 172, in deepcopy y = _reconstruct(x, memo, *rv) File "python3.9/copy.py", line 270, in _reconstruct state = deepcopy(state, memo) File "python3.9/copy.py", line 146, in deepcopy y = copier(x, memo) File "python3.9/copy.py", line 230, in _deepcopy_dict y[deepcopy(key, memo)] = deepcopy(value, memo) File "python3.9/copy.py", line 161, … -
Websocket not working with django on deployment
i hope that u can help me. I deployed my django application to an ubuntu 20.04 server with nginx and gunicorn. This is my settings: gunicorn.service [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=ubuntu Group=www-data WorkingDirectory=/var/www/PlugSell ExecStart=/var/www/PlugSell/env/bin/gunicorn --access-logfile - --error-logfile - -k uvicorn.workers.UvicornWorker --workers 3 --bind unix:/run/gunicorn.sock minible.asgi:application [Install] WantedBy=multi-user.target app nginx conf server { server_name 3.73.206.145 127.0.0.1 sell.plug-shop.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /var/www/PlugSell; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } location /ws/ { proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Url-Scheme $scheme; proxy_redirect off; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection $connection_upgrade; proxy_pass http://unix:/run/gunicorn.sock; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/sell.plug-shop.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/sell.plug-shop.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host = sell.plug-shop.com) { return 301 https://$host$request_uri; } # managed by Certbot listen 80; server_name 3.73.206.145 127.0.0.1 sell.plug-shop.com; return 404; # managed by Certbot } in settings.py i have CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [("127.0.0.1", 6379)], }, }, } and in my asgi.py os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'minible.settings') … -
Customize django behavior on requests from mobile app and any sort of web browser
Good day, So I have made a mobile Android/IOS app that communicates with django backend through the http requests. As you understand the backend is hosted on some https://www.example.com domain... However, in case a user accesses that domain or any extensions (/home, /profile and etc..) from any web browser from any platform, I want to display just a plain page (maybe the name of the app). How can I do so? Thanks -
NOT NULL constraint failed: new__BRS_user.tables_id
When i'm trying to migrate the User model, NOT NULL constraint failed: new__BRS_user.tables_id error appears There is no field named tables in my model, i'm removed it long ago. class User(Model): id = models.AutoField(primary_key=True) first_name = models.CharField(max_length=60) second_name = models.CharField(max_length=60) third_name = models.CharField(max_length=60) email = models.CharField(max_length=320, unique=True) password = models.CharField(max_length=127) is_admin = models.BooleanField(default=False) is_student = models.BooleanField(default=True) is_teacher = models.BooleanField(default=False) input = models.OneToOneField(Input, on_delete=models.CASCADE, null=True) Class = models.IntegerField() -
AttributeError in Django Overlapping validation checking
i am cretaing a validation rule in djano to check overlapping but i am getting this error, can you guys help me there is two data field , when the data field will be overlapped than validation error will rise. start_r= model.integerfield(blank=True, Null=True) end_t=model.intergerfield(blank=True,Null=True) form.py class CheckForm(forms.ModelForm): def clean(self): start_r = cleaned_data.get("start_r",[]) end_t =cleaned_data.get("end_t",[]) if (start_r.end >= end_t.start) and (start_r.start <= end_t.end): raise ValidationError("Overlap not allowed.") i am getting error this one 'NoneType' object has no attribute 'end' -
Django + Vue google maps
I have a django + vue (for learn) project. I'm trying to implement google maps. I installed django-location-field and Google Vue 3 maps. For example, the output from the django location field is 51.39772199999999,16.2095788 and Google Vue 3 maps require input like this {lat: 51.093048, lng: 6.842120}, I don't really know how to write it in js. I know you have to use the split(",") option but I could use a little help from you. I'd like to split input from django and assign to two variables and do something like this center: {lat: value1, lng: value2}, this is my code <template> <section class="portfolio-block projects-cards"> <div class="container"> <div class="heading"> <h2>{{ firma.nazwa_firmy }}</h2> </div> <div class="row"> <p>{{ firma.opis }}</p> <p>{{ firma.strona_www}}</p> <p>{{ firma.miasto}}</p> <GoogleMap api-key="myapikey:)" style="width: 100%; height: 500px" :center="center" :zoom="15"> <Marker :options="{ position: center }" /> </GoogleMap> <p>{{ delta }}</p> </div> </div> </section> </template> <script> import axios from 'axios' import { GoogleMap, Marker } from "vue3-google-map"; export default { name: 'FirmaDetails', setup() { const center = { lat: 40.689247, lng: -74.044502 }; return { center }; // Get toast interface // const toast = useToast(); // return { toast } }, data() { return { firma: [], lokali: [], errors: … -
unrecognized arguments: --username appuser when When I try to run the createsuperuser command
My code class UserManager(BaseUserManager): use_in_migrations = True def _create_user(self, email, password, **extra_fields): if not email: raise ValueError("email field is required") email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password, **extra_fields): extra_fields.setdefault("is_staff", False) extra_fields.setdefault("is_superuser", False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault("is_staff", True) extra_fields.setdefault("is_superuser", True) extra_fields.setdefault("username", None) 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, password, **extra_fields) class User(AbstractUser): username = "user" email = models.EmailField('email adress', unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] class Meta: db_table = "USER" Note that my user must only authenticate with his email and password. Terminal outpout usage: manage.py createsuperuser [-h] [--email EMAIL] [--noinput] [--database DATABASE] [--version] [-v {0,1,2,3}] [--settings SETTINGS] [--pythonpath PYTHONPATH] [--traceback] [--no-color] [--force-color] [--skip-checks] manage.py createsuperuser: error: unrecognized arguments: --username appuser