Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is it better to store fk directly or get from another related table?
For example I have two models. What I get confused here is it will be better to store department_id directly on the Sale model or use product.department whenever you need it. The use case for the department in sales model can be, filter sales by department, reports sales of department or so on. class Product(): name = models.CharField() department = models.ForeignKey(Department) class ProductSale() product = models.ForeignKey(Product) department = models.ForeignKey(Department) # other fields Or just class ProductSale() product = models.ForeignKey(Product) # other fields -
Unsafe redirect to URL with protocol 'account'
I am trying to redirect to login page with return url through a middleware . I am getting this error so can anyone answer the question why i am getting this error and how to solve this error from django.shortcuts import redirect def auth_middleware(get_response): def middleware(request): print("Middleware") return_url = request.META['PATH_INFO'] if not request.session.get('user_id'): return redirect(f'account:login?return_url={return_url}') response = get_response(request) return response return middleware -
Django Channels Disconnect Notification Issue
I'm working on a project where we are using Django channels. We have to send a notification in the room if any of the users disconnect. To start with each room will be limited to 2 users only. I have a utility function inside websocket_disconnect(), to send messages to the room to notify other users. The issue, that notification is being sent for all requests even when a user is sending a message(using receive_json(), send_json()). Here message is sent, but still the function send_external_msg_to_channel() from websocket_disconnect() is being triggered. I am using AsyncJsonWebsocketConsumer. The frontend uses a reconnecting-websocket package. class InterviewConsumer(AsyncJsonWebsocketConsumer): async def websocket_disconnect(self, message): print("disconnecting") await send_external_msg_to_channel(self.room_name, {"type": "send_json", "event": "disconnect"}) return await super().websocket_disconnect(message) -
context must be a dict rather than JsonResponse
I want to send JsonResponse(convert python objects into JSON) to the HTML page. for that, I write a view like this: from django.shortcuts import render from django.http import JsonResponse def send_json(request): data = [{'name': 'Peter', 'email': 'peter@example.org'}, {'name': 'Julia', 'email': 'julia@example.org'}, {'name': True, 'data': None}] a = JsonResponse(data, safe=False) return render (request, 'index.html', a) But, It shows context must be a dict rather than JsonResponse. error. In HTML: {{ a }} -
Add user to "django-celery-results" table
we created one concurrency task in Django using celery. then we stored results in database using Django-celery-results. now my requirement is after some time i like to retrieve task results with user id. @shared_task(bind=True) def SayHello(self ,*args, **kwargs): return "Done" so help me how i can add and get data from celery table -
How to Restrict App Model from Django Admin
I am trying to create a system in django admin model where admin can see all apps in django admin index. Staff can see only restricted apps. I was able to change the app list index for different roles, but for restricted user they can access directly through url. Note - I am using AbstractBaseUser and unregister group model model.py class User(AbstractBaseUser): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) first_name = models.CharField(('first name'), max_length=30, null=True) last_name = models.CharField(('last name'), max_length=30, null=True) date_of_birth = models.DateField(null=True) date_joined = models.DateTimeField(('date joined'), auto_now_add=True) # avatar = models.ImageField(upload_to='avatars/', null=True, blank=True) phone = PhoneNumberField(null=True) country = CountryField(null=True) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) staff = models.BooleanField(default=False) is_consumer = models.BooleanField(default=True) # premium_referral = models.CharField(('Premium Referral Code'), max_length=30, null=True,blank=True, unique=True) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] def __str__(self): return self.email def has_perm(self, perm, obj=None): "Does the user have a specific permission?" # Simplest possible answer: Yes, always return True def has_module_perms(self, app_label): "Does the user have permissions to view the app `app_label`?" # Simplest possible answer: Yes, always return True def get_full_name(self): ''' Returns the first_name plus the last_name, with a space in between. ''' full_name = '%s %s' … -
Highcharts Highstocks cumulativeSum Issue
I recently wanted to take advantage of the highcharts library to add a cumulative year existence unfortunately when I activate the cumulative option True implemented since version 9.3.2 my graph breaks the mouth yet it displays the correct information would there be an option to activate or deactivate to have the cumulative without all the graph is sorted graph before the activation of the cumulative option graph after the activation of the cumulative option I develop in python framework django with a url that I call in ajax My python code Thank you in advance for your help!! -
Django TemporaryUploadedFile different behavoiur under Python2/3 with delete=False
Why does the TemporaryUploadedFile get deleted in Python 3 while in Python 2 it stays in /tmp/ directory? And how would I keep the behavior of Python 2 while using 3? from django.core.files.uploadedfile import TemporaryUploadedFile with TemporaryUploadedFile('something.txt', 'text/plain', 0, 'UTF-8') as tmp_file: tmp_file_path = tmp_file.temporary_file_path() tmp_file.file.delete = False print(tmp_file_path) Running this block of code under Python 2 keeps the file in /tmp/ directory while on Python 3 it gets deleted. [ray@fedora tmp]$ ls | grep tmp tmpvSmI8b.upload #generated in Python 2 PY2 version 2.7.18 PY3 version 3.7.12 Django 1.11.29 -
kombu.exceptions.EncodeError: queryset is not JSON serializable. Celery task error in Django
that's my views.py def create(self, request, *args, **kwargs): instance = self.get_object() serializer = self.get_serializer(instance, data=request.data) serializer.is_valid(raise_exception=True) matching_fields = serializer.validated_data['matching_fields'] add.delay(matching_fields, instance, request) return Response(status=201, data={ 'total': '11', 'success': True }) for function add pass argument on request, but i get error kombu.exceptions.EncodeError: <ImportRecord: ImportRecord object (19)> is not JSON serializable that's my task.py @shared_task() def add(matching_fields, instance, request): helper = ImportData(matching_fields, instance, request) helper.import_data() -
Django Post-request within for-loop is not working
I am stuck with a page containing two post-requests where one of them is inside of a for-loop. The user has an input file that uses a autocomplete function. This function uses the shop-Model in Django. After submitting, the product will be added to the Shopping_List-Model in Django. It will be displayed in another div of the page. This is currently working without a problem. The user then should have the possibility to delete the product from the list by clicking a button. But the button is not working, it is not processing the post-request. I have also tried different elif-Statements (e.g. elif request.POST["shop_delete"]), but none of them worked. Please note as I have not figured out how to get the button to work, the action does only contain print("delete"). I would write the necessary code afterwards. Any suggestions are much appreciated! Many thanks in advance! Here is my code: HTML <div> <!--Input field and autocomplete--> <form id="product_add" action="{% url 'index' %}" method="post"> {% csrf_token %} <input type="text" name="shop_product" id="shop_product"> <!--Code for autocomplete--> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <script> $(function () { $("#shop_product").autocomplete({ source: "{% url 'index' %}", minLength: 2 }); }); </script> <input type="submit" name="button_add" value="Add"> </form> </div> <div> <table> … -
How to implement Specific field data into one list and Another filed data into another list in Django
I'm using Django 3x. I have one table called Book. When I write query for this I'm getting data like this: book_details = Book.objects.all().values() print(book_details) <QuerySet [{'id': 1, 'author': 'ABC', 'price': 150, 'category': 'Comic', 'available': 1}, {'id': 2, 'author': 'XYZ', 'price': 500, 'category': 'Historical Fiction', 'available': 1}, {'id': 3, 'author': 'MNO', 'price': 200, 'category': 'Horror', 'available': 0}]> I'm trying to create data in this below format {'id':[1,2,3], 'author':['ABC', 'XYZ', 'MNO'], 'price':[150,500,200], 'category':['Comic', 'Historical Fiction', 'Horror'], 'available':[1,1,0]} How to create data in this format. Please advise best way to do this. And explanation would be much appreciated. Thanks!. -
getting black image after converting base64 string(tiff format to jpeg) using python
I am converting base 64 string to jpeg format and it is working fine but in case of tiff format string I am getting black image img = Image.open(io.BytesIO(base64.b64decode(b64_string))).convert('RGB') temp_file = tempfile.TemporaryFile() img.save(temp_file, 'jpeg') temp_file.seek(0) return temp_file can anyone help me out -
Django fields for timing
I have the following codes: models.py class Job(models.Model): jobname = models.CharField(max_length = 1000) owner = models.CharField(max_length = 150) enabled = models.BooleanField() freq_type = models.IntegerField(default = 1) freq_interval = models.IntegerField(default = 0) freq_recurrence = models.IntegerField(default = 0) start_date=models.CharField(max_length=10) end_date=models.CharField(max_length=10, blank = True) start_time=models.CharField(max_length=6) end_time=models.CharField(max_length=6, blank = True) date_added = models.DateTimeField(auto_now_add = True, null = True) date_modified=models.DateTimeField(auto_now = True, null = True) version=models.IntegerField(default = 1) views.py def job_edit(request, pk): job = Job.objects.get(pk=pk) if request.method =="POST": job_form = JobForm(request.POST) if job_form.is_valid(): option = request.POST.get('check') time = request.POST.get('servicetime') date = request.POST.get('servicedate') version = request.POST.get('version') Job.objects.filter(pk=pk).update(enabled=option,start_time = time,start_date = date,version = version) return redirect('/job/', {'job':Job.objects.all}) return render(request, 'interface/job_edit.html',{'job': job}) When i create entry to Job, date_added and date_modified will have the same date and time stored. (Not sure if this is the intended way for auto_now_add and auto_now). But when i attempt to edit the same entry, this date_modified does not change at all. Is there something I am missing in my function? Like something to trigger this auto_now to insert the timing i edit the entry -
Azure web-app - Multi-container unit was not started successfully for Django app
Ok having a real issue here with Azure Web-app for multi-containers, no matter what I do, I can't get it to work. I've spend hours on this myself and also with Microsoft representatives. The issue is that I can't get web-apps for multiple containers to work with my docker-compose file with related Docker images. The service is in "preview-mode" i.e. being some sorts of beta-version (my guess) so it may be some bug here at Microsoft's end, but I still wanted to write this post in hope that someone may have insight to help me figure this out. This is the logs I'm getting when trying to access the application in the browser, and this is the only logs available, I have checked this with the Microsoft support: 2021-11-24T08:53:40.341Z INFO - Pull Image successful, Time taken: 0 Minutes and 0 Seconds 2021-11-24T08:53:40.357Z INFO - Starting container for site 2021-11-24T08:53:40.360Z INFO - docker run -d -p 9688:80 --name companybe_backend_0_df9f2437 -e WEBSITES_ENABLE_APP_SERVICE_STORAGE=false -e WEBSITES_PORT=8000 -e WEBSITE_SITE_NAME=companybe -e WEBSITE_AUTH_ENABLED=False -e WEBSITE_ROLE_INSTANCE_ID=0 -e WEBSITE_HOSTNAME=companybe.azurewebsites.net -e WEBSITE_INSTANCE_ID=*** -e HTTP_LOGGING_ENABLED=1 companycontainerregistry.azurecr.io/companybe:latest 2021-11-24T08:57:30.785Z ERROR - multi-container unit was not started successfully 2021-11-24T08:57:30.799Z INFO - Container logs from companybe_backend_0_df9f2437 = 2021-11-24T08:53:44.889298525Z projectile/manage.py:8: UserWarning: Not reading projectile/.env - it … -
Django - How to make Dynamic fields on Quizz App form
I started to make a Quiz system with Django and I'm using Django Template to show some questions randomly on each video. Actually I've just set the questions implemantation (admin can add questions on each videos and thats works good), so the model looks like this: class Question(models.Model): class TypeChoices(models.TextChoices): SINGLE = "single" MULTIPLE = "multiple" uid = models.UUIDField(default=uuid.uuid4, primary_key=True) playlist_media = models.ForeignKey(PlaylistMedia, on_delete=CASCADE) created_at = models.DateTimeField(auto_now_add=True) text = models.CharField(max_length=255) type = models.CharField( max_length=10, choices=TypeChoices.choices, default=TypeChoices.SINGLE ) options = ArrayField(models.CharField(max_length=255)) responses = ArrayField(models.CharField(max_length=255)) So the questions type can be "single" or "multiple" so the template can show radios or checkboxes depending of the type. Here an example of one question with type single: Here another example with a multiple type: My question is: How can I create a dynamic form? because if a create a simple form (with forms.py) I won't know how many fields user can send. Because It can have 1 question or 2 or 3 (max). note: even single or multiple type, the "responses" is always a list. Here the template just in case to let you know how it will be: {% if questions %} <div class="is-size-4 has-text-weight-medium mb-4 "> <span class="">Quizz</span> </div> <form action="{% url … -
I would like to run for loop to each of li tag and want to add content dynamically from django backend admin
I have created a navbar and content can be added from the backend but only the home nav bar shows the icon and the other navbar name is with the same icon. I want to add a different nav bar with a different icon. and want to run if, elif and else condition. please help me how to use if elif and else dynamically. initial HTML without dynamic content <!-- Nav Links --> <li class="nav-item"> <a class="nav-link fs-5" href="#समाचार"> <i class="fas fa-address-book mr-1"> </i>समाचार </a> </li> <li class="nav-item active"> <a class="nav-link fs-5" href="/"> <i class="fas fa-home mr-1"></i> होमपेज </a> </li> <li class="nav-item"> <a class="nav-link fs-5" href="#भिडियो"> <i class="far fa-clone mr-1"> </i>भिडियो </a> </li> <li class="nav-item"> <a class="nav-link fs-5" href="#विजनेस"> <i class="far fa-calendar-alt mr-1"> </i>विजनेस </a> </li> <li class="nav-item"> <a class="nav-link fs-5" href="#ग्यालरी"> <i class="far fa-chart-bar mr-1"> </i>ग्यालरी </a> </li> <li class="nav-item"> <a class="nav-link fs-5" href="#प्रोफाइल"> <i class="far fa-copy mr-1"> </i>प्रोफाइल </a> </li> Dynamic backend added HTML which suppose to change in order to work: {% for i in nav_data %} {% if forloop.first %} <li class="nav-item active"> <a class="nav-link fs-5" href="/"> <i class="fas fa-home mr-1"></i> {{i.name}} </a> </li> {% elif forloop.first %} <a class="nav-link fs-5" href="/"> <i class="fas fa-home mr-1"></i> … -
How to keep parsed data available in django project
I am fairly new to django so please bare with me. I have an XML file that I need to parse in order to use its contents for configuration purposes. (I know that there might be better ways but I cannot do otherwise, it's a HARD constraint). I would like to have the resulting dictionary available in all files of my django project, without re-parsing each time the same file. How do I do it? And where should I parse the file? Thanks for the help! -
How to get a cache value by a key using Django & Memcached
I have a simple app for testing caching in Django with Mimecached, and I faced a problem. I override a function, which does generate cache keys with prefix and version, but after the cache key was generated, I can't get this value from the cache instance of django.core.cache. def make_key(key, key_prefix, version): print('creating a key') print(key) return '%s-%s-%s' % (key_prefix, version, key) Key example(in Memcached): set prefix-1-views.decorators.cache.cache_header..a2a1ec9f23d237cd78fef02b25c149c2.ru.Europe/Moscow 1 60 29 In python shell I do smth like that: from django.core.cache import cache cache.get('prefix-1-views.decorators.cache.cache_header..a2a1ec9f23d237cd78fef02b25c149c2.ru.Europe/Moscow') And the output is None What am I doing wrong? In memcached over telnet connection, I also can't get anything by key. I'm new to this topic, hope for community support :) -
use django_cron to achieve token expiration and log out
I wrote a django that uses the TokenAuthentication verification of the django rest framework. When logging out, delete the previous token and recreate the token. Now I want to use django_cron to achieve token expiration and log out.Can someone teach me how to write? -
Django refresh page without reload whole page
I want to refresh the page at certain intervals, for example, every 10 seconds, without reloading the page. I'm sending get request to api. My ajax codes refreshes the page well but it's causing problems because it loads all the divs again and again. How can I make the div-focused refresh delete the same previous div when refreshing? part of my div; <div id="testdiv" class="row"> <div class="col-md-4"> {%if XXX > 1000 %}<div class="dashcontrol2 featured">{%else%}<div class="dashcontrol featured">{%endif%} <h4>{%if XXX> 1000 %}<span style="color: red;">XX</span><box-icon type='solid' name='badge' color="red"></box-icon>{%else%}<span style="color: green;">XX</span><box-icon type='solid' name='badge-check' color="green"></box-icon>{%endif%} </box-icon></h4> <h4>{{XX|intcomma}}</h4> <a target="_blank" href="XX"><h6>KIBANA</h6></a> </ul> </div> </div> url.py; url(r'^dashcontrol$', views.dashcontrol, name='dashcontrol'), ajax; <script> setInterval(function() { $.get("/dashcontrol", function(data, status){ $("body").html(data); }); }, 15000); </script> -
Changing URL path of API in Django Rest Framework
I'm working on a Django web app and it's running really fine and well, but I'm facing a small issue where after I deployed the app on a VPS, the Django Rest Framework default API URL is pointing at the home IP address like in the image below. The issue here is that when I'm running my app on the server, the above highlighted URL is directing me toward my home IP address on my local machine. How can I change this URL with the IP address of the VPS or domain? Is that possible? -
Redirecting to wrong pages in Django
I have a problem in Django where my pages are redirecting to wrong pages. It just somehow happen to the new page I am coding which I have no idea why. urls.py path('job/', JobListView.as_view(), name = 'jobs'), path('job/edit/<int:pk>/', views.job_edit, name='job-edit'), path('device_add/', views.device_add, name='device-add'), views.py class JobListView(ListView): model = Job template_name = 'interface/job.html' #<app>/<model>_<viewtype>.html context_object_name = 'jobs' ordering = ['date_added'] def job_edit(request, pk): job = Job.objects.get(pk=pk) #if request.method =="POST": return render(request, 'interface/job_edit.html',{'job': job}) My html for my job_edit has the following: <div class="row"> <div class="col-md-12"> <div class="text-sm-right"> <button class="btn btn-outline-secondary" type="submit">Save</button> <a href="{% url 'jobs' %}"> <button class="btn btn-outline-secondary"> Back</button> </a> </div> </div> </div> As stated in my urls.py, the url is job/ and name = jobs, which I want the back button to redirect back to job/. But whenever i pressed the back button, it somehow redirect back to device_add/. Same goes for my save button. As in my views, I have not coded the if part for request.method=='POST'. But when i attempt to press the save button, it redirect to device_add/. Can anyone explain what I am doing wrong? -
Custom decorator to pass custom data to function in Django
I want to create custom decorator that checks current user and run a query for this user to get some data that belongs him and then if has defined data function is called with whole list passed else returns 403 error. How can i approach this? -
Why doesn't i18n return to home directory when changing language?
I am trying to include Turkish and English languages in my application. My application's native language is Turkish, so when it says ' ' it should go to the home directory. However, when I change language with i18n, when I try to switch back to the mother tongue, it goes to 127.0.0.1/tr/. I want to send this to 127.0.0.1, how should I do it? urls.py (root) urlpatterns += i18n_patterns( path('', include(home_patterns), name="Home"), path(_('haberler/'), include(news_patterns), name="New"), path('change_language/', change_language, name='change_language'), path('i18n/', include('django.conf.urls.i18n')), prefix_default_language=False,) settings.py _ = lambda s :s LANGUAGES = ( ('tr', _('Türkçe')), ('en', _('English')), ) view.py def change_language(request): response = HttpResponseRedirect('/') if request.method == 'POST': language = request.POST.get('language') if language: if language != settings.LANGUAGE_CODE and [lang for lang in settings.LANGUAGES if lang[0] == language]: redirect_path = f'/{language}/' elif language == settings.LANGUAGE_CODE: redirect_path = '/' else: return response translation.activate(language)`enter code here` response = HttpResponseRedirect(redirect_path) response.set_cookie(settings.LANGUAGE_COOKIE_NAME, language) return response -
Backend docker image does not wait until db becomes available
I am trying to docker-compose up my containers, one for backend and another one for the database (postgis). If I docker-compose up db, I see db_1 | 2021-11-23 10:36:02.123 UTC [1] LOG: database system is ready to accept connections, so, it works. But if I docker-compose up the whole project, I get django.db.utils.OperationalError: could not connect to server: Connection refused web_1 | Is the server running on host "db" (172.23.0.2) and accepting web_1 | TCP/IP connections on port 5432? As far as I know, it means that my backend image does not waiting for until db becomes available, and throws an error. If this idea is correct (is it?), the one of solutions could be: to add some code to force backend image to wait for db, like it described here: 1Docker-compose up do not start backend after database . I tried to implement solutions using while loop (see commented lines in docker-compose.yaml), but in my case it doesn't work, and, to be honest, I do not quite understand the "anatomy" of these commands. I have two subquestions now: Do I understand my problem correctly? How to solve it? Many thanks in advance to anybody who try to help me! …