Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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! … -
Is there any dropdown option in django python which fill textbox (itemcode) by selection dropdown value(Item) from single table?
My table1 Id Item ItemCode 1 sensor s001 2 PCB p00034 Output- dropdown- sensor textbox- s001 I am new to python please provide me solution. Thanks in advance -
Why we use model = User in class Meta When we customize our UserCreationForm or AuthenticationForm in django?
I am unable to give labels in class Meta these fields username, password1 and password2, I can only modify these fields in outside class Meta, why? And why we use model = User while we are overriding our UserCreationForm? from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django.forms import widgets class SignUpForm(UserCreationForm): password2 = forms.CharField(widget=forms.PasswordInput,label="Confirm Password") class Meta: model = User #why we use User here fields = ["username", "first_name", "last_name", "email"] labels = {"email": "Email" } -
Django, deployment on google cloud services, app.yaml file
I'm trying to deploy my django project on google cloud services, but it seems i need an app.yaml file. GCS provide an example yaml file, but i dont know if that example will work for my project as it is because i dont know how to fill the file (i have found other examples that look different from the GCS one), i dont know in which folder that file needs to be, and after watching some tutorials, it seems i need other files besides the app.yaml for the deployment. Its my first project, so i'm a bit lost, if you can help me, i'll be very gratefull. -
Maintain collapse-state after Django renders another page
In my sidebar, I included a collapse button to show/hide some content. Now I want to maintain the collapse-state when rendering another page: If Projects was collapsed before refreshing the page, it must stay like this after rendering another page. Let's say I click on See All projects: This will call the view projects: The view basically is loading another HTML page (but keeping the same sidebar) @login_required def projects(request): return render(request, 'projects.html') After the view is executed and projects.html rendered, the Projects appear un-collapsed. How can I keep the collapse status when rendering other pages? Projects code: <li id="sidebarProject" class="sidebar-element {% if nbar == 'projects' %}active{% endif %}"> <div class="card projects-card"> <div class="card-header" id="headingOne"> <h5 class="mb-0"> <svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" fill="currentColor" class="bi bi-kanban-fill" viewBox="0 0 16 16"> <path d="M2.5 0a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h11a2 2 0 0 0 2-2V2a2 2 0 0 0-2-2h-11zm5 2h1a1 1 0 0 1 1 1v3a1 1 0 0 1-1 1h-1a1 1 0 0 1-1-1V3a1 1 0 0 1 1-1zm-5 1a1 1 0 0 1 1-1h1a1 1 0 0 1 1 1v7a1 1 0 0 1-1 1h-1a1 1 0 0 1-1-1V3zm9-1h1a1 1 0 0 1 1 1v10a1 1 … -
Celery task just skips or doesn't running task in Django
I have a little experience on Celery and maybe I'm doing something wrong. In views.py call celery task 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.apply_async((matching_fields, instance, request), serializer='my_custom_excel') return Response(status=201, data={ 'success': True }) that's my tasks.py def my_custom_excel_encoder(obj): """Uncomment this block if you intend to pass it as a Base64 string: file_base64 = base64.b64encode(obj[0][0]).decode() obj = list(obj) obj[0] = [file_base64] """ return str(obj) def my_custom_excel_decoder(obj): obj = ast.literal_eval(obj) """Uncomment this block if you passed it as a Base64 string (as commented above in the encoder): obj[0][0] = base64.b64decode(obj[0][0]) """ return obj register( 'my_custom_excel', my_custom_excel_encoder, my_custom_excel_decoder, content_type='application/x-my-custom-excel', content_encoding='utf-8', ) app = Celery('tasks') app.conf.update( accept_content=['json', 'my_custom_excel'], ) @app.task def add(matching_fields, instance, request): helper = ImportData(matching_fields, instance, request) helper.import_data() to class ImportData we pass arguments in excel file,ImportData is an helper class for importing excel. The problem is that my task on celery does not start -
Running into a Circular Import issue
I have two apps(front and lrnadmin) in project(portal) this is my root directory the problem is that when I import the models in each other it gives me error this is my front.models.py from datetime import datetime, timezone from django.db import models from django.db.models import expressions from django.db.models.base import Model from django.utils import timezone from lrnadmin.models import Qualification this is my lrnadmin.models.py from django.contrib.auth.models import AbstractUser from django.db import models from django.utils import timezone from front.models import User How Can I handle this File "E:\lrn\portal\lrnadmin\models.py", line 4, in <module> from front.models import User File "E:\lrn\portal\front\models.py", line 7, in <module> from lrnadmin.models import Qualification ImportError: cannot import name 'Qualification' from partially initialized module 'lrnadmin.models' (most likely due to a circular import) (E:\lrn\portal\lrnadmin\models.py) -
Fill The ForeignKey Field in Django CreateView Automatically
Here is my scenario. I want one of my model fields to be auto-fill based on whether the user is authenticated or not. Like when the user submits the form, I need to check if the user is authenticated and then fill the created_by field up with <User Object> otherwise, leave it Null if possible. Here is my model: class Snippet(models.Model): # --- create_by = models.ForeignKey( User, on_delete = models.CASCADE, null=True, ) # --- Here is my view: class SnippetCreateView(CreateView): # --- def save(self, request, *args, **kwargs): if request.user.is_authenticated: user = User.objects.get(username=request.user.username) request.POST['create_by'] = user # --->> TraceBack: due to immutability.. return super().post(request, *args, **kwargs) # --- Since the request.POST QueryDict is immutable, how can I implement it?? I have tried multiple ways like creating a copy of that but nothing happens and it doesn't change anything. But.. I can implement it like this and it works with no problem. I think this solution is dirty enough to find a better way. What do you think about this solution?? class Snippet.CreateView(CreateView): # --- def save(self, request, *args, **kwargs): if request.user.is_authenticated: user = User.objects.get(username=request.user.username) data = { 'title': request.POST['title'], # --- 'create_by': user if user else None, } snippet = Snippet.objects.create(**data).save() … -
How do I do calculations in javascript from my formset in django?
I have a doubt, what happens is that I already managed that my first form within the table could do operations and represent them. I was also able to create a dynamic formset. But now I have the problem that I want my formset in Django to do different calculations and represent them. Any idea? The javascript that I placed I followed it from several tutorials, the problem becomes complex because I have to use the JS for calculations and that it is also dynamic, I do not know where to start Forget the format, I still haven't put the HTML right ... I just want to multiply the green input (quantity) by the red input (unit price), place the total in the blue input (total price), add the blue ones and represent them in the purple input (total) Thanks for your help :D I put the code that I was already using add-parts-row.js function updateEmptyFormIDs(element,totalForms){ var thisInput=element var currentName=element.attr('name') //THIS IS WHAT PREFIX REPLACES WITH totalForms var newName=currentName.replace(/__prefix__/g,totalForms) //this is what replaces name with the number totalForms thisInput.attr('name',newName) //this is what replaces id with the totalForms number thisInput.attr('id',"id_"+newName) var newFormRow=element.closest(".form-row"); var newRowId="row_id_"+newName newFormRow.attr("id",newRowId) newFormRow.addClass("new-parent-row") var parentDiv=element.parent(); parentDiv.attr("id","parent_id_"+newName) var inputLabel=parentDiv.find("label") … -
Why do I get [INFO] Worker Exiting (pid: 2) when deploying cloud run service with docker? (On VSCode with cloud code extension)
I'm really new to this stuff, I'm a 16 year old currently doing a research project/internship, and I've just started 2 weeks ago. So I'm extremely confused. I've pretty much only got to this point by brute force. Please let me know if you need any other information. My dockerfile is FROM python:slim # Keeps Python from generating .pyc files in the container ENV PYTHONDONTWRITEBYTECODE=1 # Turns off buffering for easier container logging ENV PYTHONUNBUFFERED=1 # Install pip requirements COPY requirements.txt . RUN python -m pip install -r requirements.txt WORKDIR /app COPY . /app # Creates a non-root user with an explicit UID and adds permission to access the /app folder # For more info, please refer to https://aka.ms/vscode-docker-python-configure-containers RUN adduser -u 5678 --disabled-password --gecos "" appuser && chown -R appuser /app USER appuser # During debugging, this entry point will be overridden. For more information, please refer to https://aka.ms/vscode-docker-python-debug CMD ["gunicorn", "--bind", "0.0.0.0:8080", "pyaudio:app"] When I try to open the URL provided, it says "Service not available". The URL is: https://internship-aiffpkop5q-as.a.run.app/ The logs I'm receiving in Cloud Run Logs when I try to open the URL are: 2021-11-24T03:55:09.124682Z [1] [INFO] Listening at: http://0.0.0.0:8080 (1) 2021-11-24T03:55:09.124702Z [1] [INFO] Using worker: … -
ModelViewset in django
My name is Leo and I'm newbie of Django Rest-framework. I use Modelviewset to create API for project. I want to get list of thing not by id and i use lookup_field to do that. But it is only return 1 object. How can i custom it to return multible object? this is my model class Rating(models.Model): dayandtime = models.DateTimeField(auto_now_add=True) ratingpoint = models.IntegerField(null=True,blank=True) ratingcomment = models.TextField(null=True, blank=True) img = models.ImageField(upload_to='static',default=None) product = models.ForeignKey(Product,on_delete=models.CASCADE) user = models.ForeignKey(User,on_delete=models.CASCADE) This is my views class RatingViewSet(viewsets.ModelViewSet): queryset = Rating.objects.all() serializer_class = RatingSerializer lookup_field = "product" This is my Serializer class RatingSerializer(ModelSerializer): class Meta: model=Rating fields=["id","dayandtime","ratingpoint", "ratingcomment","img","product","user"] lookup_field = "product" Please help me to sovle this problem. Thank you very much -
Django Form submission not updated when back to previous page using browser back button
I have a 2 pages, 1 page with things to display such as name and bio. Another page with form to change the name and bio. So I have submit the form and it is successful but when back button are clicked the name and bio are not updated until I refresh the page. How do I achieve so that the name and bio are updated instantly after form submission success. I know about the back button automatically reload but I don't want that approach. How to get the form submission to be updated so when I click back button the info are updated without refreshing the pages ? -
Was wondering why iterating through a dictionary using .keys in django would not work?
I know that .items would be useful to grab the value, but wanted to see why this would not work? Data: ... city_data = { 'city': json_data['name'], 'country': json_data['sys']['country'], 'temp': json_data['main']['temp'], 'feels_like': json_data['main']['feels_like'], 'temp_max': json_data['main']['temp_max'], 'temp_min': json_data['main']['temp_min'] } return render(request, ..., context={'city_data':city_data}) template: ... {% for key in city_data.keys %} <li>{{city_data.key}}</li> {% endfor %} ... -
Django - Class Based View - Restrict Access to Views based on User or Group Permissions - UserPassesTestMixin
My project is running Django 3.05 and was set up with Django cookiecutter, and the custom user model that it creates. AUTH_USER_MODEL = "users.User" I have a set of Class Based Views where I want to restrict access based on group or user permissions. I do not want to use the PermissionRequiredMixin and redirect to a 403 page. Instead, if a user does not have correct permissions I would simply like to redirect to the referring page, and display a "permission denied" banner message at the top (see screen shot below). The problem is that these permissions are not working as expected when implemented my Views. I am able to use either the admin panel or the django shell to assign permissions. For example here is the permissions as they show up in the shell: In [7]: from django.contrib.auth import get_user_model In [8]: User = get_user_model() In [9]: user = User.objects.get(id=8) In [10]: permission = Permission.objects.get(name='can run batch actions') In [11]: user.user_permissions.add(permission) In [12]: from django.contrib.auth.models import Permission ...: from django.contrib.auth.models import User In [13]: group_permissions = Permission.objects.filter(group__user=user) In [14]: group_permissions Out[14]: <QuerySet [<Permission: slatedoc | slate doc | Can add slate doc>, <Permission: slatedoc | slate doc | can … -
Why isn't my JavaScript code being executed in the order it was written [duplicate]
I am working on a dating web app using Django. One of the tabs of the app displays profiles of possible dating candidates, one profile at a time. When the user clicks on the like button on one of the profiles, a post request is sent to the server using fetch, the like is added to the database and the code checks whether there is a match or not between the user and the person (python). In case there is a match, I want to hide the person's profile and display a div with a message acknowledging the match (JavaScript). The idea is for this message to be displayed for a few seconds and then the page would refresh and move on to the next profile. My code is not executing correctly. After clicking on the like button, the person's profile displays for a few seconds and then I can see the message for a split of second and the page moves on to the next profile. How can I make this code execute according to my requirements? This is the code: function wait(ms){ var start = new Date().getTime(); var end = start; while(end < start + ms) { end … -
How to check if all modelForm data are empty?
I have created a view that renders multiple related forms together, and all of them are submitted by a single submit button to create a single parent instance with all its related forms with it. Here is a simplified example from my model classes: class Parent(models.Model): name = models.CharField(max_length=100) child1 = models.ForeignKey(Child1, blank=True, null=True, on_delete=CASCADE) class Child1(models.Model): name = models.CharField(max_length=100, blank=True) As you can see, my foreign key child1 could be null. I have also created a modelForm for each model. My view renders a Parent form and a Child1 form. Question: On POST request, I got all my POST data and pass them to my forms, so a Child1 instance is created weather its fields are empty or not, then it got attached to the Parent instance. This is not the behavior that I need. The required behavior: If all the fields in my Child1 form is empty, ignore it and don't create an instance of it, and subsequently don't attach it to the Parent instance. How can I achieve this? -
AWS media forbidden
I get the 403 error when my Heroku app tries to access pictures from my AWS bucket. I followed the Heroku guide on user uploads with Python: https://devcenter.heroku.com/articles/s3-upload-python and changed it a little so it would only affect user uploads and not my static files. Even though I turned off "block all public access" it is still forbidden My settings: AWS_ACCESS_KEY_ID = os.environ.get('my key') AWS_SECRET_ACCESS_KEY = os.environ.get('my secret key') AWS_STORAGE_BUCKET_NAME = 'my bucket name' #STATICFILES_STORAGE = 'storages.backends.s3boto3.S3StaticStorage' #DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3StaticStorage' if DEBUG == False: MEDIA_URL = 'http://' + AWS_STORAGE_BUCKET_NAME + '.s3.eu-west-1.amazonaws.com/' # MEDIA_ROOT = os.path.join(BASE_DIR, 'media') # ADMIN_MEDIA_PREFIX = STATIC_URL + 'admin/' AWS_QUERYSTRING_AUTH = False and here is my CORS: [ { "AllowedHeaders": [ "*" ], "AllowedMethods": [ "GET", "HEAD", "POST", "PUT" ], "AllowedOrigins": [ "*" ], "ExposeHeaders": [] } ] but it is copied and pasted directly from Heroku's guide so I doubt it is the problem.