Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django-Ckeditor seems to turn dropped PDFs into .. an image?
When people drop PDF files into posts on my forum, django-ckeditor somehow magically turns it into an image of page-one! (The PDF is gone.) Now, I've peeked behind the scenes at this piece of software enough to know that "step-one should be for me to ask somebody." What's causing this behavior? (Which is very unexpected, actually ...) And, what can I do to cause the PDF to instead display as the visible attachment that the user (and, I ...) undoubtedly anticipated? Thanks in advance! -
Django: No module named 'projectxproject.urls'
I have multiple urls files in a folder with an __init__.py so it is treated as a module however Django keeps returning ModuleNotFoundError: No module named 'projectxproject.urls' Here is my folder structure, the code in my __init__.py file and my ROOT_URLCONF settings. -
Match an url with slash at the end in Django url.py
I have an endpoint: url(r'^reports/(?P<site>.*)', Scan.report) that match, for example, https://www.google.com and the same url with a slash at the end. But, when I send https://www.google.com/ my endpoint clean the final slash from the url. How can I resolve this? I need the slash at the end to be optional. And Django doesnt remove it. -
Reverse for "new_entry" not found
Working through Python Crash Course and completely hung up on this error: NoReverseMatch at /new_entry/1/ Reverse for 'new_entry' with arguments '('',)' not found. 1 pattern(s) tried: ['new_entry/(?P<topic_id>[0-9]+)/$'] Request Method: GET Request URL: http://127.0.0.1:8000/new_entry/1/ Django Version: 3.0.4 Exception Type: NoReverseMatch Exception Value: Reverse for 'new_entry' with arguments '('',)' not found. 1 pattern(s) tried: ['new_entry/(?P<topic_id>[0-9]+)/$'] Exception Location: C:\Users\KentSurface\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\urls\resolvers.py in _reverse_with_prefix, line 677 Python Executable: C:\Users\KentSurface\AppData\Local\Programs\Python\Python38-32\python.exe Python Version: 3.8.2 Python Path: ['C:\\Users\\KentSurface\\PycharmProjects\\learning_log', 'C:\\Users\\KentSurface\\AppData\\Local\\Programs\\Python\\Python38-32\\python38.zip', 'C:\\Users\\KentSurface\\AppData\\Local\\Programs\\Python\\Python38-32\\DLLs', 'C:\\Users\\KentSurface\\AppData\\Local\\Programs\\Python\\Python38-32\\lib', 'C:\\Users\\KentSurface\\AppData\\Local\\Programs\\Python\\Python38-32', 'C:\\Users\\KentSurface\\AppData\\Local\\Programs\\Python\\Python38-32\\lib\\site-packages'] Server time: Thu, 19 Mar 2020 19:40:21 +0000 Error during template rendering In template C:\Users\KentSurface\PycharmProjects\learning_log\learning_logs\templates\learning_logs\base.html, error at line 0 Reverse for 'new_entry' with arguments '('',)' not found. 1 pattern(s) tried: ['new_entry/(?P<topic_id>[0-9]+)/$'] 1 <p> 2 <a href="{% url 'learning_logs:index' %}">Learning Log</a> - 3 <a href="{% url 'learning_logs:topics' %}">Topics</a> 4 </p> 5 6 {% block content %}{% endblock %} 7 -
Django: In deployment where stays the static files of admin?
i have a web application runing, the statics files from apps works but in /admin/ seems like doesn't have a css file. In the production the admin page works fine. My question is where is the css file from admin page of django? Just in case if somebody want to check, this is my configuration of static files of the web-app in deployment STATIC_URL = '/static/' STATIC_ROOT = '/apps_wsgi/generic_name/main/static/' MEDIA_URL = '/media/' MEDIA_ROOT = '/apps_wsgi/generic_name/main/media/' -
PostgreSQL: Create extension not working when called from init script
I'm using docker-compose to create a database capable of performing a trigram similarity search using the pg_trgm extension: postgres-db: restart: always image: postgres:12.2 env_file: - ../../.envs/_compose_prod.env expose: - 5432 volumes: - database-data:/var/lib/postgresql/data/ - ../entrypoints/init.sql:/docker-entrypoint-initdb.d/init.sql ../entrypoints/init.sql: create extension pg_trgm; I used docker-compose down -v first. Here's an excerpt from the output of docker-compose up --build: postgres-db_1 | 2020-03-19 19:36:42.352 UTC [46] LOG: database system was shut down at 2020-03-19 19:36:42 UTC postgres-db_1 | 2020-03-19 19:36:42.360 UTC [45] LOG: database system is ready to accept connections postgres-db_1 | done postgres-db_1 | server started postgres-db_1 | CREATE DATABASE postgres-db_1 | postgres-db_1 | postgres-db_1 | /usr/local/bin/docker-entrypoint.sh: running /docker-entrypoint-initdb.d/init.sql postgres-db_1 | CREATE EXTENSION postgres-db_1 | postgres-db_1 | postgres-db_1 | 2020-03-19 19:36:42.643 UTC [45] LOG: received fast shutdown request postgres-db_1 | waiting for server to shut down....2020-03-19 19:36:42.647 UTC [45] LOG: aborting any active transactions postgres-db_1 | 2020-03-19 19:36:42.649 UTC [45] LOG: background worker "logical replication launcher" (PID 52) exited with exit code 1 postgres-db_1 | 2020-03-19 19:36:42.650 UTC [47] LOG: shutting down postgres-db_1 | 2020-03-19 19:36:42.686 UTC [45] LOG: database system is shut down postgres-db_1 | done postgres-db_1 | server stopped postgres-db_1 | postgres-db_1 | PostgreSQL init process complete; ready for start up. postgres-db_1 | … -
Django - Custom admin page not displaying properties
In my project, I use the AbstractUser class to override the default User model so I can add extra properties. I want these properties to be added to the admin page, therefore I can view them. The code below is how I have customized my admin page so far. forms.py: class CustomUserCreationForm(UserCreationForm): class Meta: model = User fields = ('username', 'email', 'following', 'posts') class CustomUserChangeForm(UserChangeForm): class Meta: model = User fields = ('username', 'email', 'following', 'posts', ) admin.py: class CustomUserAdmin(UserAdmin): add_form = CustomUserCreationForm form = CustomUserChangeForm model = User list_display = ['username', 'email', 'bio', 'profilePic',] When I click on a user object on the admin page, I can view all the properties such as a users username and email, however I want to view properties such as following and posts, which are both ManyToManyFields. I supply these properties in the CustomUserCreationForm and the CustomUserChangeForm, however I can't still view these properties. Does anybody know how I can view these fields when I view or create a new user object? Thank you. -
Django MEDIA_URL, unable to source image
Whenever I try to run the code below I get the error: the system cannot find the path specified: 'app_pickfeel/images/' I'm trying to source a random image from the following directory: 'PickFeel/app_pickfeel/static/app_pickfeel/images' Using a custom template tag (random_image.py) random_image.py import os import random from django import template from django.conf import settings # module-level variable register = template.Library() @register.simple_tag def random_image(image_dir): try: valid_extensions = settings.RANDOM_IMAGE_EXTENSIONS except AttributeError: valid_extensions = ['.jpg', '.jpeg', '.png', '.gif', ] if image_dir: rel_dir = image_dir else: rel_dir = settings.RANDOM_IMAGE_DIR rand_dir = os.path.join(settings.MEDIA_ROOT, rel_dir) files = [f for f in os.listdir(rand_dir) if os.path.splitext(f)[1] in valid_extensions] return os.path.join(rel_dir, random.choice(files)) html template: <img src="{{ MEDIA_URL }}{% random_image "app_pickfeel/images/" %}"> settings.py MEDIA_ROOT = '' MEDIA_URL = '/images/' STATIC_URL = '/static/' Any help would be greatly appreciated. -
Django loggers don't work when DEBUG=False
I'm using Django==2.2.11 and djangorestframework==3.11.0. When I run ./manage.py runserver and make an http request to the endpoint that has some database queries I got all the logging information. This is only when DEBUG = True. If I set DEBUG=False I won't get any logging to console at all: settings.py: DEBUG = False LOGGING = { 'version': 1, 'handlers': { 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', } }, 'loggers': { 'django.db.backends': { 'level': 'DEBUG', 'handlers': ['console'], 'propagate': False }, 'django.request': { 'handlers': ['console'], 'level': 'DEBUG', 'propagate': False }, } } -
Problem witch pyplot graphics from a same view in django
I use a view to create a graph with matplotlib. This view is like this and depend on the id_projet argument. def Graphique_view(request,id_projet): """ s'occupe de l'affichage du graphique d'un projet """ projet = Projet.objects.get(pk=id_projet) date_debut = projet.date_debut semaine_fin = delta_semaine(date_debut,projet.date_fin) f= plt.figure(figsize=(16,9)) plt.title('graphique') x1=[] y1=[] semaine = 0 ETP = 0 while semaine <= semaine_fin : compteur = 0 for bilan in Bilan_horaire.objects.filter(projet=projet): if delta_semaine(date_debut,bilan.date) == semaine : ETP += bilan.ETP compteur +=1 bilan_semaine=bilan if compteur != 0 : x1.append(bilan_semaine.date) y1.append(ETP) semaine+=1 plt.plot(x1,y1,label = 'ETP travaillés') ETP = 0 for livrable in projet.livrables : semaine = delta_semaine(date_debut,livrable.dernier_jalon.date_jalon) for utilisateur in projet.utilisateurs: ETP += ETP_ressources_livrable.objects.filter(utilisateur=utilisateur).filter(livrable=livrable).order_by('date_modification').reverse()[0].ETP_estime x=[date_debut,livrable.dernier_jalon.date_jalon,livrable.dernier_jalon.date_jalon] y=[ETP,ETP,0] plt.plot(x,y,label=livrable.libelle) myFmt = mdates.DateFormatter('S%W - %Y') axes = plt.gca() axes.xaxis.set_major_locator(mdates.DayLocator(interval=7)) axes.xaxis.set_major_formatter(myFmt) plt.xticks(rotation = '-50') plt.xlabel('temps (semaines)') plt.ylabel('heures (ETP)') plt.legend() canvas = FigureCanvasAgg(f) response = HttpResponse(content_type='image/jpg') canvas.print_jpg(response) matplotlib.pyplot.close(f) return response The url associate is projet/<int:id_projet>/graphique This is the result for projet/9/graphique for instance And this is the result for projet/10/graphique for instance Now if try to display this 2 images in a html like this : <img src="{% url 'graphique_projet' 9 %}" /> <img src="{% url 'graphique_projet' 10 %}" /> I have that which is not what I want. Any help would be appreciate. … -
Django Models relation with primary key add extra "_id" to the column
these are my two data tables, when I try to open City page on Django I got an error called : "column city.country_id_id does not exist". I dont know why python add extra _id there.. country_id = models.CharField(primary_key=True,max_length=3) country_name = models.CharField(max_length=30, blank=True, null=True) class Meta: managed = False db_table = 'country' class City(models.Model): city_id=models.CharField(primary_key=True,max_length=3) city_name=models.CharField(max_length=30, blank=True, null=True) country_id = models.ForeignKey(Country, on_delete=models.CASCADE) class Meta: managed = False db_table = 'city'``` [enter image description here][1] [1]: https://i.stack.imgur.com/Shj7x.png -
Django Rest Framework - Search Filter, How to use FilePathField with Serializer
I am using multiple fields for the search filter including a FilePathField as below : class Entity(models.Model): uuid = models.CharField(max_length=255, default="") description = models.CharField(max_length=255, default="") file = models.FilePathField(blank=False, max_length=1000, null=False) segment_start = models.PositiveIntegerField(default=0) class EntitySearchFilterSerializer(serializers.ModelSerializer): class Meta: model = Entity fields = ('uuid', 'description', 'file', 'segment_start', ) class StandardResultsSetPagination(PageNumberPagination): page_size = 5 page_size_query_param = 'page_size' max_page_size = 1000 class EntitySearchList(generics.ListAPIView): model = Entity serializer_class = EntitySearchFilterSerializer queryset = Entity.objects.all() filter_backends = [filters.SearchFilter] search_fields = ['description', ] pagination_class = StandardResultsSetPagination However, I see the following error when I introduce the FilePathField only. [19/Mar/2020 19:14:37] "GET /api/search/entity/?search=cat HTTP/1.1" 500 20295 Internal Server Error: /api/search/entity/ Traceback (most recent call last): res = instance.__dict__[self.name] = self.func(instance) File "/usr/local/lib/python3.6/dist-packages/rest_framework/serializers.py", line 363, in fields for key, value in self.get_fields().items(): File "/usr/local/lib/python3.6/dist-packages/rest_framework/serializers.py", line 1072, in get_fields fields[field_name] = field_class(**field_kwargs) File "/usr/local/lib/python3.6/dist-packages/rest_framework/fields.py", line 1535, in __init__ allow_folders=allow_folders, required=required File "/usr/local/lib/python3.6/dist-packages/django/forms/fields.py", line 1109, in __init__ for f in os.scandir(self.path): FileNotFoundError: [Errno 2] No such file or directory: '' What could be the reason for this ? -
Getting Started on Heroku with Python, Django - "Application Error"
I have been following this article https://devcenter.heroku.com/articles/getting-started-with-python I successfully did everything up until pushing local changes -> https://devcenter.heroku.com/articles/getting-started-with-python#push-local-changes I managed to run it on localhost and to display the teapot, I then did the following: git add . git commit -m "Demo" git push heroku master and finally when I run heroku open The website doesn't open anymore. It tried for 30 seconds and then comes with this message: An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details. You can do this from the Heroku CLI with the command heroku logs --tail I have no idea what I'm doing reading the logs, as I have no idea what any of it means. The errors that I can see are the following: 2020-03-19T19:13:32.915941+00:00 heroku[router]: at=error code=H20 desc="App boot timeout" method=GET path="/" and then x3 2020-03-19T19:13:53.251678+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" I don't know how to proceed from here. -
How to test uploading pdf file with APITestCase in Django Rest Framwork
from django.core.files.uploadedfile import SimpleUploadedFile from django.urls import reverse from rest_framework.test import APITestCase class BrokerTest(APITestCase): broker_url = reverse('user_registration', kwargs={'user_type': 'broker'}) @staticmethod def company_information(username, email, phone_number="+905380706512", file=None): company_valid_data = { "user": { "username": username, "first_name": "Tom", "last_name": "Jerry", "phone_number": phone_number, "password": "deneme123", "email": email }, "company": { "mc_number": 1234, "company_name": "Example Company", "file": file, } } return company_valid_data def setUp(self) -> None: file = SimpleUploadedFile('file.docx', b"file_content", content_type="documant/docx") self.broker_valid_data = self.create_broker_information(username='deneme', email='deneme12@gmail.com', file=file) def test_create_broker(self): responce = self.client.post(self.broker_url, self.broker_valid_data, format='json') //400 Bad Request !!!! self.assertEqual(200, responce.status_code) -
aiohttp network call is taking too much time within a django view
So, I wanted to build an api that takes a bunch of domains and used a third part api to fetch information regarding them and send the result to frontend. As i wanted the response time of api to be faster which constitutes of multiple network calls, sync way was not possible. So in my api i divide the domains in batch of certain size, call a celery task on each batch, celery task perform multiple network calls using asyncio and aiohttp. My code is : The api endpoint is : class BulkDomainCheckerView(APIView): def post(self, request): domains = request.data.get("domains") from math import ceil from itertools import islice num_domains = len(domains) Inputt = iter(domains) # slicing domains in 500 size batch domain_lists = [list(islice(Inputt, 500)) for e in range(ceil(num_domains / 500))] total_go_daddy_batch_size = len(domain_lists) Inputt = iter(domain_lists) # Make again a batch of size 5 of those batches in domain_lists domain_lists = [list(islice(Inputt, 5)) for e in range(ceil(total_go_daddy_batch_size / 5))] i = 1 for domain_batch in domain_lists: start = time() check_domain_avalaibality_async.apply_async([domain_batch, i, start], queue='celery_default_tools') i = i + 1 return success_response(status=HTTP_200_OK, msg="", data=[]) Celery Task: @app.task def check_domain_avalaibality_async(domain_batch, batch, start): asyncio.run(fetcher(domain_batch, batch)) Async code: async def fetch(session, domains, idx, batch): t … -
YearArchiveView.date_field is required. ImproperlyConfigured
I open up the documentation to Django. I try to use the (YearArchiveView) view. when I go through the URL index/2020/ I get this error( YearArchiveView.date_field is required. ) what I understand that I have to use the attribute that called date_field and I already use. so, how can I fix that error? also, I need to know how can I access on this URL by any link into another page?, like from index.html views.py from django.shortcuts import get_object_or_404, Http404, render_to_response from django.views.generic import ListView, DetailView from .models import Article, User from .forms import ContactForm from django.views.generic.edit import FormView from django.urls import reverse_lazy from django.views.generic.dates import ArchiveIndexView, YearArchiveView class ArticleYearArchiveView(YearArchiveView): queryset = Article.objects.all() template_name = 'index/article_archive_year.html' date_field = "date" allow_future = True urls.py from . import views from django.urls import path urlpatterns = [ path("<int:year>/", views.YearArchiveView.as_view(), name="article_archive_year") ] artcile_archive_year.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Archive year</title> </head> <body> {% for date in date_list %} <li>{{ date|date }}</li> {% endfor %} </body> </html> -
Is there some way to "lock" page in case another user is editing - DJANGO
I need some help. I got a page and I can switch it to another view where I got a form and I can change some texts on that page and save it. Is there any way how to lock/hide button if some user is editing, so another user can not access the editing form page and is only allowed to see the "view" of the page. I want to implement, so two users will not be able to edit page at the same time. I was trying to find something on the internet but I did not found anything useful for DJANGO. Thanks a lot for some recommendation how to do it. -
argparse library conflict between Django and Google Cloud SDK - how to resolve
I am trying to run my Django app in PyCharm and getting the following error: TypeError: __init__() got an unexpected keyword argument 'allow_abbrev' (This only occurs when I run it from the 'Run' menu in PyCharm, not from the terminal). The error comes from django.core.management.base.py. The CommandParser class in there inherits from ArgumentParser, but the interpreter is mixing up the standard from argparse import ArgumentParser, which does have the keyword argument allow_abbrev, with the ArgumentParser in the Google Cloud SDK, which doesn't have the argument allow_abbrev. I believe this only started when I upgraded the Google Cloud SDK tools. I am running a virtual environment with a recent version of Python but I am confused as to how it is picking up Google's ArgumentParser instead of the one Django is expecting. -
django gunicorn app spams the console with "Not Found: /api/templates/menu_main/" every second or so
I've built a simple django app and I'm working on dockerizing it. I'm able to create the image and start it. It even works fine locally via "docker run -it -p 8000:8000 project:0.1". However, the project logs this message to the console about every seconds or so: Not Found: /api/templates/menu_main/ I don't have a rest api or anything in the app, just a couple tables and several views. Here's requirements.txt: beautifulsoup4==4.8.2 certifi==2019.11.28 chardet==3.0.4 Django==2.0.7 django-auth-ldap==2.1.0 django-background-tasks==1.2.5 django-bootstrap4==1.1.1 django-compat==1.0.15 django-phone-field==1.8.0 gunicorn==20.0.4 idna==2.9 mysqlclient==1.4.6 psycopg2==2.8.4 pyasn1==0.4.8 pyasn1-modules==0.2.8 PyJWT==1.7.1 python-ldap==3.2.0 pytz==2019.3 requests==2.23.0 six==1.14.0 soupsieve==2.0 twilio==6.36.0 urllib3==1.25.8 whitenoise==5.0.1 Googling for the error message didn't reveal anything that I could act on. Any idea what the message means? How do I stop it from filling up the logs? Thank you! -
filters inside django trans tag : first translates then applies filters; unlike other tags
I encountered a weird behavior from django trans tag. As you know whenever we use a filter inside a tag, the filter first applies and then gives the result as input to the tag. But this is in reverse order for trans tag. Example: Suppose I have this django.po file: msgid "msgid-world" msgstr "world" msgid "msgid-" msgstr "message" Now see the result of these tags: {% trans "msgid-"|add:"world" %} result: messageworld (first translate then concat) Expected result: "world" (first concat then translate the key) -
Can I use the field of a related model in a Django UniqueConstraint?
Is it possible to make a UniqueConstraint using the field of a foreignkey model? For example, how could I constrain all books written by authors of the same age to have a unique title? (A contrived example, but you get the idea.) models.py: class Author(models.Model): name = models.CharField(max_length=100) age = models.IntegerField() class Book(models.Model): class Meta: contraints = [ models.UniqueConstraint( # THIS DOESN'T WORK fields=["author__age", "title"], name="my_constraint", ) ] title = models.CharField(max_length=100) author = models.ForeignKey(Author, related_name="books") This gives the following error: django.core.exceptions.FieldDoesNotExist: Book has no field named 'author__age ' -
NameError at /register/ name 'user' is not defined
I am currently developing a blogging webapp and I tried to extend my Django User Framework With a One To One Field, everything is working fine, but when I'm trying to register a new user, it's throwing a NameError. It is also worth noting that the user is being created and stored(I checked it from the admin page). It is saying that this statement profile.user = user in my views.py is creating the problem. Can anyone please help me with this? my views.py from django.shortcuts import render, redirect from django.contrib import messages from django.contrib.auth.decorators import login_required from .forms import UserRegisterForm, ProfileForm def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) profile_form = ProfileForm(request.POST) if form.is_valid() and profile_form.is_valid(): form.save() profile = profile_form.save(commit=False) profile.user = user profile.save() username = form.cleaned_data.get('username') messages.success(request, f'Your account has been created! You are now able to log in') return redirect('login') else: form = UserRegisterForm() profile_form = ProfileForm return render(request, 'users/register.html', {'form': form, 'profile_form': profile_form}) @login_required def profile(request): return render(request, 'users/profile.html') my models.py from django.db import models from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') CHOICES = ( ('AB+', 'AB+'), ('AB-', 'AB-'), ('A+', 'A+'), ('A-', 'A-'), ('B+', 'B+'), ('B-', 'B-'), ('O+', 'O+'), … -
Pass query and html from views to modal popup
I have background page: views: @login_required def dashboard(request): return render(request, 'app/dashboard.html') and html: {% extends 'app/basenobar.html' %} {%load staticfiles %} <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <body> {% block content %} <body> <a href="#" id="winOpener2">Open PopUp</a> <div id="window2" title="Test Window"> {% for member in family %} {{ member.pk }} {% endfor %} </div> Now, if I click on the button it open popup and everything work but I need to pass a query from view to popup body For example, I have a query in a view: @login_required def myquery(request): family = Books.objects.all() return render(request, 'app/myquery.html', {family:'family'}) and I need to pass this values inside my popup when I click for open it. Any idea? -
UML association class and OOP languages
I am building a web application with Django, I did the design app with UML2. i read that association class concept does not exist in object oriented programming languages, is that true ?? thank you. class diagram -
Django autocomplete-light
I have used autocomplete-light in my django form to fetch the names from person table. Also I have to create the new person record, when ever the name I search for does not exist. This works fine for me. Now I want to add some more additional details(ideally with a new window to fill details) for the person as a input from the users when ever they select the option to create new users . enter image description here