Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
(Nginx+Daphne+Django) Error during WebSocket handshake: Unexpected response code: 404
I have an Django(3.0) app using Daphne as an app container and Nginx as proxy server. Daphne -u /home/ubuntu/virtualenvs/src/app/app.sock app.asgi:application My problem is that the websocket connection failed. (index):16 WebSocket connection to 'ws://example.com/ws/chat/1/' failed: Error during WebSocket handshake: Unexpected response code: 404 I'm pretty sure that my app setting and route is just fine. Because if I stop Nginx, bind Daphne to 0.0.0.0:8000 and use real IP("ws://xx.xx.xx.xx:8000/ws/chat/1") as URL, the websocket connection established and very stable. How should I modify my Nginx to make websocket work? #my nginx setting upstream websocket { server unix:/home/ubuntu/virtualenvs/src/app/app.sock; } #websocket settings map $http_upgrade $connection_upgrade { default upgrade; '' close; } server { listen 80; listen [::]:80 default_server; listen 443 SSL default_server; listen [::]:443 SSL default_server; server_name example.com; return 301 https://example.com$request_uri; ssl on; # certificate settings ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; ssl_session_timeout 10m; #ssl_session cache shared:SSL:1m; #ssl_protocols TLSv1 TLSv1.1 TLSv1.2 SSLv2 SSLv3; #ssl_prefer_server_ciphers on; #ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!$ location / { root /home/ubuntu/virtualenvs/ include proxy_params; proxy_pass https://websocket; proxy_set_header Host $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; proxy_set_header X-Frame-Options SAMEORIGIN; proxy_pass_request_headers on; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; } location ~* \.(js|css)$ { expires -1; } } -
Django: runserver: How to customize the "[DD/MMM/YYYY HH:MM:SS] GET / HTTP/1.1" log statement [duplicate]
This question already has an answer here: Django logging requests 2 answers I am running a django project. I run the server using python manage.py runserver When i open a page in the browser it outs [13/Jan/2020 08:36:21] "GET / HTTP/1.1" 200 298 Not Found: /favicon.ico [13/Jan/2020 08:36:22] "GET /favicon.ico HTTP/1.1" 404 2683 I want to cutomize this to [13/Jan/2020 08:36:21] "GET / HTTP/1.1" 200 298 $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ ######################################################################### @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ Not Found: /favicon.ico [13/Jan/2020 08:36:22] "GET /favicon.ico HTTP/1.1" 404 2683 $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ ######################################################################### @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ I want to add some divider lines because many times it gets mixed up -
How to send information to a different application django?
im trying to link up 2 different projects through a url link. There will be a button for me to press. Upon pressing this button , i wish to be able to send out a primary key to the other project , which will then be captured in the other project's database eventually. The first programme is done using python django , and the second project is done using c# , is there a way to accomplish this? -
Will It be easier to develop a flight booking system with Django? [closed]
I am a newbie to web development but I know python. I have to make a flight booking system within two weeks with a seating arrangement of the flight that changes dynamically when booking a seat. Should I use Django as it comes with many pre-built tools or I should go for express.js or any other stack? I will learn Django while developing the website. -
Attendance system in Django
I'm working on Attendance system in Django. but I'm facing some issue. model.py attendance_choices = ( ('absent', 'Absent'), ('present', 'Present') ) class AttendenceTable(models.Model): schedule_name = models.ForeignKey(ScheduleTable, on_delete=models.CASCADE, blank=True) RollNo = models.CharField(max_length=46, blank=True, null=True) student_name = models.TextField(blank=True, null=True) status = models.CharField(max_length=8, choices=attendance_choices, blank=True) def __str__(self): return self.RollNo ** views.py ** def take_attendance(request, id): schedule = get_object_or_404(ScheduleTable, pk=id) userlist = User.objects.filter(college = schedule.college).filter(is_student=True).filter(section=schedule.section) context = { "userlist":userlist, "schedule_name": schedule, } return render(request, "take.html", context ) def AttendanceStore(request, id): sch = get_object_or_404(ScheduleTable, pk=id) userlist = User.objects.all().filter(college=sch.college).filter(section=sch.section) attendance = OnlineAttendanceTable() insert_list = [] for user in userlist: userstatus = request.POST.get(str(user.username)) attendance.schedule = sch.name attendance.usn = user.username attendance.status = userstatus insert_list.append(attendance) print(insert_list) OnlineAttendanceTable.objects.bulk_create() return render(request, "submitattendance.html" ) result As per screenshot, it is replicating data in model but i need one data per user suggest me any idea to make attendance system in Django -
Improving Admin using django-pagedown
I am currently trying to utilize django-pagedown to preview posts in admin. However, there are a few things that I would like to add that I don't know how. The two issues are that I do not know how to align the textarea correctly, and I cannot render LaTeX using MathJax in Pagedown correctly. This is what I'm talking about: So far, this is what I have done: This is my Problem Model: class Problem(models.Model): slug = models.CharField(max_length = 250, unique = True) topic = models.ForeignKey(Topic, on_delete = models.CASCADE) questionToProblem = models.TextField() solutionToProblem = models.TextField() class Meta: ordering = ('questionToProblem',) def get_url(self): return reverse('solution_details', args = [self.topic.slug, self.slug]) def __str__(self): return self.questionToProblem Like what the documentation says, I have added a separate form for Problem: class ProblemForm(forms.ModelForm): questionToProblem = forms.CharField(widget=AdminPagedownWidget()) solutionToProblem = forms.CharField(widget=AdminPagedownWidget()) class Meta: model = Problem fields = "__all__" And finally, in admin.py, I used: @admin.register(Problem) class ProblemModelAdmin(admin.ModelAdmin): form = ProblemForm fields = ('questionToProblem', 'solutionToProblem') Unfortunately, changing the variable names from questionToProblem and solutionToProblem solves this issue, but the resulting textarea is completely blank. Another issue is that how would I implement MathJax in django-pagedown so that LaTeX code can be displayed properly? Please help. -
drf-yasg - How remove the URL endings with {format}
How can I remove the generated URL that ending with {format}? -
Django Paginator. Custom use
Model class Book(models.Model): text = models.CharField(max_length=100) number = models.IntegerField() chapter = models.IntegerField() View class Book(TemplateView): template_name = "book.html" def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) try: page_num = self.request.GET['page'] except KeyError: page_num = 1 context['book'] = Book.objects.all() paginator = Paginator(context['book'], 6) context['data'] = paginator.get_page(page_num) return context The chapter field is the chapter of the book. It is necessary to make sure that when you click on the links, you go to the page of a specific chapter of the book with all its entries (text field). Is it possible to do this using the Django paginator? It seems there is a class Page (object_list, number, paginator) -
http://127.0.0.1:8000 django development server not loading on chrome or any browser
enter image description here enter image description here Dear All, Development server is not loading on browser. I have used chrome, IE, edge. Though the server is running without any error in terminal. Using Django 2.x in atom text editor. Please suggest.. -
Forbidden 403 CSRF verification failed. Request aborted. drf
i am trying to upload image with drf: urls.py: path('eventimageupload/<int:category>/', views.EventImageUploadView.as_view()), views.py: class EventImageUploadView(generics.ListCreateAPIView): authentication_classes = [] permission_classes = [] def post(self, request,category): file = request.data['file'] data={ 'image':file, 'category_id':category, } EventsImage.objects.create(**data) return JsonResponse(json.dumps({'message': "Uploaded"}), status=200, safe=False) its working good on localhost but from server its getting this error -
docker-compose exec web python manage.py makemigrations problem
Problem I created a new Django project and tried to change the database from default to PostgreSQL. After changing the DATABASES in settings.py, I tried to run python manage.py migrate in local environment and docker-compose containers. While it worked ok in local settings, the docker-compose didn't. It throws django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: No module named 'psycopg2'. error. So, is there any way to fix this? Steps to replicate the error OS: WSL Ubuntu 4.4.0-18362-Microsoft docker-compose up -d docker-compose exec web pipenv install psycopg2-binary==2.8.4 docker-compose down docker-compose exec web python manage.py migrate Database settings and Docker Files DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'Bardwolf@314', 'HOST': 'localhost', 'PORT': 5432 } } My docker-compose.yml, Dockerfile Dockerfile FROM python:3.8 ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 WORKDIR /code COPY Pipfile Pipfile.lock /code/ RUN pip install pipenv && pipenv install --system RUN pipenv run pip install psycopg2-binary==2.8.4 COPY . /code/ docker-compose.yml version: '3.7' services: web: build: . command: python /code/manage.py runserver 0.0.0.0:8080 volumes: - ./code ports: - 8080:8080 depends_on: - db db: image: postgres:11 -
Django unquote() with url parameters
I had used unquote in my urls before to get special characters in the url like so: path('example/<str:phone_number>', views.find_user_by_phone_number.as_view(), name='api.find_user_by_phone_number'), #call with example/+849323212231 and in my views: from urllib.parse import unquote ..... phone_number = unquote(str:phone_number) print(phone_number) and it worked greate and i got +849323212231 with special character + But now i need to make url with multiple parameters that can has phone_number in it: path('example', views.find_user_by_phone_number.as_view(), name='api.find_user_by_phone_number'), #call with example?phone_number=+849323212231 With view to handle parameter: ... phone_number = unquote(request.GET.get('phone_number')) print(phone_number) And the result from the print i got was " 849323212231" with whitespace at the start. Seems like value from request.GET.get('phone_number') return " 849323212231" so plus turned into whitespace. How do i get special character with named parameter in url ? -
expire JWT token if new JWT token id generated
How do i expire generated JWT token if new JWT token is generated for same credentials. user = User.objects.get(email=req['email']) payload = jwt_payload_handler(user) token = jwt_encode_handler(payload) -
Django: Trouble with logging user using Bootstrap login.html
I'm using Django 3.0.2 + Boostrap. I have created a registration/login.html page. The contents of this page are: The page renders correctly and most of it works OK. However, I am unable to login to my website through this page. I keep getting Your username and password did not match. Please try again. I can login to the admin website without any issues if I use the same username/password. I am not sure what is wrong with my login.html. Any ideas? {% extends "base.html" %} {% block content %} {% if form.errors %} <p>Your username and password did not match. Please try again.</p> {% endif %} {% if next %} {% if user.is_authenticated %} <p>Your account does nohave access to this page. To proceed,please login with an account that has access.</p> {% else %} <p>Please login to see this page.</p> {% endif %} {% endif %} <div class="container-fluid"> <div class="row justify-content-center"> <div class="col-lg-6"> <div class="p-5"> <div class="text-center"> <h1 class="h4 text-gray-900 mb-4">Welcome Back!</h1> </div> <form class="user" method="post" action="{% url 'login' %}"> {% csrf_token %} <div class="form-group"> <input type="text" class="form-control form-control-user" id="exampleInputUserName" placeholder="Username"> </div> <div class="form-group"> <input type="password" class="form-control form-control-user" id="exampleInputPassword" placeholder="Password"> </div> <input type="submit" class="btn btn-primary btn-user btn-block" value="Login"> <input type="hidden" … -
How to integrate google authenticator app with django application for 2 step verification?
I want to integrate the Google Authenticator App for 2 step verification in my Django App. After the user logs in using his user ID and password, I want to redirect the user to a page where he will be asked to enter the code from the Google Authenticator app. Are there any pip packages to achieve this requirement? -
After adding new field in permission page Django admin is miss behaving
I am unable to add my code so I have added images of codes please view and please inform me if there is any problem with my code. [First image is models.py][1] [Second is settings.py][2] [Third is admin.py][3] [In fourth image password is in text field ][4] [Permissions selection box is missing][5] [1]: https://i.stack.imgur.com/Gq7Sf.png [2]: https://i.stack.imgur.com/3vACA.png [3]: https://i.stack.imgur.com/84fve.png [4]: https://i.stack.imgur.com/MWmfR.png [5]: https://i.stack.imgur.com/pJgqd.png -
Django storage S3 - Save File Path only without file with ModelSerializer
I'm using boto3 to upload files to S3 and save their path in the FileField. class SomeFile(models.Model): file = models.FileField(upload_to='some_folder', max_length=400, blank=True, null=True) For the above model the following code works to create a record. ff = SomeFile(file='file path in S3') ff.full_clean() ff.save() Now, I want to use ModelSerializer to do the same. class SomeFileSerializer(serializers.ModelSerializer): class Meta: model = SomeFile fields = ('file') Now the following below throws the error rest_framework.exceptions.ValidationError: {'file': [ErrorDetail(string='The submitted data was not a file. Check the encoding type on the form.', code='invalid')]} serializer = SomeFileSerializer(data={'file': 'file path to S3'}) serializer.is_valid(raise_exception=True) I need help in setting up the serializer to accept file path without actually having the file. -
Django: How to get a users coordinates (latitude, longitude) in a view?
I need to be able to check the user's location before determining where their redirect will be sent. Is there an easy way to do this in Django/Python? views.py @login_required def update(request): if users coords in range(....): form = UpdateForm(request.POST or None) if request.method == "POST": if form.is_valid(): update = form.save(commit=False) update.user = request.user update.save() value = form.cleaned_data['update'] return redirect('main-home') return render(request, "main/update.html", {'form': form}) else: return render(request, "main/error.html") -
I was trying to deploy my project online using heroku but received an error
I'm trying to deploy my application online using heroku. I received this error ! [remote rejected] master -> master (pre-receive hook declined)error: failed to push some refs to 'https://git.heroku.com/mypersonalwebsite7487.git' I used django framework to do this project and worked so hard what should I do ? I'm the maintainer I done all of it by my self. Looking forward to your reply. Best regards -
Import of local_settings doesn't take effect
So im currently trying to deploy a django application to production so i need to have an local_settings.py for api keys n such to be stored outside the git rep for it to be updated and for security reasons, but when i try importing local_settings.py it doesnt take effect idk why tho so i hope somebody could help. So what i have tried placeing this in the bottom of settings.py: try: from .local_settings import * except ImportError: pass Nothing happens like, it doesn't even try. I also tried adding from settings import * in local_settings.py example what i try to import: ALLOWED_HOSTS = [ 'localhost', 'mydomain.com' ] Aswell as the database to instead of using sqlite to use postgresql What could be the problem? -
I want python/django code for text compare line by line
I want python/django code for text compare line by line like text-compare.com ,any reference please send me the details. -
Django: How to get list of APIs in django project
I wonder if there is a way to get name and methods of APIs in django -
python-social-auth django Linkedin : how to callback to my domain?
I'm working through this tutorial, have found the same problem with other tutorials, but nobody seems to be talking about the solution (?) https://realpython.com/linkedin-social-authentication-in-django/ I can get this to redirect to localhost:port I change the redirect url in the linkedIn app from http://127.0.0.1:6000/complete/linkedin-oauth2/ to https://tbxdata.com/complete/linkedin-oauth2/ then I get the error below. https://www.linkedin.com/uas/oauth2/authorization?client_id=81iyqzf06ghqzh&redirect_uri=http://127.0.0.1:6000/complete/linkedin-oauth2/&state=foo-bar-blah&response_type=code The redirect_uri does not match the registered value I've not found any discussions on how to fix this. I feel this must be a common goal and my google fy is failing. -
Django + python-social-auth Authentication failed: You need to pass the "scope" parameter
Working through this tutorial atm, but had similar problem on other tutorials. https://realpython.com/linkedin-social-authentication-in-django/ I'm able to deploy load the page and connect to linkedin. Then this error. Request URL: http://127.0.0.1:6000/complete/linkedin-oauth2/? error=invalid_request&error_description=You+need+to+pass+the+%22scope%22+parameter Digging around I find we need (?) to nominate these three keys. SOCIAL_AUTH_LINKEDIN_SCOPE = ['r_emailaddress'] # These fields be requested from linkedin. SOCIAL_AUTH_LINKEDIN_FIELD_SELECTORS = ['email-address'] SOCIAL_AUTH_LINKEDIN_EXTRA_DATA = [('emailAddress', 'email_address'),] nb: even when I only use SOCIAL_AUTH_LINKEDIN_SCOPE I see no change. https://python-social-auth-docs.readthedocs.io/en/latest/backends/linkedin.html I'm at a bit of a loss here. Usually I can debug things. -
Using Django ContentTypes to define a dataset
I want users to define a set of content they want to work on in a Django site with (potentially) quite diverse types of content. I am using ContentTypes and the GenericForeignKey relation to be able to tag any and all content to a particular dataset. My problem is giving the user a sensible series of steps, something like this: 1. Choose which Apps hold data of interest [form] 2. Choose which Models for each App hold data of interest [form] 3. Any columns you don't care about? [form] 4. Any rows you don't care about? [form] 5. all surviving rows are now IN, and we save them as GenericForeignKey entries against the Dataset. I am a bit stuck as to how to implement this logic, because ContentTypes is already a compound, modeled by 'app_label' and 'models'. class Row_link(models.Model): content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') class Dataset(models.Model): setname = models.CharField(max_length=20, default="[empty]") members = models.ManyToManyField(Row_link) I could add 'app_labels', 'models', and 'columns' fields to the Dataset but they ought to be derived properties from the 'members' field once that field is fully selected. But 'app_labels', 'models' and 'columns' are only needed to guide the user through …