Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Form action is not calling the required function from views.py in Django
I am new in Django and doing my first project in it. I had made a form in my index.html file and that form took an image, and sent it to a predictImage function in views.py file. The predictImage function applied YOLO model on the image and returned the image with labels to the same index.html page. This was working fine and I was getting the required results. After the submit button was clicked, I was getting redirected to index.html/predictImage where the results were being shown. (I had conditions added in my index.html to show the results) Then, I decided to add a Users Model and made a Login page for me, user was required to login before he could upload the image. For this, I added sessions as well. Now, I created a Photo model, to store every photo that every user uploads. All of this was successfully made but now, when I tried to do the same thing again, i.e., upload the image and submit it, it didn't work and it instead redirected me to index.html I tried to debug this, and I found out that I was not even going to views.predictImage when I clicked the submit … -
What is the easiest way to create a histogram (with target line) in Chart.js?
I have a matplotlib code that seems to do what I want it to do. I am trying to use it in a django web app. For example: home_totals_dict[a] = [ 140, 130, 120, ...] a = team_name plt.figure() plt.hist(x=home_totals_dict[a], bins='auto', color='#0504aa',alpha=0.7, rwidth=0.5) plt.hist(x=away_totals_dict[b], bins='auto', color='#d62728',alpha=0.7, rwidth=0.5) plt.axvline(x = c, color = "k",linestyle = "--" ) plt.xlabel(a + "/ "+ b) The result is the image attached. Every time I try do something similar in chart.js the x axis gets all messed up and am having trouble normalizing the x-axis prior to adding the data to chart.js -
Serializer returns media files URLs in http not in https in Django Rest Framework
I'm trying to serialize a model and one of its fields is a FileField when calling serialiser.data it returns the URL of the FileField in an HTTP schema, not an HTTPS. I get { "id": 1, "name": "demo", "file": "http://domain-name.com/media/image.png" } I want it to be { "id": 1, "name": "demo", "file": "https://domain-name.com/media/image.png" } I'm using Nginx and set proxy_set_header X-Forwarded-Proto https; Then in your Django settings added the following: USE_X_FORWARDED_HOST = True SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') And the problem is not fixed, what should I do to solve it? -
send_mail (smtp) from docker-compose (django + nginx + gunicorn)
I am trying to send email via Django. The mail should be sent to the user who would register to our system using Gmail. I am also using docker-compse django, nginx, gunicorn and postgres. This is my email configurations inside the django. EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = '587' EMAIL_USE_TLS = True EMAIL_HOST_USER = get_secret("EMAIL_HOST_USER") EMAIL_HOST_PASSWORD = get_secret("EMAIL_HOST_PASSWORD") DEFAULT_FROM_EMAIL = EMAIL_HOST_USER and docker-compose version: '3.7' services: web: build: context: ./dj-psych dockerfile: Dockerfile.prod command: gunicorn config.wsgi:application --bind 0.0.0.0:8000 volumes: - static_volume:/home/app/web/static/ - media_volume:/home/app/web/media/ expose: - 8000 env_file: - ./.env.prod depends_on: - db db: image: postgres:13.0 volumes: - postgres_data:/var/lib/postgresql/data/ env_file: - ./.env.prod.db nginx: build: ./nginx volumes: - static_volume:/home/app/static - media_volume:/home/app/static ports: - server-port:80 depends_on: - web volumes: postgres_data: static_volume: media_volume: nginx.conf upstream config { server web:8000; } server { listen 80; location / { proxy_pass http://config; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /static/ { alias /home/app/static/; } location /media/ { alias /home/app/media/; } } I think the smtp server port (586) should be open in docker. So I tried binding port web and nginx. But I can't. how can i do it?? I tried. from django.core.mail import EmailMessage email = EmailMessage('subject', 'body', to=['yj.jeon.gn@gmail.com']) email.send() This is … -
Django: Cannot filter against a non-conditional expression during trying to relate every values written to the current user
I want to relate every values written to the current user ,( the story that i want to print some fields of a form) and am afraid in case more than 1 user logged in the same time and want to generate a pdf, both of them print the same last -values entered in the printout. So i want to filter the values of fields based on the current user logged in with session. First Step: I have add another class in models.py models.py class UserSession(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) session = models.ForeignKey(Session, on_delete=models.CASCADE) Second Step: in views.py:(the function that is responsible for generating the pdf) , I have coded like that: def forms_render_pdf_view(request, *args, **kwargs): template_path = 'pdf.html' user = request.user user_sessions = UserSession.objects.filter(user = user) field_name = 'emploi' obj_m = Loads.objects.filter(user_sessions).last() field_obj_m = Loads._meta.get_field(field_name) field_value_m = field_obj_m.value_from_object(obj_m) emploi = str(field_value_m) when i try to generate my printout it gives me: Cannot filter against a non-conditional expression. Thanks in advance, How i can relate every values written to the current user correcly . -
Adding an object to ManyToMany field doesn't work
I have 2 models: class User(AbstractUser): pass class Post(models.Model): poster = models.ForeignKey('User', on_delete=models.CASCADE, related_name='posts') body = models.TextField() likes = models.IntegerField(default=0) likers = models.ManyToManyField('User', blank=True, null=True, related_name='liked_posts') Post model has a manytomany field to User model. I try to add a user object to the field with the view function below but it doesn't work. When I check the post in the admin page, the user is not added to the likers. @csrf_exempt def likepost(request, like, post_id): if (request.method == 'PUT'): post = Post.objects.get(pk=post_id) if like: post.likers.add(request.user) else: post.likers.remove(request.user) post.save() print(post.likers) return HttpResponse(status=204) else: return JsonResponse({ 'error': 'PUT request required.' }, status=400) I make the request in javascript in this way: fetch(`likepost/${likeValue}/${postId}`, { method: 'PUT' }); -
Python Django django-admin startproject admin problem
I am facing problem when I start making project via Django.....Whenever I cammand in CMD "django-admin startproject clone" It request for USER/ADMIN--- and I forget...That thing please that what to do try to help me...whenever I try to give something in input field it show me an error... After 1year I am switching in Django...It soo me some file which was on my Desktop that time...Please try to Help me...... [Output[\]\[1\]][1] --Shadab -
Basename attribute in the same routes
relatively speaking, I have two simple models: Processor and Motherboard. class Processor(Product): supply_type = models.CharField(max_length=10) socket = models.CharField(max_length=20) cores_amount = models.IntegerField() threads_amount = models.IntegerField() technological_process = models.IntegerField() class Motherboard(Product): socket = models.CharField(max_length=20) ram_generation = models.CharField(max_length=10) ram_type = models.CharField(max_length=10) ram_slots_amount = models.IntegerField() There are also corresponding serializers written for them. class ProcessorSerializer(ModelSerializer): class Meta: model = Processor fields = '__all__' class MotherboardSerializer(ModelSerializer): class Meta: model = Motherboard fields = '__all__' And of course viewsets. class ProcessorViewSet(ModelViewSet): queryset = Processor.objects.filter(is_published=True) serializer_class = ProcessorSerializer lookup_field = 'slug' class MotherboardViewSet(ModelViewSet): queryset = Motherboard.objects.filter(is_published=True) serializer_class = MotherboardSerializer lookup_field = 'slug' SimpleRouter was created in urls, where the following routes were added. router = routers.SimpleRouter() router.register(r'processors', ProcessorViewSet) router.register(r'motherboards', MotherboardSerializer) When I try to make a migration I get the following error: router.register(r'motherboards', MotherboardSerializer) assert queryset is not None, 'basename argument not specified, and could ' AssertionError: basename argument not specified, and could not automatically determine the name from the viewset, as it does not have a .queryset attribute. I tried to add this attribute, however, an error appears that the get_extra_actions method is not defined. I have three old models added in the same way. The problem appeared precisely when adding new models and routes for … -
Weasyprint how fix html/css that come from email
Weasyprint generate pdfs from emails. Sometimes emails come with some html/css in it. I add example from pdf from paypal in which all pdf in html/css information. Or Microsoft default mail also use some html when send emails. Is it possible to add some default things to fix html/css in a right way? My code: filename = f'{uuid.uuid4()}.pdf' data = {"body": content} context = Context(data) template = Template('{{ body|linebreaks|safe }}') html_string = template.render(context) html = HTML(string=html_string) pdf = html.write_pdf() Some example from paypal email that come <html dir="ltr"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="viewport" content="initial-scale=1.0,minimum- scale=1.0,maximum-scale=1.0,width=device-width,height=device- height,target-densitydpi=device-dpi,user-scalable=no" /> <title>Confirm your new email address</title> <style type="text/css"> /** * PayPal Fonts */ @font-face { font-family: PayPal-Sans; font-style: normal; font-weight: 400; src: local('PayPalSansSmall-Regular'), url('https://www.paypalobjects.com/ui- web/paypal-sans-small/1-0-0/PayPalSansSmall-Regular.eot'); /* IE9 Compat Modes */ src: local('PayPalSansSmall-Regular'), url('https://www.paypalobjects.com/ui-web/paypal-sans-small/1-0-0/ PayPalSansSmall-Regular.woff2') format('woff2'), /* Moderner Browsers */ url('https://www.paypalobjects.com/ui-web/paypal-sans-small/1-0-0/ PayPalSansSmall-Regular.woff') format('woff'), /* Modern Browsers */ url('https://www.paypalobjects.com/ui-web/paypal-sans-small/1-0-0/ PayPalSansSmall-Regular.svg#69ac2c9fc1e0803e59e06e93859bed03') format('svg'); /* Legacy iOS */ /* Fallback font for - MS Outlook older versions (2007,13, 16)*/ mso-font-alt: 'Calibri'; } -
how can i use audio file in pydub through django
Well, i have a code that creates and saves audio and i need to instert in that code a silence cutting system views.py def audio(request): if request.method == 'POST': cu = request.user.customer.pk users = get_object_or_404(Customer, pk=cu) js = get_object_or_404(JsonMap, user_id=users.id) audio = request.FILES['data'] name = audio.name name = name.replace(':', '-') song = Song.objects.create() audio_cut_logic = SoundCutter() song.js = js song.name = name song.audio_file = audio song.save() return render(request, 'action.html', {'file_url': js}) models.py def remove_sil(self, file, format="wav"): sound = AudioSegment.from_file(file, format=format) non_sil_times = detect_nonsilent(sound, min_silence_len=50, silence_thresh=sound.dBFS * 1.5) if len(non_sil_times) > 0: non_sil_times_concat = [non_sil_times[0]] if len(non_sil_times) > 1: for t in non_sil_times[1:]: if t[0] - non_sil_times_concat[-1][-1] < 200: non_sil_times_concat[-1][-1] = t[1] else: non_sil_times_concat.append(t) non_sil_times = [t for t in non_sil_times_concat if t[1] - t[0] > 350] return sound[non_sil_times[0][0]: non_sil_times[-1][1]] i tried to create sound.audio_file through my function song.audio_file = audio_cut_logic.remove_sil(audio) then i tought i need to create that audio file firstly and then use my func song.audio_file = audio song.audio_file = audio_cut_logic.remove_sil(song.audiofile) but all i got is: AttributeError: 'AudioSegment' object has no attribute '_committed' -
How to Give List of Objects IDs and add a click event based on each List IDs in Django
Here in my Django code, I have a list of prices. Now I gave them unique IDs which works well, but when I try to add a click event, the click event only works for only one list item continuously. {% for price in logistic_branch_pricing %} <h1 id="select-delivery-location-{{price.id}}" onclick="calculateDeliveryPrice()">{{ price.id }}-{{price.small_kg_price}} </h1> {% endfor %} {% for price in logistic_branch_pricing %} <script> function calculateDeliveryPrice() { var omo = document.getElementById("select-delivery-location-{{ price.id }}") omo.classList.add('d-none') console.log(omo) } </script> {% endfor %} -
How do I view the profile of the authenticated user in Django Rest Framework using the Token
I am learning DRF and creating a simple DRF app that lets user login, and view the profile and update the profile. I am using Django's default User model and using Knox for Token Authentication (if it can be done easier using Django Rest Authentication, please let me know and also tell me the procedure). I have successfully created the API to register and login the user which works fine, but I am stuck at showing the profile to the Authenticated User through a Token. I am only one Model that is Details which acts as to store the Profile details of the user. I have LoginSerializer which is connected to Login API and MainUserSerializer & UserSerializer, both of which are connected to User API (which acts to show the Profile details on frontend). I have tried a lot, searched everywhere, but all they show is how to authenticate the user with token through a url (some thing like using curl https://localhost:8000/api/user... etc.), postman, somehing like http post -a... command in terminal and other ways, but I don't want to test or implement using these ways. I want something that if I open my user profile url after logging in … -
Django list DB entries if LDAP group and key parameter match
Having hard time to figure out mechanism for my django app. I have tabele in db with list of Agents and every agent has assigned specific name of LDAP group in this table. Now i need to somehow compare LDAP group of logged user this LDAP value from agent table and list only those agents which matches LDAP group. I know how to get LDAP group of user. Just need to figure out how to match this value with list of agents and list them. End effect: User logging in and can list agents only which matches his LDAP group. -
Add object to ManyToMany field doesn't work
I have 2 models: class User(AbstractUser): pass class Post(models.Model): poster = models.ForeignKey('User', on_delete=models.CASCADE, related_name='posts') body = models.TextField() likes = models.IntegerField(default=0) likers = models.ManyToManyField('User', blank=True, null=True, related_name='liked_posts') Post has a manytomany field to User model. I try to a user object to the field with the view function below but it doesn't work: @csrf_exempt def likepost(request, like, post_id): if (request.method == 'PUT'): post = Post.objects.get(pk=post_id) if like: post.likers.add(request.user) else: post.likers.remove(request.user) post.save() print(post.likers) return HttpResponse(status=204) else: return JsonResponse({ 'error': 'PUT request required.' }, status=400) -
How to do Total Sum from JS in Django
let x = document.getElementById("food_price"); console.log(x); I want to get total of food items from js, but i could not get the solution, can anyone help me. -
How can I read csv files from the link stored in django model within views file?
I am creating a map with Folium, Django and Pandas. I created a django model where I store my csv file's url. I want to read csv files from there dynamically so that I can use different data dynamically. How can I do that? I used a url of a csv file. I want to make it dynamic so that I can fetch one from models directly. Here is my code. I will be very grateful for your assistance. def mapview(request, map_pk): srlist = Map.objects.filter(pk=map_pk) bd = pd.read_csv("https://docs.google.com/spreadsheets/d/1IohEgJi8ajDoHyPF315vi13F3m0vDtbl7DzmSmtUHpA/gviz/tq?tqx=out:csv") df = pd.DataFrame(bd) lat = df[['lat']] lng = df[['lng']] m = folium.Map(title='Bangladesh', location=[23.7805733, 90.2792399], zoom_start=7) for i, row in df.iterrows(): folium.Marker(location=[row['lat'], row['lng']]).add_to(m) m = m._repr_html_() context = { 'm':m, 'bd':bd, 'lat': lat, 'lng': lng, 'srlist':srlist, 'df':df, } return render(request, 'map/mapview.html', context) -
one django project two apps, problem with generic views( class view)
i have two apps in one project: store and basket. In urls.py in core of project: urlpatterns = [ path('admin/', admin.site.urls), path('', include('jewelry_store.urls', namespace='jewelry_store')), path('basket/', include('basket.urls', namespace='basket')), ] in urls.py in basket app : from django.urls import path from basket import views app_name = 'basket' urlpatterns = [ path('', views.BasketSummary.as_view(), name='basket_summary') ] in urls.py in jewelry_store app : from django.urls import path from jewelry_store.models import Category from . import views app_name = 'jewelry_store' urlpatterns = [ path('', views.AllListView.as_view(), name='all_products'), path('<slug:slug>', views.ProductView.as_view(), name='product_detail'), path('category/<slug:slug>/', views.CategoryView.as_view(), name='all_categories'), path('collection/<slug:slug>/', views.CollectionView.as_view(), name='all_collections'), ] i wold like to have class based view in views.py, like this : from msilib.schema import ListView from django.shortcuts import render import basket from jewelry_store.models import Product # Create your here. class BasketSummary(ListView): model = Product template_name = "jewelry_store/basket/summary.html" but it generate error like this when it is done in functions mode everything is correct. What is proper configuration for class views ? -
Not able to redirect to a specific page on login
I am trying to create django authentication but I am not able to redirect to a specific page. Here is my urls.py file. I think the error may be in this file but I am not able to get it. """demo_project URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/4.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path, include from django.contrib.auth import views as auth_views from blog.forms import LoginForm urlpatterns = [ path('admin/', admin.site.urls), path('blogs/', include('blog.urls', namespace='blogs')), path('login/', auth_views.LoginView.as_view(template_name='blog/login.html', authentication_form=LoginForm), name='login'), ] The problem is on clicking the login button the url comes as http://localhost:8000/login/blogs/get_blogs instead of http://localhost:8000/blogs/get_blogs/. Here is the settings.py file. """ Django settings for demo_project project. Generated by 'django-admin startproject' using Django 4.0.3. For more information on this file, see https://docs.djangoproject.com/en/4.0/topics/settings/ For the full list of settings and their values, … -
django.db.utils.OperationalError: (1054, "Unknown column 'titile' in 'where clause'")
could anyone help me out with this? operations = [ migrations.RunSQL(""" INSERT INTO store_collection(title) VALUES('collection1') """, """ DELETE FROM store_collection WHERE titile='collection1' """) ] I try searching for a solution but couldn't find anything so I have to post this. -
I am trying to retreive data from data from django backend to react but keep getting TypeError: get() missing 1 required positional argument: 'pk'
I have two concerns here. I am trying to retrieve data from django which contains images and contents. My first concern is whether using "Content-Type": "application/json" is right. The last and major problem is am getting: TypeError: get() missing 1 required positional argument: 'pk'. What could be the issue? Below is the code: import React, { useEffect, useState} from 'react' import axios from 'axios' const GetPostData = () => { const [postState, setPostState] = useState({ loading: true, posts: null }) const config = { headers: { "Content-Type": "application/json", Authorization: `JWT ${localStorage.getItem("access")}`, Accept: "application/json", }, }; useEffect(()=> { const res = axios.get( `${process.env.REACT_APP_API_URL}/api/list/PostView/`, config ); const allPosts = res.data setPostState({loading: false, posts: allPosts}) console.log(res.data) }, [setPostState]) return ( <div className='container'> <h1>Latest Posts</h1> <div> </div> </div> ) } export default GetPostData -
Django i18n set_language for other template extends not work
i am a beginner in django, and i am confused in i18n settings, i have checked many articles to figure out the problem, but it always failed, below is my templates structure: templates folder: |____layouts | |____base.html | |____includes | |____navigation.html | |____home |____index.html In base.html's body, i use {% include 'includes/navigation.html' %} make sure each page has a navigation bar, and index.html use {% extends "layouts/base.html" %} to make my home page. In my settings.py, i followed i18n tutorial to setup multi language, below is my settings: MIDDLEWARE: MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] TEMPLATES context processors: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_DIR], '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', 'django.template.context_processors.i18n', ], }, }, ] Internationalization: from django.utils.translation import gettext_lazy as _ LANGUAGE_CODE = 'en' LANGUAGES = ( ('en', _('English')), ('zh-hant', _('Traditional Chinese')), ('vi', _('Vietnamese')), ) TIME_ZONE = 'Asia/Ho_Chi_Minh' USE_I18N = True USE_L10N = True LOCALE_PATHS = [os.path.join(CORE_DIR, 'locale')] USE_TZ = True In my navigation.html, i put a select form to let users choose their prefer language: <form action="{% url 'set_language' %}" method="POST"> {% csrf_token %} <select class="form-select" name="language" onchange="this.form.submit()"> {% get_current_language as LANGUAGE_CODE %} {% get_language_info_list for … -
Is it possible to use Django to parse locally stored files (csv for example) without uploading them?
I would like to develop a WebApp that parses locally stored data and allows users to create a sorted excel file. It would be amazing if I could somehow avoid the uploading of the files. Some users are worried because of the data, the files can get really big so I have to implement async processes and so on... Is something like that possible? -
django.db.utils.IntegrityError: NOT NULL constraint failed: main_profile.name
I am creating a telegram bot that is a database. There is such an error:django.db.utils.IntegrityError: NOT NULL constraint failed: main_profile.name. What must I do ? Models.py from django.db import models class Profile(models.Model): external_id = models.PositiveIntegerField( verbose_name='User ID', unique=True, ) name = models.TextField( verbose_name='User name', default='None' ) def __str__(self): return f' ID: {self.external_id} | Username: {self.name}' class Meta: verbose_name = 'Profile' class Message(models.Model): profile = models.ForeignKey( to='main.Profile', verbose_name='Profile', on_delete=models.PROTECT, null=True, ) text = models.TextField( verbose_name='Text', ) Forms.py from django import forms from .models import Profile class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = ( 'external_id', 'name', ) widgets = { 'name': forms.TextInput } -
How to assign bulk parameter to Django object values list?
How to assign bulk parameters to the Django object values list? Bulk parameter assignment strlist = ["a","b","c"] model1. objects.filter(**kwargs).values_list(strlist) Result: TypeError: unhashable type: 'list' Manual assignment model1. objects.filter(**kwargs).values_list("a","b","c") Result is ok How to assign a bulk parameter assignment? -
Program not save and update new data in Django
I create program stock management system by using Django. When I will update data it can't save and update data. It redirect with same data. I am very new so please introduce me. Program can running but can't save. [This is error in command prompt][1] [forms.py][2]