Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Nothing happens when I run 'py manage.py runserver'
I am following the tutorial on the Django website. I have changed the directory to where mysite is and nothing happens when I run the script from the tutorial in the Command Prompt. It just goes to the next line with no errors. I read from previous responses it has to with Environment Variables but when I added the directory it still did not work. I have the latest version of Python and Django. -
dockerized django gunicorn nginx doesn't find static files when i add URL to urls.py
This is really weird and i've tried fixing it for over 20 hours over the past few days, but no luck. This is a project that i'm trying to dockerize and it's almost done except for being able to show static files. My issue is that the static files aren't being served when I add the URL to the urls.py file that is creating a path to my index app. Basic urls.py (main project urls.py) from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), ] If I visit http://localhost:8000 the admin static files are shown perfectly with no issues at all with the config above. If I then add the URL to my index app like the following inside urls.py (main project urls.py) from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('index.urls', namespace="index",)), ] And once again I navigate to http://localhost:8000 and this time the static files aren't being shown! I am baffled and honestly have no idea. I have the full source code available on Github. Feel free to take a look in there, clone the project and try for yourself. -
Django tries to find template in a non-existing folder
I'm new to Django and I'm following the guide at https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django. So I thought I would follow along but not entirely copy the code. I must have made some basic mistake, but I can't figure it out. I read many threads describing similar problems but none solved mine. When I try to access any page other than index.html I get this Error message: TemplateDoesNotExist at /catalog/livros/ catalog/livro_list.html Template-loader postmortem Django tried loading these templates, in this order: Using engine django: django.template.loaders.filesystem.Loader: C:\Users\Gledyson\PROJECTS\Websites\Library\templates\catalog\livro_list.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\Gledyson\PROJECTS\Websites\Library\myvenv\lib\site-packages\django\contrib\admin\templates\catalog\livro_list.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\Gledyson\PROJECTS\Websites\Library\myvenv\lib\site-packages\django\contrib\auth\templates\catalog\livro_list.html (Source does not exist) Django is trying to find my templates in 'templates/catalog/' instead of 'templates/'. I tried moving my templates to 'library/catalog/templates/catalog/' and it works. But I can't manage to make it find my template in 'library/templates'. My project tree looks somewhat like this: Library/ | -- catalog/ | | | -- static/, admin.py, apps.py, models.py, tests.py, urls.py, views.py | -- locallibrary/ | | | -- settings.py, urls.py, wsgi.py -- myvenv/ | -- templates/ | -- base.html, index.html, livro_detail.html, livro_list.html My locallibrary/settings.py is: 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__))) # Quick-start development settings - unsuitable for … -
Serializer is not valid
When I try to make a POST request to my API endpoint to create a user in my Users table, I get mysterious Serializer errors. The error says that the email, password, codename (3 strings needed to create a user) are required. But I am sending all three strings. It is because the serializer is NOT valid (go to serializers.py, the if serializer.is_valid() check)... but I can't figure out why it's not valid. Entire said error message: {'codename': [ErrorDetail(string=u'This field is required.', code=u'required')], 'password': [ErrorDetail(string=u'This field is required.', code=u'required')], 'email': [ErrorDetail(string=u'This field is required.', code=u'required')]} All these files are in my users folder within my Django directory. serializers.py: from rest_framework import serializers from .models import User class UserPostSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('email', 'password', 'codename') views.py: from rest_framework.response import Response from rest_framework.decorators import api_view from rest_framework import status from .serializers import * from .models import User from argon2 import PasswordHasher import json @api_view(['POST']) def create_user(request): print("inside create_user") """ POST = Create user. """ data = {} # print("request.data:\n", request.data) serializer = UserPostSerializer(data=request.data) print("got serializer") if serializer.is_valid(): print("serializer is valid!") email = serializer.data['email'] codename = serializer.data['codename'] password = serializer.data['password'] user = User.objects.filter(email=email) if not user: # Apply Argon2 … -
Modify QuerySet data and return a paginated QuerySet in Django REST API
I want to create an API endpoint that returns all upcoming products. If a product is upcoming is determined by the values release_date and timezone. To reduce the database load I want to return a paginated result. The problem is that I need to call a function on every entry that can't be achived by SQL (as far as I know). The following code works but it's very inefficient because first I load all data from the database, then I filter it by calling the is_upcoming() function and then I'm creating another queryset with the filtered products. Is there a way to improve the code so to make the filtering directly in the query? # views.py class ListProducts(ListAPIView): # ... def get_queryset(self): products = Product.objects.all() upcoming_products = [product.pk for product in products if product.is_upcoming()] return Product.objects.filter(pk__in=upcoming_products) # models.py class Product(models.Model): # ... release_date = models.DateTimeField() timezone = timezone = models.CharField(max_length=100, choices=TIMEZONE_CHOICES) def is_upcoming(): timezone = pytz.timezone(self.timezone) return now().astimezone(tz) < self.release_date.astimezone(tz) -
Searching for a Python-Mentor
I am currently learning Python with Mosh's Python online course on codewithmosh.com and I was wondering if there is someone who would be interested in becoming "a mentor". What would that mean? In case that I have questions, I would send you a message on Discord, WhatsApp, .. (whatever you prefer) to get some help. Maybe you could even teach me some stuff. Therefore, If I learn the language, we could maybe start projects together and I could help you as much as I can in return - while learning. There are probably people who think this is a waste of time and it is totally fine for me if you have that opinion, but I would like to please you to accept my request and not blaming me for it. I am really willed to learn the language, but as a not-native-english speaker it is tough. To make it a bit easier, I am looking for the mentor thingy. If you are interested, just send me a message on Discord (Mievo#6594) or answer on this post. Thank you in advance! :) PS: I'm a 27 year old nurse and student from Germany. -
Improve Django queryset performance when using annotate Exists
I have a queryset that returns a lot of data, it can be filtered by year which will return around 100k lines, or show all which will bring around 1 million lines. The objective of this annotate is to generate a xlsx spreadsheet. Models representation, RelatedModel is manytomany between Model and AnotherModel Model: id field1 field2 field3 RelatedModel: foreign_key_model (Model) foreign_key_another (AnotherModel) Queryset, if the relation exists it will annotate, this annotate is very slow and can take several minutes. Model.objects.all().annotate( related_exists=Exists(RelatedModel.objects.filter(foreign_key_model=OuterRef('id'))), related_column=Case( When(related_exists=True, then=Value('The relation exists!')), When(related_exists=False, then=Value('The relation doesn't exist!')), default=Value('This is the default value!'), output_field=CharField(), ) ).values_list( 'related_column', 'field1', 'field2', 'field3' ) -
Django queries with cursor slow
I have a problem with some queries that are taking 15 seconds onwards (it is a lot) with cursor in Djando (without using orm because it takes even more) and directly in mysql it takes 4 or 5 seconds, which I think I can be affecting cursor = connection.cursor() cursor.execute("select m.ub ,m.eq , MONTH(m.fecha) as fecha, AVG(m.cantidad) as cantidad , e.contt from mytable as m left join table2 as e on e.id = m.equipo_id where m.equipo_id = %s and m.udm = 8 and YEAR(m.fecha) = %s GROUP BY MONTH(m.fecha)",[eq,anio]) -
Configure Django's builtin authentication to use a different template folder other than "registration"
When using Django's built-in authentication mechanism, how can I configure it to look for template pages like login.html in a different directory besides "registration"? -
Django get model field
I am trying to select a user_id base on the user that was selected and then pass the user_id to another function to perform some calculation for the selected user when a form entry is saved. But I am not sure how to accomplish that. When a new entry is added and save (add_monthly_entitlement) and the form is saved, I want to pass the selected user_id to another method to perform some calculation. class month_and_year(models.Model): user = models.ForeignKey(User, default='', on_delete=models.CASCADE) Month = models.CharField(max_length=100, default="", null=True) Year = models.CharField(max_length=100, default='') def __str__(self): return self.user.first_name @login_required() def add_monthly_entitlement(request): if request.POST: entitlement_form = update_entitlement_form(request.POST) my_field = month_and_year._meta.get_field('user_id') if entitlement_form.is_valid(): calculate_monthly_entitlement(my_field) entitlement_form.save() return HttpResponseRedirect('/staff_balances') else: entitlement_form = update_entitlement_form args = {} args.update(csrf(request)) args['form'] = entitlement_form return render(request, 'update_entitlement_form.html', args) def calculate_monthly_entitlement(get_id): get_id = get_id get_leave_balance_id = Leave_Balance.objects.get(user_id=get_id) get_entitlement_id = monthly_entitlement.objects.get(user_id=get_id) get_leave_balance_id.Leave_current_balance = get_leave_balance_id.Leave_current_balance + get_entitlement_id.entitlement get_leave_balance_id.save() -
Django count objects field
I need to create a field that count the number of registered books of each own library. Each book is related to a library by a ForeighKey If I register or delete a book it should update automatically in a "book_count" field related to your own library. I tried it: libraries/models.py from django.db import models from books.models import Books class Libraries(models.Model): name = models.CharField(max_length=50) book_count = models.IntegerField(default=0) def save(self, *args, **kwargs): self.book_count = self.Books.count() super(User, self).save(*args, **kwargs) def __str__(self): return self.name books/models.py from django.db import models from libraries.models import Libraries class Books(models.Model): library = models.ForeignKey(Libraries, on_delete=models.DO_NOTHING, blank=True, null=True) book = models.CharField(max_length=200, null=True, blank=True) def __str__(self): return self.book But return this error: from libraries.models import Libraries ImportError: cannot import name 'Libraries' How can I create this simple book counter in the model of each library? -
Django CKEditor different toolbar settings for django admin
Is there any way to set the different CKEditor toolbar settings for the Django Admin Panel with django-ckeditor. My toolbar settings in settings.py looks as below 'toolbar_Custom': [ ['Format', 'Bold', 'Italic', 'Link', 'NumberedList', 'BulletedList', 'Table', 'HorizontalRule', 'Image', 'Youtube', 'Smiley', 'Undo', 'Redo', 'Preview', 'Source'], ], I want to set just ['Format', 'Bold', 'Italic', 'Link', 'Undo', 'Redo'] for non-admin pages. -
Transferring multiple values from template to views - Django
I am working on a simple game where the user can select many numbers in the template and then I would like to pass them on to the views. My template looks like this: <div class="col-lg-2"> <div class="card text-center bg-gradient-primary border-0 hover-shadow-lg hover-translate-y-n3 mb-4 ml-lg-0"> <div class="card-body"> <div class="d-inline-flex align-items-start"> <div class="pl-0"> <span class="d-block h2 text-white mr-2 mb-1"><b>1</b></span> </div> </div> </div> </div> </div> <div class="col-lg-2"> <div class="card text-center bg-gradient-primary border-0 hover-shadow-lg hover-translate-y-n3 mb-4 ml-lg-0"> <div class="card-body"> <div class="d-inline-flex align-items-start"> <div class="pl-0"> <span class="d-block h2 text-white mr-2 mb-1"><b>2</b></span> </div> </div> </div> </div> </div> Now the user selects the field 9, 13, 16, 19, 22. I would like to pass all the values at once after click button "Choices number". Without refreshing the page (until the button is clicked). How can I do this? I was thinking about using a hidden field <input type="hidden" name="number1" value="1"> but it would refresh every time my template. One option would be to pass the value using method get, setting something like that for each card element href=?button_number_1=1 and then, get them in the view using request.GET['button_number_1']. And avter this save all using method post. But maybe there is another way to do it? Any help … -
How to fix "origin 'null' has been blocked by CORS policy" when authenticating Angular/Django with external SSO service?
My application has a Django backend and Angular frontend. If the user tries to access the backend directly, it authenticates correctly. However, when a user goes to the Angular frontend I get the following error: redirected from [site] from origin 'null' has been blocked by CORS policy The basic flow in this case is Angular will authenticate with a Django api. If the user is not logged into Django, they will be redirected to an external SSO api, authenticated, and redirected back. From what I've read, the reason the origin is 'null' is due to this redirect. That being said, I am not sure on how to implement this authentication process without doing the redirects. Is there a way around this issue? -
Math Operations on DateField Django
When someone makes an entry, the date and time will be recorded as expected. What I'm curious about is how to do math operations on that date. Like I want to show the date of when the object was created, and also the date 2 weeks in the future. models.py from django.db import models class Checkout(models.Model): member_id = models.IntegerField(null = True) title = models.CharField(max_length = 1000) date_checkout = models.DateField(auto_now = True) # expected_return = date_checkout * 2 I thought I had stumbled across a useful resource online that mentioned something about this but I can't find it anymore. If you could just point me to some resources online that would be awesome. -
Django formtools, how to set wizard_view cookie expiration date?
I am using django formtools to split a long form. I want users to have the possibility to continue filling the forms after they logout/login to the site and after closing/opening their browser. However, the cookie set by formtools has an expiration date value of Session. Therefore, if the user closes the browser the cookie is deleted and the user must start filling the form from the beginning. Is there any way to set the cookie wizard_submissions_wizard_view in the picture below to let say the 2019-01-01? -
Django REST Framework tutorial sends Page Not Found on part 1
I'm new to Django and API developing, so I started following Django REST Framework tutorial, and I have an error in the first part of it. When I go to "127.0.0.1:2000/" on my browser, the Api Root page appears (I hosted it on port 2000), so it seems to be working, but when I try to go to "127.0.0.1:2000/snippets/", I get a Page Not Found error. I imagine this is a very simple thing I'm just overlooking, but I'm kind of stuck right now, and would appreciate the help. Should my "tutorial/urls.py" include the snippets in any way? I followed the tutorial from the beginning, and re-viewed it, so I don't think so, but its a hypothesis. -
Django Rest Framework - Can't avoid null fields being serialized in response
I have this class: class PropertySerializer(serializers.ModelSerializer) class Meta: model = Properties fields = ( 'key', 'value' ) I'm serializing a ManyToManyField field in a model leading to Properties. It has only one record. This is what I'm getting (which is correct): properties": [ { "key": "test_property", "value": null, } ] This is accurate, but I'd like to filter out all null value fields. So far everything I tried failed. Still getting the null value serialized out. I tried: setting blank=False on the value field in the Properties Model. adding value = serializers.CharField(allow_null=False) to PropertySerializer adding extra_kwargs = {'text': {'allow_null': False}} to PropertySerializer What am I doing wrong? Is there a working elegant way other than manually iterating the serializer.data and removing all null values myself? -
Session key changing after login
I am trying to save data of anonymous user if in future the user decides to become a authenticated user but it seems when I am trying to get data of anonymous user using session key after login, the key changes. I want to use the same key after login as well hoe can i do that? Any help will be greatly appreciated, Thank You. Below is the views.py of the code where I am trying to retrieve data. -
Using mod rewrite to preserve // in a parameter inside a url
I am passing a parameter in a URL and sometimes it has a // inside of the parameter that I need to keep but my apache/mod_wsgi config replaces it with a single / . This is a problem since I am performing queries using the parameter and they will come up as they do not exist. I tried writing some rules into my views to handle this but it doesn't work well with the classes that I am using. Can someone help me with some mod_rewrite statements to handle this? A couple examples of the urls are: http://98.8.61.133:8080/viewLit/OGYX/106462//ZYO/ http://98.8.61.133:8080/viewLit/OGYX/106462//ZYO/edit http://98.8.61.133:8080/viewLit/WS/KJUS/260849/ / WXN / http://98.8.61.133:8080/viewLit/01/KG--/069265/ /SED/ http://98.8.61.133:8080/viewLit/49/KFGS/273672//MS/ The /edit needs to be preserved as well because this is what directs the url to another view. I did write some rules in python that look like this that worked on functions but not classes: ruleList=["/SB", "/ZYO", "/ZYO /", "/MS", "/CLVI", "ELG"] for rule in ruleList: if(len(re.findall(rule + "$", circuitid))>0): circuitid=re.sub(rule+"$","/"+rule, circuitid) record = Circuitinfotable.objects.get(circuitid=circuitid) I need to handle this before it gets passed back to my python classes and thought that mod_rewrite might be the right way? I am new to apache but I started to try it and I am lost: … -
html after {% block content %} and {% endblock content %} is showing before the content in Django?
I have a base and child templates. In my base html file i have this: <html> <head> <title>{% block title %}{% endblock %}</title> </head> <body> <ul id="barra"> <li>Inicio</li> <li>Enlace1</li> <li>Enlace2</li> <li>Enlace3</li> <li>Enlace4</li> <li>Ayuda</li> </ul> {% block content %} {% endblock %} </br> <a>asdasdasdasdasdasd</a> </body> </html> but when i see the web in a browser, the "asdasdasdasdasdasd" is shown below ul and over {% block content}. See image Does anyone knows the origin of this behavior, i think its a really simple structure and i cant get why its failing. Thank you very much! -
500 error: null value in column "timeline_id" violates not-null constraint
I'm currently a student and am trying to create a full stack web application with python/django and React. While building my back-end I have run into a problem where, when posting an object containing an association, the association's id is lost between the response payload and the database. I know that the state is updating as it should and that other objects that don't use associations on the back-end can be created without a problem. I assume my mistake has to be somewhere in the models or serializers that I made, but so far I haven't found it. 500 error message: Integrity error at "api/v1/event" null value in column "timeline_id" violates not-null constraint DETAIL: failing row contains (index_id, junk_data, junk_data, 1, null) my models: from django.db import models class Timeline(models.Model): name = models.CharField(max_length=50, default='n/a') def __str__(self): return self.name class Event(models.Model): name = models.CharField(max_length=25, default='n/a') description = models.CharField(max_length=150, default='n/a') coordinate = models.IntegerField(default=0) timeline = models.ForeignKey(Timeline, on_delete=models.CASCADE, related_name="events") def __str__(self): return self.name class Note(models.Model): article = models.TextField(default='n/a') event = models.ForeignKey(Event, on_delete=models.CASCADE, related_name='notes') # event = models.ManyToManyField(Event) def __str__(self): return self.article my views: from rest_framework import viewsets from .serializers import TimelineSerializer, EventSerializer, NoteSerializer from .models import Timeline, Event, Note class TimelineView(viewsets.ModelViewSet): queryset = … -
Is it possible to Sum time (02:41:54) in Django?
I am getting time base 24 hrs from data base. (example: 02:25:41) I want to Sum all of them and I was wondering if that is possible. I mean just Suming 02:25:41 + 01:05:01 = 03:30:42, for example I was thinking in converting time into seconds then Sum the Integers and then convert them again into HHMMSS. That is what I was doing until now, just suming the seconds and then convert them into HHMMSS but that was because I was getting seconds from data base here things have changed since I am not getting seconds but Time. this is what I´ve been doing until now query_t = jssDatejj.objects.values('direction') \ .filter(date__range=(start, end)).order_by('direction').annotate( serv= Sum('serv20'), servicioR= Sum('serv10'), servicioA= Sum('serv11'), pavgmt= Sum('prom20'), pavgst= Sum('prom10'), sClient= Sum('clients'), sDeriv= Sum('deriv'), sAten= Sum('aten'), service= Round(Cast(Sum('serv20'), FloatField())/Cast(Sum('serv10'), FloatField()))*100, tme= Sum('promedio_avgmt') / Sum('serv10'), tmo= Sum('promedio_avgst') / Sum('serv11'), totalTmp = Sum('deriv') + Sum('aten') ) all those values are send to html where I use them and convert them into HHMMSS through javascrit to be printed in a Datatable. so I need to add 2 more values but are sent in time (02:04:52) and I can´t Sum them just the way I have been doing it -
why is dj-database-url throwing me an error of : a bytes-like object is required, not 'str'
so i am a student attempting to create a django based app...my app is finished and im wanting to launch it on heroku. The error message comes when i run: python3 manage.py makemigrations I am using dj-database-url for the db url and have the env stored as : DATABASES = {'default': dj_database_url.parse(os.environ.get('DATABASE_URL'))} The versions of everything I am using are: chardet==3.0.4 dj-database-url==0.5.0 Django==2.2.7 heroku==0.1.4 idna==2.8 psycopg2==2.8.4 python-dateutil==1.5 pytz==2019.3 requests==2.22.0 sqlparse==0.3.0 stripe==2.40.0 urllib3==1.25.7 and the traceback error message I am receiving is : File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\Jakey Poo\PycharmProjects\artwork\venv\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\Jakey Poo\PycharmProjects\artwork\venv\lib\site-packages\django\core\management\__init__.py", line 325, in execute settings.INSTALLED_APPS File "C:\Users\Jakey Poo\PycharmProjects\artwork\venv\lib\site-packages\django\conf\__init__.py", line 79, in __getattr__ self._setup(name) File "C:\Users\Jakey Poo\PycharmProjects\artwork\venv\lib\site-packages\django\conf\__init__.py", line 66, in _setup self._wrapped = Settings(settings_module) File "C:\Users\Jakey Poo\PycharmProjects\artwork\venv\lib\site-packages\django\conf\__init__.py", line 157, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Users\Jakey Poo\AppData\Local\Programs\Python\Python37-32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\Jakey Poo\PycharmProjects\artwork\artwork\settings.py", line 89, in <module> … -
try to read csv using python to pythonanywhere host
We try to read csv file using view.py in pythonanywhere.com host. We try to get three cells (id, statement, and paragraph) from each row in the 1.csv file until last one. The code is: def home(request): Stats = Statments.objects.all() __file__ = '1.csv' module_dir = os.path.dirname(__file__) # get current directory file_name = os.path.join(module_dir, 'Politi_Stat/1.csv') #Load statments to database from CSV with open(file_name,"r", encoding = 'utf-8') as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') for row in csv_reader: book = Statments(id = row[0] ,statment=row[1], Paragraph=row[2]) book.save() d = deque(posts) d.extendleft(reversed(Stats)) We import the csv and os. It seems an encoding problem of the unicode UTF-8 of csv. The output of the site is: Server 500 The output from the log file is: Traceback (most recent call last): File "/home/fattoh/.virtualenvs/django2/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/fattoh/.virtualenvs/django2/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/fattoh/.virtualenvs/django2/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/fattoh/Politi_Stat/app/views.py", line 46, in home for row in csv_reader: File "/home/fattoh/.virtualenvs/django2/lib/python3.7/codecs.py", line 322, in decode (result, consumed) = self._buffer_decode(data, self.errors, final) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa0 in position 82: invalid start byte 2019-11-27 19:20:54,714: Internal Server Error: / Traceback (most recent call last): File …