Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Difference in time between database and value displayed
I am trying to fix strange problem with time in my project. First of all my settings are as follows: settings.py LANGUAGE_CODE = 'pl-pl' TIME_ZONE = 'Europe/Warsaw' USE_I18N = True USE_L10N = False USE_TZ = True DATETIME_FORMAT = 'Y-m-d H:i:s' DATE_FORMAT = 'Y-m-d' Every DateTimeField field, for example: models.py class Order(models.Model): date_zal = models.DateTimeField() is displayed correctly in my home.html file with the help of {{ order.data_zal }} but when I look into my database (still Sqlite3, going to switch to MySql soon) there is ALWAYS date with 1 hour earlier (e.g. 11:40 displayed vs 10:40 in database). Not sure where lies the problem since it is displayed properly. -
Django RestApi Problem : viewsets in views not found
I tried to create an api for my project, but somehow I cant retrieve the viewsets on my function, what did I do wrong? -
Make thumbnail from jpg, jpeg or png
I have the following method to create a thumbnail, but I would like it also to generate it in case the file type is png, as it currently throws an error for them: from io import BytesIO from django.core.files import File from PIL import Image def make_thumbnail(image, size=(600, 600)): im = Image.open(image) im.convert('RGB') im.thumbnail(size) thumb_io = BytesIO() im.save(thumb_io, 'JPEG', quality=85) thumbnail = File(thumb_io, name=image.name) return thumbnail How can I effectively accept png, jpg and jpeg to generate the thumbnail? -
drf_yasg - swagger request url issue
I have a project with Django + Nginx + Gunicorn setup. In this project, I am running Nginx with 8000 port, here when I test endpoints using postman it is working fine but when I use Swagger it is not working. Swagger was trying to access the URL without the port ( ex: curl -X GET "http://172.16.235.109/runs/" -H "accept: application/json" ). so it is not working. I explored a lot but I could not find the right way to solve this problem. Anyone, could you please help me to resolve this issue? Requirements am using Django==3.0.3 drf-yasg==1.17.1 (SWAGGER) gunicorn==20.0.4 -
QueryDict Object has no attribute session Django
So I basically have a login form which I have defined like this: def login_request(request): if request.method == 'POST': data = request.POST auth_backend = AuthenticationBackend() login_form = LoginForm(data) if login_form.is_valid(): user = auth_backend.authenticate(data, password=data['password'], email=data['email']) if user: login(data, user) # redirect to homepage else: login_form.add_error('password', "Password doesn't match email") else: data = {} login_form = LoginForm() return render(request, 'login.html', {'form': login_form, 'data': data}) If the given conditions match, the user must be logged in. However, when I do login(data, user) I get this error: Internal Server Error: /users/login/ Traceback (most recent call last): File "C:\Users\Iyappan\PycharmProjects\pyDjangoTest\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Iyappan\PycharmProjects\pyDjangoTest\venv\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Iyappan\PycharmProjects\pyDjangoTest\users\views.py", line 34, in login_request login(data, user) File "C:\Users\Iyappan\PycharmProjects\pyDjangoTest\venv\lib\site-packages\django\contrib\auth\__init__.py", line 99, in login if SESSION_KEY in request.session: AttributeError: 'QueryDict' object has no attribute 'session' Why is this happening? How can I fix this? Please help me, thanks in advance! -
too late for learning flask? and how shloud I shoose my DB?
I'm a junior web developer and I completed all of what I need from front end develpoment and a little more: html/css/js vue python c# ps: dropped this one and now I'm starting with backend development, so I started with django and found out that it's a little too complicated but I continued for a while and now I hear people saying that if you want to start with a web framework you should start with flask even if your end goal is django. So that got me thinking that I'm still finding django a bit hard and slow to learn for me and I thought that am I doing it wrong and that I should stop learning django and just start slow. keep in mind I don't know that much of django to say I'm too late or early and I should switch. so what do you think I should do at this point? and additionally I searched about answers to what sql should I learn and got lost in the answers. sql sounds nice, sqlite comes with django and flexible, mongodb is too easy and postgresql also seems like a good choice so I don't know where to … -
index page not displaying and returning error 200 on Django terminal
i have an index page which extends a navbar.html in Django and is followed by other codes. when i run the server, the server runs but displays "GET /health/ HTTP/1.1" 200 4619" which i understand is a blank page but my index.html is not blank. The page shows the extended navbar.html but nothing more. The views look like: def index(request): return render(request, 'My_Doc/index.html') And urls look like: urlpatterns = [ path('', views.index, name='index'), ] Requesting for help>>>> -
Django 3.1.1 - changing password success but success page don't show
I config urls and add custom template (override registration/password_change_done.html and registration/password_change_form.html:) in my project but when I change password success the url have changed correctly (http://127.0.0.1:8000/accounts/password/change/done/ url) but success page didn't show, it still shows the change password form. My code as below: configuration urls.py: from django.conf.urls import url from django.contrib.auth import views as auth_views urlpatterns = [ url('password/change/', auth_views.PasswordChangeView.as_view(), name='password_change'), url('password/change/done/', auth_views.PasswordChangeDoneView.as_view(), name='password_change_done'), url('password/reset/', auth_views.PasswordResetView.as_view(), name='password_reset'), url('password/reset/done/', auth_views.PasswordResetDoneView.as_view(), name='password_reset_done'), url('password/reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(), name='password_reset_confirm'), url('password/reset/complete/', auth_views.PasswordResetCompleteView.as_view(), name='password_reset_complete'), ] password_change_done.html: {% extends "base.html" %} {% block content %} <div class='row'> <div class="col-12 text-center py-5"> <h1 class='my-5 py-5'>Password successfully changed!</h1> </div> </div> {% endblock %} password_change_form.html: {% extends "base.html" %} {% block content %} <div class='row'> <div class='col-md-6 col-10 mx-auto'> <h1>Change your Password</h1> <form method='post' action=''>{% csrf_token %} {{ form.as_p }} <span style='margin-bottom: 12px;'></span> <button type="submit" class='btn btn-block btn-info'>Save</button> </form> </div> </div> {% endblock %} -
DRF object with slug_field="" doesn't exist
I'm creating a very simple api with drf and that's my problem: I have this code in serializers.py: class PostSerializer(serializers.ModelSerializer): comments = serializers.SlugRelatedField( queryset= Comment.objects.all(), many= True, slug_field='body' ) class Meta: model = Post fields = ['pk', 'user', 'title', 'content', 'comments', ] read_only_fields = ['pk', 'user'] When l open api/1 in my browser l get this as expected: { "pk": 1, "user": 1, "title": "Lorem", "content": "First post", "comments": [ "My Comment", "Second Comment" ] } When l try to update this with PUT method all fields work fine, except comments, when l try to add a new one it gives me this error: { "comments": [ "Object with body=my new comment does not exist." ] } How do l solve that, so when l add a new comment it's get pushed to db? -
I use bootstarp navbar. When I scroll up.. the block content appear behind the navbar. Navbar fixed on the top
I use bootstarp navbar. When I scroll up.. the block content appear behind the navbar. Navbar fixed on the top. My Navbar <main id="navfix" class="m-5"> <nav class="navabar_bgc py-0 navbar navbar-expand navbar-light fixed-top"> {% include 'sidebar.html' %} <div class="collapse navbar-collapse" id="collapsibleNavId"> <ul class="navbar-nav ml-auto mt-lg-0"> <div>...</div> </ul> </div> </nav> </main> <div class="block__content"> {% block content %} {% endblock %} </div> My css: #navfix { width: 100%; } .navabar_bgc { background-color: rgba(103, 250, 34, 0.4) !important; box-shadow: 0px 0px 8px !important; z-index: 10 !important; } .block__content { z-index: 5; overflow: auto; } Any other suggestion please give me..Thanks. -
how to link to search results in pagination Django 3.1
I want to implement pagination on the search results page of my site. My Django project has a few apps that have different models and the search will look in every table for results. for ex.: # views.py def search(request): queryset_list_ip_sensor = Ip_sensor.objects.all() queryset_list = ControlValves.objects.all() queryset_list_water_quality_sensor = Water_quality_sensor.objects.all() context = { 'ip_sensors': result_list_ip_sensor, 'controlvalves': result_list_control_valves_2, 'water_quality_sensor': result_list_water_quality_sensor, 'values': request.GET, 'keywords': keywords } return render(request, 'pages/search.html', context) I implemented pagination like this: # views.py def search(request): # ... result = (result_list_ip_sensor, result_list_control_valves, result_list_water_quality_sensor) paginator = Paginator(result, 1) page = request.GET.get('page') paged_queries = paginator.get_page(page) context_pagination = {'ip_sensors': result_list_ip_sensor, 'controlvalves': result_list_control_valves_2, 'water_quality_sensor': result_list_water_quality_sensor, 'queries': paged_queries, 'keywords': keywords, 'values': request.GET } return render(request, 'pages/search.html', context_pagination) Before pagination I used to show results like this: {% if ip_sensors %} {% for ip_sensor in ip_sensors %} <div class="col-12 col-sm-12 col-md-4 col-lg-4 col-xl-4 mb-4"> <div class="card"> <div class="card-header"> I/P Sensor </div> <img class="card-img-top" src="{{ ip_sensor.cover.url }}" alt=""> <div class="card-body"> <div class="text-center"> <h4 class="text-dark">{{ ip_sensor.title }}</h4> <p> {{ ip_sensor.description | truncatewords:10 }}</p> </div> <hr> <div class="row py-2 text-dark"> <div class="col-6"> Product Name: {{ ip_sensor.product_name | truncatewords:2 }}</div> <div class="col-6"> Usage: {{ ip_sensor.usage | truncatewords:4}}</div> </div> <hr> <a href="{% url 'ip_sensor_item' ip_sensor.title %}" class="btn btn-light btn-block">More Info</a> </div> … -
How to play a generated mp3 on the user's browser?
My django view.py generates an mp3 file on the server at ./speech.mp3 after user interaction. How do I play it on the user's browser? If I just play the mp3 file using python code in view.py, it'll only be played on the server PC, not the user's browser. I'm thinking of 2 solutions: Either I have to pass the mp3 to the user's browser through ajax OR upload it to a cloud service. Not sure how to approach though. -
Django : Tables in SQL duplicates
I'm trying to migrate my migrations and I get those weird duplicated tables inside my SQL database. I have used Meta class for all my models to change their names inside the database: class Meta: db_table = 'User_Computer_Knowledge' I have two apps (accounts - for authentication and else, main - for all other things) Pastebin links: My whole accounts model My whole main model After migrating I get these results : What's the problem? -
Django limit user view rights for model object
I have an app with multiple users from different companies. I need to restrict access such that certain users from certain companies can only see model objets relevant to their company. For e.g. when I display a drop-down in a template, I want the dropdown contents to be different for each user based on their predefined permissions. I am not a developer so I may be reading the Django documentation poorly, but if I were to guess it doesn't seem possible. If indeed it is not straight forward via Django built-ins, is there any clever workaround? -
Bootstrap DatePickerPlus Format Doesn't Change
I am using Bootstrap DatePickerPlus and although I'm setting the format to DD/MM/YYYY, the form is often failing validation with the error Enter a valid date/time as it is trying to validate as MM/DD/YY. For example, 23/02/2020 will fail, but 02/23/2020 will pass. I have tried many things but the stuff I have tried seems to be for Django's DatePicker, not Bootstrap's DatePickerPlus. Any help would be greatly appreciated. models.py date = models.DateTimeField('Date (dd/mm/yyyy)', default=now) forms.py class Meta: model = Booking fields = '__all__' widgets = { 'date': DatePickerInput( options={ "format": "DD/MM/YYYY", "showClose": False, "showClear": False, "showTodayButton": False, } ), } Thank you. -
Error during WebSocket handshake: Unexpected response code: 400-ReactJs and django socket.io
I've a django socketio as server and reactjs as client django server wsgi.py import os from django.core.wsgi import get_wsgi_application from app.views import sio import socketio os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'quantsite.settings') django_app = get_wsgi_application() application = socketio.WSGIApp(sio, django_app) views.py import os from django.http import HttpResponse import socketio async def index(request): return web.Response(text="hello", content_type='text/html') @sio.event async def connect(sid, environ): print('Client connected',sid) await sio.emit('message', "good") @sio.event async def disconnect(sid): print('Client disconnected',sid) @sio.on('message') async def message(sid, data): print("server received message!", data) await sio.emit('reply', data) Client side-Reactjs import io from 'socket.io-client'; let socket ; componentDidMount() { socket=io('localhost:8000',{transports:['websocket']}); socket.on('connect', ()=> { console.log("connected"); // true }); socket.on('message', function(msg){console.log('message!', msg)}); socket.on('reply', function(msg){console.log('reply!', msg)}); socket.on('disconnect', () => { console.log(socket.connected); // false }); } When i'm running both cilent and server,i'm getting error WebSocket connection to 'ws://localhost:8000/socket.io/?EIO=3&transport=websocket' failed: Error during WebSocket handshake: Unexpected response code: 400 at client side and "GET /socket.io/?EIO=3&transport=websocket HTTP/1.1" 400 11 at server side socket.io-client verison-2.3.0 -
Django - accessing a stored excel file in Django model viewer
I am trying to access excel files through the django-admin model viewing portal. Each excel file is generated through a seperate algorithm, and is already in a directory called excel_stored each excel file is generated with an ID that corresponds to its model # in django. So it would be excel_%ID%.xlsx or excel_23.xlsx for example. I want my django FileField() to access the relevant excel file so that I can download it from my django admin portal, just like I can access my other model information (city name, time uploaded, etc). Here is a pseudo-code of what I'd want to do: My models.py would look like this excel = models.FileField() The process of saving would look like this create_excel() ### EXCEL WAS SAVED TO DIR: excel_stored ### save_excel = Model(excel = file.directory((os.path.join(BASE_DIR, 'lead/excel_stored/excel_%s.xlsx' %ID)) save_excel.save() Id then be able to download it like this https://i.stack.imgur.com/4HRUU.gif I know there's a lot I'm missing, but most documentation I find refers to uploading an excel file through forms, not accessing it. I've been stuck on this for a while, so I'd appreciate some direction! Thank you! -
"Visual" set up project page for django?
I would like to sell app to lot of people. The problem i got is, i don't want people have to set variable into settings.py file, because they have no knowledge into programmation. So i would like to know if it's possible to do this kind of stuff : They connect to the site on admin (or maybe just connect first time) That redirect them to a page with form They choose their settings and that update it directlty into settings.py Like that they will just set the project with a beautiful view, and they have no edition of settings.py to do manually. Thank for your help ! -
How to count Artist in ManyToMany Field in Django
i want to count the number of videos made by a single artist so please tell me where am i wrong? Here is My code in admin.py File class ArtistAdmin(admin.ModelAdmin): list_display = ['name', 'date_of_birth', 'artist_videos'] def artist_videos(self, obj): count = 0 for artistcount in Artist.objects.all(): if artistcount.name == VideoList.artists: count = count + 1 return count And her is my code in models.py class Artist(models.Model): name = models.CharField(max_length=200) date_of_birth = models.DateTimeField() def __str__(self): return self.name class VideoList(models.Model): title = models.CharField(max_length=200) artists = models.ManyToManyField(Artist) def __str__(self): return self.title -
How to save json in django database?
I need to save json file from API in database (postgresql) using django. I have classic model which extends the AbstractUser with the default fields for first name, last name and etc. I made a research but can't find how to achieve saved json from API in database while using django. I will appreciate any help or guide. -
Recieving errors when running server with manage.py
im trying to run a server on my laptop, when in the console i type 'python manage.py runserver' i recieve some errors. could it be i need to import some modules i tried 'pip install python-cron' but that didnt work. the error says: [2020-11-10 09:04:47,241] autoreload: INFO - Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/threading.py", line 932, in _bootstrap_inner self.run() File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/utils/autoreload.py", line 76, in raise_last_exception raise _exception[1] File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/management/__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'django_cron' the cron.py file i have is: from django.contrib.auth.models import User import os import datetime from crontab import CronTab #from django_common.helper import send_mail from … -
How to configure Geonode's geoserver on my ubuntu server using nginx
I have configured geonode and it is working fine on my local machine. I have proceeded to move it to an ubuntu server and I am using Nginx and gunicorn. I am having a challenge in starting my GeoServer on this URL 'geonode1.local.com/geoserver where I get the error below in my error.log: 2020/11/10 07:36:38 [error] 825#825: *7 "/usr/share/nginx/html/geoserver/web/index.html" is not found (2: No such file or directory), client: 197.232.113.55, server: geonode1.local.com, request: "GET /geoserver/web/ HTTP/1.1", host: "geonode1.local.com" my question: How do I get GeoServer to start on this URL? Do I need to install tomcat9 on my server? /etc/nginx/sites-available/geonode server { listen 80; server_name geonode1.local.com; location = /favicon.ico { access_log off; log_not_found off; } location ^~ /static/ { alias /home/user/Geosites/geonode/static/; } location ^~ /uploaded/ { alias /home/user/Geosites/geonode/uploaded/; } location /geoserver/ { proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } # gunicorn wsgi proxy location / { proxy_pass http://unix:/run/gunicorn.sock; proxy_pass_header Server; proxy_set_header Host $http_host; proxy_redirect off; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Scheme $scheme; proxy_connect_timeout 20; proxy_read_timeout 20; } location ^~ /static/admin/ { alias /home/user/Geosites/geosite_env/lib/python3.6/site-packages/django/contrib/admin/static/admin/ } } -
default integer value for non-primary field in django with postgresql
I have a non-primary key integer field in my Django model and I use Postgresql for database. class TestModel(models.Model) pid = models.IntegerField(blank=True) some_field = models.CharField() I want my pid field to have default values, that appear in database, I set the serial type for the pid field on the DB side alter column pid type serial not null; but when I create some record without without specifying value for pid, Django gives an error "null value in column "pid" violates not-null constraint", although it works fine when inserting data via SQL directly into database. I found this Django and PostgreSQL sequence for primary key autoincrement, but it's not working for me -
How to query ManyToManyField linked with a Foreign Key and that Foreign Key is linked with another Foreign Key?
I have created a TimeTable model that is linked to the Period Model via ManyToManyField and the Period Model is linked to the PeriodData via a Foreign Key. The models are working fine but I have very little idea of how to query the data. Here is the TimeTableModel - TimeTable Model class TimeTable(models.Model): class_id = models.OneToOneField(Classes, on_delete=models.CASCADE) monday = models.ManyToManyField('Period', related_name='monday', blank=True) tuesday = models.ManyToManyField('Period', related_name='tuesday', blank=True) wednesday = models.ManyToManyField('Period', related_name='wednesday', blank=True) thursday = models.ManyToManyField('Period', related_name='thursday', blank=True) friday = models.ManyToManyField('Period', related_name='friday', blank=True) saturday = models.ManyToManyField('Period', related_name='saturday', blank=True) Period Model class Period(models.Model): period_id = models.CharField(unique=True, max_length=50) class_id = models.ForeignKey(Classes, on_delete=models.CASCADE) period1 = models.ForeignKey('PeriodData', related_name='period1', blank=True, null=True, on_delete=models.CASCADE) period2 = models.ForeignKey('PeriodData', related_name='period2', blank=True, null=True, on_delete=models.CASCADE) period3 = models.ForeignKey('PeriodData', related_name='period3', blank=True, null=True, on_delete=models.CASCADE) period4 = models.ForeignKey('PeriodData', related_name='period4', blank=True, null=True, on_delete=models.CASCADE) period5 = models.ForeignKey('PeriodData', related_name='period5', blank=True, null=True, on_delete=models.CASCADE) PeriodData Model class PeriodData(models.Model): period_data_id = models.CharField(unique=True, max_length=50) class_id = models.ForeignKey(Classes, on_delete=models.CASCADE) subject_id = models.ForeignKey(Subject, null=True, on_delete=models.SET_NULL) teacher = models.ForeignKey(Teacher, null=True, on_delete=models.SET_NULL) start_time = models.TimeField() end_time = models.TimeField() Let's say that there is a class1 and on monday it has maths as its period1 and bio as its period2 and so on. And there's another class2 and on monday it has physics as its period1 … -
django digitalocean deploy cannot serve static files
[![enter image description here][1]][1]I try to deploy my app on digitalocean, when i configure the ngnix server, everything works except all the css and js file are not being served. I have done collectstatic, and my /etc/nginx/sites-available looks like this server { listen 80; server_name my ip; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/djangodeploy/portfolio-blog; } location /media/ { root /home/djangodeploy/portfolio-blog; } location / { include proxy_params; proxy_pass http://unix:/home/djangodeploy/portfolio-blog/mysite.sock; } } and my file structure looks like this [1]: https://i.stack.imgur.com/sg34k.png