Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Returning a scalar from a Django function
I have a silly question I really want the below to return a single number, but it still returns an iterable object. Do you know how I can get it to return a scalar? pts = skills.objects.filter(creator=request.user).raw('''SELECT sum(cast(points as int)) as id FROM myapp_skills WHERE status = 'closed' and creator = %s ''',[request.user.username]) Here is my skill model: class skills(models.Model): skill_name = models.CharField(max_length=400, default="data") points = models.CharField(max_length=400, default="data") time_required = models.CharField(max_length=400, default="data") target_date = models.CharField(max_length=400, default='none') category = models.CharField(max_length=400, default="data") status = models.CharField(max_length=400, default="data") skill_id = models.CharField(max_length=400, default="data") creator = models.CharField(max_length=400, default="data") syllabus = models.CharField(max_length=40000, default="data") -
Error while using createdb command postgresql on windows 10
I am a new user of PostgreSQL, and I am learning it so that I can use it with Django, so I am trying to use createdb command to create a new database, but even though I am entering the correct password for my account, I am getting this error. I reinstalled everything and checked everything I could think of but I was not able to solve this error. So, if I can get some help regarding this issue it would be nice. Even using the command psql, and submitting the correct password, gives the same error. As far as I checked, I needed to enter the password I used while installing PostgreSQL. By the way, I am using the latest version of PostgreSQL 14.0.1 Thank You in advance. command I used: createdb testdatabase createdb: error: connection to server at "localhost" (::1), port 5432 failed: FATAL: password authentication failed for user "<username_placeholder>" -
App not compatible with buildpack, django Heroku
Using buildpack: heroku/python but still it says not compatible. I am a beginner in Django please help. Here is build log : -----> Building on the Heroku-20 stack -----> Using buildpack: heroku/python -----> App not compatible with buildpack: https://buildpack-registry.s3.amazonaws.com/buildpacks/heroku/python.tgz More info: https://devcenter.heroku.com/articles/buildpacks#detection-failure ! Push failed -
Create sub directories within django?
I'm trying to create a simple website that contains entries (blog posts) organized in the url by example.com/category_id/post_id However what I'm currently doing only resolves example.com/category_id. Can someone show me how to change the code to make it: List all blog posts when going to example.com/blog List all blog posts of a particular category when going to example.com/blog/category_id List a particular blog post when going to example.com/blog/category_id/post_id Thank you! If I need to provide more information please let me know. blog.urls.py from django.urls import path from . import views app_name = "blog" urlpatterns = [ path('', views.index, name='index'), path('<int:welcome_id>/', views.welcome_detail, name='welcome_detail'), path('blog/<int:category_id>/', views.category, name="category"), path('blog/<int:category_id>/<int:blog_id>/', views.category, views.blog_post_detail, name="blog_detail"), ] blog/models.py from django.db import models class WelcomePage(models.Model): greeting_text = models.TextField(max_length=2000) def most_recently_published(self): return Status.objects.order_by('id')[0] def __str__(self): return self.greeting_text class Categories(models.Model): name = models.CharField(max_length=200) category_title = models.CharField(max_length=200, default='') def get_categories(self): return Status.objects.order_by('id') def __str__(self): return self.name class BlogPost(models.Model): blog_title = models.CharField(max_length=200) blog_text = models.TextField(max_length=10000) pub_date = models.DateTimeField('date published') categories = models.ForeignKey(Categories, null=True, on_delete=models.SET_NULL) def most_recently_published(self): return Status.objects.order_by('id')[:5] def __str__(self): return self.blog_title blog/views.py from django.shortcuts import render from django.template import loader from django.http import HttpResponse, Http404 from .models import WelcomePage, BlogPost, Categories def index(request): latest_welcome_message = WelcomePage.objects.order_by('id') latest_blog_posts = BlogPost.objects.order_by('id') categories = Categories.objects.order_by('id') … -
Django Static Files - CSS File doesnt load
I'm learning Django. I am trying to load a static css file, but it doesn't work. That's part of my base.html: {% load static %} <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- css --> <link rel="stylesheet" type="text/css" href="{% static 'HomePage/style.css' %}"> </head> and that's part of my settings.py file: STATIC_URL = '/static/' STATICFILES_DIRS = [ BASE_DIR / "static", '/var/www/static/', ] STATIC_DIR = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static_in_env", "static_root") Where did I make mistake ? I have already used python manage.py collectstatic in command prompt -
Can the code in django be made to read by the javascript?
what happens is that I already have the behavior to add rows (JS and HTML) with my plus sign, however I have the problem that the form that is duplicated (with the formset) does not have the code in django, and obviously what I want is that I add the rows with the HTML, JS and Django. I wish I could recycle my code so that cell1.outerHTML (and the others) could contain something like this: {% render_field form.code class = "form-control"%} I just don't know if it can be done, hopefully because my knowledge of JS is minimal :( presupuestos-forms.html <table class="table table-bordered table-nowrap align-middle" id="childTable1"> <thead class="table-info"> <tr> <th scope="col">Código</th> <th scope="col">Descripción</th> <th scope="col">Cantidad</th> <th scope="col">Precio Unitario</th> <th scope="col">Precio Total</th> <th scope="col">Libre de Impuestos</th> <th scope="col">Agrega Fila</th> </tr> </thead> <tbody> <tr> <td> {{presupuestosparteform.codigo}} </td> <td> {{presupuestosparteform.descripcion}} </td> <td> {{presupuestosparteform.quantity}} </td> <td> {{presupuestosparteform.unit_price}} </td> <td> {{presupuestosparteform.total_price}} </td> <td> <div> {{presupuestosparteform.tax_free}} </div> </td> <td> <input type="button" class="btn btn-block btn-default" id="addrow" onclick="childrenRow()" value="+" /> </td> </tr> <tr> {{ formset.management_form }} {% for form in formset %} <td> {% render_field form.codigo class="form-control" %} </td> <td> {% render_field form.descripcion class="form-control" %} </td> <td> {% render_field form.quantity class="form-control" %} </td> <td> {% render_field form.unit_price class="form-control" … -
getting errolist when using htmx and tinymce
Im trying to implement post request with htmx and for rich text editor using tinymce. my form : <!--<form method="POST"> {% csrf_token %}--> <form onsubmit='copyContent()' method= "post" hx-post= "{% url 'forum:forum-detail' post.pk %}" hx-swap="innerHTML" hx-target = "#comment-list"> <div class="modal-body"> <div class="form-group"> <label for="threadTitle">Your Answer</label> <textarea name="reply" class="form-control summernote" placeholder="Input your answer here"></textarea> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-light" id="cancelForm">Cancel</button> <button type="submit" class="btn btn-primary" name="btn-post-question">Post</button> </div> </form> The error I get : <ul class="errorlist"><li>reply<ul class="errorlist"><li>This field is required.</li></ul></li></ul> it works just ok when I used the traditional post request with TinyMCE. when I used htmx without TinyMCE its work just ok too. it just when I combine htmx and TinyMCE. -
Manager isn't available; 'auth.User' has been swapped for 'accounts.User'
I have created a custom user model 'User' and have declared in settings.py as AUTH_USER_MODEL Also i have two other models consumer and workman which has an onetoone relation with my custom user. i created two forms for registering customer and workman but as i fill form(it doesnt even check validation) and submit, it says: Manager isn't available; 'auth.User' has been swapped for 'accounts.User' models.py: from django.contrib.auth.models import AbstractUser from django.contrib.auth import get_user_model # Create your models here. class User(AbstractUser): class Types(models.TextChoices): CONSUMER = "CONSUMER" , "Consumer" WORKMAN = "WORKMAN" , "Workman" type = models.CharField(max_length=20,choices=Types.choices,default=Types.WORKMAN) is_consumer = models.BooleanField(default=False) is_workman = models.BooleanField(default=False) class Consumer(models.Model): user = models.OneToOneField(get_user_model(),on_delete=models.CASCADE,primary_key=True) location = models.CharField(max_length=100) class Workman(models.Model): user = models.OneToOneField(get_user_model(),on_delete=models.CASCADE,primary_key=True) contact = models.CharField(max_length=100) views.py: from .forms import ConsumerCreationForm, WorkmanCreationForm from .models import Workman,Consumer class consumersignupview(CreateView): model = Consumer form_class = ConsumerCreationForm template_name = 'accounts/register.html' success_url = '/' class workmansignupview(CreateView): model = Workman form_class = WorkmanCreationForm template_name = 'accounts/register.html' success_url = '/' forms.py: from django.contrib.auth.forms import UserCreationForm from django import forms from .models import Consumer,Workman class ConsumerCreationForm(UserCreationForm): location = forms.CharField( max_length=100, required=False) class meta(UserCreationForm.Meta): model = Consumer class WorkmanCreationForm(UserCreationForm): contact = forms.CharField(max_length=100) class meta(UserCreationForm.Meta): model = Workman error: -
How to pass an array from django views to external JS file for chart
I am designing a dashboard where i need to pass labels and data to my chart from django views to Variables in Java Script. This below code is not displaying lables or data in chart. Django Views def chartd(request): labelss=['JANS', 'FEBS', 'MARS', 'APRS', 'MAYS', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC'] datas = [120, 123, 125, 90, 92, 70, 75, 60, 90, 80, 110, 100] context = {"labelss":labelss, "datas": datas} return render(request, 'charts.html',context) Java Script for charts.html var chart_labels ={{labelss}}; var chart_data ={{datas}}; var ctx = document.getElementById("chart1").getContext('2d'); var gradientStroke = ctx.createLinearGradient(0, 230, 0, 50); gradientStroke.addColorStop(1, 'rgba(72,72,176,0.1)'); gradientStroke.addColorStop(0.4, 'rgba(72,72,176,0.0)'); gradientStroke.addColorStop(0, 'rgba(119,52,169,0)'); //purple colors var config = { type: 'line', data: { labels: chart_labels, datasets: [{ label: "dataset", fill: true, backgroundColor: gradientStroke, borderColor: '#d346b1', borderWidth: 2, borderDash: [], borderDashOffset: 0.0, pointBackgroundColor: '#d346b1', pointBorderColor: 'rgba(255,255,255,0)', pointHoverBackgroundColor: '#d346b1', pointBorderWidth: 20, pointHoverRadius: 4, pointHoverBorderWidth: 15, pointRadius: 4, data: chart_data, }] -
Django-pay pal IPN response not receiving
I am trying to integrate a payment gateway for my Project , but I am having trouble understanding how to handle the IPN listener part of it, I am really confused about whether to create a new view for it , or where should form reside and also how to implement the signals which it sends , I have spent hours looking for an answer but no avail ! thanks in advance class PaymentProcess(View): def get(self,request): host = request.get_host() payment = PaymentRecords.objects.get( order_id = request.session['order_id'] ) print(payment.total_amount) print(host) paypal_dict = { 'business': settings.PAYPAL_RECEIVER_EMAIL, 'amount': payment.total_amount, 'item_name': 'Item_Name_xyz', 'invoice': 'Test Payment Invoice'+'INV12323244'+str(randint(10,5000)), 'currency_code': 'USD', # 'notify_url': 'http://{}{}'.format(host, reverse('paypal-ipn')), <--- how to deal with this one # 'return_url': 'http://{}{}'.format(host, reverse('payment_done')), # 'cancel_return': 'http://{}{}'.format(host, reverse('payment_canceled')), } form = PayPalPaymentsForm(initial=paypal_dict) return render(request , 'restprac/index.html',{'form':form}) signals.py def show_me_the_money(sender, **kwargs): ipn_obj = sender print(sender) if ipn_obj.payment_status == ST_PP_COMPLETED: # WARNING ! # Check that the receiver email is the same we previously # set on the `business` field. (The user could tamper with # that fields on the payment form before it goes to PayPal) if ipn_obj.receiver_email != "receiver_email@example.com": # Not a valid payment return # ALSO: for the same reason, you need to check the … -
python-socketio How to support Socket.IO-Client-Swift
I'm using Socket.IO-Client-Swift for my iOS app and am using python-socketio for my Django server. However, when I try to connect to the server as a client from the iOS app, python-socketio gives this error: The client is using an unsupported version of the Socket.IO or Engine.IO protocols (further occurrences of this error will be logged with level INFO) Thanks in advance. -
Extended the User model, but not quite sure how to serialize fields for both User and UserExtended
I extended my User model with a new model just called UserExtended: # Django imports from django.db import models from django.contrib.auth.models import User class UserExtended(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) crm_guid = models.UUIDField(unique=True) security_q1 = models.CharField(max_length=255, blank=True, null=True) security_a1 = models.CharField(max_length=255, blank=True, null=True) security_q2 = models.CharField(max_length=255, blank=True, null=True) security_a2 = models.CharField(max_length=255, blank=True, null=True) attempts = models.SmallIntegerField(blank=False, null=False, default=0) key = models.CharField(max_length=255, blank=True, null=True) key_expires = models.DateTimeField(blank=True, null=True) method = models.CharField(max_length=4, blank=True, null=True) class Meta: db_table = 'auth_user_extended' I was hoping by just doing that some Django magic would take care of the rest and I wouldn't have to change my views.py or serializers.py. But when I send a request to the end-point I get: [api] django.core.exceptions.ImproperlyConfigured: Field name `guid` is not valid for model `User`. So it does apparently need to be specified. I've been looking at the documentation and similar SO questions to find an answer. This is what I have for my views.py: # Django imports from django.contrib.auth.models import User # Third party imports from rest_framework import generics from rest_framework.permissions import IsAdminUser # App imports from users.serializers import UserSerializer class UsersListCreateView(generics.ListCreateAPIView): permission_classes = [IsAdminUser] serializer_class = UserSerializer def get_queryset(self): queryset = User.objects.all() email = self.request.query_params.get('email') username = self.request.query_params.get('username') if … -
Which files are binaries in a python wheel?
The documentation says that Python Wheel is a binary distribution format. To understand the difference between the source code and binaries distributed within a Python wheel, I am manually inspecting a .whl file from the package django. The specific .whl I am looking at is this. I decompressed the wheel file and the top-level directory of the file looks like this: . ├── Django-3.2.9.data ├── Django-3.2.9.dist-info └── django The Django-3.2.9.data file contains a script called admin.py. The directory structure for Django-3.2.9.dist-info looks like this: . ├── AUTHORS ├── LICENSE ├── LICENSE.python ├── METADATA ├── RECORD ├── WHEEL ├── entry_points.txt └── top_level.txt The WHEEL file in this directory seems to contain information of the WHEEL version that was used to build this .whl. The top-level directory structure for the django file looks like this: . ├── __init__.py ├── __main__.py ├── apps ├── bin ├── conf ├── contrib ├── core ├── db ├── dispatch ├── forms ├── http ├── middleware ├── shortcuts.py ├── template ├── templatetags ├── test ├── urls ├── utils └── views Here, except the bin folder, all the other files are source code files that are present on the django repository. Therefore, my guess was that the bin folder … -
Django: Why my objects do not add database correctly?
I am working on a simple Django project and suffice to say I am just a beginner. I have 2 classes in models.py: from django.db import models from django.db.models.deletion import CASCADE class Category(models.Model): category_name=models.CharField(max_length=225,null=True) def __str__(self): return f"ID: {self.category_name}" class Book(models.Model): cover_img = models.URLField(max_length=200, null=True) author=models.CharField(max_length=128,null=True) summery=models.TextField(max_length=1000,null=True) category = models.ForeignKey(Category,related_name="book_categories",on_delete=CASCADE,null=True) def __str__(self): return f"{self.cover_img} ,{self.author},{self.summery}" On the first page of my website(Menu.html), I create a button for each category using jinja: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.10.2/dist/umd/popper.min.js" integrity="sha384-7+zCNj/IqJ95wo16oMtfsKbZ9ccEh31eOz1HGyDuCQ6wgnyJNSYdrPa03rtR1zdB" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.min.js" integrity="sha384-QJHtvGhmr9XOIpI6YVutG+2QOK9T+ZnN4kzFN1RtK3zEFEIsxhlmWl5/YESvpZ13" crossorigin="anonymous"></script> <title>Menu</title> </head> <body> {% for cat in categories %} <a type="button" class="btn btn-danger" href="{% url 'cat_detail' cat.id %}"> <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-book" viewBox="0 0 16 16"> <path d="M1 2.828c.885-.37 2.154-.769 3.388-.893 1.33-.134 2.458.063 3.112.752v9.746c-.935-.53-2.12-.603-3.213-.493-1.18.12-2.37.461-3.287.811V2.828zm7.5-.141c.654-.689 1.782-.886 3.112-.752 1.234.124 2.503.523 3.388.893v9.923c-.918-.35-2.107-.692-3.287-.81-1.094-.111-2.278-.039-3.213.492V2.687zM8 1.783C7.015.936 5.587.81 4.287.94c-1.514.153-3.042.672-3.994 1.105A.5.5 0 0 0 0 2.5v11a.5.5 0 0 0 .707.455c.882-.4 2.303-.881 3.68-1.02 1.409-.142 2.59.087 3.223.877a.5.5 0 0 0 .78 0c.633-.79 1.814-1.019 3.222-.877 1.378.139 2.8.62 3.681 1.02A.5.5 0 0 0 16 13.5v-11a.5.5 0 0 0-.293-.455c-.952-.433-2.48-.952-3.994-1.105C10.413.809 8.985.936 8 1.783z"/> </svg>{{cat.category_name}} </a> {% endfor %} </body> </html> Then If the user clicks on one of these … -
Annotating specific attributes of a Datetime Field - Cannot resolve keyword 'toordinal' into field. Join on 'created_at' not permitted
I'm developing a scoring system for posts on a website. It considers other relational fields (comments, views, and reactions_emojis) to have a more insightful way to order the results. But since it's not desirable to have popular posts, but too old, on the front page, I decided to consider the post creation time. The problem is, the DateTime value is too precise, and ordering by it would completely ignore the scoring system and return a simple chronological feed. While testing some solutions, I tried the toordinal built function to have a single value representing the days passed since January 1 of year 1. My idea was to concatenate this value with the post_hour and the result of (post_minute // 14). This way, there would be a 14 minutes window in which all posts would be ordered exclusively by their scores. It looks good enough, and any adjustments would be simple to make. Looking along with some SO posts and Django documentation, I found that I could do this by passing the attribute I was trying to access with a dunder inside an F expression: posts = Post.objects.all().annotate( score=((F("view_count")/20) + (Count("post_emojis")/10) + (Count("post_comments")/5)), ordinal_time=(F('created_at__toordinal')) ) This returns the following error: Cannot … -
Display multiple views in single page
I have a Django Webapp which has a few forms for adding data to the database. Once this data has been added, I want to present this on a dashboard. So I have views that were written that add the logic for the data to be presented, but as far as i can work out you only map 1 view to a template otherwise the data won't be displayed on the template. I think there is a way to pass the data as a context, but I can't get my head around how to write this for my view. A really simple view i have to display events def all_events(request): event_list = Event.objects.all() return render(request, 'pages/event_list.html',{'event_list': event_list}) I'm passing this to event_list which works fine. But if I % include % on the dashboard I get the HTML but not the data, which I now understand is right. But being an absolute bigger with Django, I could really do with an example of the above which I can then apply to all my other views. Thanks -
Python/Django looping over request object and display in a table
Hi so I have a file called b2c2.py where I am making a request to return my balances this request returns b'{"LTC":"0","DOG":"0","USD":"51075.676738623","ADA":"9493.1937","ETH":"3.4E-9","UST":"2977","LNK":"42.422","XLM":"0","GBP":"-58153.761361914","USC":"0.9999995","XRP":"78448.38","EOS":"0","BNB":"0","BTC":"-0.250000004644","EUR":"0.0026082","BCH":"0","DOT":"0","UNI":"0","AUD":"0","CAD":"0","CHF":"0","CNH":"0","ETC":"0","ICP":"0","JPY":"0","KSM":"0","MXN":"0","NZD":"0","SGD":"0","TRX":"0","XAU":"0","XMR":"0","XTZ":"0","ZEC":"0"}' I then pass this into my views.py called b2c2_response_content and pass it into the context, in my template I am then trying to loop through it to show the balance name and balance holdings in a table. But I am unsure on how I can do this for example I want it to display as bitcoin name in a column with its quantity in the column next to it and Ethereum in the row below with its name in one column and its quantity in the next column. Thank you for your help in advance. -
Django - Delete db entry when ForeignKey was deleted
So I am having trouble to solve this issue, even though I thought I understood the on_delete function. I have a model called Project and a model called UserProject. In the Userproject I have two foreign Keys pointing to a User and a Project. What I tried was to use on_delete = CASCADE on the project-Foreign Key. This seems to only affect the Project-field in the Userproject model. So when I delete a Project wich also has Userproject entries, those dont get deleted. How could I achieve this? from django.db import models from django.contrib.auth.models import User # Create your models here. class Project(models.Model): id = models.AutoField(db_column = 'db_ID', primary_key = True) name = models.CharField(max_length=500, default = None) descriptor = models.CharField(max_length = 1000, null = True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: db_table = 'projects' def __str__(self): return self.name class Userproject(models.Model): id = models.AutoField(db_column = 'db_ID', primary_key = True) user = models.ForeignKey(User, on_delete= models.SET_NULL, null = True) project = models.ForeignKey('Project', on_delete = models.CASCADE,default = 1, null = True) created_at = models.DateTimeField(auto_now_add=True, null=True) updated_at = models.DateTimeField(auto_now=True, null = True) class Meta: db_table = 'UserProjects' def __str__(self): return self.id -
Download file in Nginx-Django with X-Accel-Redirect
I have a Django webpage running on Nginx-Uwsgi. I want to let the user download files of over 10GB. For this purpose, I am using X-Accel-Redirect. The idea is that the user should go to http://XXX.XX.XX.XX/main/download and there it can download a file. After several configurations, now I get a 403 HTTP error on the browser and the following trace on Nginx: 2021/11/11 16:11:45 [error] 29309#0: *1 open() "/home/myuser/direct/example.txt" failed (13: Permission denied), client: 2.136.173.243, server: _, request: "GET /main/download HTTP/1 My Nginx configuration is as follows: events { worker_connections 10000; } http { log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main; sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; include /etc/nginx/mime.types; default_type application/octet-stream; client_max_body_size 128M; proxy_max_temp_file_size 0; proxy_buffering off; server_names_hash_bucket_size 256; # Load modular configuration files from the /etc/nginx/conf.d directory. # See http://nginx.org/en/docs/ngx_core_module.html#include # for more information. include /etc/nginx/conf.d/*.conf; upstream django { server 127.0.0.1:8000; } server { listen 80 default_server; listen [::]:80 default_server; server_name _; root /usr/share/nginx/html; # Load configuration files for the default server block. include /etc/nginx/default.d/*.conf; location /download { internal; alias /home/myuser/direct; proxy_max_temp_file_size 0; } location /main { uwsgi_pass django; uwsgi_param Host $host; uwsgi_param X-Real-IP $remote_addr; … -
TemplateDoesNotExist at / index.html After dividing settings.py into 3seperate files
I was working on a Django project. my urls.py: urlpatterns = [ path('', index, name='index') ] my views.py: def index(request): return render(request, 'index.html') in my settings.py: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [(BASE_DIR / "templates")], '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', ], }, }, ] Till this point, all works perfectly, the template also rendered as it should. Now I approach to divide my settings.py into 3 separate files for my production purpose like: Settings (Folder) | base.py | development.py | production.py Here the base.py contains almost all necessary settings, development.py and production.py inherit the base.py and have only allowed host and debug values. development.py and production.py are also properly hooked up with manage.py and wsgi.py file of the project. Now after this work it shows me an error like: TemplateDoesNotExist at / index.html I also try with def index(request): return HttpResponse("Hello, world. You're at the diagnosis index.") It also works perfectly! maybe it only has problem with template/Base dir. Please suggest how can I fix this? -
Two projects use the same Postgres database, and the project on Django
I have two projects that use the same Postgresql database. One of these projects is written with Golange and the other with Django. I have a task in the Django project, to take the data from the table that is created in another project. More precisely I have to take the data from the Clients table, which is not created in Django. There is no information about Clients table on the Django project. Below is how I take the date from the Cook table, which is created in the Django project. How can I take the date from the Clients table in the same way as above? Below are both project repositories, and some screenshots from the database. https://github.com/NarminSH/Go-Client.git https://github.com/NarminSH/Lezzetly Thanks in advance. -
DRF simple-jwt error "detail": "No active account found with the given credentials"
I can create an account with DRF_simple_jwt but when it comes to loging in to that account, it says {"detail":"No active account found with the given credentials"} I tried googling and tried this and more but all in vain . I don't know where the problem lies. here is my serializers.py code from rest_framework import serializers from .models import * from rest_framework_simplejwt.tokens import RefreshToken from rest_framework_simplejwt.serializers import TokenObtainSerializer from django.contrib.auth.hashers import make_password class EmailTokenObtainSerializer(TokenObtainSerializer): username_field = User.EMAIL_FIELD class CustomTokenObtainPairSerializer(EmailTokenObtainSerializer): @classmethod def get_token(cls, user): return RefreshToken.for_user(user) def validate(self, attrs): data = super().validate(attrs) refresh = self.get_token(self.user) data["refresh"] = str(refresh) data["access"] = str(refresh.access_token) class UserSerializer(serializers.ModelSerializer): """ Serializer for user object """ isAdmin = serializers.SerializerMethodField(read_only=True) class Meta: model = User fields = ('id', 'username','isAdmin', 'email','phone','room','hostel') def get_isAdmin(self, obj): return obj.is_staff def validate_password(self, value: str) -> str: """ Hash value passed by user. : param value: password of a user :return: a hashed version of the password """ return make_password(value) and here is code for views.py file class EmailTokenObtainPairView(TokenObtainPairView): serializer_class = CustomTokenObtainPairSerializer and here is urls.py: path("login/", EmailTokenObtainPairView.as_view(), name="token_obtain_pair"), path("refresh/", TokenRefreshView.as_view(), name="token_refresh"), You can ask for further codes. Thanks for helping because you are my last hope. -
How to put the 'non_field_errors' in the end of the form in Django
By default The non_field_errors are placed in the beginning of the form, and I want to place it at the end of the form. This is how I am calling the form : <div ... > {{ form.media }} {% crispy form form.helper %} </div> -
Error while outputting template engine maximum recursion depth exceeded while calling a Python object
The problem is that I get an error when I try to display a block on a page, I don't really know what to do, since I'm working with a template engine for the first time. this is code of views.py class IndexView(generic.ListView): template_name = 'Homepage/index.html' model = Goods context_object_name = 'goods' def sale(request): return render(request, 'articles/sale.html') this is code of index.html {% include "article/sale.html" %} {% block sale %} {% endblock %} this is code of sale.html {% extends "Homepage/index.html" %} {% block sale %} <td class ="sale"> <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/b/b6/Image_created_with_a_mobile_phone.png/1280px-Image_created_with_a_mobile_phone.png"> <h1 class="description">ОписаниеОписаниеОписаниеОписание</h1> <a class="buy" href="#openModal" > <span >Купить</span></a> <h1 class="price">цена</h1> </td> {% endblock %} This is building a template in the end it gives an error maximum recursion depth exceeded while calling a Python object вот TraceBack -
Get coordinates of click event on image with Django
I am a beginner in Django and writing a Django app for labelling objects in images via bounding boxes. I want users to be able to draw a bounding box on the image and the box coordinates should be saved directly in the db. In my app, the images are already displayed and users can select the object type: However, now I am struggling with how to capture a click event using django. Specifically: How do I capture the coordinates of a click event on the image so I can save the click coordinates in my db? I know how to capture inputs via <input type="..." > but I haven't found a related method to find click coordinates on a grid. I found this great project which contains a more advanced image labeller based on django - but I can't seem to find the code location where the coordinates of a click are saved. I'd be very thankful for hints of which packages/functions to look into to find a solution.