Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
How can I use NPM modules with Django inside an app?
I have a Django project with 2 apps. I want to use the Notion API in one of the apps, so I have to install it's NPM module. However, I have never use NPM nor a bundler (I understand I have to use one for the import statement). I have no idea on how to do it, where should I install the module? Should I install Webpack or something similar? How can I integrate both of this technologies with Django? Can someone please explain this to me, or reffer to an article/video explaining? I have been trying for hours now and I can't find anything detailed. I have checked the following links: Django how to use npm modules with static/ templates https://gist.github.com/brizandrew/685a588fbefbd64cd95ed9ec4db84848 https://www.saaspegasus.com/guides/modern-javascript-for-django-developers/integrating-javascript-pipeline/ https://www.saaspegasus.com/guides/modern-javascript-for-django-developers/integrating-javascript-pipeline/ https://www.techiediaries.com/django-webpack-react/ https://owais.lone.pw/blog/webpack-plus-reactjs-and-django/ https://pythonrepo.com/repo/owais-django-webpack-loader-python-developing-restful-apis And a lot more. They either don't have what I need (they are for react), or I can just not understand them. I know there are probably a lot of articles on this, but either I just can't find them, or they are too complicated for me (sorry I'm dumb). If anyone can help me, it would make my day. Thanks! -
Django REST - hide deserialized data
I would like to store some data in one of my database field. The data is added to that field while deserialization with POST method. Later when I want to show data with GET method I don't want that one field to be presented. When I do POST I deserialize that string: { "car_id": 3, "rating": 3 } Later in views.py I do the deserialization while POST: @api_view(['POST']) def car_rate(request): if request.method == 'POST': rate_data = JSONParser().parse(request) rate_serializer = CarRateSerializer(data=rate_data) if rate_serializer.is_valid(): try: car_obj = Car.objects.get(pk=rate_data['car_id']) except Car.DoesNotExist: return JsonResponse({'message': 'The car with given ID does not exist!'}, status=status.HTTP_404_NOT_FOUND) # check if rate is from 1 to 5 r = rate_serializer.validated_data['rating'] if int(r) >= 1 and int(r) <= 5: rate_serializer.save() return JsonResponse({'message':'The rate is in the scope!'}) else: return JsonResponse({'message':'The rate is NOT in the scope!'}) return JsonResponse(rate_serializer.errors) And there is my models.py: class Car(models.Model): make = models.CharField(max_length=15) model = models.CharField(max_length=15) avg_rating = models.FloatField(default=0) def __str__(self): # print it when Car instance is needed return self.make class CarRate(models.Model): car_id = models.ForeignKey(Car, related_name='rates', on_delete=models.CASCADE, default=0) rating = models.PositiveIntegerField(default=0) The code does works (somehow). For now there can be added rates for one car (multiple rates) with POST moethods. I store the … -
Setting a CSS variable in Django
I am creating custom user pages where they are able to change basic features like the font, color, or background color of different link boxes. Currently, I am passing the saved variables from the database to the HTML template but I was wondering if I could pass them into the external CSS style sheet. I am having to do inline CSS styling inside the HTML template. I'd like the link hover effect to stay but whenever I set the background color of the link via inline CSS in my HTML template it will break the hover effect. Note: Only including part of my index.html file index.html {% load static %} <link rel="stylesheet" type="text/css" href="{%static 'css/style.css' %}"/> <div id="links"> <a class="link" style="color:{{ linkcolor }}; background-color:{{ linkbc }}; font-family:{{ linkfont }};" href="https://www.instagram.com" target="_blank"><Instagram</a> style.css #links { max-width: 500px; width: auto; display: block; margin: 20px auto; } .link { display: block; box-shadow: 10px 10px black; text-align: center; margin-bottom: 20px; padding: 17px; text-decoration: none; font-size: 1.4rem; font-weight: 300; transition: all .25s cubic-bezier(.08, .59, .29, .99); border-radius: 10px; } .link:hover { background-color: rgba(255, 255, 255, 0.3); color: #000000; border: none; } views.py def index(request): editor = cssEditor.objects.get(pk=1) return render( request, "SocialLinks/index.html", { "linkcolor":editor.link_color, "linkfont":editor.link_font, "linkbc":editor.link_bc … -
Quickly check existence of a Many-To-Many relationship without too many queries in Django
On my old system, The apps installed for each website would look like this (if they had been in Django): class Website(models.Model): name = models.CharField(max_length=255) ... class Apps(models.Model): website = models.ForeignKey(Website, on_delete=models.CASCADE) blog = models.BooleanField(default=False) shop = models.BooleanField(default=False) ... # To see if the shop app is installed, you can easily do this from a `Website` instance loaded previously in the code website = Website.objects.get(pk=1) ... if website.apps.shop: pass It's nice because you can quickly check if an app is installed, however it feels wrong as you need a separate apps table where every app detail is, and that table is not linked to websites. So the other solution, which follows conventions and best practices I think, is to have a Many-To-Many relationship like this: class App(models.Model): name = models.CharField(max_length=255) ... class Website(models.Model): name = models.CharField(max_length=255) apps = models.ManyToManyField(App) ... # To see if the shop is installed, would I need to do this every time from a `Website` instance: if website.apps.filter(name="shop").exists(): pass I like the latter as it feels cleaner and the App table can have more columns to hold details about each app. However the check to see if an app is installed is quite long and tedious, … -
How to save file in the file system and its path in the database using Python?
I want to save file to the file system, currently I am working with django and it provides a pretty neat way of doing this: models.py class Report(models.Model): name = models.CharField(max_length=120) image = models.ImageField(upload_to = 'charts', blank=True, null=True) remarks = models.TextField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) author = models.ForeignKey(Profile, on_delete=models.PROTECT) utils.py (this file is created by me): import base64, uuid from django.core.files.base import ContentFile def get_report_image(data): f, str_img = data.split(';base64, ') decoded_img = base64.b64decode(str_img) img_name = str(uuid.uuid4())[:12] + '.png' data = ContentFile(decoded_img, name=img_name) return data And to save this data to the data base I use django orm Report.object.create(name="report name", remarks='Report Remarks', author=request.user.id, image=get_report_image(base64_encoded_image)) But I want to do the same thing without django Sorry for any mistake I made in asking the question or explaining my problem, I am a beginner -
Split Model declaration among several app in Django
I am working and building my website with Django and I am facing this logical issue. My project is made by several app. I would like to declare in each one of these a "piece" of a bigger model that will be represented in one single table- Example: model Person model DetailsPerson As each single app specifies a specific part of the person, my idea was to decentralize the declaration of DetailsPerson model so that they figure in one single table but each app enlarge the fields the app needs to work. Is this possible? -
Windows Deploying Django
https://realpython.com/django-hosting-on-heroku/#step-7-deploy-your-django-project-to-heroku Following this I am running into an issue with deploying Django with Python using Windows. It seems that it can't find the Procfile even though it's inside the folder. (portfolio) C:\Users\arund\Desktop\Code\Django\portfolio-project>heroku local [WARN] Cannot read property '1' of null [FAIL] No Procfile and no package.json file found in Current Directory - See run --help TypeError: Cannot convert undefined or null to object at Function.keys (<anonymous>) at Index.run (C:/Users/arund/AppData/Local/heroku/client/7.59.2/node_modules/@heroku-cli/plugin-local/lib/commands/local/index.js:30:38) at Index._run (C:/Users/arund/AppData/Local/heroku/client/7.59.2/node_modules/@oclif/command/lib/command.js:44:31) (portfolio) C:\Users\arund\Desktop\Code\Django\portfolio-project> After I ran $ echo "web: python manage.py runserver 0.0.0.0:\$PORT" > Procfile $ git add Procfile $ git commit -m "Specify the command to run your project" -
HTML can't load image on page
in the following html, i want to load and image but as the you can see below the image has been send but not displayed. Any ideas? maybe problem with css? (I am using materiallized css) <html> {% extends "main/header.html" %} {% load static %} {% block content %} <img class="responsive-img" src="{% static 'images/MOA_LOGO_p.jpg' %}" alt="logo" > {% endblock %} -
Django Application Wont Load User Uploaded Image
I used Django Admin to upload an image and I am trying to get it to display in a template. The alt text is displayed but I keep getting a 404 error for the image and it does not display. When I uploaded the image the path that it pulls in the template media/images/mari-profile-pic.png is valid and contains the image I am trying to display. models.py from django.db import models # Create your models here. class Image(models.Model): title = models.CharField(max_length=50) image = models.ImageField(upload_to='images/') views.py from django.shortcuts import render from django.http import HttpResponse from .models import Image # Create your views here. def index(request): imageModel = Image.objects.get(pk=1) return render( request, "SocialLinks/index.html", { "profile_pic_title":imageModel.title, "profile_pic":imageModel.image } ) index.html template <div id="profile"> <img id="userPhoto" src="{% get_media_prefix %}{{ profile_pic }}" alt="{{ profile_pic_title }}"> </div> settings.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') I have tried removing and adding the {% get_media_prefix %} tag and the image still does not display.