Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
How to get the sum of transactions per month in django
I'm building a transaction application and need to display the data in charts using chart.js. I don't know how to get the sum for each month of the year. my model class Transaction(models.Model): trans_id = models.CharField(max_length=100, primary_key=True) trans_date = models.DateTimeField(auto_now_add=True) group_id = models.ForeignKey('Group', on_delete=models.CASCADE) username = models.ForeignKey(User, on_delete=models.CASCADE) trans_amount = models.FloatField() trans_type = models.CharField(max_length=20, default="contribution") def __str__(self): return str(self.trans_id) How can I get the sum totals? -
Duplicating checkbox in Django template
I'm building a web app and I went through something I'm unable to fix: in my app, I have a list of movies, and each movie has a little checkbox that shows the users if he has seen or not the mentioned movie. Everything works fine, every user can flag/unflag their movies. The problem begins when the user flags more than one movie: if one/none movie is flagged, everything works fine, when the user flags more than 2 movies, the checkboxes begin to duplicate, so that if I have 5 movies flagged, I'll have 5 checkboxes for each movie. I know where is the problem, but I don't really know how to fix it. Really, I spent over 2 days thinking about a possible solution, but I don't get it. Hope you will help me! <form action="" method="POST"> {% csrf_token %} <div class="row"> {% for film in films %} ... {% if user.seen.all %} {% for film2 in user.seen.all %} <input class="form-check-input" type="checkbox" id="check_seen" name="check_seen" value="{{film.pk}}" {% if film2.name == film.name %}checked{% endif %}> {% endfor %} {% elif not user.seen.all %} <input class="form-check-input" type="checkbox" id="check_seen" name="check_seen" value="{{film.pk}}"> {% endif %} (little save button)... </form> Essentially, what is happening here … -
Django constraints for UniqueConstraint does not work
I have tried to implement constraints for UniqueConstraint for two foreign keys in the Django model. So far it has not been working as expected. Here below is the model definition : class AssetMember(models.Model): asset = models.ForeignKey(Asset, null=True, related_name='assetmember_asset', on_delete=models.CASCADE) project = models.ForeignKey(Project, null=True, related_name='assetmember_project', on_delete=models.DO_NOTHING) class Meta: constraints = [ models.UniqueConstraint(fields=["asset", "project"], name="assetmember_unique_object") ] Yet, when I try to create two assetmember objects with the same asset and project as foreign key, I can see that the constraints are not working as expected : How shall I implement the model and the UniqueConstraint, so that it will not create the same object with asset and project twice? -
Error websocket djangochannelsrestframework
I did websocket connection by djangochannelsrestframework library, it connects but when I send some message it gets this error below Error image -
django test case setUp - queryset not updating
I'm experiencing issues trying to update a queryset on setUp: class MyTestCase(BaseTestCase): OPERATOR_USERNAME = "test_operator" OPERATOR_PASSWORD = "secret" OPERATOR_EMAIL = "test@example.org" @classmethod def setUpClass(cls): super().setUpClass() cls.operator = Operator.objects.create_superuser( username=cls.OPERATOR_USERNAME, password=cls.OPERATOR_PASSWORD, email=cls.OPERATOR_EMAIL ) def setUp(self) -> None: self.client.login(username=self.OPERATOR_USERNAME, password=self.OPERATOR_PASSWORD) utd_ids = MyModel.objects.filter( ref_year=2021).values_list("id", flat=True )[:10] utd_qs = MyModel.objects.filter(id__in=utd_ids) # just added another step for debugging purposes # update initial utd status _updates = utd_qs.update(status="INITIAL_STATE_VALUE") print(_updates) # it prints 10 self.ssn_list = list(utd_qs.values_list("user__ssn", flat=True)) self.client.login(username=self.OPERATOR_USERNAME, password=self.OPERATOR_PASSWORD) print(MyModel.objects.filter(id__in=utd_ids).values("status").distinct()) # this should retrieve 1 value but instead it retrieve multiple values different from INITIAL_STATE_VALUE am I doing something wrong? I tried the same update through python manage.py shell on a similar queryset and it works as expected -
Trying to set a minimum value within a form based on the total amount in the inventory
Views.py ( Where I want to check) def addInProcess(request): if request.user.is_authenticated: form = inProcess_form() if request.method =="POST": calc = InProcessPowder.objects.create( date = request.POST.get('date'), tc_date = request.POST.get('tc_date'), tc_weight = request.POST.get('tc_weight'), tc_remarks = request.POST.get('tc_remarks'), tgl_date = request.POST.get('tgl_date'), tgl_weight = request.POST.get('tgl_weight'), tgl_remarks = request.POST.get('tgl_remarks'), checked_by = request.user, ) context = {'form': form} return render(request, 'base/InProcess/InProcess_form.html', context) else: return render (request, 'landing.html') and in our Home view we call this as the total inventory amount def home(request): if request.user.is_authenticated: totalCal_yld = calamansi.objects.all().aggregate(Sum('yld')) ['yld__sum']or 0.00 This gets the total yield of calamansi juice from the calamansi object I want to compare tc_weight with totalCal_yld What I am trying to do is I want to minues tc_weight(processes calamansi) from totalCal_yld and equal a total which will represent the inventory of calamansi. Since calamansi is an ingredient in TC we are trying to make sure that it wont go negative or even not give them the option to do so. Help is very much appreciated -
JSON.parse: unexpected character at line 1 column 1 of the JSON data(django)
i was making an ecommerce website using django & trying to send data using fetch in javascript but this message is keep showing up. tried 100 times to figure out what's the issue but can't find one. i'm new btw total = total bill ship = True means, shipping is necesarry bcz the product is not digital. form is a form where the user added their info var userFormData = { "name": "null", "email": "null", "total": total, }; var shippingFormData = { "address": null, "city": null, "zipcode": null, "state": null, }; if (user == "AnnonymousUser") { userFormData.name = form.name.value; userFormData.email = form.email.value; } if (ship == "True") { shippingFormData.address = form.address.value; shippingFormData.city = form.city.value; shippingFormData.zipcode = form.zipcode.value; shippingFormData.state = form.state.value; } console.log(userFormData); console.log(shippingFormData); var url = "/checkout_info_process/"; fetch(url, { method: "POST", headers: { "Content-Type": "application/json", "X-CSRFToken": csrftoken, }, body:JSON.stringify({ "userform": userFormData, "shippingform": shippingFormData, }), }) .then((response) => response.json()) .then((data) => { console.log(data); -
How serve django media files on production? [Shared Hosting]
I have my django project running on Namecheap Shared Hosting but when I turn off the debug mode it stops fetching the media files. As I am on shared hosting I cannot edit the Apache Config file and Namecheap will not allow me to modify it. How can I serve the media file in shared hosting? Settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] STATIC_ROOT = os.path.join(BASE_DIR, 'root') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') Urls.py urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Please suggest me what to do in this scenario for shared hosting.