Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Third test in Django with Pytest is failed because "django.template.exceptions.TemplateDoesNotExist"
I got 3 tests in django using pytest, the first two tests are alright untill third one which cannot find Template. Last 2 of 3 are working with same template but second one cannot find the template. FAILED app_wallet/accounts/tests/test_pytest.py::test_login_failed - django.template.exceptions.TemplateDoesNotExist: main_layout.html #test_pytest.py import pytest from django.urls import reverse from django.contrib.auth.models import User pytestmark = pytest.mark.django_db def test_create_account_success(client): client_url = reverse('accounts:create') data = { 'username': 'test', 'email': 'test@domain.pl', 'password1': 'myPassword123', 'password2': 'myPassword123', } response = client.post(path=client_url, data=data) user = User.objects.all().first() assert response.status_code == 302 # redirected to another page - valid data assert User.objects.all().count() == 1 assert user.username == data.get('username') assert user.email == data.get('email') def test_login_success(client): client_url = reverse('accounts:login') user = User.objects.create_user(username='test123', password='Password123', email='test@domain.pl') data = { 'username': 'test123', 'password': 'Password123' } response = client.post(path=client_url, data=data) assert response.status_code == 302 # redirected to another page - valid data assert User.objects.all().first().username == data.get('username') assert User.objects.all().first().email == 'test@domain.pl' def test_login_failed(client): client_url = reverse('accounts:login') user = User.objects.create_user(username='test123', password='Password123', email='test@domain.pl') data = { 'username': 'test123', 'password': 'Password12' } response = client.post(path=client_url, data=data) assert response.status_code == 200 assert User.objects.all().count() == 1 assert User.objects.all().first().username != data.get('username') #login.html {% extends 'main_layout.html' %} {% block head %} <title> Test 123 </title> {% endblock %} {% block main %} … -
Django application visible in the home network only if run by root
I have a web app on Django that I'm running with the internal server to make it see on my home network. If I run with my user with python manage.py runserver 0.0.0.0:8080 I can see it work but only within my host. If I try to reach on another PC on the same network I have connection refused. If I run the same command but with root user, so using sudo su, everything works and I can reach the server from any PC on the network. I'm using Python 3.10.12 and Ubuntu 22.04.3 LTS 6.2.0-26-GENERIC -
AttributeError: module 'django.db.models' has no attribute 'JSONField' in django 3.0.5
I am trying add a model in my app like this: class WarehouseTablePreferences(models.Model): owner = models.ForeignKey(User, on_delete=models.PROTECT) column_preferences = models.JSONField(default=dict) and in the app I have: Django==3.0.5 django-cors-headers==3.2.1 djangorestframework==3.11.0 but its still giving me the following error: File "/Users/rahulsharma/PycharmProjects/Trakkia-Backend copy/users/models.py", line 407, in <module> class WarehouseTablePreferences(models.Model): File "/Users/rahulsharma/PycharmProjects/Trakkia-Backend copy/users/models.py", line 409, in WarehouseTablePreferences column_preferences = models.JSONField(default=dict) AttributeError: module 'django.db.models' has no attribute 'JSONField' -
why view inheritance in django does not work
django(i am new) view inheritance dont work <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>coding Django</title> </head> <body> <h1>Welcome to this shit show</h1> {% block content %} {% endblock content %} </body> </html> this is sub component and does not show inside base view i tried to include it in the base.html does not work either {% extends "base.html" %} {% block content %} <h1> this is from sub component <h1> {% endblock content %} -
How can i integrate salesforce to my Django Application
Previously I worked with ROR where I used Restforce Gem. I am new to this Django can someone suggest what are the best ways to be followed to integrate salesforce to my e-commerce application I am new to this Django is there any rest api calls that i need to make. What is the project structure i need to keep in my mind while implementing this in Django -
How to access the fields from other models in Django
I am trying to make a application where the data incoming is in this format { "author name": "J. K. Rowling", "books" : ["Harry potter 1" , "Harry potter 2"] } Now i made the models for author and books in the following format class Author(models.Model): name = models.CharField(max_length=100) class Book(models.Model): name = models.ForeignKey(Author,on_delete=models.CASCADE) title = models.CharField(max_length=200) The seralizers are :- class BookSerializer(serializers.ModelSerializer): class Meta: model = Book fields = '__all__' class AuthorSerializer(serializers.ModelSerializer): books = BookSerializer(many=True, required=False) # Use the BookSerializer here class Meta: model = Author fields = '__all__' Views are: class AuthorViewSet(viewsets.ModelViewSet): queryset = Author.objects.all() serializer_class = AuthorSerializer class BookViewSet(viewsets.ModelViewSet): queryset = Book.objects.all() serializer_class = BookSerializer Custom View:- class ImportDataViewSet(ViewSet): @action(methods=["POST"],detail=False) def import_data(self,request): data = request.data print(data) # deseralize the data and check book_seralizer = [BookSerializer(data = book_data) for book_data in data.get("books",[])] author_seralizer = AuthorSerializer(data = data.get("author")) if(author_seralizer.is_valid() and all(seralizer.is_valid() for seralizer in book_seralizer)): author_instance = author_seralizer.save() for book_instance in book_seralizer: book_instance.validated_data['author'] = author_instance print("hello ",book_instance.data) book_instance.save() return Response({"message","Data imported successfully"},status=200) else: author_errors = author_seralizer.errors if (author_seralizer.is_valid() == False) else {} book_errors = [serializer.errors for serializer in book_seralizer if(serializer.is_valid() == False)] errors = { "author_errors": author_errors, "book_errors": book_errors } return Response(errors,status=400) URLS:- router = DefaultRouter() router.register(r"authors",AuthorViewSet) router.register(r"books",BookViewSet) import_data_view … -
How to update an instance with fields of related model
I have a Store model and store's types models class Store(models.Model): user = models.ForeignKey(User, on_delete=models.PROTECT) name = models.CharField(max_length=128, blank=True, default="", verbose_name="name") class AmazonStore(models.Model): store = models.ForeignKey(Store, on_delete=models.CASCADE, null=True, verbose_name="Amazon store") amazon_api_key = models.CharField(max_length=255, blank=True, default="", verbose_name="amazon token") class AliStore(models.Model): store = models.ForeignKey(Store, on_delete=models.CASCADE, null=True, verbose_name="Ali store") ali_api_key = models.CharField(max_length=255, blank=True, default="", verbose_name="ali token") I have a view (GenericViewSet, CreateModelMixin, ListModelMixin) to create and list stores and now I want to add an update method to update Store (and fields of its related model) I want to be able to update store's name and store's api key in one update() method and one serializer. Depending on the type of store, different data may be sent in the request.data. Examples: 1. AmazonConnectOptions: { name: 'New store name', ApiKey: 'new api key' } AliConnectOptions: { name: 'New store name', ApiKey: 'new api key' } I want to use UpdateModelMixin and add an update() method: def update(self, request, *args, **kwargs): partial = kwargs.pop("partial", False) instance = self.get_object() serializer = self.get_serializer(instance, data=request.data, partial=partial) serializer.is_valid(raise_exception=True) return Response(status=200) But I don't know how to update store and its keys in one serializer. -
Interactive Table Tree Structure (Datatable) in Django Bootstrap4 & Ajax
I have a project model that can have WBS and activities, WBS can also have activities. I want to load it in a tree table style so the user can edit any one record from one screen. Is it possible in Django? I have tried using datatable examples which are great but what to do if I wish to load a tree like structure and use Ajax to Add/Update? -
Errors with Deploying a Django and React App to Railway
I'm struggling to deploy my django app to railway. The app continues to successfully deploy to Railway, however when visiting the URL of my railway app, I continue to get the error: TemplateDoesNotExist at /index.html. Since I'm using react with Django, I understand the process of serving the static files from react after they are built, and when running this project locally, everything has been working fine, the issue only started once I began to deploy to Railway. For reference, the folder where I've stored my reactapp is called 'reactapp'. Here are the key components of my manage.py file: ALLOWED_HOSTS = ["myprojecturl.railway.app", "127.0.0.1"] CORS_ALLOWED_ORIGINS = [ "http://127.0.0.1:8000/home/", "myprojecturl.railway.app" ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'api/templates/api'), BASE_DIR / 'reactapp/build', ], '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', ], }, }, ] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = 'static/' STATICFILES_DIRS = [ BASE_DIR / 'reactapp/build/static', ] My main urls.py file: path('', TemplateView.as_view(template_name='index.html')) I'm confused because this project works fully well locally, but the problems keep arising when deploying to Railway. Any help is appreciated, Thanks! -
how to get current user data from forms.py file in Django application?
Can't figure out how to get user data when getting form data. The idea is that the label and date-attribute('data-word-translate') should store the data obtained from the user's tables. It seems to me that it should be something like this: enter image description here I tried to change the values of the required fields at the view.py level, but this does not work reliably.enter image description here -
Disable perfomance measures for some transactions in Sentry
Our application written on stack Django\Postgres\Redis\Celery + Vue. As one of the monitoring tool we are using Sentry. Sentry measures performance for transactions. It's possible to control how many transaction will be covered by Sentry with set up sample rate. Also we can control which transaction could be covered with filtering them by (for example) path. How can i exclude transactions from performance monitoring (but still watch them for issues)? -
How to create *working* data migration using relation ot custom User in Django?
I've just started a new project and I'm using custom User model (from django-authtools). Everything works perfect until I got tired of constantly creating example data after wiping the db and decided to add a data migration for development purposes. Mind you, I specifically don't want to use fixtures for this. I have a ContactPerson model that references settings.AUTH_USER_MODEL and I'm using apps.get_model() calls in the migration. Everything by the books (or so it seems): # clients/models.py ... class Client(models.Model): name = models.CharField(max_length=128) class ContactPerson(models.Model): client = models.ForeignKey(Client, on_delete=models.CASCADE) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="as_contact_person", ) # migration from django.contrib.auth import get_user_model from django.db import migrations def create_example_data(apps, schema_editor): Client = apps.get_model("clients", "Client") ContactPerson = apps.get_model("clients", "ContactPerson") User = get_user_model() jim_user = User.objects.create_user( email="j.halpert@dundermifflin.com", password="*", name="Jim Halpert" ) dunder_mifflin = Client.objects.create( name="Dunder Mifflin, Inc.", ) ContactPerson.objects.create( client=dunder_mifflin, user=jim_user, ) class Migration(migrations.Migration): dependencies = [ ("clients", "0001_initial"), ] operations = [ migrations.RunPython(create_example_data) ] But trying to run the migration I get this error: ValueError: Cannot assign "<User: Jim Halpert j.halpert@dundermifflin.com>": "ContactPerson.user" must be a "User" instance. Other migrations are fresh and the built-in User model had never been used. I've also checked that the User model in the migration is of … -
how to connect service to django admin panel actions
I have the model Machine, that is inherited from models.Model: class Machine(models.Model): ... The model is registered in django admin panel using: admin.site.register(Machine) When I create new model using Add... button, I need to proceed some service code, along with creating new Machine. How can I connect my service code to default django admin panel? I've tried to connect code using re-defining methods in model class, based on information I found in Internet, but that didn't work. -
Full path is not saved to media when I implement django-tenants in my django project
I am implementing multitenant in a django project with PostgreSQL for this I implemented a library called django-tenants but I have a small problem what I wanted was to save the media files for each scheme in a folder with the same name of the scheme for it in the official documentation It told me that I had to put this configuration in my settings.py. DEFAULT_FILE_STORAGE = 'django_tenants.files.storage.TenantFileSystemStorage MULTITENANT_RELATIVE_MEDIA_ROOT = "" To be able to save a folder of the media of my models for each scheme, when I test my model class Product(models.Model): name = models.CharField(max_length=150, verbose_name='Name') image = models.ImageField(upload_to='product/%Y/%m/%d', null=True, blank=True, verbose_name='Image') Actually saving in the correct folder is called schema/product/2023/08/30/imagen.png but when I consult the path in the database it only saves me product/2023/08/30/imagen.png how do I get it to be save the schematic also in the path? I tried to find a solution by all means but none worked. -
I get some error when create new model in Django
I created 2 model for one to one in Django model So model codes is very simple enter image description here I executed CMD after put the above code python manage.py migrate But I get this error message enter image description here` -
Django-admin on react page
I'm trying to put the django-admin page in a react component so that it appears to the user on the frontend. it's a project just for programmers so everyone is authorized. However, I'm having difficulties using the iframe to display the page, how can I do this without harming the application's security? I'm currently trying to use the iframe for this, but some security problems are appearing, mainly those related to crsf. -
Can't serve files located in static root with whitenoise
I am trying to serve my static files in my testing environment that's suppose to mirror my production environment that uses Whitenoise. In setting.py, I believe these are the relevant parts of the issue: DEBUG = True INSTALLED_APPS = [ 'whitenoise.runserver_nostatic', 'django.contrib.admin', # the rest of the apps ] STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' if not DEBUG: STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = 'static/' else: STATIC_URL = 'static/' STATIC_ROOT = os.path.join(BASE_DIR, "static") # STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static')] WHITENOISE_USE_FINDERS = False I set WHITENOISE_USE_FINDERS = False to ensure that my development environment is serving files the way Whitenoise would. Regardless, none of the static assets are being served. The only time things seem to work is when I uncomment STATICFILES_DIRS and set STATIC_ROOT = 'static/, but I can't have that for my production environment. This problem has been troubling me for a long while now and if anyone can offer some insight, I'd appreciate it a lot. -
django-avatar // not enough values to unpack (expected 2, got 1)
https://django-avatar.readthedocs.io/en/latest/ Django returns "not enough values to unpack (Expected 2, got 1) when trying to open this html template: {% extends 'base.html' %} {% load account %} {% load avatar_tags %} {% block content %} <div style="border: 2px solid #ffffff; text-align:center"> <h1>Dashboard</h1> <div> {% avatar user %} <a href="{% url 'avatar_change' %}">Change your avatar</a> </div> <div> <p>Welcome back, {% user_display user %}</p> </div> </div> {% endblock content %} and highlights "{% avatar user %}" Here's the traceback: https://dpaste.com/B7EX28LNB Environment: Request Method: GET Request URL: http://127.0.0.1:8000/dashboard/ Django Version: 4.2.4 Python Version: 3.11.5 Installed Applications: ['yt2b2', 'home', 'dashboard', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'embed_video', 'avatar', 'allauth', 'allauth.account', 'allauth.socialaccount'] Installed Middleware: ['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'] Template error: In template C:\Users\Pedro\Documents\GITHUB\YT2B2-new-dev\YT2B2\youtube2blog2\dashboard\templates\dashboard\dashboard.html, error at line 10 not enough values to unpack (expected 2, got 1) 1 : {% extends 'base.html' %} 2 : {% load account %} {% load avatar_tags %} 3 : 4 : {% block content %} 5 : 6 : <div style="border: 2px solid #ffffff; text-align:center"> 7 : <h1>Dashboard</h1> 8 : <div> 9 : 10 : {% avatar user %} 11 : 12 : <a href="{% url 'avatar_change' %}">Change your avatar</a> 13 : 14 : </div> 15 … -
How to send emails in the same thread in Django?
I am wondering how can I send email in the same email thread using django.core.mail. I have an APIView that handles post requests from my contact form. It receives the contact form input and sends it to my email. In case when the email address from form input was already used (e.g. first form was submitted with mistakes), I would like such forms to be sent in the same email thread, rather than in separate emails. So basically every thread should contain submitted forms with the same email address as replies to the original email. views.py from rest_framework.views import APIView from rest_framework.response import Response from .serializers import ContactFormSerializer from rest_framework import status from django.conf import settings from django.core.mail import EmailMultiAlternatives from django.template.loader import render_to_string from django.utils.html import strip_tags class ContactFormAPIView(APIView): def post(self, request): serializer = ContactFormSerializer(data=request.data) if serializer.is_valid(): contact_form = serializer.save() subject = 'New Contact Form Submitted' context = { 'name': contact_form.name, 'email': contact_form.email, 'subject': contact_form.subject, 'message': contact_form.message, 'submitted_at': contact_form.submitted_at, } html_content = render_to_string('api/contact_form.html', context) text_content = strip_tags(html_content) email = EmailMultiAlternatives( subject, text_content, from_email=settings.EMAIL_HOST_USER, to=[settings.EMAIL_HOST_USER] ) email.attach_alternative(html_content, 'text/html') try: email.send() except Exception as e: return Response({'detail': f'Failed to submit the contact form: {str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) return Response({'detail': 'Contact form submitted successfully.'}, … -
Authorization button not appearing in Django Ninja API docs
I am using Django Ninja to build an API, and I am having trouble getting the authorization button to appear in the API docs. I have already added the rest_auth app to my INSTALLED_APPS and add this REST_AUTH_DEFAULT_AUTHENTICATION_CLASS = 'rest_auth.authentication.TokenAuthentication' to my Django settings file, but the button is still not appearing.and this is my api docs and as you see the authorization button don't appear I expected the authorization button to appear in the API docs, so that I could use it to authenticate with my API. However, the button is not appearing. -
Django Allauth - ModuleNotFoundError: No module named 'allauth.account.middleware' even when django-allauth is properly installed
"ModuleNotFoundError: No module named 'allauth.account.middleware'" I keep getting this error in my django project even when django-allauth is all installed and setup??? I tried even reinstalling and changing my python to python3 but didn't change anything, can't figure out why all other imports are working but the MIDDLEWARE one... Help pls? settings.py: """ Django settings for youtube2blog2 project. Generated by 'django-admin startproject' using Django 4.2.4. For more information on this file, see For the full list of settings and their values, see """ from pathlib import Path import django import os import logging import pyfiglet import allauth # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-l_pc%*s54c__=3ub&@d)s&@zp*46*=@)y*uv@v&(b6+hwq1&u5' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # CUSTOM CODE # os.environ['FFMPEG_PATH'] = '/third-party/ffmpeg.exe' # os.environ['FFPROBE_PATH'] = '/third-party/ffplay.exe' OFFLINE_VERSION = False def offline_version_setup(databases): if (OFFLINE_VERSION): # WRITE CODE TO REPLACE DATABASES DICT DATA FOR OFFLINE SETUP HERE return True return banner_ascii_art = pyfiglet.figlet_format("CHRIST IS KING ENTERPRISES") logger = logging.getLogger() logger.setLevel(logging.DEBUG) print("\n - CURRENT DJANGO VERSION: " + … -
How to update django user profile information from a form?
I'm creating a web application to track my friends personal bets amongst eachother.. I have added a UserBalance value to the user model, but now I want superuser/admins to be able to update that upon submitting a form. List of all bets Leaderboard with user balances How would I go about making it so the form in last column of first screenshot will update both bettor's balances? accounts models.py: from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver # Create your models here. class UserBalance(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) balance = models.IntegerField(default=0) @receiver(post_save, sender=User) def create_user_balance(sender, instance, created, **kwargs): if created: UserBalance.objects.create(user=instance) I assume I need to add a method somewhere to take the winner/loser form info and then change the corresponding user's balances but I'm not sure where to do that or how -
not being able to access a variable in python flask
Let me briefly explain to you what I want to do: I want to get the username of the commenter to comment on an article. for this I perform a query from the articles table (sorgu2). Finally, I find the username of the person who made the comment, but I get an error. mistake:UnboundLocalError: cannot access local variable 'cevaplanan' where it is not associated with a value how do i solve this please help `@app.route('/yorum/string:article_title/', methods=["GET","POST"]) def yorum_ekle(article_title): cevap = CevapVer(request.form) form = ArticleForm(request.form) if request.method=="POST" and cevap.validate(): icerik = cevap.icerik.data cursor2 = mysql.connection.cursor() cnt = form.content.data tit = form.title.data sorgu2 = "SELECT author FROM articles WHERE title = %s AND content = %s " cursor2.execute(sorgu2,(cnt,tit)) sonuclar = cursor2.fetchall() cevaplanan = None cursor = mysql.connection.cursor() sorgu = "insert into yorum(icerik,cevaplayan,cevaplanan) values(%s,%s,%s)" cursor.execute(sorgu,(icerik,session["username"],cevaplanan)) mysql.connection.commit() cursor.close() flash("Yorum eklendi","success") return render_template('cevapla.html', article_title=article_title, cevap=cevap) ` I was trying to get a username with sql but couldn't get it -
Order tracking in django
I am a beginner in django and I want to create a web app where a user can enter an order ID and the status of that order will be displayed(eg pending) , and If I change the status it will also change for the user(Ie from pending to processed) how do I go about it Just started out haven’t tried anything yet -
Getting csrf token and sessionid from response headers in react app
We are creating some site. We have react + django rest framework.We use SessionAuthentication in django. So, we have issues with authentication. When frontend is trying to login, he get's status 200, but he can't get csrf token and sessionid from response headers, that backend hash sent. We can see them(csrf token and sessionid) in browser Network as Set-cookie values, also we see them in Postman, but not in js. Why? How can we get them? There is part of my settings.py: MIDDLEWARE = [ "corsheaders.middleware.CorsMiddleware", 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.middleware.cache.UpdateCacheMiddleware', 'django.middleware.cache.FetchFromCacheMiddleware', 'django.contrib.messages.middleware.MessageMiddleware' ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.SessionAuthentication', ] } CORS_ALLOWED_ORIGINS = [ 'http://localhost:5173', ] CORS_ALLOW_CREDENTIALS = True CSRF_TRUSTED_ORIGINS = [ 'http://localhost:5173', ] SESSION_COOKIE_HTTPONLY = False CSRF_COOKIE_HTTPONLY = False CSRF_COOKIE_SECURE = False SESSION_COOKIE_SECURE = False CSRF_COOKIE_SAMESITE = 'None' SESSION_COOKIE_SAMESITE = 'None' I've tried many of settings, have tried to combine them in separate ways, but it didn't help There is react code: import axios from "axios"; axios.defaults.withCredentials = true; export default async function login(data){ axios.post( 'http://127.0.0.1:8000/user/session/', data ) .then( (response) => { console.log(response) // const headerKeys = Object.keys(response.headers); // console.log(headerKeys); // console.log('Set-Cookie:', response.headers['set-cookie']) }) } This is screenshot of what we get in jsresponse js This is what …