Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django path('challenges/',include(challenges.urls)) NameError: name 'challenges' is not defined
When I comment urlpatterns = [ path('admin/', admin.site.urls), #path('challenges/',include(challenges.urls)) ] it is working fine but for urlpatterns = [ path('admin/', admin.site.urls), path('challenges/',include(challenges.urls)) ] it is throwing an error enter image description here why the error is occurring when I am using urlpatterns = [ path('admin/', admin.site.urls), path('challenges/',include(challenges.urls)) ] -
Problem in adding tags with taggit in Django
class Events(models.Model): user_name = models.TextField() e_url = models.URLField(null=True, blank=True) tags = TaggableManager() def __str__(self) -> str: return self.e_name def create_event(self, value): self.user_name = value['username'] self.e_url = value['url'] self.tags = value['tags'] Tags are not storing. When i store them from admin view its working properly. Bur when i try from my webpage its not working. Here value['tags'] contain string with comma separated tag name e.g. 'python,cpp,django'. My tags table is storing nothing in this case MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR / 'media' -
django-log-viewer: LOG_VIEWER_FILES_PATTERN
I have 2 types of log files, with various "filenames": filename.log filename.log.1 How to configure this in LOG_VIEWER_FILES_PATTERN? This does not work: LOG_VIEWER_FILES_PATTERN = "*.log??" Note: django-log-viewer version 1.1.7 -
In my autocomplete search bar in django app i want that user always gets the most relevant search when he type his query in search bar
So suppose in my app there is a product name "DispoVan 10ml 21mg" and when user gives its query in search bar as 'DispoVan' it works fine but as he mis spell or do some typo error in search query like "dispo 1" search bar did not suggest him any product. i want that if user searches for any product and even if he do some typing error in the name of the product he should get the relevant product. even is there is a space in the search query,any relevant matches should be shown to him. This is my view which is showing list of all the products which matches to search. def search_address(request): address = request.GET.get('query') payload = [] print(address) if address: prod = Product.objects.filter(Q(name__icontains=address)).values_list('name',flat=True) for prod in prod: payload.append(prod) return JsonResponse({'status':200, 'data':payload}) -
What causes 'Broken pipe' errors in a Django application on GKE, and how can I prevent them?
I have deployed a Django application on a Google Kubernetes Engine (GKE) cluster, and it has been functioning well. However, recently I encountered a "Broken pipe" error with the message "Broken pipe from ('35.191.194.192', 57892)" in my application logs. Notably, I did not release any updates during this time, and there were no indications of a broken error in the load balancer logs. and , the error disappeared after some days, even though no new updates were deployed. I would like to understand the root cause behind this issue and learn how to prevent it from occurring in the future. I did not take any specific action to address the issue since it resolved itself after some days. However, I expected to understand the cause of the "Broken pipe" error and find ways to avoid it in the future. -
Got "token": [ "Ensure this field has no more than 500 characters." ] in drf social oauth2
REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'oauth2_provider.contrib.rest_framework.OAuth2Authentication', 'drf_social_oauth2.authentication.SocialAuthentication', ), } AUTHENTICATION_BACKENDS = ( 'social_core.backends.google.GoogleOAuth2', # drf-social-oauth2 'drf_social_oauth2.backends.DjangoOAuth2', # Django 'django.contrib.auth.backends.ModelBackend', ) SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = 'my key' SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = 'my secrect' # Define SOCIAL_AUTH_FACEBOOK_SCOPE to get extra permissions from Facebook. # Email is not sent by default, to get it, you must request the email permission. SOCIAL_AUTH_GOOGLE_OAUTH2_SCOPE = [ 'https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile', ] I am using drf-social-oauth2 for Google login. After getting a Google credential from React site. i tried to use 'curl -X POST -d "grant_type=convert_token&client_id=<django-oauth-generated-client_id>&client_secret=<django-oauth-generated-client_secret>&backend=google-oauth2&token=<google_token>" http://localhost:8000/auth/convert-token' But I got "token": ["Ensure this field has no more than 500 characters."] -
How can I fix the 'zsh: command not found' error when trying to set up PostgreSQL for my Django project?
I am on the django official tutorial trying to set up PostgressSQL as the database for my project.I run the command CREATE DATABASE database_name I am getting the error message zsh: command not found. What have I tried so far: It instructs me to install the appropriate database bindings which I believe is psycopg2. I have installed psycopg2. After that it tells me to replace the engine and name values which I have done so substituting the blank strings for values. I don't think I am supposed to share my password or database name so I left it blank. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': '', 'USER': '', 'PASSWORD':'', 'HOST': 'localhost', 'PORT': '5432', # default PostgreSQL port } } I went ahead and replaced the engine and name values as they told me. So I am wondering why It acts like I do not have postgress installed when I ran the installer and pgadmin and sucessfuly set it up. A programmer more experienced than myself was able to create a project without fail. Link to django tutorial here: https://docs.djangoproject.com/en/4.2/intro/tutorial02/. What have I tried already, and what steps have I taken to solve the problem: I have tried researching … -
django uwsgi: Server Error (500) - while accessing view model without "q" parameter
I started facing an issue since upgrading my server from Ubuntu 18.04 LTS to Ubuntu 20.04 LTS. It seems that I'm encountering an issue (Server Error (500)) with only one model, specifically with the URI /admin/mymodule/mymodel/. Please refer uwsgi logs below: [pid: 27771|app: 0|req: 4/8] 192.168.1.101 () {72 vars in 1623 bytes} [Fri May 26 06:11:11 2023] GET /admin/mymodule/mymodel/ => generated 145 bytes in 210 msecs (HTTP/1.1 500) 6 headers in 184 bytes (1 switches on core 0) But when trying the same URI with query parameter (/admin/mymodule/mymodel/?all=&q=2022-12-19), it is working fine. Please refer uwsgi logs below: [pid: 27768|app: 0|req: 3/9] 192.168.1.101 () {70 vars in 1627 bytes} [Fri May 26 06:11:15 2023] GET /admin/mymodule/mymodel/?all=&q=2022-12-19 => generated 100205 bytes in 1013 msecs (HTTP/1.1 200) 9 headers in 463 bytes (1 switches on core 0) [pid: 27770|app: 0|req: 3/10] 192.168.1.101 () {68 vars in 1468 bytes} [Fri May 26 06:11:16 2023] GET /admin/jsi18n/ => generated 3187 bytes in 12 msecs (HTTP/1.1 200) 6 headers in 189 bytes (1 switches on core 0) I don't understand the behavior as I'm able to access all other view models and custom views successfully without any issues. And able to access this view with any … -
Retrieve bank account number through plaid in Django
I am creating a financial app using django. I want a user can connect to any bank using Plaid and on the UI, I want to see the bank account number and balance. I am not sure how to retrieve the dummy bank account number I tried to connect to any bank using Plaid and I did that successfully. I have my account id and access token -
custom django sub-admin custom permission provided by admin
I have a django custom django admin panel and now i have create a new app where admin will be able to register sub admin once subadmin is registered he will get into another app where he has to select the sub admin from the drop down and will see the different app name with two option read or rea/write admin has to select one and that specific app with that select permission will be allocated the subadmin Pleas let me know how i can achieve this -
Django - Function Based View update record - error - Record Already exists
I am trying to update an existing record using Django 4.2, Crispy Forms, and Function Based View. The field currency_code in the table Currency is used as a ForeignKey in another table(s). I cannot update the currency record without getting the message that the record already exists. Below is the code and screenshot: MODELS.PY: class Currency(models.Model): currency_code = models.CharField(max_length=3) currency_name = models.CharField(max_length=80) class Meta: verbose_name_plural = "Currencies" def __str__(self): return self.currency_code class Forex(models.Model): currency_code = models.ForeignKey(Currency, on_delete=models.CASCADE) forex_rate = models.DecimalField(max_digits=8, decimal_places=4) last_updated_on = models.DateTimeField(auto_now=True) class Meta: verbose_name_plural = "Forex Rates" def __str__(self): return self.currency_code.currency_code FORMS.PY: class UpperCase(forms.CharField): def to_python(self,value): if value: return value.upper() class CurrencyForm(forms.ModelForm): currency_code = UpperCase(label='Currency Code', min_length=3, max_length=3, error_messages={'required': 'Currency Code Cannot Be Blank'}, required=True) currency_name = UpperCase(label='Currency Name', min_length=5, max_length=80, error_messages={'required': 'Currency Name Cannot Be Blank'}, required=True) class Meta: model = Currency fields = ['currency_code', 'currency_name'] # Method 2 for checking duplicates working ok def clean_currency_code(self): currency_code = self.cleaned_data.get('currency_code') if Currency.objects.filter(currency_code=currency_code).exists(): raise forms.ValidationError('Currency Code {} already exists!'.format(currency_code)) return currency_code VIEWS.PY: def currency_edit(request, id): obj = Currency.objects.get(id=id) if request.method == 'POST': form = CurrencyForm(data=request.POST, instance=obj) if form.is_valid(): form.save() return redirect('currency_list_page') else: form = CurrencyForm(instance=obj) return render(request, 'main/currency_edit.html', locals()) CURRENCY_EDIT.HTML <form action="{% url 'currency_edit_page' id %}" class="row g-3 … -
Is there the parameter to pass a billing address to "Payments" on Stripe Dashboard after a payment on Stripe Checkout?
I'm trying to pass a billing address to Payments on Stripe Dashboard but I couldn't find the parameter to do it in payment_intent_data. So instead, I used payment_intent_data.metadata as shown below. *I use Django: # "views.py" from django.shortcuts import redirect import stripe checkout_session = stripe.checkout.Session.create( line_items=[ { "price_data": { "currency": "USD", "unit_amount_decimal": 1000, "product_data": { "name": "T-shirt" }, }, "quantity": 2 } ], payment_intent_data={ "shipping":{ "name": "John Smith", "phone": "14153758094", "address":{ "country": "USA", "state": "California", "city": "San Francisco", "line1": "58 Middle Point Rd", "line2": "", "postal_code": "94124" } }, "metadata":{ # Here "name": "Anna Brown", "phone": "19058365484", "country": "Canada", "state": "Ontario", "city": "Newmarket", "line1": "3130 Leslie Street", "line2": "", "postal_code": "L3Y 2A3" } }, mode='payment', success_url='http://localhost:8000', cancel_url='http://localhost:8000' ) return redirect(checkout_session.url, code=303) Then, I could pass a billing address to Payments on Stripe Dashboard as shown below, but if there is the parameter to pass a billing address to Payments on Stripe Dashboard, it is really useful: I know that there are address parameter when creating a customer and address parameter when updating a customer but both address doesn't have name and phone parameters. # "views.py" from django.shortcuts import redirect import stripe def test(request): customer = stripe.Customer.search(query="email:'test@gmail.com'", limit=1) shipping={ "name": "John … -
Django cant link user to profile page from login
I have been trying to make a redirect link for the login of my django site, its supposed to take the user back to their profile page once they hit the login button, im trying to identify the user based on their id, which is defined in the models section, but for some reason it wont let me reference it by id, which is weird because it lets me do this for updating, and also viewing specific profiles sign in form {% extends 'base.html' %} {% block content %} <main class="form-signin w-100 m-auto"> <form action='<int:id>/' method='GET'> {{form.as_p}} <input type='Submit' value='Save ' /> </form> </main> {% endblock %} Models form where the id is defined from django.db import models from django import forms from django.utils.formats import date_format import datetime from datetime import date, timedelta from django.urls import reverse # Create your models here. class User(models.Model): GENDERS = [ ("F","FeMale"), ("M","Male"), ("O","Other"), ("N/A","Choose not to identify"), ("AH!","Attack Helicopter"), ] email = models.CharField(max_length=30,default=False) username = models.CharField(max_length=30,default=False) password = models.CharField(max_length=30,default=False) remember_login= models.BooleanField(blank=True) FA2 = models.BooleanField(default=False) dob = models.CharField(max_length=30) gender = models.CharField(max_length=4, choices=GENDERS) def get_absolute_url(self): return reverse("users:user-profile", kwargs={"id":self.id}) #could make a list of users to reference based on id, but this would prob be visible … -
blog post image slideshow
What I've got in my mind is that there is a blog section on my Django website. there are posts in this blog section. every post has a main photo. when you click on the main photo and post summary you can see more about that post. in the post details, there is a photo slide show which shows a couple of photos from the database. I defined my model like this: model.py: from django.db import models from django.contrib.auth.models import User class Post(models.Model): author = models.ForeignKey(User, on_delete=models.DO_NOTHING, null=True) image = models.ImageField(upload_to='blog_images/', default='blog_images/default.jpg') title = models.CharField(max_length=255) content = models.TextField() status = models.BooleanField(default=False) def __str__(self) -> str: return self.title class Images(models.Model): post = models.ForeignKey(Post, default=None, on_delete=models.CASCADE) images = models.ImageField(upload_to='blog_images/', default='blog_images/default.jpg') and of course, we have admin site settings. admin.py: from django.contrib import admin from .models import Post, Images class ImagesAdmin(admin.StackedInline): model = Images @admin.register(Post) class PostAdmin(admin.ModelAdmin): inlines = [ImagesAdmin] list_display = ('title',) admin.site.register(Images) at last, we have views! views.py: from django.shortcuts import render from blog.models import Post, Images def blog_single(request, **kwargs): posts = Post.objects.filter(status=1) if pid := kwargs.get('pid'): post = posts.get(id=pid) images = Images.objects.filter(post__id=post.id) context = {'post':post, 'images':images} return render(request, 'blog/blog-single.html', context) The problem is that I cannot find a way to … -
Wagtail error that 'wagtail.models.i18n.Locale' is not in installed apps
I'm attempting to upgrade from Wagtail 4.1 LTS to 5.0. I've paid attention to the documentation and the upgrade considerations, and changed all my import statements and models accordingly. I wasn't using any localization support other than anything enabled by default, for example, I didn't have WAGTAIL_I18N_ENABLED in my settings.py When I attempt to makemigrations I am getting the error that RuntimeError: Model class wagtail.models.i18n.Locale doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. I am unsure how to resolve this as I am not using anything to do with localization, and I can't see anything relating to it in upgrade considerations. The error seems to be coming from files specific to wagtail base code and not any of my applications. What steps can I take to troubleshoot and resolve this? -
How to implement update mechanism in my django/django rest framework project
I’m trying to do an app which is able to get data from other websites and get updated itself without handling from the user. For instance: when it is 2pm my script is launched in my app, it gets data, then my database is updated by using my model and serializers/forms. Do you have an idea that is it possible to do it on a django project? Thanks for all! -
Silk UI not loading: ERROR CODE 103 - Enable JavaScript to run this app
I'm experiencing an issue while trying to access the Silk statistics for my Django app. When I request the corresponding URL (http://localhost:8000/silk/), I'm getting the following response: ERROR CODE 103: You need to enable JavaScript to run this app. Interestingly, instead of showing the Silk UI, it displays the UI of my React app, which makes API calls to the Django app. In my Django Settings.py file, I have the Silk middleware configured as follows: MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'silk.middleware.SilkyMiddleware', ] Furthermore, I can confirm that Silk operations are being logged in the console, indicating that data is being successfully recorded in the database. I think that this tool would be very useful for me to be able to do an analysis of the performance of my Django app, but until now I have not been able to make it work completely. Any help, thanks in advance! -
on_connect() missing 3 required positional arguments: 'userdata', 'flags', and 'rc'
I am writing a django application which should act as MQTT publisher and as a subscriber. but when i run it , it give me: TypeError at / on_connect() missing 3 required positional arguments: 'userdata', 'flags', and 'rc' this is my code : from django.shortcuts import render from .models import Video from .form import VideoForm import paho.mqtt.client as mqtt from django.http import HttpResponse import time def on_connect(client, userdata, flags, rc): print("Connected with result code "+str(rc)) client.subscribe("a") #global result def on_message(client, userdata, msg): global result result = msg.payload.decode("") print("Received message:", result) client = mqtt.Client("p1") client.connect("127.0.0.1", 1883) client.publish("test", 'C:/Users/HP/Desktop/NV_4.mp4') client.on_connect = on_connect client.on_message = on_message -
Vue.Js Routing issues, when visiting product and Visit other links after that, links stack one on top of another
I am building an E-Commerce with Vue.js and Django Rest Framework. Everything is working fine, the only problem is that when I press and visit a product page, then open menu and press any other link it sends me to a blank page and then stacks slug on top of another slug or like link on top of another link which breaks the view. Lets imagine we visit "lechuga crespa" and then press in menu on "products" it will send you to a blank view and the link would be like that: :8000/lechuga-crespa-verde/productos when it should replace /lechuga-crespa/ by /productos/. How could I solve that? Thank you. Here is my router.js: import { createRouter, createWebHistory } from 'vue-router' import store from '../store' import axios from 'axios' import Home from '../views/Home.vue' import Products from '../views/shop/Products.vue' import Product from '../views/shop/Product.vue' import About from '../views/About.vue' import Corporate from '../views/Corporate.vue' import Contact from '../views/Contact.vue' import ContactThankYou from '../views/ContactThankYou.vue' import Login from '../views/auth/Login.vue' import SignUp from '../views/auth/SignUp.vue' import ResetPassword from '../views/auth/ResetPassword.vue' import ResetPasswordToken from '../views/auth/ResetPasswordToken.vue' import ResetPasswordMessage from '../views/auth/ResetPasswordMessage.vue' import ResetSetNewPassword from '../views/auth/ResetSetNewPassword.vue' import Account from '../views/auth/Account.vue' import ComplaintsBook from '../views/ComplaintsBook.vue' import PrivacyPolicy from '../views/PrivacyPolicy.vue' import Favorites from '../views/Favorites.vue' import Cart from '../views/shop/Cart.vue' import Checkout … -
Django validation (Django Rest Framework) doesn't work with parallel queries
In my DRF Film serializer I have general validate() method: def validate(self, data): request = self.context.get('request') existing_film = Film.objects.filter(title__iexact=data.get('title'), release_date=data.get('release_date'), director__iexact=data.get('director')) if request.method == 'POST': if existing_film: validation_error_message = 'Film with such parameters (title, director, release date) already exists' logger.warning(f'Validation error - {validation_error_message}') raise serializers.ValidationError(validation_error_message) return data As you can see, it makes request to the database and compares posted film with the existing one. Everything works well when queries are sequential. But if I try to make parallel queries (for example, from two terminal windows) validate() doesn't work properly and both identical films are being pushed to the database, which is definitely not what I expect. Should I use some sort of transactions or something? Thank you! -
React/Django/Redux 400 Bad Request when registering a new user
I've been struggling with this error for a while now. Pretty new to python, Django and Redux so trying to solve this has been a struggle. I've been trying to register a new user through my react frontend but the console gives me a 400 (Bad Request). I'm able to make new users through Django admin, but can't through my frontend register page. I have no idea if my frontend or backend is the issue. Any help would be appreciated RegisterPage.js import React, { useEffect, useState } from "react"; import { Link, useLocation, useNavigate } from "react-router-dom"; import { Form, Button, Row, Col } from "react-bootstrap"; import { useDispatch, useSelector } from "react-redux"; import Loading from "../components/Loading"; import ErrorMessage from "../components/Error"; import FormContainer from "../components/FormContainer"; import { login, register } from "../actions/userActions"; import axios from "axios"; function RegisterPage() { const [first_name, setFirst_name] = useState(""); const [email, setEmail] = useState(""); const [password, setPassword] = useState(""); const [confirmPassword, setConfirmPassword] = useState(""); const [errorMessage, setErrorMessage] = useState(""); const location = useLocation(); const navigate = useNavigate(); const dispatch = useDispatch(); const redirect = location.state ? Number(location.state) : "/"; const userRegister = useSelector((state) => state.userRegister); const { error, loading, userInfo } = userRegister; const submitHandler … -
Django how to get the values with an id as key and shows it in template
I have got a DICT like this: {4: {'26.00': "{'tac': {'4.99': '1.30'}}"}, 2: {'32.00': "{'tac': {'4.99': '1.60'}}"}} Where 4 and 2 are the respective user id. I send the DICT to template and I also have access to the user id in a for loop. Is it possible to get only the data to the respsctive user in the template: I would like to learn a workout to get the dict data for each user by user.id. Is it possible to do something like this? Remembering that the DICT isnt inside any model. So it is a static data generated before the tamplate renders. user_name: John user_email: j@j.com user_id = 2 amount = 32.00 tac = 4.99 : 1.60 user_name: Charles user_email: c@c.com user_id = 4 amount = 26.00 tac = 4.99 : 1.3 Thank you very much for any ideas os directions to solve it. -
Interval callback is interrupting download callback in Dash. Is there a way to stop this?
I have an app built using django-plotly-dash in a container. The app uses an interval callback to periodically check the container for new files that are added from a backend process and update the frontend with said files. There is also a callback to download the file from the container. I've noticed when downloading a file, the interval callback is hammering away and interrupting the download callback. When the interval callback is disabled, the download works fine. I've disabled the interval callback and replaced it with a manual refresh button for the time being. It's currently satisfying the client's needs, but they would like it to automatically update instead of pressing "Refresh" until the files appear. Can anyone point me in the right direction on how to go about this issue? -
No module named 'django' | Django installed | Python 3 | No virtual env
I am trying to use Django Models in another python script script.py. This is my script from os import environ environ['DJANGO_SETTINGS_MODULE'] = 'settings' import sys sys.path.append("C:/.../djangoproject/djangoproject") from settings import * sys.path.append("C:/.../djangoproject/myapp") from models import video vid = video(video_title='a title') vid.save() This is my folder structure: djangoproject _script.py _djangoproject: __settings.py __ ... _myapp __models.py __ ... This is the error Traceback (most recent call last): File "C:\...\djangoproject\script.py", line 11, in <module> from models import video File "C:\...\djangoproject/myapp\models.py", line 1, in <module> from django.db import models ModuleNotFoundError: No module named 'django' Django is installed I only have python 3 I am not using a virtual env Is there a fix to this problem? Thank you -
SMTP AUTH extension not supported by server - Outlook SMTP & smtplib
I am trying to get emails sent from my django server using Outlook SMTP but I am getting this error: SMTPNotSupportedError( smtplib.SMTPNotSupportedError: SMTP AUTH extension not supported by server. I have tried: Set up 2FA on outlook and created app password for django to use, same error. Here is my configuration in settings: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.office365.com' EMAIL_PORT = 587 EMAIL_USE_STARTTLS = True EMAIL_HOST_USER = {removed} EMAIL_HOST_PASSWORD = {removed} Here is the view sending the email: def password_reset(request): if request.method == "POST": body_unicode = request.body.decode('utf-8') body_data = json.loads(body_unicode) email = body_data['email'] try: user = User.objects.get(email=email) token = default_token_generator.make_token(user) subject = 'x: Password Reset' body = f'Here is the link you requested to reset your password: http://localhost:3000/api/user/reset/{token}' sender = os.environ.get('EMAIL_NAME') recipient_list = [email] send_mail(subject, body, sender, recipient_list) return HttpResponse("Email sent") except User.DoesNotExist: return HttpResponse("User does not exist") else: return HttpResponse("Invalid HTTP method") Can anyone point me in the right direction? Thanks in advance!