Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django REST framework returns 400 error in test
FAIL: test_post (ecapp.tests.test_api.ProductApiTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Users\lion-\Desktop\portfolio\ecapp\tests\test_api.py", line 82, in test_post self.assertEqual(response.status_code, status.HTTP_201_CREATED) AssertionError: 400 != 201 I get this Error when I run test below test_api.py from django.core.files import File from django.core.files.uploadedfile import SimpleUploadedFile from django.test import TestCase, Client from django.test.client import encode_multipart from django.urls import reverse from django.utils.timezone import localtime from faker import Faker from rest_framework import status from rest_framework.test import APIRequestFactory, force_authenticate, APIClient, APITestCase from ..models import Product from ..views import ProductViewSet from .factories import ProductFactory, UserFactory class ProductApiTest(APITestCase): def test_post(self): user = UserFactory() view = ProductViewSet.as_view({'post': 'create'}) filename = 'test_img' file = File(open('static/default_icon.jpg', 'rb')) uploaded_file = SimpleUploadedFile( filename, file.read(), content_type='multipart/form-data') client = APIClient() client.force_authenticate(user=user) data = { 'name': 'test', 'description': 'test', 'price': 1, 'amount': 1, 'image': uploaded_file, 'owner': 1 } url = reverse('product-list') response = client.post(url, data, format='multipart') self.assertEqual(response.status_code, status.HTTP_201_CREATED) self.assertEqual(Product.objects.count(), 1) factories.py import factory.fuzzy import random import datetime from django.contrib.auth import get_user_model class UserFactory(factory.django.DjangoModelFactory): class Meta: model = get_user_model() django_get_or_create = ('username',) email = factory.Sequence(lambda n: f'person{n}@example.com') username = factory.Faker('name') address = factory.Faker('address') icon = factory.Faker('image_url') message = factory.Faker('word') last_login_date = datetime.date.today() models.py from django.db import models class Product(models.Model): """商品""" name = models.CharField(max_length=100) description = models.TextField(blank=True) price = models.PositiveIntegerField(default=0) amount = … -
Wagtail models.py: How to create Custom folder in Media?
In Wagtail, How to add custom folder in Media and sync it into the database (Example) ? NOTE: The Wagtail's Collection function is good, but for more than 1000 images/documents into a single folder will be pretty awkward to manage for I in the future (Ex: migration,...), so there is nothing to mention about Collection function in this question. # If in Django (models.py) works: class post(models.Model): img = models.ImageField(upload_to='posts') # So how in Wagtail (models.py) works: class Posts(models.Model): img = models.ForeignKey( "wagtailimages.Image", 👉🏽 upload_to='posts', # How to add this line correctly ? on_delete=models.SET_NULL, null=True, blank=False, related_name="+", ) Idea for Media Folder in Wagtail: Media authors images original_images posts images original_images ... -
Method Not Allowed — Django Put-Method
I have this API View: class NewWordList(APIView): def put(self, request, *args, **kwargs): word_list = Word.objects.filter(user=request.user) for word in word_list: word.currently_studying = False word.save() words = [] default_word_list_length = request.user.profile.word_list_length for word in word_list: words.extend([word.id] * (6 - word.level)) word_list_length = default_word_list_length if len(word_list) >= default_word_list_length else len(word_list) for i in range(word_list_length): selected_word = random.choice(words) selected_word_object = Word.objects.filter(id=selected_word).first() selected_word_object.currently_studying = True selected_word_object.save() words = [i for i in words if i != selected_word] messages.success(request, 'Your wordlist have been changed successfully!') return Response({}, status=204) In settings.py DEFAULT_RENDERER_CLASSES = [ 'rest_framework.renderers.JSONRenderer', ] if DEBUG: DEFAULT_RENDERER_CLASSES += ['rest_framework.renderers.BrowsableAPIRenderer'] REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": [ 'rest_framework.authentication.SessionAuthentication' ], 'DEFAULT_RENDERER_CLASSES': DEFAULT_RENDERER_CLASSES } The put() function goes through the user's Word objects, and changes each Word Object's currently_studying. I got Method Not Allowed: /my-url-path/. I also tried replacing put with post, but it gets the same result. When I run it in the url path, it works (but it still gives the Method Not Allowed), but it doesn't work when I'm making a XMLHttpRequest. How do I fix this? -
How to create and update two separate table in Django-rest viewset
I am currently working on a bookmarking function, where it allows the user to add bookmarks to the book in the bookcase. Before creating the bookmark instance the function should detect the following requirement: If the book exists, then creates the bookmark instance and link the bookcase to the bookmark If the book exists, and bookmark exists, then update the bookmark with a new chapter id if the book does not exist, then add the book to the bookcase and create a bookmark for it. Model.py class BookMark(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='User', blank=True, null=True, related_name='user_marked') chapter = models.ForeignKey(Chapter, on_delete=models.CASCADE, verbose_name='Chapter', related_name='marked_chapter', blank=True, null=True) class Bookcase(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='User bookcase') book = models.ForeignKey(Book, on_delete=models.CASCADE, verbose_name='Book', blank=True, null=True) bookmark = models.ForeignKey(BookMark, on_delete=models.CASCADE, verbose_name='bookmark', related_name='marked_book', blank=True, null=True) serializer.py class BookCaseDetailSerializer(serializers.ModelSerializer): book = BookSerializer() class Meta: model = Bookcase fields = ('user', 'book', 'id') class BookMarkSerializer(serializers.ModelSerializer): user = serializers.HiddenField( default=serializers.CurrentUserDefault() ) class Meta: model = BookMark fields = '__all__' class BookMarkDetailSerializer(serializers.ModelSerializer): class Meta: model = BookMark fields = '__all__' class BookCaseSerializer(serializers.ModelSerializer): user = serializers.HiddenField( default=serializers.CurrentUserDefault() ) class Meta: model = Bookcase validators = [ UniqueTogetherValidator( queryset=Bookcase.objects.all(), fields=('user', 'book'), message='Already existing in the bookcase' ) ] fields = ('id','user', 'book', 'bookmark') view.py … -
Pycharm django test not using new manage.py
I have modified manage.py to use different settings files based on whether I am running the django app or tests. When I do python manage.py test modified manage.py runs fine. But when I run a django test server from Pycharm, it does not run new manage.py file. I tried following things: recreating the Django tests configuration in Pycharm Restarting pycharm -
Django/Sqlite3 Module Load Path in Python Virtual Environment
I've developed a website in Django (3.0.8) using the latest Python version (3.8.3). The web server that is hosting the site only has Python 3.6.9 installed, which includes Sqlite version 3.7.17. Django apparently requires Sqlite 3.8 or higher... So, I compiled a local copy of the latest Python following the guide here: https://www.a2hosting.com/kb/developer-corner/python/using-a-newer-version-of-python I set up a virtual environment as described above and everything is working smoothly, except that Python is still using the old Sqlite dll. After hours of work trying to figure all this out I'm stumped. I can access Python and Sqlite3 via command line in standard environment: -bash-4.2$ python --version Python 3.6.9 -bash-4.2$ python >>> import sqlite3, inspect >>> sqlite3.sqlite_version '3.7.17' >>> inspect.getfile(sqlite3) 'opt/rh/rh-python36/root/usr/lib64/python3.6/sqlite3/__init__.py' and in virtual environment: -bash-4.2$ source bin/venv/bin/activate (venv) -bash-4.2$ python --version Python 3.8.3 -bash-4.2$ python >>> import sqlite3, inspect >>> sqlite3.sqlite_version '3.7.17' >>> inspect.getfile(sqlite3) 'users/.../lib/python3.8/sqlite3/__init__.py So, despite running Python 3.8.3 and pointing to the correct library (as far as I can tell) in the virtual environment, the sqlite version is still the same as the standard environment. Any suggestions would be greatly appreciated! -
Testing a class based Django view which returns a JsonReponse
What is the proper way to test a class based Django view which returns a JsonResponse type. For example, the beginning of my class looks like this: class MyView(LoginRequiredMixin, View): def get(self, request): return JsonResponse({ "status": 200, "message": "message to return." }) I have similar 'post' and 'delete' functions. The url /myview is connected to this view. When I attempt something like this: c = Client() response = c.get('/myview') 'response' is a HttpResponsePermanentRedirect type, and I am unsure how the JSON data can be obtained from that. -
Wagtail: Prevent same page editing collision Example?
I am new to Wagtail CMS, I found this question. I know WordPress have the function preventing same page editing (Example). 👉🏽 But in Wagtail how to do it ? I have not known how and where to write the correct code yet. I would like to know some Code Examples about it. -
Python web app running on django with cPanel showing error: page not found
I didn't face this issue 1 month ago, all of a sudden my web app shows this error when I go to a particular page. Page not found (404) Request Method: POST Request URL: https://database.opticscouting.com/admin/users/player/1/change/ Raised by: django.contrib.admin.options.change_view Using the URLconf defined in opticdb.urls, Django tried these URL patterns, in this order: admin/ [name='login'] logout/ [name='logout'] password-change/ [name='password_change'] dashboard/ [name='dashboard'] player/<int:pk>/ [name='player'] favorites/ [name='favorites'] favorite/<int:pk>/ [name='favorite'] The current path, player/1/change/, didn't match any of these. The python version running on the site is 3.3.7. The error log looks like this: App 633453 output: /opt/passenger-5.3.7-4.el6.cloudlinux/src/helper-scripts/wsgi-loader.py:26: DeprecationWarning: the imp module is deprecated in favour of importlib; see the module's documentation for alternative uses App 633453 output: import sys, os, re, imp, threading, signal, traceback, socket, select, struct, logging, errno App 633453 output: [ pid=633453, time=2020-06-27 15:18:00,715 ]: Not Found: /admin/users/player/1/change/ -
How to lock out users when they input wrong password three time in python django
I try to write a login page that will lock the user by inputting the wrong password three times and the username will go to the blacklist so that it will be locked. The login page works well and the blacklist works well. One problem is the loop does not work, I had while count < 3 in the beginning, but it only gives the user one chance to input password, then I rewrite the code as if ... elif... format to check what goes wrong. What I find is it stuck on "1 Username or Password is incorrect 1" which means it only goes to the first if and the count always is 1 which means the count goes back 0 every time. I think that because after the user clicks the login button, the page refresh and makes the count 0 again, so how should I solve it? @unauthenticated_user def loginPage(request): if request.method == "POST": username = request.POST.get('username') # Get username input first password = request.POST.get('password') user = authenticate(request, username=username, password=password) BL = BlackList.objects.values_list('list', flat=True) # Read all data into array if username in BL: # Check if the username is in blacklist messages.info(request, 'Username in black list, … -
Using Markdown2
I have never asked a question here before, please bear with me. I am working on a wiki project that has a requirement to convert markdown files using markdown2. return render(request, "encyclopedia/entry.html", { "content": markdown2.markdown(util.get_entry(title)), "title": title }) Above is how I pass it to the HTML page and it renders on the page with the proper HTML tags, but it doesn't seem to use them. Below is how it appears on the browser. <pre><code> # HTML </code></pre> <p>HTML is a markup language that can be used to define the structure of a web page. HTML elements include</p> <ul> <li>headings</li> <li>paragraphs</li> <li>lists</li> <li>links</li> <li>and more! most recent major version of HTML is HTML5.</li> </ul> I am passing it directly to a Django template with the safe filter included as shown below. <textarea name="content" rows="5" cols="50" readonly> {{ content|safe }} </textarea><br> Thank you ahead of time, I hope I provided enough information to make my problem clear. -
Django ImageField does not validate image
I can upload the code, however it is a very basic form that has an ImageField and a Model with and ImageField, however I can upload any file type. I have installed PIL and I am successfully writing the uploaded files to the media directory but as I stated, they can be whatever I like as no validation appears to be happening. -
No changes done by static function in HTML in Django
Html File <!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <title>Hello World</title> <link rel="stylesheet" type="text/css" href="{% static "css/style.css" %}"/> </head> <body> <h1>This is from index.html</h1> {{help_me}} <img src="{% static "images/DjangoGuitar.jpg" %}" alt="sorry text not loaded"> </body> </html> CSS file h1{ color: red; } Output: This is from index.html Welcome to the page sorry text not loaded -
Django channel Error "took too long to shut down and was killed."
I am getting this error on my console log, and on form submit it keeps loading not posting data to server. /home/Python/Working/Benutzerverwaltung/env/lib/python3.6/site-packages/channels/sessions.py:183> wait_for=<Future pending cb=[<TaskWakeupMethWrapper object at 0x7fab9fe51408>()]>> for connection <WebSocketProtocol client=['127.0.0.1', 59462] path=b'/ws/stream/Sales'> took too long to shut down and was killed. I have tried several solution provided on internet, but unfortunately no one worked. Here is my code for closing channel. async def disconnect(self, code): async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel ) await self.close() async def websocket_disconnect(self, event): print("Disconnect", event) await self.send({ "type": "websocket.close" }) Any one who know about this issue, and can help me to fix this would be very helpful. because it's happening on production. -
Django REST: ManyToMany field - don't update other records
The employees field is a list of users which are employees of the user. Every user can have every user as employee, a user can also be an employee and have employees. I have a problem where it automatically adds the user as an employee to all the employees added to the user. So when you add user 2 as employee to user 1, it also adds user 1 as employee of user 2. How can I make it so it doesn't change other records? I simply want to add employees to the user being added. I'm using Django REST 2.2. The employees field is a ManyToMany field, is this incorrect for my usage? users/models.py class MyUserManager(BaseUserManager): def create_user(self, email, password=None): if not email: raise ValueError('Users must have an email address') user = self.model( email=self.normalize_email(email), ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password): user = self.create_user( email=self.normalize_email(email), password=password, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class CustomUser(AbstractBaseUser): username = None email = models.EmailField(verbose_name='email address', max_length=255, unique=True) date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_employee = models.BooleanField('is_employee', default=False) employees … -
Django 2 socket timeout errors in django core
I am upgrading a Django application from 1.11 to 2.2 and I am seeing new errors come from the Django core library Exception happened during processing of request from ('127.0.0.1', 57226) Traceback (most recent call last): File "/usr/lib/python3.7/socketserver.py", line 650, in process_request_thread self.finish_request(request, client_address) File "/usr/lib/python3.7/socketserver.py", line 360, in finish_request self.RequestHandlerClass(request, client_address, self) File "/usr/lib/python3.7/socketserver.py", line 720, in __init__ self.handle() File "/home/<user>/venv/lib/python3.7/site-packages/django/core/servers/basehttp.py", line 171, in handle self.handle_one_request() File "/home/<user>/venv/lib/python3.7/site-packages/django/core/servers/basehttp.py", line 179, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "/usr/lib/python3.7/socket.py", line 589, in readinto return self._sock.recv_into(b) socket.timeout: timed out The only new thing done to the code base was a version upgrade from Django 1.11 to 2.2 and none of the code referenced is part of my code base. The application calls its own api in some spots but I do not know where the core problem lies outside of the Django core library -
How to insert multiple data in one field in database in a form of Django
I am newbie in coding. Could some help me on my problem? I have a table in Database named Siblings with a field named sibname. In my form I displayed two(2) textbox where user can put 2 siblings. I want those data to save in sibname upon saving. Thank you. Regards, Ian -
Django Models - Link multiple users to one city?
How can the persons row be fixed so that multiple persons can be associate with a given city instead of just one person. class City(models.Model): cityname = models.CharField(max_length=255) persons = models.ForeignKey(User, on_delete=models.CASCADE) -
__str__ returned non-string (type NoneType) django 3.0.8
I tried every solution: return str(self.transaction_id) & return format think like that & return str(self.transaction_id) if self.transaction_id' ' -
H10 error: Failed to find attribute 'app' in 'Project'
I cant seem to find anything online to help with this... In my Project Directory 2020-07-11T21:32:30.429053+00:00 heroku[web.1]: Starting process with command `gunicorn Project:app` 2020-07-11T21:32:33.237673+00:00 heroku[web.1]: Process exited with status 4 2020-07-11T21:32:33.276690+00:00 heroku[web.1]: State changed from starting to crashed 2020-07-11T21:32:33.279492+00:00 heroku[web.1]: State changed from crashed to starting 2020-07-11T21:32:33.081762+00:00 app[web.1]: [2020-07-11 21:32:33 +0000] [4] [INFO] Starting gunicorn 20.0.4 2020-07-11T21:32:33.082711+00:00 app[web.1]: [2020-07-11 21:32:33 +0000] [4] [INFO] Listening at: http://0.0.0.0:26233 (4) 2020-07-11T21:32:33.082944+00:00 app[web.1]: [2020-07-11 21:32:33 +0000] [4] [INFO] Using worker: sync 2020-07-11T21:32:33.088701+00:00 app[web.1]: [2020-07-11 21:32:33 +0000] [9] [INFO] Booting worker with pid: 9 2020-07-11T21:32:33.093101+00:00 app[web.1]: Failed to find attribute 'app' in 'Project'. 2020-07-11T21:32:33.093289+00:00 app[web.1]: [2020-07-11 21:32:33 +0000] [9] [INFO] Worker exiting (pid: 9) 2020-07-11T21:32:33.131174+00:00 app[web.1]: [2020-07-11 21:32:33 +0000] [4] [INFO] Shutting down: Master 2020-07-11T21:32:33.131273+00:00 app[web.1]: [2020-07-11 21:32:33 +0000] [4] [INFO] Reason: App failed to load. -
Django Rest Framework API View
In views.py @api_view(['PUT']) @permission_classes([IsAuthenticated]) def update_word_list_view(request, *args, **kwargs): serializer = WordListSerializer(data=request.data) if serializer.is_valid(raise_exception=True): word_list = Word.objects.filter(user=request.user) for word in word_list: word.currently_studying = False word.save() words = [] default_word_list_length = request.user.profile.word_list_length for word in word_list: words.extend([word.id] * (6 - word.level)) word_list_length = default_word_list_length if len(word_list) >= default_word_list_length else len(word_list) for i in range(word_list_length): selected_word = random.choice(words) selected_word_object = Word.objects.filter(id=selected_word).first() selected_word_object.currently_studying = True selected_word_object.save() words = [i for i in words if i != selected_word] messages.success(request, 'Your wordlist have been changed successfully!') return Response({}, status=204) return Response({}, status=500) serializers.py class WordListSerializer(serializers.ModelSerializer): class Meta: model = Word fields = ['word', 'id', 'user', 'definition', 'synonym', 'sentence', 'user', 'currently_studying'] I have a model Word, and I want it to modify all the currently_studying field for all the user's Word in this view. Instead, I get Bad Request, 400, 404, and 405. How do I fix it? -
Send JsonResponse with related objects
I want to send JsonResponse with related objects. Here's my playground. I do it as def get_stocks(qty=9): return Stock.objects.values()[:9] # Returning stocks stocks = api_services.get_stocks() return JsonResponse(list(stocks), safe=False) My models are like class Sector(models.Model): name = models.CharField(max_length=200, null=True, blank=True) original_name = models.CharField(max_length=200) slug = models.CharField(max_length=200) class Industry(models.Model): name = models.CharField(max_length=200, null=True, blank=True) original_name = models.CharField(max_length=200) slug = models.CharField(max_length=200) class Stock(models.Model): name = models.CharField(max_length=200) ticker = models.CharField(max_length=200, unique=True) logo = models.CharField(max_length=200, null=True, blank=True) website = models.CharField(max_length=200, null=True, blank=True) sector = models.ForeignKey(Sector, on_delete=models.CASCADE, null=True) industry = models.ForeignKey(Industry, on_delete=models.CASCADE, null=True) How can I get my json with related objects? Now I get 0 Object { id: 1, name: "Tesla", ticker: "TSLA", … } id 1 name "Tesla" ticker "TSLA" logo null website "http://www.tesla.com" sector_id 1 industry_id 1 I need to get sector and industry as well -
Django cannot find static files 404
Here's my settings: import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static/') Here's my project directory: root blog-app/ static/ styles.css templates/ migrations/ models.py views.py urls.py admin.py tests.py static/ css/ styles.css media/ manage.py .gitignore I have run python3 manage.py collectstatic already. But when I tried to access my page, it always says "GET /static/css/style.css HTTP/1.1" 404 1766 Here's how I'm loading it in my .html file: {% load static %} <link rel="stylesheet" href="{% static 'css/styles.css' %}"> I googled a lot and tried this way {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}"> still, got the same 404 error, anyone could help shed any light would be greatly appreciated! -
Django - How to serialize (and later iterate through) list of dictionaries?
I am having hard time with serializing data from API since this is the first time that I am doing this. I would like to ask you for your help. From API i receive dictionary with some keys. Value for key "Search" is list of dictionaries that I would like to print in a for loop in my template later. But I failed. Here are my results that I managed to put together from few hours of googling and browsing through stack overflow. Here is my views.py: def results(request): title = request.POST.get("Title") api_key = "111111" url = f"http://www.omdbapi.com/?s={title}&type=movie&apikey={api_key}" response = requests.get(url) serializer = SearchListSerializer(data=response.json()["Search"], many=True) if serializer.is_valid(): serializer.save() movies = serializer.objects.all() else: print(serializer.errors) print("Something went wrong.") return render(request, 'movie_database/results.html', movies) And here is my serializers.py: class MovieSerializer(serializers.ModelSerializer): class Meta: model = Movie fields = '__all__' class SearchSerializer(serializers.DictField): Title = serializers.CharField(max_length=300) Year = serializers.CharField(max_length=100) class SearchListSerializer(serializers.ListField): child = SearchSerializer() I currently receive error: TypeError at /results/ __init__() got an unexpected keyword argument 'data' But I know that it is only a tip of the iceberg. And one of the problems. -
Pandas-Django Dataframe read and flattening *extremely* slow
i'm using pandas and i'm trying to solve this issue, basically i have many measurements in a Postgres database with a JSON field that contains measurements like shown below: { "Hz":50.026, "IL1":0.549, "IL2":0.241, "IL3":0.371, "PL1":0.018, "PL2":0.01, "PL3":0.015, "VLN1":236.181, "VLN2":237.243, "VLN3":236.377, "IL_AVG":0.387, ... } So, this is my code, i don't know why, but i'm expecting very high performances from pandas (my database has more of 150 millions of measurements!), but with only 85k of measurement it will take 14 seconds to render the chart... df = read_frame(self.queryset) #Here it seems where the bottleneck is present (4 seconds to read frame) df = df.join(json_normalize(df["data"].tolist()).add_prefix("data.")).drop(["data"],axis=1) # Json flattening also here it seems that there is a bottleneck present (5 seconds to flatten the JSON) plot = df.plot(x='insert_time', y=['data.VLN1', 'data.VLN2', 'data.VLN3']).get_figure() The rest of the time (3 seconds) is spent on on DB for a simple query of selection with a time filter and an order by clause. I know that my test environment is my dev-workstation (MBP16"-2019), but i was not expecting those bad results