Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Change language in custom middleware
I would like to change language in my custom middleware. For some reason code below doesn't work. class LanguageMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): print('set language to spanish...') translation.activate("es") request.LANGUAGE_CODE = "es" response = self.get_response(request) translation.deactivate() return response settings.py LANGUAGES = ( ("en", "English"), ("es", "Spanish"), ) LOCALE_PATHS = (os.path.join(BASE_DIR, "locale"),) USE_I18N = True USE_L10N = True LANGUAGE_CODE = "en" if I change LANGUAGE_CODE is settings to "es" I get spanish API responses but I would like to be able to change it programmatically in my middleware. -
Unable to subscribe to the Django Rest-frameworks channel
I am trying to write an API which would subscribe to all the instances of a Django's model. To accomplish this I have been referring to the documentation of package djangochannelrestframeowork. I did everything as told in the documentation. This is what my asgi.py file looks like - import os from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from django.core.asgi import get_asgi_application import yacht_away os.environ.setdefault("DJANGO_SETTINGS_MODULE", "yacht_away.settings") django_asgi_app = get_asgi_application() application = ProtocolTypeRouter( { "http": django_asgi_app, # Just HTTP for now. (We can add other protocols later.) "websocket": AuthMiddlewareStack( URLRouter(yacht_away.urls.websocket_urlpatterns) ), } ) In my setting.py file, I have declared - ASGI_APPLICATION = "yacht_away.asgi.application" CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [("redis", 6379)], }, }, } Also, in the installed apps - INSTALLED_APPS = [ "channels", ... ] In my project's urls.py - from messaging.urls import websocket_urlpatterns websocket_urlpatterns = [ path("api/messaging/", URLRouter(websocket_urlpatterns)), ] And in the apps.py - from django.urls import path from messaging.views import CustomerOwnerMessagesView websocket_urlpatterns = [ path( "customer/<int:customer>/owner/<int:owner>/", CustomerOwnerMessagesView.as_asgi(), ), ] After that, I wrote a view class which will create a record in the database and at the same time if subscribed to the method subscribe_to_customer_owner_messages_activity then it must return the newly created … -
How to upload a json.dump into a model filefiedl
I seem to not be able to work around this problem. I have a model with a Filefield. Now I'm trying to create a file json data. I've been working around this in different ways and I have come to the conclusion (right or wrong) that I shouldn't need to write a file, but be able to dump the data inte the file directly. All this is embedded in a custom_command. My model class Free_FileHistory(models.Model): free_file= models.FileField(upload_to=get_inv_file_filepath, null=True, blank=True, verbose_name='File',validators=[validate_file_size]) .... My code OBJ = Free_FileHistory.objects.get(free_transfer_id=ID) # ID is a unique identifier file = (ID) # CreateDictioneryJSON is a function that take two given arrays of keys and values and create one data directory data = CreateDictioneryJSON(HEADER,ROW) read=json.dumps(data, indent=4) print(read) OBJ.free_file.save(file,read) print(read) displays the data just as I want it. I get the error: 'str' object has no attribute 'closed' -
Is any other process to download packages without pip?
I am stuck to download pip install fiona package but still it is not downloaded on my windows 10 system. 1.Help to download fiona package 2.How to control cache packages on pip -
Decimal calculation different on my local machine vs Heroku server
I have a Django project that I deployed to Heroku. I noticed that the calculations are not working when I used smaller numbers for some reason. Everything works fine on my local Windows machine. For example this calculation newBalance = Decimal(str(userObj.user_coins)) - Decimal(str(betValue)) when the calculation would be 2000 - 12 I get an answer of 2.2E+3 instead of 1988. If the calculation would be 2000 - 120 I get an answer of 1900 or 1.9E+3 instead of 1880. On my local machine this was working correctly. I don't understand what might be going wrong here. -
Can someone explain me how to do a register/login with django and kivy application?
I want to create a application with kivy and django and with a register/login and I don't know where I have to begin, I already did the front-end but not the backend. Thanks for your answers ! -
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, …