Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Validators.py
please your help. I have the next code: form.py from .validators import MaxSizeFileValidator class ProductForm(forms.ModelForm): name = forms.CharField(min_length=5, max_length=50) image = forms.ImageField(required=False, validators=[MaxSizeFileValidator(max_file_size=2)]) validator.py from django import forms from django.core.exceptions import ValidationError class MaxSizeFileValidator: def __init__(self, max_file_size=5): self.max_file_size = max_file_size def __class__(self,value): size = value.size max_size = self.max_file_size * 1048576 if size > max_size: raise ValidationError(f"Not permitted size image, must be: {self.max_file_size}MB") return value When a run the code, the page show the next: TypeError at /add-product/ 'MaxSizeFileValidator' object is not callable Request Method: POST Request URL: http://127.0.0.1:8000/add-product/ Django Version: 3.1.5 Exception Type: TypeError Exception Value: 'MaxSizeFileValidator' object is not callable Thanks!!! -
How to create Django custom admin page? (Not overriding list or object page)
I want to add "upload image" page to django model admin. So I add "upload image" action button to image list page. when click "upload image" button, redirect to upload image page. In this case, there are not url navigation (breadcrumbs) and login information on header bar. How to show these items? Which class should I use? I already tried TemplateView, ModelAdmin, but I cannot implement what i want. Or, How to pass the model and the model admin to custom templage page? here is example of my admin template. {% extends "admin/app_index.html" %} {% load i18n admin_urls static admin_list %} {% block breadcrumbs %} <div class="breadcrumbs"> <a href="{% url 'admin:index' %}">{% trans 'Home' %}</a> &rsaquo; <a href="{% url 'admin:app_list' app_label=opts.app_label %}">{{ opts.app_config.verbose_name }}</a> &rsaquo; {% if has_view_permission %}<a href="{% url opts|admin_urlname:'changelist' %}">Images</a>{% else %}Images{% endif %} </div> {% endblock %} I copied this code from templates/admin/change_form.html for showing breadcrumbs. In this case, how to get opts, app_label and/or app_list? -
Image is showing twice after upload
I ma building a Social Media Webapp and I build a story feature. What i am trying to do :- I am trying to save images in stories, BUT when i select and save image then it shows twice . BUT when i check in admin then there is only one photo. I don't know where is the problem. models.py class Story(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE,default='',null=True) images = models.FileField(null=True) views.py def new_story(request,pk): form = NewStoryForm(request.POST,request.FILES) requested = request.user if request.method == 'POST': form = NewStoryForm(request.POST,request.FILES) if form.is_valid(): new_video = form.save() new_video.user = request.user new_video.save() return redirect('story') else: form = NewStoryForm() context = {'form':form,'requested':requested} return render(request, 'new_story.html', context) new_story.html <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button name="Submit">Add Story</button> </form> story.html <script> var currentSkin = getCurrentSkin(); var stories = new Zuck('stories', { backNative: true, previousTap: true, skin: currentSkin['name'], autoFullScreen: currentSkin['params']['autoFullScreen'], avatars: currentSkin['params']['avatars'], paginationArrows: currentSkin['params']['paginationArrows'], list: currentSkin['params']['list'], cubeEffect: currentSkin['params']['cubeEffect'], localStorage: true, stories: [ // {% for story in stories %} Zuck.buildTimelineItem( '{{ story.user.id }}', '{{ user.profile.file.url }}', '{{ story.user }}', 'https://{{story.id}}.codes', timestamp(), [ [ '{{story.user.id }}-1', 'photo', 3, '{{ story.images.url }}', '', false, false, timestamp(), ], ] ), // {% endfor %} ], }); </script> I don't know what am i … -
How can i add multiple queries in my List View Django
My View class profit_loss(generic.ListView): model = PartyCompleteLedgers template_name = 'report/Profit_Loss/profit_loss_show.html' context_object_name = 'all_profit' def get_queryset(self): a = PartyCompleteLedgers.objects.values('party_category').order_by("party_category").annotate(debit = Sum('party_debit_amount'),credit= Sum('party_credit_amount'),balance = (Sum('party_debit_amount')+Sum('party_credit_amount'))) for item in a: item['party_category'] = CategoryMaster.objects.get(id=item['party_category']) return a success_url = reverse_lazy('financial_accounting_app:profit_loss-detail') Using this for loop inside this view helps me to render actual data according to their id but i am unable to add more queries in the same view. Remenber both (PartyCompleteLedgers) and (CategoryMaster) has a foreign key relation. -
Send notification by firebase cloud messaging on a topic by django
I have implemented a firebase cloud messaging app which sends a notification to an android device based on its device token which works fine. I've used django-fcm module. But, storing device registration code for each user device is a little difficult in the practical application as I've to modify the front end source code which I don't want to. Therefor I decided to go with topic messaging. I cannot find any useful documentation regarding this. view.py def send_notification(registration_id,message_title, message_body): try: push_service = FCMNotification(api_key=FCM_DJANGO_SETTINGS['FCM_SERVER_KEY']) result=push_service.notify_single_device(registration_id=registration_id, message_title=message_title, message_body=message_body) return result except: pass def send_noti(request): device_token = "dEMspOwATpiFVumQGi1QOS:APA91bEZsTu7SbRTYRDGJjhNhHRErYd_UHs43rrPY6uN4yXe5_UHnPpepocFP60wnnU2IImCBXcem0rVuEUj7PCPc9EfkC0W4cLrNSmBCoWM5mz8jp9YgYF-VurJ1JyoRH627IH5Ujxn" send_notification(device_token,"title","body") return JsonResponse({"status": "success"}, safe=False) urls.py urlpatterns = [ path('noti/', views.send_noti, name='send_noti'), ] Can anyone help to send notification on topic using django? -
RUN command not executed in dockerfile image building
I have following file structure Django/ - IoT.yml - Dockerfile_Build_Django - requirements.txt My dockerfile (Dockerfile_Build_Django) for budiding image is as below: FROM python:3.10.0a7-alpine3.13 ENV PYTHONUNBUFFERED 1 RUN mkdir /code/ WORKDIR /usr/src/app COPY . . RUN pip install -r requirements.txt My docker-compose file as below: Django_2.2: build: context: ./ dockerfile: Dockerfile_Build_Django # Give an image name/tag image: python:3.10.0a7-alpine3.13 container_name: Django_2.2 depends_on: - Django_Mongo_4.2.12 tty: true after "docker-compose -f IoT.yml up" to setup and run container, then I use "docker exec -it Django_2.2 /bin/sh" to SSH access the Django_2.2 container, I found: no folder "/code" was created according to "RUN mkdir /code/" in docker file nothing was copied over to working directory according to dockerfile. Django was not installed according to above dockerfile. it makes me feel whether Docker.Inc tested properly before they release the software/product, they can not rely on users to do testing and raising bugs/defects for them. or, the Docker official document was truely poorly written, which resulted in a huge waste of time from developers all over the world. https://docs.docker.com/compose/compose-file/compose-file-v3/#build Following official guide just does not work out for you, was that on purpose? so that enterprise needs to hire Docker Specialist or buy professional service from Docker … -
How does django decide which transaction to choose on transaction.on_commit()
I had to use transaction.on_commit() for synchronous behaviour in one of the signals of my project. Though it works fine, I couldn't understand how does transaction.on_commit() decide which transaction to take. I mean their can be multiple transactions at the same time. But how does django know which transaction to take by using transaction.on_commit() -
Change HTTP Response message Django
I am using http response to handle exception in my website. I want to show proper message / validation during create and update data. But It shows HTTP responses like Bad Request , Internel server error. Here is my code: from django import http from rest_framework import viewsets class SaleViewSet(viewsets.ModelViewSet): def create(self, request, *args, **kwargs): data = request.data try: // Some code return http.JsonResponse(response) except Exception as e: logger.error(e) return http.HttpResponseBadRequest(content=e) In dialog box message it shows ,"Bad Request". Instead of "Bad Request" in dialog box message I want to show custom message. I want to do , except Exception as e: logger.error(e) return http.HttpResponseBadRequest(My message) -
TypeError: 'list' object is not callable in Django Channes
HTTP POST /room/ 200 [0.01, 127.0.0.1:59330] WebSocket HANDSHAKING /ws/chat/100/ [127.0.0.1:59334] Exception inside application: 'list' object is not callable Traceback (most recent call last): File "/usr/lib/python3.9/site-packages/channels/staticfiles.py", line 44, in call return await self.application(scope, receive, send) File "/usr/lib/python3.9/site-packages/channels/routing.py", line 71, in call return await application(scope, receive, send) File "/usr/lib/python3.9/site-packages/channels/sessions.py", line 47, in call return await self.inner(dict(scope, cookies=cookies), receive, send) File "/usr/lib/python3.9/site-packages/channels/sessions.py", line 254, in call return await self.inner(wrapper.scope, receive, wrapper.send) File "/usr/lib/python3.9/site-packages/channels/auth.py", line 181, in call return await super().call(scope, receive, send) File "/usr/lib/python3.9/site-packages/channels/middleware.py", line 26, in call return await self.inner(scope, receive, send) TypeError: 'list' object is not callable I have been having this error in django channels and i have no clue on how to go about it -
how do I fix PEP fields.E339 in django models through/through_fields?
I am trying to link vulnerability cve models with products via intermediate models to link/match each vulnerability based on the product / cve class Vulnerability(models.Model): cveid = models.CharField(max_length=32, null=True, blank=True) affected_products = models.ManyToManyField( Product, through='ProductVulnerability', through_fields=("product", "vulnerability") ) class ProductVulnerability(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) vulnerability = models.ForeignKey(Vulnerability, on_delete=models.CASCADE) class Meta: unique_together = [("product", "vulnerability")] service | ERRORS: service | api.Vulnerability.affected_products: (fields.E339) 'ProductVulnerability.product' is not a foreign key to 'Vulnerability'. service | HINT: Did you mean one of the following foreign keys to 'Vulnerability': vulnerability? service | api.Vulnerability.affected_products: (fields.E339) 'ProductVulnerability.vulnerability' is not a foreign key to 'Product'. service | HINT: Did you mean one of the following foreign keys to 'Product': product? service | SystemCheckError: System check identified some issues: -
Django/Python - Comparing 2 lists of dictionaries and adding a key,value when a common key is identified
I have two lists of dictionaries. The first list will contain significantly more dictionaries than the second list. There could be up to 200-300 dictionaries in list1 and no more than 10-15 dictionaries in list2. For example, any dictionary in list1 that has the same 'g': h key/value as that of list2 needs to add key/value 'j': k to list 1. list1 = [{'a': b, 'c': d, 'e': f, 'g': h}, {'a': b, 'c': d, 'e': f, 'g': h}, {'a': b, 'c': d, 'e': f, 'g': h}, {'a': b, 'c': d, 'e': f, 'g': h} ] list2 = [{'g': h, 'j': k}] I'm struggling on finding any previous examples of this type and cannot figure out a function of my own. -
How to do a quick user registration & CRUD on simple app
I have been asked to perform a simple task where I can do the following User can register and login as a doctor or patient Doctor has many clinics. clinic include (name, price, date, start_time, end_time) Patients can reserve doctor clinics Display doctors and patients reservations Use Python, django, django rest framework and relational database to complete the task. I participate in a big project for creating an app for doctor clinics where I'm responsible for creating the previous tasks. class User(AbstractUser): ... # fields objects = MedicalUserManager() class MedicalUserManager(models.UserManager): def create_user(self, username, email=None, password=None, **extra_fields): # pop all fields you want to use for `Doctor` or `Patient` from `extra_fields` doctor_pin = extra_fields.pop('doctor_pin', None) pid = extra_fields.pop('pid', None) user = super().create_user(username, email, password, **extra_fields) if doctor_pin: doctor = Doctor.objects.create(user=user, upin=doctor_pin) user.is_doctor = True # not needed if `is_doctor` is in `extra_fields` because it would have been saved when creating the `User` user.save() elif pid: patient = Patient.objects.create(user=user, pid=pid) user.is_patient = True user.save() return user or the following: class User(AbstractUser): is_doctor = models.BooleanField(default=False) is_patient = models.BooleanField(default=False) class Patient(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) user.is_patient = True pid = models.AutoField(unique=True, primary_key=True) #patient identification class Doctor(models.Model): upin = models.AutoField(primary_key=True) #unique physician identification number user … -
How to make subdomain in Django?
I want to make subdomains for every django apps in my project. I know that there are third party apps like django-hosts & django-subdomains but I don't want to use them when I can create subdomain without using them. While I was searching about creating subdomain in django, I found that we have to do something with the middleware. I don't know much about coding so please try to give me specific code to create subdomains in django. -
How to change button from drop down to manual input python django
I am making an attendance web app and after I made the relationship of the database one to many, the button changed from manual input to drop down type like so: this is my html code: <form method="post"> {% csrf_token %} <div class="input-group mb-2"> <div class="input-group-prepend"> <label for="name">Enter Your Full Name:</label> {{form.name}} <button type="submit" name="checkName" value="checkName" class="btn btn-outline-success">Submit</button> </div> </div> </form> models.py: class employeeName(models.Model): employee = models.CharField(max_length=200) def __str__(self): return self.employee class Name(models.Model): name = models.ForeignKey(employeeName, null=True,on_delete=models.CASCADE) timeIn = models.TimeField() timeOut = models.TimeField(default=datetime.now()) date = models.DateField(auto_now=True) def __str__(self): return str(self.name) -
Getting CSRF session cookie from Django while using React for frontend
Background I've been trying to make a POST request to my application's backend (written in Django) from my React frontend, but the request fails because the request does not include a CSRF token. Here is the code I use to setup and send my request: const formData = new FormData() // 'image' is a user uploaded image formData.append( "myImage", image, image.name ) const data = await axios.post("http://localhost:8000/myendpoint", formData) return data My application is very simple in that there is no log-in/session-keeping that I need to do and to use the app the user simply needs to give some data (upload an image to be precise) to my Django API's endpoint and then get some results. For reference, here is what I see on my Django server logs: Forbidden (CSRF cookie not set.): /myendpoint And here is the error I see in the browser's console: POST http://localhost:8000/myendpoint 403 (Forbidden) Based on some questions that appear similar to mine, the suggestion seems to be to retrieve this CSRF token from the csrftoken cookie that Django sends and then including it in subsequent POST requests (for instance, this answer). I didn't think this would work since I did not see any cookies in … -
I've been working on my blog app and everything was going smoothly until I try to add a new field to my Post model
I've been working on my blog app and everything was going smoothly until I try to add a new field to my Post model. It's giving me an error of no such table: blog_post_likes. Is there something about the django models that I need to know like anything going on behind the scenes that I am not aware of? from django.db import models from django.urls import reverse from django.contrib.auth.models import User # Create your models here. STATUS = ( (0, 'Draft'), (1, 'Published'), ) class Post(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(blank=False, unique=True, default='travel-blog-post') author = models.ForeignKey(User, on_delete=models.CASCADE) date_created = models.DateTimeField(auto_now_add=True) body = models.TextField() status = models.IntegerField(choices=STATUS, default=0) # meta descrption for SEO benifits metades = models.CharField(max_length=300, default="new post") category = models.CharField(max_length=200, default='uncategorized') likes = models.ManyToManyField( User, related_name='post_like', blank=True) class Meta: ordering = ['-date_created'] def __str__(self): return self.title def get_absolute_url(self): return reverse('article-detail', kwargs={'slug': self.slug}) class Category(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name def get_absolute_url(self): return reverse('index') ** -
Django Static files are being served with HTTPS while the running server is HTTP
I'm using Amazon lightsail instance and introduced Certbot into my service on the Nginx-Gunicorn-Django stack in order to serve my site with SSL implemented. I took a snapshot of this server and created a new one which I want to serve without SSL but when the server turns on I can see the page but all images, css, js show ERR_CONNECTION_REFUSED. Which I found the issue comes from searching for these files in HTTPS when I want them to be served in HTTP. Here are some things I've tried Removed SSL Setting Nginx Completely removed Nginx serve and ran server on manage.py 8000 Disabled SSL related settings and DEBUG MODE = True Image shows up if I open url to http://img.jpg How can I solve this issue? JS ERROR IMG -
My detail page for my app isn't showing in the browser
There is my html template which works perfectly. No template errors. {% extends 'learning_logs/base.html' %} {% block title %}Topic {% endblock title %} {% block content %} <p>Topic: {{ topic }}</p> <p>Entries:</p> <ul> {% for entry in entries %} <li> <p>{{ entry.date_added|date:'M d, Y H:i' }}</p> <p>{{ entry.text|linebreaks }}</p> </li> {% empty %} <li>There are no entries for this topic yet.</li> {% endfor %} </ul> {% endblock content %} You will find below my view.py. In actual fact the application does not any error. def topic(request, topic_id): """Show a single topic and all its entries.""" topic = Topic.objects.get(id=topic_id) entries = topic.entry_set.order_by('date_added') context = {'topic': topic, 'entries': entries} return render(request, 'learning_logs/topic.html', context) ``class Entry (models.Model): topic = models.ForeignKey('Topic', on_delete = models.CASCADE, max_length = 200) text = models.TextField() date_added = models.DateTimeField(auto_now_add = True)` -
Django form updates front end even if username already exists
Below is my Django form that allows users to update their username and email. If they enter a username or email that's already taken by another user, the form correctly displays an error message. However, the front end still updates with the username or email that they entered. How can I update the else block in views.py below to show the username/email that is actually stored in the database, not the one the user just entered? Screenshot: forms.py class UserUpdateForm(forms.ModelForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email', 'lat', 'long', 'travel_radius', 'location_name'] widgets = {'lat': forms.HiddenInput(), 'long': forms.HiddenInput(), 'travel_radius': forms.HiddenInput(), 'location_name': forms.HiddenInput()} views.py @login_required def account(request): if request.method == 'POST': u_form = UserUpdateForm(request.POST, instance=request.user) if u_form.is_valid(): u_form.save() messages.success(request, f'Your account has been updated!') return redirect('account') else: #<- HOW CAN I SHOW THE ORIGINAL USERNAME, NOT THE USERNAME ENTERED? stored_user = User.objects.filter(id=request.user.id).first() u_form = UserUpdateForm(request.POST, instance=request.user) u_form.username = stored_user.username # Get the values on this user that are stored in the DB u_form.email = stored_user.email u_form.fields['username'].initial = stored_user.username return render(request, 'users/account.html', {'u_form': u_form} ) else: u_form = UserUpdateForm(instance=request.user) context = { 'u_form': u_form } return render(request, 'users/account.html', context) -
Django REST Fw - How to dynanically create fk relation when neither object exists initially?
[I'm asking about DRF but this question is more about a general approach to a situation like mine] Let's say on my backend I have a Category and a Question model like these: class Category(models.Model): name = models.TextField() class Question(models.Model): text = models.TextField() category = models.ForeignKey( Category, on_delete=models.SET_NULL, null=True, related_name="questions" ) I have a vue frontend in which I have a form that allows me to create categories and questions. The way it's laid out is I have an add button for categories in the form, an add button for questions, and for each question I can select the category it belongs to. All questions and categories are keyed with a uuid in my vue.js frontend, but that's not the id they end up having on the db of course. When I POST my form to the DRF backend, neither the categories nor the questions exist yet, so I can't just send the questions like this: { text, categoryId }. A simple way to handle this could be to send the form like this: categories: [ { name: "cat1", questions: [ { text: "question1" }, // ... }, // ... ] However, the actual structure of my app is more … -
ValueError at /app/ when accessing model data
I am new with django, I've learnt by following the documentation, but it seems django doesn't want to retrieve any data from the model, on a new project. The issue is with the line : "latest_weapons = Weapon.objects.order_by('-id')[:5]". I tried other field names, other parameters, but still a value error... :( If someone has any idea, I would greatly appreciate! >//< app/views.py : from .models import Weapon # OK ! def detail(request, weapon_id): return HttpResponse("Analyzing weapon n°%s" % weapon_id) # No way ! def index(request): latest_weapons = Weapon.objects.order_by('-id')[:5] # Crash (maybe because it returns None?) template = loader.get_template('armory/index.html') context = { 'latest_weapons': latest_weapons, } return HttpResponse(template.render(context, request)) app/models.py : # The Model class Weapon(models.Model): id = models.AutoField(db_column='ID', primary_key=True) # Identifier id_item = models.ForeignKey('Item', models.CASCADE, db_column='ID_Item') # Global ID of this weapon in the items table. lvl = models.PositiveIntegerField(db_column='LVL') # Level of the weapon. name = models.CharField(db_column='Name', max_length=32) # Label of the weapon (rewrites item name). attack = models.IntegerField(db_column='ATK') # Attack of the weapon. crit = models.IntegerField(db_column='CTR') # Critical Hit of the weapon. weapon_type = models.ForeignKey('WeaponType', models.CASCADE, db_column='Type') # ID of the weapon type. class Meta: managed = False db_table = 'Weapons' def __str__(self): return self.name # Only returning the name … -
how to keep track of user opened profile like linkedin in django and flutter and to give notification too like that?
I want to keep track of the user, who has opened whose profile and how to give notifications too as in linkedin . I am going to implement it using Django as back-end and Flutter as Front-end. -
django.db.utils.OperationalError: (1044, "Access denied for user to database) when having permissions
I'm trying to connect my django project to its MySQL db in an Amazon EC2 instance, but I keep getting the error in the title. What's weird is that I granted all the privileges to the user, but I still keep getting the error: django.db.utils.OperationalError: (1044, "Access denied for user 'chile_analyst'@'%' to database 'lms_chile_integration_local'") I triple-checked the usernames and passwords coming from the environment file and they are OK. I also checked the grants for the user: mysql> SHOW GRANTS FOR 'chile_analyst'@'%'; +--------------------------------------------------------------------------------------------------+ | Grants for chile_analyst@% | +--------------------------------------------------------------------------------------------------+ | GRANT ALL PRIVILEGES ON *.* TO 'chile_analyst'@'%' WITH GRANT OPTION | | GRANT ALL PRIVILEGES ON `lms_chile_integration_local`.* TO 'chile_analyst'@'%' WITH GRANT OPTION | +--------------------------------------------------------------------------------------------------+ 2 rows in set (0.00 sec) I can connect to the databse using: mysql -u chile_analyst -p, but Django seems to be throwing this error when trying to migrate. What am I missing? -
Django 3 - ORM "AND" logic in filtering
I have a Query. qu = Product.objects .filter(color = 'black') .filter(color = 'white') .all() That gives me "And" logic which I'm looking for. Now I want to pass dict of criterions. my_crit = { 'color': 'black', 'color': 'white' } qu = Product.objects .filter(**my_crit) .all() That gives me OR, which is bad for me. So I tried Q. crit1 = Q(color='black') crit2 = Q(color='white') qu = hello = Product.objects .filter(crit1 & crit2) .all() This returns query with 0 results. So the question is - how can I use filter chain (AND logic) with dynamic inputs? (my own dict, etc). -
React/Django ; Error: Static/frontend/main.js not found
I am not sure why my static/frontend/main.js is not found when I clearly have it: Before running the server, I ran the dev script for webpack successfully, and it looks like everything was compiled into my main.js. I setup an API app and a frontend app on the same django project, and I am just testing to try and render information from my api to my frontend, but am unable to because of the error listed above. My API is called events and my frontend is react_frontend. I have listed below my App.js, my index.html, my views.py, my urls for both backend and frontend. App.js import React, { Component } from "react"; import { render } from "react-dom"; class App extends Component { constructor(props) { super(props); this.state = { data: [], loaded: false, placeholder: "Loading" }; } componentDidMount() { fetch("events/api") .then(response => { return response.json(); }) .then(data => { this.setState(() => { return { data, loaded: true }; }); }); } render() { return ( <div> {this.state.data.map(Events => { return ( <div> Event: {Events.title} Details {Events.details} </div> ); })} </div> ); } } export default App; const container = document.getElementById("api"); render(<App />, container); Index.html {% load static %} <!DOCTYPE html> …