Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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! … -
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 %} ...