Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django localhost returns ok but curl localhost returns the 404 error
The localhost of a Django app runs normal on an AWS server like the following: (env) manage.py runserver 0.0.0.0:8000 Performing system checks... System check identified no issues (0 silenced). Django version 2.2, using settings 'xyz.settings' Starting development server at http://0.0.0.0:8000/ Quit the server with CONTROL-C. The curl -i localhost is returning the 404 error. (env) $ curl -i localhost HTTP/1.1 404 Not Found Server: nginx/1.14.0 (Ubuntu) Content-Type: text/html Content-Length: 178 Connection: keep-alive <html> <head><title>404 Not Found</title></head> <body bgcolor="white"> <center><h1>404 Not Found</h1></center> <hr><center>nginx/1.14.0 (Ubuntu)</center> </body> </html> What does this mean? Does it mean the Django app was installed ok but the Nginx is not working properly? What do I check them out? The tech stack is Django/Python/gunicon/Nginx on Ubuntu 18. -
Django value too long for type character varying(50)
I am trying to create a Site object. http://test-ecommerce-project-dev.us-west-1.elasticbeanstalk.com/ And when I try to create a new Site with the above domain, I got this error value too long for type character varying(50) i think this is caused because my domain is too long. But I don't know how to solve it. I thought of overriding Site class, but i don't know how to do it either. Any ideas appreciated. -
account/register not found in django project
I am new to django and started with a basic. The problem is while following a tutorial I created an account app that has a register page. For some reason whenever I am trying to go to my register page, django tells me that it doesn't match any of the paths. below is the given code: accounts app url.py from django.urls import path from . import views urlpatterns = [ path('register', views.register, name="register") ] accounts app's views from django.shortcuts import render def register(request): return render(request, 'register.html') register.html is: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Registeration</title> </head> <body> <form action="register" method = "post"> {% csrf_token %} <input type= "text" name="first_name" placeholder="First Name"><br> <input type= "text" name="last_name" placeholder="Last Name"><br> <input type= "text" name="username" placeholder="UserName"><br> <input type= "text" name="password1" placeholder="Password"><br> <input type= "text" name="password2" placeholder="Verify Password"><br> <input type= "submit"> </form> </head> <body> </body> </html> ``` web_project urls.py ``` from django.contrib import admin from django.urls import include, path from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path("", include('travello.urls')), path('admin/', admin.site.urls), path('accounts/', include('accounts.urls')), ] urlpatterns = urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) the error I am getting is given below: Page not found (404) Request Method: … -
How to create a customized filter search function in Django?
I am trying to create a filter search bar that I can customize. For example, if I type a value into a search bar, then it will query a model and retrieve a list of instances that match the value. For example, here is a view: class StudentListView(FilterView): template_name = "leads/student_list.html" context_object_name = "leads" filterset_class = StudentFilter def get_queryset(self): return Lead.objects.all() and here is my filters.py: class StudentFilter(django_filters.FilterSet): class Meta: model = Lead fields = { 'first_name': ['icontains'], 'email': ['exact'], } Until now, I can only create a filter search bar that can provide a list of instances that match first_name or email(which are fields in the Lead model). However, this does now allow me to do more complicated tasks. Lets say I added time to the filter fields, and I would like to not only filter the Lead model with the time value I submitted, but also other Lead instances that have a time value that is near the one I submitted. Basically, I want something like the def form_valid() used in the views where I can query, calculate, and even alter the values submitted. Moreover, if possible, I would like to create a filter field that is not … -
TypeError while running Python manage.py runserver command
I'm new to Python/Django and trying to launch a virtual environment in this project for the first time. When entering the final command - 'python manage.py runserver'- I am getting a TypeError: (myenv) C:\Users\katie\bounty>python manage.py runserver Traceback (most recent call last): File "C:\Users\katie\bounty\manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\Users\katie\bounty\myenv\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\katie\bounty\myenv\lib\site-packages\django\core\management\__init__.py", line 345, in execute settings.INSTALLED_APPS File "C:\Users\katie\bounty\myenv\lib\site-packages\django\conf\__init__.py", line 83, in __getattr__ self._setup(name) File "C:\Users\katie\bounty\myenv\lib\site-packages\django\conf\__init__.py", line 70, in _setup self._wrapped = Settings(settings_module) File "C:\Users\katie\bounty\myenv\lib\site-packages\django\conf\__init__.py", line 177, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "c:\users\katie\appdata\local\programs\python\python39\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 850, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "C:\Users\katie\bounty\bounty\settings.py", line 173, in <module> AWS_S3_CUSTOM_DOMAIN = AWS_STORAGE_BUCKET_NAME + '.s3.us-east-2.amazonaws.com' TypeError: unsupported operand type(s) for +: 'NoneType' and 'str' I'm not sure how I could have caused the error since I haven't done anything other than clone the repository and work to launch the virtual environment in command prompt. I also tried python3 manage.py runserver but then received the error: … -
How to create multiple directory in django template folder?
I want to change php website into django. In php, we have controller and view folder. Inside view, I have many folder in view. View --- Users --- user1.ctp --- user2.ctp --- Layouts --- layout1.ctp --- layout2.ctp Now I am using django this is how my directory looks MyProject --- myapp --- views.py --- urls.py --- migrations --- __pycache__ --- static --- myapp --- mycss.css --- templates --- myapp --- Users --- user1.html --- user2.html --- Layouts --- layout1.html --- layout2.html --- MyProject Whenever I am putting user1.html inside /templates/myapp, I am able to render but I want to put Users related file in Users folder. I am getting template does not exist urls.py (Inside myapp) from django.contrib import admin from django.urls import path from django.urls.conf import include from . import views,login urlpatterns = [ path("",views.index), ] urls.py (Inside MyProject) urlpatterns = [ path('admin/', admin.site.urls), path('',include('myapp.urls')), ] -
How do i ensure I have unique ids within a loop in a template
I have the queryset from a formset which is something like this {[Item 1],[Item 2]}. To display them, i loop thru them in the template. But due to the loop, i have warning that my div have same ids. Can anyone suggest what to do? I can just leave it like that if my page purpose is to display the data only. But the page purpose is to view and update the data and correct me if im wrong, the div with identical ids will affect the update to the database. -
How to fix the error: 'This XML file does not appear to have any style information associated with it'
I hosted a small django project on virtual machine on digital ocean. Before I started using digital ocean to serve static files everything worked fine. But immediately I created a storage space and push my static files there the static files are not being served on the webpage, including django admin page (the project pages are showing net::ERR_ABORTED 403 (Forbidden). I have already installed django_storages and boto3. I got some hint as to the possible cause of the problem when I clicked on digital ocean aws bucket url that looks like https://django-space-storage.nyc3.digitaloceanspaces.com. When I cliked on it I got the following error: This XML file does not appear to have any style information associated with it. The document tree is shown below. It seems the browser is rendering my django pages as xml instead of html. I might be wrong with this assumption because I'm finding a hard time trying to understand what is actually going on. My question is, how do I cause the browser to render my django pages as html instead of xml? -
Python script to web page
I’ve done some research about turning a python script that I have written into an HTML web page. My experience with HTML is somewhat limited, but from what I can tell, I would have an HTML file, and would incorporate Django into said HTML file. Is it as simple as putting something in the HTML file like <p> The function call is: <> myFunctionCall() </><> Or is there a lot more to it than that? -
You're accessing the development server over HTTPS, but it only supports HTTP. code 400, message Bad request syntax
I just started learning Django framework, and I tried to deploy my first project on the server from DigitalOcean. If I run python3 manage.py rumserver 0.0.0.0:8000 The server launches. However, once I try to access it from (my-rent-ip):8000 I get this: [25/Aug/2021 01:49:01] code 400, message Bad request syntax ('\x16\x03\x01\x02\x00\x01\x00\x01ü\x03\x03GÛî}ز\x921\x0e\x94\x17\x9cÏe¹\x88ñÿÃ\x16\x01éÖRÝ\x00\x95F\x8aG\tÉ 8¯,úÂ\x93´ù\x06Ý\x14¾z\x13Âe4[\x9a,.æ\x96+$<~\x8eq<´\t\x00"ZZ\x13\x01\x13\x02\x13\x03À+À/À,À0̨̩À\x13À\x14\x00\x9c\x00\x9d\x00/\x005\x00') [25/Aug/2021 01:49:01] You're accessing the development server over HTTPS, but it only supports HTTP How is this possible if I run production server, not a development one? I might be doing something wrong with the setting.py since it had to be changed a lot for the production purposes. I made a production branch, changed settings.py file, and cloned to the server using GitHub. Here it is: from pathlib import Path from dotenv import load_dotenv #for python-dotenv method load_dotenv() # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! import os SECRET_KEY = os.environ.get('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False # DEBUG = os.environ.get('DJANGO_DEBUG', '') != 'False' ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ … -
Run celery inside a docker container in production (plesk)
I am trying to use celery with docker in plesk, plesk (no support for using docker-compose) can i run celery inside my container for production use? -
How do I return a value from database to template?
I have a database which uses formset to help store data. How do i get the ‘value’ of the numbers of data in the template. Like example i got a queryset of {[Item 1],[ Item 2]}. How do i get the value of 2 in the template to tell me theres 2 items? I want to use this value to control the amount of stuff i can clone with a click of the button. Im using django for the web -
How to make django publish messages to mqtt on views?
I am trying to integrate paho.mqtt into django to publish msgs to mosquitto broker, I have searched but I havent found much tutorials on how I can achieve it. Well i tried to put this code into mqtt.py: from paho.mqtt import client as mqtt_client topic = "#topic#" def connect_mqtt() -> mqtt_client: def on_connect(client, userdata, flags, rc): if rc == 0: print("Connected to MQTT Broker!") else: print("Failed to connect, return code %d\n", rc) client = mqtt_client.Client(topic) client.username_pw_set('#username#', '#psswd#') client.on_connect = on_connect client.connect('####the host##', 1883) return client def publish(client): msg = 'test test' result = client.publish(topic, msg) def run(): client = connect_mqtt() publish(client) client.loop_forever() and in init.py from . import mqtt client.loop_start() and when I call run() on views it doesn't work, and runserver it doesn't seem like the right way to do it. Can somebody explain to me how should I structure my files and system to do it right. Please any help would be much appreciated. -
Django Project works on local but not on heroku
If I try to run the server on local it works without errors but when trying to run it with heroku I get 2021-08-24T23:55:05.395710+00:00 app[web.1]: Internal Server Error: / 2021-08-24T23:55:05.395718+00:00 app[web.1]: Traceback (most recent call last): 2021-08-24T23:55:05.395719+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute 2021-08-24T23:55:05.395720+00:00 app[web.1]: return self.cursor.execute(sql, params) 2021-08-24T23:55:05.395720+00:00 app[web.1]: psycopg2.errors.UndefinedTable: relation "main_chapter" does not exist 2021-08-24T23:55:05.395721+00:00 app[web.1]: LINE 1: ...er_text", "main_chapter"."chapter_footnotes" FROM "main_chap... 2021-08-24T23:55:05.395722+00:00 app[web.1]: ^ 2021-08-24T23:55:05.395723+00:00 app[web.1]: 2021-08-24T23:55:05.395723+00:00 app[web.1]: 2021-08-24T23:55:05.395723+00:00 app[web.1]: The above exception was the direct cause of the following exception: 2021-08-24T23:55:05.395724+00:00 app[web.1]: 2021-08-24T23:55:05.395724+00:00 app[web.1]: Traceback (most recent call last): 2021-08-24T23:55:05.395724+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner 2021-08-24T23:55:05.395725+00:00 app[web.1]: response = get_response(request) 2021-08-24T23:55:05.395725+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response 2021-08-24T23:55:05.395726+00:00 app[web.1]: response = wrapped_callback(request, *callback_args, **callback_kwargs) 2021-08-24T23:55:05.395726+00:00 app[web.1]: File "/app/main/views.py", line 10, in home 2021-08-24T23:55:05.395726+00:00 app[web.1]: last = chapter_list.last() 2021-08-24T23:55:05.395727+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/django/db/models/query.py", line 679, in last 2021-08-24T23:55:05.395727+00:00 app[web.1]: for obj in (self.reverse() if self.ordered else self.order_by('-pk'))[:1]: 2021-08-24T23:55:05.395727+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/django/db/models/query.py", line 280, in __iter__ 2021-08-24T23:55:05.395728+00:00 app[web.1]: self._fetch_all() 2021-08-24T23:55:05.395728+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/django/db/models/query.py", line 1324, in _fetch_all 2021-08-24T23:55:05.395728+00:00 app[web.1]: self._result_cache = list(self._iterable_class(self)) 2021-08-24T23:55:05.395729+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/django/db/models/query.py", line 51, in __iter__ 2021-08-24T23:55:05.395729+00:00 app[web.1]: results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) 2021-08-24T23:55:05.395729+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/django/db/models/sql/compiler.py", line 1175, in execute_sql 2021-08-24T23:55:05.395730+00:00 … -
Django's password reset URL customized isn't loading after the first try
I'm using Django's password-reset URLs and I have created my own templates for them, but after I put in my Email address it redirects me to the default templates instead of redirecting me to my custom template. urls.py path('password_reset/', auth_views.PasswordResetView.as_view(template_name="authsystem/password_reset.html"), name='password_reset'), path('password_reset/done', auth_views.PasswordResetDoneView.as_view(template_name="authsystem/password_reset_sent.html"), name='password_reset_done'), path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name="authsystem/password_reset_form.html"), name='password_reset_confirm'), path('reset/done/', auth_views.PasswordResetCompleteView.as_view(template_name="authsystem/password_reset_done.html"), name='password_reset_complete'), After It moves from 'password_reset.html' it's supposed to render 'password_reset_sent.html' but it renders Django's default template. -
i cant submit integer field in django Rest Framework ? TypeError 'BoundField' object is not iterable
this is my views.py class ClinicList(ListCreateAPIView): serializer_class=CliniDetailcSerializer permission_classes=[IsAuthenticatedOrReadOnly] def get_queryset(self): qs=Clinic.objects.all().order_by('-id') return qs def post(self,request,format=None): if request.user.is_authenticated and request.user.profile.type == 'doctor': serializer = CliniDetailcSerializer(data=request.data) if serializer.is_valid(): print(serializer.data.values()) Clinic.objects.create(doctor=request.user.profile,name=serializer["name"],price=serializer.data["price"],days=serializer["days"],start_time=serializer["start_time"],end_time=serializer["end_time"]) context={"data":serializer.data,"message":"clinic added successffullt"} return Response(serializer.data) else: return Response({"message": "invalid data"}) else: return Response({"message": "your are not a doctor"}) and i got this error when i submit: 'BoundField' object is not iterable -
2026, SSL connection error: unknown error number - encountered by my django app after upgrading mysql from 5 to 8
I upgraded mysql from 5.7 to 8.0 and started encountering this error which is preventing my app from connecting to the database. django.db.utils.OperationalError: (2026, 'SSL connection error: unknown error number') I have my own ca.pem server-cert.pem server-key.pem which mysql uses. The django app properly sets the ca cert in settings. Everything works in 5.7. -
Django Admin make field editable for specific user group
Lets say i have two user groups (user, admin) in my application. Both can see the fields of an instance on the admin model. I have a field named "approved" which is a boolean field. The admin should be able to edit this field, but for the user it should be a read-only field. I tried to use the get_readonly_fields method from django, but it doesent seem to work in combination with the list_display and list_editable attributes. My approach looks like this: @admin.register(Component) class ComponentAdmin(admin.ModelAdmin): exclude = ("created_by",) list_display = ( "id", "approved" ) list_editable = ("approved") def get_readonly_fields(self, request, obj=None): if is_admin_or_mod(request): return [] return ["approved"] -
Django - custom getter for 1 field in model
I am writing a model for an external Oracle DB, which I need to pull info from to my project. One of the fields in that Oracle DB is an XMLType, and it hosts large portion of data, which needs to be pulled via .getClobVal() method, instead of querying it straight as it is. I was wondering, if Django supports any sort of custom logic, for Model's specific fields. Something along the lines of a getter for each field, which I could overwrite to query that specific field as XMLType.getClobVal() instead of just XMLType. At the same time, I don`t want to touch the logic for querying the rest of the Model's fields. Any ideas? -
How to use django-taggit in a template?
I want to list articles by tag to have the title of the tag in the title and the titles of the articles in the list. My view.py looks like this: from taggit.models import TaggedItem class ArticlesByTagsList(ListView): template_name = 'articles/articles_by_tags.html' context_object_name = 'articles_list' def get_queryset(self): return TaggedItem.objects.filter(tag=self.kwargs['tag']) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['tags_list'] = Tag.objects.all() return context My articles_by_tags.html template looks like this: {% block content %} <h1>Список публикаций {{ articles_list.item }}</h1> {% for item in articles_list %} <h2>{{ item }}</h2> {% endfor %} {% endblock %} I end up with the following output:ArticlesByTagsList.as_view() result How can I solve this problem? -
Pytest failed when testing API with correct URL and data
When I am creating a Clinic via Swagger or Postman it works fine and field with the same data when test it ! model class Clinic(models.Model): name = models.CharField(max_length=50) price = models.FloatField() doctor = models.ForeignKey(User, on_delete=models.CASCADE, related_name='doctor_clinic') date = models.ManyToManyField(ClinicDate, related_name='clinic_date') serializer class ClinicDateSerializers(serializers.ModelSerializer): class Meta: model = ClinicDate fields = ['day','start_time', 'end_time'] class ClinicSerializers(serializers.ModelSerializer): doctor = serializers.StringRelatedField(required=False) date = ClinicDateSerializers(many=True, required=True) class Meta: model = Clinic fields = ['name', 'price', 'doctor', 'date'] def create(self, validated_data): dates_data = validated_data.pop('date') user = self.context['request'].user clinic = Clinic.objects.create(doctor=user, **validated_data) for date_data in dates_data: dt = ClinicDate.objects.create(**date_data) clinic.date.add(dt) return clinic URL path('add/', views.ClinicCreateView.as_view(), name='clinic-create'), pytest @pytest.mark.django_db class TestClinic: @pytest.fixture def setup(self): User.objects.create_doctor(email="doctor1@doctoronline.com", password="12345") data = { 'email':'doctor1@doctoronline.com', 'password':'12345', } response = client.post(reverse('token_obtain_pair_doctor'), data=data) self.access_token = response.json()['access'] client.credentials(HTTP_AUTHORIZATION='Bearer ' + self.access_token) def test_valid_create_clinic(self, setup): data = { "name": "Clinic 1", "price": 1000, "date": [ { "day": "SATURDAY", "start_time": "2021-08-24T21:21:17.960Z", "end_time": "2021-08-24T21:21:17.960Z" } ] } response = client.post(reverse('clinic-create'), data=data) assert response.status_code == status.HTTP_201_CREATED Hint there is no problem with setup or data -
error on calling a django rest framework endpoint from the same server
I have an API endpoint let's say sampleapi.domain.com/api/v1/1 that worked well in development, both locally (127.0.0.1) and online sampleapi-dev.domain.com, but when I call the same endpoint sampleapi.domain.com/api/v1/1 from the server from which the call is being made sampleapi.domain.com, I get json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) which is unusual since the same code works in development and online. When I changed how I'm starting gunicorn from gunicorn --certfile=crt --keyfile=key --bind 0.0.0.0:8000 a.wsgi to gunicorn --certfile=crt --keyfile=key --bind 0.0.0.0:8000 a.wsgi -w 1 --threads 2 This seems to solve the error, but I'm not entirely sure why that is the case. Was it that the single thread was not available to call the API because it was busy loading the page the API is on? If this isn't the reason, what could be the reason? -
Django displaying 2 tables side by side
As the title says, i'm trying to display 2 tables side by side. I tried a couple of methods but no one shows results. Right now this is the code of the 2 tables: <div> <table style="float: left" class="table table-striped table-bordered table-sm"> {% for item in product %} {% if item.orden_ref_id == orden.id %} <tr> <td> {{ item.articulo }} </td> </tr> {% endif %} {% endfor %} </table> <table style="float: right" class="table table-striped table-bordered table-sm"> {% for item in valor %} {% if item.refer_id == orden.id %} {% if item.show_ref == '2' %} <tr> <td> {{ item.costo }} </td> </tr> {% endif %} {% endif %} {% endfor %} </table> </div> but it look like this: Tables look How can i solve this issue? -
Django Deployment in Local network
I have a Django application to deploy on my company's server (local network). I asked to create a Virtual Machine (Windows), my questions are: 1- which is good for deployment, Windows or Linux VM? 2- Do I need to use any other software like Apache webserver or just I can run my Django server? 3- Is there anything I should do? All my best -
How to set up your python django project on godaddy
I have a complete project built with python django and I need to host it on GoDaddy. But in the cPanel File Manager there is so many folders inside and I don't know where to put my Django project. I searched up in the net and only found people using different hosting companies. Where do I put the files? cPanel File Manager I have a domain already and I connected it to the hosting. Django Project Looks Like