Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django project - problem because the sql server database has column names with spaces, i got how to use it in models.py but not in the template file
the sql server I'm connecting to has column name with spaces in between I changed the models.py but I don't know what to do in the templates file. Code for the template file: <div id="CPU Utilization" class="tabcontent"> <h1>CPU Utilization</h1> <center> <table border = "1"> <tr> <th>SQL Server Process CPU Utilization</th> <th>System Idle Process</th> <th>Other Process CPU Utilization</th> <th>Event Time</th> </tr> {% for datadisplay in sqlserverconn2 %} <tr> <td>{{datadisplay.SQL Server Process CPU Utilization}}</td> <td>{{datadisplay.System Idle Process}}</td> <td>{{datadisplay.Other Process CPU Utilization}}</td> <td>{{datadisplay.Event Time}}</td> </tr> {% endfor %} </table> </center> </div> I tried the using the custom filters and defining attribute but it said it is not a registered tag library. -
pip install -r requirements_dev.txt
I am trying to install requirements for python django using command "pip install -r requirements_dev.txt" but I am getting the following error: × Getting requirements to build wheel did not run successfully. │ exit code: 1 ╰─> [2 lines of output] <string>:8: DeprecationWarning: pkg_resources is deprecated as an API. See https://setuptools.pypa.io/en/latest/pkg_resources.html proj executable not found. Please set the PROJ_DIR variable.For more information see: https://pyproj4.github.io/pyproj/stable/installation.html [end of output] anyone can help with that ? I tried to install "pyproj" and "proj" but with no hope, and try to set "PROJ_DIR" as mentioned in the error to "venv/bin/proj" but getting: subprocess.CalledProcessError: Command '/Users/../venv/bin/proj' returned non-zero exit status 1. -
I get error 404 on all URLs (when I click on a menu item on home page) in production. Everything works on localhost. What am I missing please?
I have deployed a django app on a shared hosting server using cpanel. The home page loads fine (I see only 1 error - 404 on favicon on developer's console). All the pictures and styling are showing as expected on the home page. I have placed my images on a google cloud bucket and I am referencing CSS/js from CDNs. My problem is that when I click on menu items, none of the the URLs are working. 'File not found' is displayed. On the dev console/Network I see error 404. There are no errors in the logfile. This exact question was asked previously but there was no resolution as far as I can tell: URL working on localhost but not in production I have tried so many things including: Setting DEBUG=True in settings, TEMPLATE_DEBUG=True, specifying default django template loaders one by one then together in TEMPLATES. I have made sure that all my apps are listed in INSTALLED_APPS. I even ran collectstatic and tried pointing DIRS to this static folder. After every change I restart the Python App in Cpanel and clear the browser cache Initially I had installed whitenoise to serve static files but I commented it out in … -
How to check in real time that a email is already registered in django if not then the user should get a cross sign while he is typing the email
How to check in real time that a email is already registered in django if not then the user should get a cross sign while he is typing the email -
What is the free web hosting platform for Django applications? [closed]
I want to host a Django application which is a small application. could anyone suggest to me the free web hosting platform for hosting that Django Application? I need a better web hosting platform for the Django application where the Traffic may get increased -
Django save one image two times in model
I am seeking for solution on how to upload one picture to a two ImageField fields for gallery. Fore this moment I need two upload two pictures. Then do resizing of first "image" to "image300" for gallery. models.py from django.db import models import PIL from PIL import Image from django.db.models.signals import pre_save from django.dispatch import receiver # Create your models here. class Images(models.Model): PICTURES = "PIC" MAPS = "MPS" YOUR_PICTURE = "YOP" GALLERY = [ (PICTURES, "Picture"), (MAPS, "Map"), (YOUR_PICTURE, "Your picture"), ] gallery = models.CharField( max_length=3, choices=GALLERY, default=YOUR_PICTURE, ) name = models.CharField(max_length=200, null=True, blank=True, default='picture') image = models.ImageField(upload_to="images1080/%Y/%m/%d/") image300 = models.ImageField(upload_to="images300/%Y/%m/%d/", null=True, blank=True) def save(self, *args, **kwargs): super().save(*args, **kwargs) def __str__(self): return self.gallery def save(self, *args, **kwargs): super().save(*args, **kwargs) img = Image.open(self.image.path) widthCheck = img.width - img.height if img.width > 1080: baseWidth = 1080 wPercent = (baseWidth/float(img.size[0])) hSize = int((float(img.size[1])*float(wPercent))) img = img.resize((baseWidth,hSize), Image.Resampling.LANCZOS) img.save(self.image.path) if widthCheck >= 0: baseWidth = 300 wPercent = (baseWidth/float(img.size[0])) hSize = int((float(img.size[1])*float(wPercent))) img = img.resize((baseWidth,hSize), Image.Resampling.LANCZOS) img.save(self.image300.path) else: new_height = 300 new_width = int(new_height * img.width / img.height) img = img.resize((new_width, new_height), Image.Resampling.LANCZOS) img.save(self.image300.path) I tried to save only image field, but can't resize empty image300 field so it need's some picture link … -
Need to Implement Click Payment Gateway - Uzbekistan
I need to create payment gateway Click which based on Uzbekistan PG. this Doc link :https://docs.click.uz/en/click-api-request/ Here don't understand the implementation flow for Marchant API there is 2 main api : 1. Prepare 2. Complete. I need to implement Marchant API, first I created create invoice API but now I don't understand the flow which api need to create first Prepare/ Complete or only merchant APIS. From when we can get the testing data for Click PG? here is attachment of API which implement. from flask import Flask, request, jsonify import hashlib import time import requests app = Flask(__name__) class ClickPay: def __init__(self): self.baseurl = "https://api.click.uz/v2/merchant/" self.secret_key = 'AAAAAA' self.merchant_id = 1111 self.service_id = 11111 self.merchant_trans_id = 11111 self.timestamp = str(int(time.time())) self.digest = hashlib.sha1((self.timestamp + self.secret_key).encode()).hexdigest() self.auth = f"{self.merchant_trans_id}:{self.digest}:{self.timestamp}" self.accept = "application/json" self.content_type = "application/json" self.headers = { "Accept" : self.accept, "Content-Type" : self.content_type, "Auth" : self.auth } def CreateInvoice(self, amount, phone_number): url = f"{self.baseurl}/invoice/create" request_body = { "service_id" : self.service_id, "amount" : amount, "phone_number" : phone_number, "merchant_trans_id" : self.merchant_trans_id } response = requests.post(url, headers=self.headers, data=request_body) return response def CheckInvoiceStatus(self, invoice_id): url = f"{self.baseurl}/invoice/status/:{self.service_id}/:{invoice_id}" response = requests.get(url, headers=self.headers) return response def CheckPaymentStatus(self, payment_id): url = f"{self.baseurl}/payment/status/:{self.service_id}/:{payment_id}" response = requests.get(url, headers=self.headers) … -
Django: Populate a model field from another model's field and make both amendable by admin
I want to create a database where an admin user can add products via the admin portal. The products will have a category field. I want the admin to also be able to add/remove category types. However I'm relatively new to django and can't work out how to do this. I feel like I need to use a ForeignKey but I'm getting confused about how I link it to the specific category name. I created a Category model and a Product model: class Category(models.Model): created_on = models.DateTimeField(auto_now_add=True) category_image = CloudinaryField('image', default='placeholder') category_name = models.CharField(max_length=50, unique=True) def __str__(self): return self.category_name class Product(models.Model): created_on = models.DateTimeField(auto_now_add=True) main_image = CloudinaryField('image', default='placeholder') item_name = models.CharField(max_length=50, unique=True) slug = models.SlugField(default="", null=False) price = models.DecimalField(max_digits=8, decimal_places=2) style = models.ForeignKey(Category, related_name='category_name', on_delete=models.CASCADE) likes = models.ManyToManyField(User, related_name='product', blank=True) def __str__(self): return self.item_name I've tried to link the style field in the Product model so that it pulls it's data from the category_name field in the Category model. Is this possible? Can I get it to appear as a dropdown on the admin portal somehow? Any help much appreciated! -
multiple django projects in one server using gunicorn and nginx with only ip and ports
I want to ask about deploying multiple django projects in one remote server using gunicorn and nginx. I've learnt that for each project I should create .socket and .service files and also configure nginx. All tutorials and videos I've seen showed project with domains, like (project1.example.com, project2.example.com). I did it once it works perfectly for domains. But what if I want to deploy them just using IP address and port for now, like (project1 in 12.34.56.78:8000, project2 in 12.34.56.78:8001.) I don't have domain and let's say I don't want it right now. Thanks in advance -
Initial form field doesn't set in Django
I have following set up. Model: class Feedbacks(models.Model): user_id = models.ForeignKey(User, on_delete=models.CASCADE, null=True) feedback = models.TextField() rating = models.IntegerField() Form: class FeedbackModelForm(ModelForm): class Meta: model = Feedbacks exclude = ['user_id'] View: @login_required def feedbackPage(request): username = request.user.id if request.method == 'POST': form = FeedbackModelForm(request.POST, initial={'user_id': username}) if form.is_valid(): form.save() return redirect('feedback_success') else: form = FeedbackModelForm() context = {'form': form} return render(request, 'feedback.html', context) Print(username) shows current current authenticated user ID. During the save procedure it doesn't save user_id field (it's NULL). I need that user_id field saved from authenticated user. -
Save data when changing DataBase in Django
I was wondering, if it is possible to move data from one to other database in django? Especially if something happens to the first database. For example: I have this DataBase DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql", "NAME": "DataBase", "USER": "user", "PASSWORD": "password", "HOST": "127.0.0.1", "PORT": "5432", } } But something happens to the database. Maybe the entire server falls down! Is it possible, to move the data of my models into a new DataBase? Maybe by presaving or something? DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql", "NAME": "NewDataBase", "USER": "new-user", "PASSWORD": "new-password", "HOST": "127.0.0.1", "PORT": "5432", } } -
Django model, How to not read data from an existing database when running my app in test mode
I have a django app that uses two databases, the default db and another readonly db called 'logs'. I create a model called alters (code below) that reads data from a table called logs in a db called logsdb, the alert model is not managed by django except on test mode. myapp/models/alert.py: class Alert(models.Model): class Meta: db_table = "logs" managed = getattr(settings, "MANAGE_ALERT_TABLE", False) id = models.IntegerField(db_column="event_id", primary_key=True) date = models.DateTimeField(db_column="record_time", null=True) label = models.CharField(db_column="name", max_length=64) settings.py: MANAGE_ALERT_TABLE=False # I set this to True when I run django in test mode DATABASES = { "default": { "ENGINE": "django.db.backends." + os.environ.get("DB_DEFAULT_ENGINE", "sqlite3"), "NAME": os.path.join(DB_DIR, DB_NAME), "TEST": {"NAME": os.path.join(BASE_DIR, "test_db.db")}, }, "logsdb": { "ENGINE": "django.db.backends." + os.environ.get("DB_DEFAULT_ENGINE", "sqlite3"), "NAME": os.path.join(DB_DIR, "logsdb.db"), } } I've also created a db router to read from the logs db: from api.models.alert import Alert class DBRouter(object): def db_for_read(self, model, **hints): if model == Alert: return 'logsdb' return None def db_for_write(self, model, **hints): if model == Alert: return 'logsdb' return None def allow_relation(self, obj1, obj2, **hints): return None def allow_migrate(self, db, app_label, model_name=None, **hints): if db == 'default': return True if db == 'logsdb': return False return None The app is working fine except when I run it … -
need an email notification service for my job portal website in django without html
I need an email notification service which sends emails to subscribed users who has subscribed for specific job location. If the location of the company and the subscribed location of the user are same an email should be sent to the user regarding the company details. also need to associate cron job which check for the new job postings and notify the users. This frequency should be tun-able. It can be 1day or 15mins. my models: company details: class JobListing(models.Model): title = models.CharField(max_length=255, null =True) location = models.CharField(max_length=200,default="") description = models.TextField() subscribed user: class UserSubscription(models.Model): username = models.CharField(max_length=150,default="sample name") email_id = models.EmailField(unique=True) job_location = models.CharField(max_length=150) serializers: class JobListingSerializer(serializers.ModelSerializer): class Meta: model = JobListing fields = '__all__' class UserSubscriptionSerializer(serializers.ModelSerializer): class Meta: model = UserSubscription fields = '__all__' views: class UserSubscriptionViewSet(viewsets.ModelViewSet): queryset = UserSubscription.objects.all() serializer_class = UserSubscriptionSerializer class JobListingViewSet(viewsets.ModelViewSet): queryset = JobListing.objects.all() serializer_class = JobListingSerializer I want an email notification service and associate cron job with it. -
Django forbidden (csrf cookie not set.): /products/ Error
I've gone through a lot of other threads and discussion forums, but none solved exactly. This solution refers to few settings in the settings.py I've applied them, Django CSRF Cookie Not Set I'm posting this question because I've tried other solutions but none exactly fixed it. This is also a just the beginning of a server, I made the project, started an app, & created a view for POST request. Let me know if any other code is required... My views.py nothing, just a basic return. When I add @csrf_exempt it works but I can't really do that. from django.views.decorators.csrf import csrf_exempt @csrf_exempt views.py from django.http import HttpResponse import json # Create your views here. def Product(request): if request.method == "POST": try: data = json.loads(request.body) # Parse JSON data from the request body if "data" in data: response_data = str(data["data"]) # Get the value of 'data' key return HttpResponse(response_data, content_type="text/plain") else: return HttpResponse( "Invalid JSON data. 'data' key is missing.", status=400 ) except json.JSONDecodeError: return HttpResponse("Invalid JSON data.", status=400) else: return HttpResponse("This API only accepts POST requests.") Settings.py """ Django settings for app_server project. Generated by 'django-admin startproject' using Django 4.2.2. For more information on this file, see https://docs.djangoproject.com/en/4.2/topics/settings/ For … -
How to extend templates from different app Django with Jinja?
I found that I have many Django projects and I want to extract all common features into an app. When working with extract the Django template I got this problem. Here is the app structure myproject/ app1/ jinja2/ app1/ app1.html app2/ jinja2/ app2/ app2.html From app2.html I want to extend app1.html What I try to do: {% extend app1/app1.html %} I get jinja2.exceptions.TemplateNotFound app1/app1.html Jinja2 setting in settings.py TEMPLATES = [ { 'BACKEND':'django.template.backends.jinja2.Jinja2', 'DIRS': [ PROJECT_DIR / 'jinjatemplates' ], 'APP_DIRS': True, }, { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] I got similar question here then I just do extent app1.html from app2.html but it got TemplateNotFound error django include template from another app Got some error and want to find a way to fix -
How can I serve multiple Django applications with Nginx and Gunicorn using multiple domains
I'm trying to host an extra website on my digital ocean droplet. I'm using Ubuntu 20.04.6 LTS. The original website is working well. I'm following this tutorial on how to Serve multiple Django applications with Nginx and Gunicorn using multiple domains (https://www.youtube.com/watch?v=koo3bF2EPqk ). After setting up everything im getting the error " DisallowedHost at / Invalid HTTP_HOST header: 'www.example.co.ke. You may need to add 'www.example.co.ke' to ALLOWED_HOSTS" Below is my /etc/nginx/sites-available/example server { listen 80; server_name subdomain.example.co.ke www.subdomain.example.co.ke; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/xxx/pyapps/xxx; } location /media/ { root /home/xxx/pyapps/xxx; } location / { include proxy_params; proxy_pass http://unix:/run/xxx.sock; } } On Django app I have added both subdomain.example.co.ke www.subdomain.example.co.ke in allowed hosts. Please note the other working site is not using example.co.ke. Both domain names point to the same droplet IP. Thank you, any help will be appreciated. I tried restarting nginix and Gunicorn but im still getting the same bug. Also, tried adding the Ip address in allowed hosting but its not working too. -
Where to put multithread-Tasks code in Django
If I need to run multithread (or multiprocessing) tasks using threading (or multiprocessing) module, where should I put threading-related code? I will need a TaskManager of some sort (which will handle tasks creation and control), Task of some sort (which will not be persistent), initialization of them, and other things. Although I will need some thread-related functions, which are not OOP, but will be used in Thread class and so on. TaskManager is not exactly Model. It's Controller of some sort. This code is running in sub-thread, this is clearly not a View. Task is model, but web-unrelated and not database-saved. And it is although running in (another) subthread. Multithreading functions and so on - are not MVC or OOP at all. Initialization code of TaskManager - where this should be? -
Why Date is not displayed in Django Admin Panel
Model date =models.DateField(auto_now_add=True) in my django model.py file and everything is working fine but the problem is it won't show data/time in django admin panel. Here Date is created as an auto_now_add=True but it not showing in an Admin Panel -
where should i add the django rest framework token in http. header or body?
Im a new in django rest framework. im developing a user registration, login and logout page for first. in many of the tutorial i found that, they add the token in the body. but in the drf documentation , they it shoud be in the body. im so confuced. anyone help me with the logic i just created a login page. the view is testing the username and the password then return user information and the token. but how do i return the token. here is my login view. can u review my code: # user login class user_login(APIView): serializer_class = login_serializer def post(self, request, format = None): print(request.data) """ serialing the data and validating it, any exception found is_valied() the functionn automatically return respond with the error message as a dictionery """ # serializing data serializer = self.serializer_class(data=request.data) # validating the data serializer.is_valid(raise_exception=True) # authenticate the user email = serializer.validated_data['email'] password = serializer.validated_data['password'] user = authenticate(request, email = email, password = password) # if user is authenticated create tocken if user: token, created = Token.objects.get_or_create(user = user) print(request.user) print(request.auth) return Response({"status":200, "email": email, "token": token.key}, status=200) # else return 401 unautherized message else: return Response({"status":401,"message":"unauthorized"}, status=401) ``` -
How to update seaborn data when I use django?
I use django and create web page. Then I click button seaborn do not update data, only add data. Scatters are added to the plot as many times as I click the button. However I want reset existing data and show new plot by new data. Django code: def index(request): if request.method == "GET": form_index = ForecastField(request.GET) if form_index.is_valid(): adress_f = form_index.cleaned_data['flat_Ad'] newdf_pl = pd.read_csv(r'newdf.csv') newdf_pl = newdf_pl.loc[newdf_pl['Address_N'] == adress_f] sns.scatterplot(data=newdf_pl, x='Area', y='Price_G') fig = plt.gcf() buff = BytesIO() fig.savefig(buff, format='png') buff.seek(0) string = base64.b64encode(buff.read()) uri_F = urllib.parse.quote(string) context = {'Index_f': ForecastField(), 'pngg_F': uri_F} html_index = "MyHome/index.html" return render(request, html_index, context) HTML code: <div class='container'> <img src='data:image/png;base64,{{ pngg_F }}' alt="image"/> </div> -
I have problem with git and django migrate
I use git in django for my project and my database is postgres. When I make a change in the file and make migrations and then migrate, it is correct and the database is correct, but when I go back to the previous commit (git checkout command) and then migrate, a new migration is created, but when I run command python manage.py migrate, it says no changes were found. When I look at the database, I see that it has the same git checkout fields as before. I went through many ways, I deleted the migrations and created them again, but it didn't help, it still said that there is no change. Only when I delete the database and create it again, the migrate command works correctly. Deleting the database is dangerous. Can you suggest another way and guide me, thank you python manage.py makemigrations Migrations for 'main_app': main_app\migrations\0001_initial.py - Create model Project - Create model Resume - Create model Experience - Create model Comment python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, main_app, sessions, users Running migrations: No migrations to apply. -
How to aggregate over multiple fields in Django?
I have a Dango model Trade that store trades information for several markets. The objects are timestamped at every 5 minutes and I need to aggregate them by market and by datetime. What is the best solution to do that with performance in mind ? As you can see below, I could extract a list of the desired timestamps, iterate and aggregate data but I'm afraid it's not the most efficient solution. class Trade(TimestampedModel): market = models.ForeignKey(Market, on_delete=models.CASCADE, null=True) datetime = models.DateTimeField(null=True) amount = models.FloatField(null=True) price = models.FloatField(null=True) trades = models.FloatField(null=True) This is my code: from django.db.models import Sum, Avg # Time order object qs = Trade.objects.all().order_by("-datetime") # Extract unique timestamps dts = qs.values_list("datetime", flat=True).distinct() for dt in dts: cum_a = qs.filter(datetime=dt).aggregate(num_a=Sum('amount'))['num_a'] cum_t = qs.filter(datetime=dt).aggregate(num_t=Sum('trades'))['num_t'] avg_p = qs.filter(datetime=dt).aggregate(avg_p=Avg('price'))['avg_p'] .... # Store aggregated data -
how can optimize query with large json data
class MyModel(models.Model): info = models.JosnField(default=dict()) # contain very large data .... .... .... .... queryset = MyModel.objects.all().order_by('id')[:200000] # it's very slow now i'm trying on compress json data -
Proper way to use bind-mount in Docker
I have a Django app. I need to dockerize it. The builtin database gets updated time to time. So I need to reflect the changes in host machine. My DockerFile is like this: FROM python:3.11-slim-buster ENV PYTHONUNBUFFERED=1 RUN pip install --upgrade pip WORKDIR /app COPY requirements.txt ./ RUN pip install --no-cache-dir -r requirements.txt And the docker-compose file is: version: '3' services: better_half: container_name: better-half-django build: context: . command: bash -c "python manage.py runserver 0.0.0.0:8000" volumes: - .:/app env_file: - .env ports: - "8000:8000" I have used bind-mount to reflect the changes. The app runs perfectly in this configuration. But I am not sure is it the best practice or not. I want to know the best practice. Sould I use copy command in the DockerFile to copy all the project code to the app directory of the docker image? I am a newbie. Can anyone help me? Thanks in advanced. -
Django custom user model with different user models
I am creating a school management system and I want that when the admin creates users using the custom user model, the admin should create users and their profiles same time but profiles have different profile models I dont know what is it that I am doing wrong. I have a custom user model and also 3 different models for different users as below class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_("email address"), unique=True) first_name = models.CharField(max_length=100, blank=True, null=True) last_name = models.CharField(max_length=100, blank=True, null=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_student = models.BooleanField(default=False) is_parent = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) date_joined = models.DateTimeField(default=timezone.now) USERNAME_FIELD = "email" REQUIRED_FIELDS = ['first_name', 'last_name'] objects = CustomUserManager() def __str__(self): return self.email The other model is class AdminHOD(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) title = models.CharField(_('Title'), max_length=4, default=MR, choices=TITLE, blank=False, null=True) bio = models.TextField() gender = models.CharField(_('Gender'), max_length=20, default=MALE, choices=GENDER, blank=False) tel = models.CharField(default='+273240000000', null = False, blank=False, max_length=15, help_text= 'Enter number with Country Code Eg. +273240000000') birthday = models.DateField(_('Birthday'), blank=False, null=False) avatar = models.ImageField(blank=True, null=True, upload_to="avatars/adminhod/") address_line_1 = models.CharField(_('Address Line 1'), max_length=125, null=True, blank=True) address_line_2 = models.CharField(_('Address Line 2'), max_length=125, null=True, blank=True) city = models.CharField(_('City'), max_length=125, null=True, blank=True) province = models.CharField(_('Province'), max_length=40, default=GAUTENG, choices=PROVINCES, blank=False, null=True) created …