Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I include username (<str:username>) in my react native Endpoint
Please im learning react native and I am stuck, my problem is that I need to be about to use something like this in my react native (API): const endpoint = "/users/<username>/"; const getUser = () => client.get(endpoint); So the gist is, I want to dynamically pass the user's username in there, because thats the only way to get the details from the backend (REST API), When i use POSTMAN and get this http://127.0.0.1:8000/api/users/*username* it returns the needed data, but when I try that, even putting the username manually it doesnt work . Secondly, is there a way to get the user's username from jwt token and pass it into the react native endpoint. Id share my code below, Please bear with me: API URL PATH IN DJANGO: path('<str:username>/', profile_detail_api_view), path('<str:username>/follow', profile_detail_api_view), API CALL IN REACT NATIVE: import client from "./client"; const endpoint = "/users/que/"; (FOR INSTANCE HERE IM PASSING THE USERNAME DIRECTLY TO TEST) const getUser = () => client.get(endpoint); export default { getUser, }; PAYLOAD ON JWT SAMPLE: { "token_type": "access", "exp": 1611483456, "jti": "47907077556234bd9b6a9fa330f5ee", "user_id": 2 } I have tried a direct endpoint (blog) and it works, but that user part doesnt even though its the same … -
How to modify the form field types in the django CreateView form
I have a model that has a couple of date fields. I am using the CreateView along with a template. In the template, I am doing fairly standard code {% extends 'instructor_base.html' %} {% load crispy_forms_tags %} {% block title %} New Section {% endblock %} {% block content %} <h1>New Section</h1> <form method="post"> {% csrf_token %} {{ form|crispy }} <button class="btn btn-success ml-2" type="submit">Save</button> </form> {% endblock %} However, when the form displays, the two date fields in the model are displayed as text boxes in the form. I would like them to display as date type. After several hours of going through documentation and tutorial sites, I can not figure out how to accomplish this. Everything I find is on how to override CreateView itself and not the form that goes with it. Any help with this would be greatly appreciated. -
Nginx stopped and failed to restart - open() "/run/nginx.pid" failed
I am running my django apis, deployed on Ubuntu 18, on Nginx and running via Supervisor. I am using Certbot for SSL certs and this is the only web service running on this webserver. No other websites are deployed here. The APIs went down today and nginx stopped working. I am not able to recreate why this happened, it had to be manually restarted. I have faced this once before and had similar error messages in the logs. Following are the nginx error logs. 2021/01/09 15:55:39 [crit] 9453#9453: *1331764 SSL_do_handshake() failed (SSL: error:1420918C:SSL routines:tls_early_post_process_client_hello:version too low) while SSL handshaking, client: <CLIENT IP ADDRESS>, server: 0.0.0.0:443 2021/01/09 20:39:55 [error] 9453#9453: *1337050 upstream prematurely closed connection while reading upstream, client: <CLIENT IP ADDRESS>, server: , request: "PUT /api/v1/APIURL/ HTTP/1.1", upstream: "http://127.0.0.1:8081/api/v1/APIURL", host: "<URL>", referrer: "<URL>" 2021/01/09 20:40:12 [error] 9453#9453: *1337057 upstream prematurely closed connection while reading upstream, client: <CLIENT IP ADDRESS>, server: , request: "PUT /api/v1/APIURL/ HTTP/1.1", upstream: "http://127.0.0.1:8081/api/v1/APIURL", host: "<URL>", referrer: "<URL>" 2021/01/09 20:41:02 [error] 9453#9453: *1337064 upstream prematurely closed connection while reading upstream, client:<CLIENT IP ADDRESS>, server: , request: "PUT /api/v1/URL/ HTTP/1.1", upstream: "http://127.0.0.1:8081/api/v1/URL/", host: "URL", referrer: "URL" 2021/01/10 03:51:29 [notice] 32527#32527: signal process started 2021/01/10 03:51:29 [error] 32527#32527: open() … -
How to include related models Django
I have 3 models: class ImageAlbum(models.Model): def default(self): return self.images.filter(default=True).first() def thumbnails(self): return self.images.filter(width__lt=100, length_lt=100) class Image(models.Model): name = models.CharField(max_length=255) image = models.ImageField(upload_to='images/') default = models.BooleanField(default=False) width = models.FloatField(default=100) length = models.FloatField(default=100) album = models.ForeignKey(ImageAlbum, related_name='images', on_delete=models.CASCADE) class Product(models.Model): title = models.CharField(max_length=300) price = models.IntegerField() description = models.TextField(max_length=2000, help_text="This is the description of the product") images = models.OneToOneField(ImageAlbum, related_name='model', on_delete=models.CASCADE) When I'm selecting product models Product.objects In the Product field images I'm having only the primary key of album. I want to get related ImageAlbum and all related Image for each ImageAlbum when I'm selecting Product model. Appreciate any help, thanks. -
Implement Page/Google-Login Counter with Django and Cookies?
I want to keep track: 1.) How many visitors went on my homepage 2.) How many logged in with the Google button For now I simply created with python a django-model: id url visitor_counter google_login_counter Everytime someone visits a page with the url x, it increases the visitor_counter. Everytime someone logs in with Google on the page x, it increases the google_login_counter. So far, so good, but now I have the problem, that if the user reloads the page, the counter increases again. I want to prevent this and wanted to ask what is the best solution? I was thinking about using cookies to check, if the user was already on the page? Is there a better solution or should I go with cookies? -
AttributeError: 'NoneType' object has no attribute 'append' error in Django project
I'm trying to store a list of items in a Django session. The code is below, def index(request): today = date.today() d = today.strftime("%A, %B %d") if request.method == 'POST': item = request.POST.get('newItem') items = request.session.get('items',[]) request.session.modified = True request.session['items'] = items.append(item) return render(request, 'todo/index.html', {'kindOfDay':d, 'newListItems': request.session.get('items', list())}) I get the following error, AttributeError: 'NoneType' object has no attribute 'append' I have included the below two lines in settings.py SESSION_SAVE_EVERY_REQUEST = True SESSION_ENGINE = "django.contrib.sessions.backends.signed_cookies" I'm a beginner and any help would be appreciated. -
SSO with Django for Matrix
I have a working Django (3.1) website and I'm trying to setup a Matrix Server (using Synapse) for the users. How can I Setup Single Sign On for synapse (It supports SAML, CAS and OIDC) where only the users of my website could login to it? I already saw Django OIDC Provider, but I didn't figure how to set it up there. Any Idea for making it easier? -
using Dockerfile as host for python development
I'm developing a Django application and using Pipenv to manage the python virtual environment. There are few dependencies that are causing the problem on installation in the host operating system. These issues are different for different operating systems (Mac, Linux, windows). I have created a Dockerfile with the following content FROM python:3.7.6-slim # Create a group and user to run our app ARG APP_USER=anychat RUN groupadd -r ${APP_USER} && useradd --no-log-init -r -g ${APP_USER} ${APP_USER} # Install packages needed to run your application (not build deps): RUN set -ex \ && RUN_DEPS=" \ libpcre3 \ mime-support \ libmagic1 \ default-libmysqlclient-dev \ inkscape \ libcurl4-nss-dev libssl-dev \ " \ && seq 1 8 | xargs -I{} mkdir -p /usr/share/man/man{} \ && apt-get update && apt-get install -y --no-install-recommends $RUN_DEPS \ && pip install pipenv \ && mkdir /app/ \ && mkdir /app/config/ \ && mkdir /app/scripts/ \ && mkdir -p /static_cdn/static_root/ \ && chown -R ${APP_USER} /static_cdn/ WORKDIR /app/ COPY Pipfile Pipfile.lock /app/ RUN set -ex \ && BUILD_DEPS=" \ build-essential \ libpcre3-dev \ libpq-dev \ " \ && apt-get update && apt-get install -y --no-install-recommends $BUILD_DEPS \ && pipenv install --deploy --system # Copy your application app to the container … -
How could I create many db objects with python for loop?
I want to create multiple db objects with for loop: if request.method == 'POST': answers_data = InterestAnswer.objects.all() for userAns in answersIDs: for answerObj in answers_data: cur = answerObj.id if userAns == cur: userAnswered = UserAnswer(answer=answerObj, user= request.user, is_checked=True) userAnswered.save() and here's my model: class UserAnswer(models.Model): is_checked = models.BooleanField(default=False) answer = models.ForeignKey(InterestAnswer, max_length=64, on_delete=models.CASCADE) user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) from html page I am getting a bunch ids of answers and for each of these ids I want to create a db object, am I doing it correctly? I am getting this error: UNIQUE constraint failed: account_useranswer.user_id When my user is completing this quiz for the first time only the first id is used to create object in database, and the others are disappearing. When the same user tries to complete the same quiz I am getting this error I mentioned before. What's the problem? -
JS not working in Django Templates (addEventListener and getPropertyValue
I have a javascript that works when I run it outside of Django; however, when I try to run it within my Django Project, I get an error saying "Uncaught TypeError: Cannot read property 'addEventListener' of null" and an error saying "Uncaught SyntaxError: Identifier 'getPropertyValue' has already been declared. I was wondering if JS works the same within Django Templates as it does it normal html. -
How to automatically create a new entry in postgresql table weekely
I am creating a weekly progress checking website in which user can add weekly progress for which i have created a new table called progress which has a foreign key user_id now I want to add an entry to this progress table automatically after every week for that particular user in which he can save current week goals, target etc. -
ERROR (spawn Error) when trying to start my supervisor conf
WebAPP_celery.conf file ; ================================== ; celery worker supervisor example ; ================================== ; the name of your supervisord program [program:webappcelery] ; Set full path to celery program if using virtualenv command=/home/brennan/webapp/env/bin/celery worker -A WebAPP --loglevel=INFO ; The directory to your Django project directory=/home/brennan/webapp/ ; If supervisord is run as the root user, switch users to this UNIX user account ; before doing any processing. user=brennan ; Supervisor will start as many instances of this program as named by numprocs numprocs=1 ; Put process stdout output in this file stdout_logfile=/var/log/celery/webapp_worker.log ; Put process stderr output in this file stderr_logfile=/var/log/celery/webapp_worker.log ; If true, this program will start automatically when supervisord is started autostart=true ; May be one of false, unexpected, or true. If false, the process will never ; be autorestarted. If unexpected, the process will be restart when the program ; exits with an exit code that is not one of the exit codes associated with this ; process’ configuration (see exitcodes). If true, the process will be ; unconditionally restarted when it exits, without regard to its exit code. autorestart=true ; The total number of seconds which the program needs to stay running after ; a startup to consider the start … -
form doesn't submit productbacklogs to database
#model.py from django import forms from projectapp.models import Project class ProjectForm(forms.ModelForm): class Meta: model = Project exclude=('proId',) fields = ['proTitle'] #forms.py from django import forms from productbacklogapp.models import Productbacklog from projectapp.models import Project class ProductbacklogForm(forms.ModelForm): class Meta: model = Productbacklog exclude=('pbId','project') fields=['pbTitle'] #views.py def productbacklogall(request): Projectinlineformset = inlineformset_factory(Project, Productbacklog, form=ProductbacklogForm) if request.method=='POST': backlogform = ProductbacklogForm(request.POST) b=backlogform.save(commit=False) b.save() formset=Projectinlineformset(request.POST,request.FILES,instance=b) if formset.is_valid(): formset.save() messages.success(request, ('new productbacklog added')) return redirect('productbacklogall') else: pb_all=Productbacklog.objects.all() return render(request,'productbacklogall.html',{'pb_all':pb_all}) -
Force Close App Browser Django ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host
I'm a beginner in Django and I'm trying to test the registration form that I created on my mobile browser, it's working fine, but every time I force close the browser application on my phone or my phone screen timed out I get [WinError 10054] I have this on my settings.py ALLOWED_HOSTS = ['myip'] and I run my server like this python manage.py runserver 0.0.0.0:8000 Error that I get: ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host Is there something I need to configure, so this error won't show up? Thank you. -
JQuery disable submit button till form is completely filled
I am trying to implement a jquery function to diable submit button till all values are filled please help as I seem not to find a solution to it..Where am I going wrong? Here is the html: <form action="{% url 'register' %}" id="registerform" class="sign-up-form" method="POST"> {% csrf_token %} <h2 class="title">Sign up</h2> <div class="row"> <div class="col-md-6"> <div class="input-field"> <i class="fas fa-user"></i> <input type="text" name="firstname" placeholder="First name"/> </div> </div> <div class="col-md-6"> <div class="input-field"> <i class="fas fa-user"></i> <input type="text" name="secondname" placeholder="Second name"/> </div> </div> <div class="col-md-6"> <div class="input-field userfield"> <i class="fas fa-user"></i> <input type="text" id="id_username" name="username" placeholder="Username"/> </div> </div> <div class="col-md-6"> <div class="input-field emailfield"> <i class="fas fa-envelope"></i> <input type="email" id="id_email" name="email" placeholder="Email"/> </div> </div> <div class="col-md-6"> <div class="input-field"> <i class="fas fa-lock-open"></i> <input type="number" name="idno" placeholder="ID/Passport Number"/> </div> </div> <div class="col-md-6"> <div class="input-field"> <i class="fas fa-user-ninja"></i> <input type="text" name="nationality" placeholder="Nationality"/> </div> </div> <div class="col-md-6"> <div class="input-field passfield"> <i class="fas fa-lock"></i> <input type="password" id="password" onkeyup="checkPasswordStrength();" name="password" placeholder="Password"/> </div> </div> <div class="col-md-6"> <div class="input-field cpassfield"> <i class="fas fa-lock"></i> <input type="password" id="cpassword" onkeyup="cpassword();" placeholder="Confirm Password"/> </div> </div> </div> <input type="submit" id="register" class="btn" style="background-color: #5995fd;!important;" value="Sign up" disabled/> <p class="copy-text">&copy;2020. All Rights Reserved</p> <h3 class="copy-text"> Kenya Airways</h3> </form> and the javascript: <script> //disable submit button (function () { … -
syntactic problem with list display in django
I'm learning django through a tutorial on youtube, and even faithfully following the video, this problem continues, how to solve? enter image description here -
no such column: ecomapp_toplist.desc can anyone find error why it is showing in django
why no such column: ecomapp_toplist.desc is showing because i make desc in model and register it also . class TopList(models.Model): image = models.ImageField(upload_to='ProductImg') title = models.TextField(max_length=500) discountpercentage = models.IntegerField(blank=True,null=True) discountPrice = models.IntegerField(blank=True,null=True) brandName = models.TextField(max_length = 100 , default='',null=True,blank=True) finalprice = models.IntegerField(blank=True,null=True) category = models.ForeignKey(Category , on_delete=models.CASCADE, default=1) desc = models.TextField(max_length=5000) class Category(models.Model): name = models.CharField(max_length=20) @staticmethod def get_all_categories(): return Category.objects.all() my admin.py by @admin.register(TopList) class TodoListModelAdmin(admin.ModelAdmin): list_display=['id','image','title','category' ] -
Dockerized Django project not able to connect to host's postgres database
So I have a Django project which is running in Docker, which is trying to connect postgres which is running on host machine. But I am getting error web_1 | django.db.utils.OperationalError: could not connect to server: Connection refused web_1 | Is the server running on host "localhost" (127.0.0.1) and accepting web_1 | TCP/IP connections on port 5432? web_1 | could not connect to server: Cannot assign requested address web_1 | Is the server running on host "localhost" (::1) and accepting web_1 | TCP/IP connections on port 5432? I know that we need to make postgres to listen for requests from other IP addresses. I have already made changes in postgres settings. Added few lines in following files. /etc/postgresql/12/main/postgresql.conf listen_addresses = '*' /etc/postgresql/12/main/pg_hba.conf host all all 172.17.0.0/16 trust In Django project settings.py has DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'django_docker', 'USER': '<postgres_user>', 'PASSWORD': '<password>', 'HOST': 'localhost', 'PORT': '5432', 'ATOMIC_REQUESTS': True } } I am not sure why I am getting this error. I also tried to use 127.0.0.1 and <public_ip> of host in Django database HOST settings, but I still get same error. All versions Django : 3.0.5 PostgreSQL : 12.5 Docker : 20.10.1 docker-compose : 1.25.0 I am … -
Django: How to render HTML template based on tuple choice
I have created a model, views and templates like so: MODEL project_choices = ( ('Speaker', ( ('help', 'Freedom'), )), ('Money', ( ('invest', 'Investment'), ) ), ( 'Children', ( ('mc', 'Mother & Child'), ) ), ) class Blog(models.Model): title = models.CharField(max_length=250) description = CKEditor5Field('Text', null=True) limitation = models.BooleanField( null=True, max_length=50, choices=project_choices) def __str__(self): return self.title Now the VIEW def view_portfolio(request): blog= Blog.objects.all() template = 'blog/blog.html' context = {'blog': blog} return render(request, template, context) then the hmtl template {% for blog in blog%} {% if blog.limitation['**help**'] %}**//I have also tried {% if portfolio.limitation == project_choices['AI']%}** <div class="col-lg-4 col-md-6"> <div class="portfolio-wrap"> <img src="{{blog.featured}}" class="img-fluid" alt=""> <div class="blog-info"> <h4>{{blog.title}}</h4> <p></p> <div class="portfolio-links"> <a href="{{blog.featured}}" data-gall="blogGallery" class="venobox" title="{{blog.title}}"><i class="bx bx-plus"></i></a> <a href="blog-details.html" title="More Details"><i class="bx bx-link"></i></a> </div> </div> </div> </div> {% endif %} {%endfor%} My goal is to show blogs based on ONLY help as the chosen choice please how can I achieve this? I am using django3 -
TodayArchiveview is not detected in urls.py(Django)
I created several date-based views in Django, and while views for year and month function as expected, the view to display today is not detected. For instance, if I try to get http://127.0.0.1:8000/blog/archive/2021/, or http://127.0.0.1:8000/blog/archive/2021/jan or http://127.0.0.1:8000/blog/archive/2021/jan/07/ the views will be displayed, http://127.0.0.1:8000/blog/archive/today/ will fail. I understand that the problem must be with urls.py configuration, but I just cannot find it in documentation. urls.py from django.urls import path, re_path from blog import views app_name = 'blog' urlpatterns = [ # Example: /blog/ path('', views.PostListView.as_view(), name='index'), # Example: /blog/post/ (same as /blog/) path('post/', views.PostListView.as_view(), name='post_list'), # Example: /blog/post/django-example/ re_path(r'^post/(?P<slug>[-\w]+)/$', views.PostDetailView.as_view(), name='post_detail'), # Example: /blog/archive/ path('archive/', views.PostArchiveView.as_view(), name='post_archive'), # Example: /blog/archive/2019/ path('archive/<int:year>/', views.PostYearArchiveView.as_view(), name='post_year_archive'), # Example: /blog/archive/2019/nov/ path('archive/<int:year>/<str:month>/', views.PostMonthArchiveView.as_view(month_format = '%b'), name='post_month_archive'), # Example: /blog/archive/2019/nov/10/ path('archive/<int:year>/<str:month>/<int:day>/', views.PostDayArchiveView.as_view(), name='post_day_archive'), # Example: /blog/archive/today/ path('archive/today/', views.PostTodayArchiveView.as_view(), name='post_today_archive'), ] views.py from django.shortcuts import render # Create your views here. from django.views.generic import ListView, DetailView, ArchiveIndexView, YearArchiveView, MonthArchiveView, \ DayArchiveView, TodayArchiveView from blog.models import Post class PostListView(ListView): model = Post template_name = 'blog/post_all.html' context_object_name = 'posts' paginate_by = 2 class PostDetailView(DetailView): model = Post class PostArchiveView(ArchiveIndexView): model = Post date_field = 'modify_dt' class PostYearArchiveView(YearArchiveView): model = Post date_field = 'modify_dt' make_object_list = True class PostMonthArchiveView(MonthArchiveView): model = … -
Query set is empty for long search input python django
When i am querying from database its gives queryset empty for long query input in the search eg. if i type "shiv" it gives all matches to this like "shivamshankhdhar" but i type "shivamshankhdhar" its return empy queryset this is my code def account_search_view(request, *args, **kwargs): context = {} if request.method == "GET": search_query = request.GET.get("q") print(f"query for {search_query}") if len(search_query) > 0: print("querying data.....") print(type(search_query)) search_results = Account.objects.filter(email = search_query) # user = request.user print(search_results) accounts = [] # [(account1, True), (account2, False), ...] for account in search_results: accounts.append((account, False)) # you have no friends yet context['accounts'] = accounts return render(request, "accounts/search_result.html", context) -
using django-synchro trying to synchronize two database and getting psycopg2.IntegrityError: duplicate key value violates unique constrain
Following is the exception getting in one database of postgres and sync is happening properly from another side. while testing in local it is working properly but when we imported users from existing database this exception occuring. Following is the exception getting in one database of postgres and sync is happening properly from another side. while testing in local it is working properly but when we imported users from existing database this exception occuring. Following is the exception getting in one database of postgres and sync is happening properly from another side. while testing in local it is working properly but when we imported users from existing database this exception occuring. Finding ref for ct: User, id: 51 found ref Reference object (869) and remote administrator@gmail.com Exception: duplicate key value violates unique constraint "synchro_reference_content_type_id_local_object_id_f2c39050_uniq" DETAIL: Key (content_type_id, local_object_id)=(21, 475) already exists. Traceback (most recent call last): File "/usr/local/lib/python3.5/dist-packages/django/db/models/query.py", line 486, in get_or_create return self.get(**lookup), False File "/usr/local/lib/python3.5/dist-packages/django/db/models/query.py", line 399, in get self.model._meta.object_name synchro.models.Reference.DoesNotExist: Reference matching query does not exist. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/lib/python3.5/dist-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) psycopg2.IntegrityError: duplicate key value violates unique constraint "synchro_reference_content_type_id_local_object_id_f2c39050_uniq" … -
ModuleNotFoundError: No module named 'models' in django
https://github.com/prathmachowksey/Attendance-System-Face-Recognition im using this repo and facing this issue can help me -
How do I play only a portion of a video stored on AWS?
I have videos hosted on AWS S3 and ideally I would access them via something like <video muted autoplay loop><source src="https://mybucket.aws.com/videos/test.mp4#t0,15"></source></video>, causing only a certain part of the video to play and have it on loop. The issue is that the bucket is not public and so involves generating a pre-signed URL. I am using Django and boto3 in order to generate the pre-signed URL, but as soon as I attempt to insert #t0,15, it fails (either the # and , will be decoded, the #t0,15 string will be removed or the URL will return access denied, depending on what was attempted). How might I go about this? -
Load external data into an admin model - DJANGO
Is it possible to load external data into a field for filling in? Example: A field with for product names. However we already have the names of the products in another location, we just need to list these products within the field in the default django admin. Using resquets. Thank you very much for your attention.