Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django custom permission class is not working
I am using Django REST for my API. Here is my custom permission class: permissions.py: from rest_framework.permissions import BasePermission from rest_framework.response import Response class ItemsPermissions(BasePermission): def has_permission(self, request, view): try: request_data = request.data print(request_data) auth_token = request_data['returnedDataFromAuthAPI'] if("accessToken" in auth_token): auth_token = auth_token['accessToken'] Response({"Permission Granted - AccessToken": auth_token}) return True #else Response({"message": "No Auth Token Provided! You Need To Login!"}) return False except Exception as ex: return Response({"message": ex}) in views.py: class ListItems(generics.ListAPIView): permission_classes = [ShippingPermissions] queryset = myModel.objects.all() serializer_class = mySerializer in urls.py: url_patterns = [ path("/items/list/", ListItems.as_view()), ] I have an authentication microservice that I get the JWT Token from, for the user to have access to the views. In the ItemsPermissions class I am checking the token. My Question: I want to grant the user access to the ListItems class, after the token is provided, but if token is not provided then the user should not have access. However, for some reason, I am able to access the /items/list/ endpoint, and it does not ask me for a token at all. What is the problem ? -
cannot cast type date to time without time zone LINE 1: ...COLUMN "creation_date" TYPE time USING "creation_date"::time (DJANGO - Heroku)
I am trying to upload my Django-project to Heroku. I run the following command like i have always done: git add . git commit -am "" git push heroku master heroku run bash $- python manage.py migrate //this for apply all the migrations Once i ran them i got the cannot cast type date to time without time zone. I have already found some answers but none of them works for me. I have already set the TIME_ZONE in settings.py This is the migration that gives me the error: # Generated by Django 3.1.7 on 2021-08-16 16:29 from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('website', '0009_order_creation_date'), ] operations = [ migrations.AlterField( model_name='order', name='creation_date', field=models.TimeField(default=django.utils.timezone.now, verbose_name='Data Ordine'), ), ] -
Gunicorn [CRITICAL] WORKER TIMEOUT, When redirection
I'm newbi in development. I would appreciate it if you could help me solve this problem. I'm making a social login system in Nginx + gunicorn + Dango by DRF. An error occurs when I request GET {api-path}/kakao/login from my server. My server has to serves to give user's token and to redirect user. The new/old user login is completed successfully, But ** user's page doesn't switch and doesn't get the token.** when I run python manage.py runserver 0.0.0.0:8000, No error occurs and a normal token value is returned. But If I use gunicorn or uwsgi, the error occurs. How can I solve this problem? I have summarized my attempts and my code below. 1. I tried https://www.datadoghq.com/blog/nginx-502-bad-gateway-errors-gunicorn/ check "Gunicorn is not running" other requst like {api-path}/admin works normally. check "NGINX can’t communicate with Gunicorn" other requst like {api-path}/admin works normally. check "Gunicorn is timing out" When I runed python manage.py runserver 0.0.0.0:8000 and tried the problematic request, It took only 2 ~ 3 seconds to response. Because gunicorn's default time limit is 30 seconds, I think reason of my error has nothing to do with Nginx's timing out & Gunicorn's timing out. I tried uwsgi, uwsgi's socket too, but … -
Filter + Paginator not working as expected
I have a filter with a dependent dropdown as well as a paginator. The paginator and filter are working as expected except if the category has a page 2 it no longer filters the results and just displays everything in the db(paginated). How do I go about carrying the filter request into the paginator. view model = Post myFilter = carFilter(request.GET, queryset=Post.objects.all()) posts = myFilter.qs page = request.GET.get('page', 1) paginator = Paginator(posts, 2) page_obj = paginator.get_page(page) page_range = paginator.get_elided_page_range(number=page) context = { 'posts':posts, 'myFilter':myFilter, 'page_range': page_range, 'page': page, 'paginator': paginator, 'page_obj': page_obj } template {% for post in page_obj %} <article> <a class="article-title" href="{% url 'post-detail' post.id %}">{{ post.year }}</a> <a class="article-title" href="{% url 'post-detail' post.id %}">{{ post.manufacture }}</a> </article> {% endfor %} <nav aria-label="Page navigation example " class="paginator"> <ul class="pagination justify-content-center"> <li class="page-item"> {% if page_obj.has_previous %} <a class="page-link" href="?page={{ page_obj.previous_page_number }}" aria-label="Previous"> <span aria-hidden="true">&laquo;</span> </a> {% else %} </li> <li class="page-item disabled"> <a class="page-link" href="#" aria-label="Previous"> <span aria-hidden="true">&laquo;</span> </a> </li> {% endif %} {% for i in page_obj.paginator.page_range %} {% if page_obj.number == i %} <li class="page-item active" aria-current="page"> <a class="page-link" href="#">{{ i }}</a> </li> {% elif i > page_obj.number|add:'-3' and i < page_obj.number|add:'3' %} <li class="page-item"><a class="page-link" … -
fetch is returning html rather than JSON response
I am working on the cs50 web development project Network. Basically building a twitter copycat. It is still in process but so far I have two fetch requests for a JSON response. Once works perfectly but the other, which is a very similar request, returns html instead of JSON, causing an error. Can't figure out why this one doesn't work. Code snippets below: Here is the one that is returning html for my profile.html file for some reason. The commented out parts are the actual fetch JSON request but I temporarily changed it to show me in the console what is was returning. profile.js: function load_posts_profile() { console.log("load_posts_profile running"); document.querySelector('#prof-posts').style.display = 'block'; fetch(`/profile_posts`) //.then(response => response.json()) .then(response => response.text()) .then(text => console.log(text)) //.then(posts => { // Print posts //console.log(posts); //posts.forEach(post => show_posts_profile(post)); //}); } profile.html: {% extends "network/layout.html" %} {% load static %} {% block body %} {% if user.is_authenticated %} <!--insert profle name below in h3--> <h2 id="profile-name"></h2> <br> <h4 id="followers"></h4> <br> <h4 id="following"></h4> <!--add js to load user's posts only--> <div id="prof-posts"> </div> {% else %} <strong> Login To See Profile</strong> {% endif %} {% endblock %} {% block script %} <script src="{% static 'network/profile.js' %}"></script> {% endblock … -
Is it possible to add notifications or receive updates on django admin panel?
Is there a way to receive notifications on django admin panel whenever a new post or order is created in django ecommerce or website? I have created my first ecommerce website using django. Is it possible to receive notifications on admin panel whenever a new order is placed? -
Custom template tag and CSRF protection
Django 3.2.6 emails/subscribe.html <form action="{% url 'emails:subscribe_result' %}" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Submit"> </form> This works fine: class SubscribeFormView(FormView): template_name = 'emails/subscribe.html' form_class = SubscribeForm success_url = 'emails/thanks/' But this does not: from django import template from django.utils.safestring import mark_safe, SafeString from django.template import Context, Template from django.template.loader import get_template register = template.Library() from emails.forms import SubscribeForm @register.simple_tag def subscribe() -> SafeString: template = get_template("emails/subscribe.html") context = {"form": SubscribeForm(), } result = template.render(context) return mark_safe(result) I get: Forbidden (403) CSRF verification failed. Request aborted. Help Reason given for failure: CSRF token missing or incorrect. Could you help me understand why custom template tag can't be used here? Maybe a request via AJAX can help? ///////////////////////////// -
Foreign key with multiple models?
I am creating ecommerce website. There are multiple categories. For example, phones, computers and others. I created a model for each of them. In OrderItems I want to foreign key each of them. So, I want to use multiple models in ForeignKey. models.py class Telefon(models.Model): name = models.CharField(max_length=200) category = models.CharField(max_length=300, choices=TELEFON, default="xiaomi") price = models.FloatField() image = models.ImageField(null=True, blank=True) def __str__(self): return self.name @property def imageURL(self): try: url = self.image.url except: url = '' return url class TV(models.Model): name = models.CharField(max_length=200) category = models.CharField(max_length=300, choices=TELEFON, default="xiaomi") price = models.FloatField() image = models.ImageField(null=True, blank=True) def __str__(self): return self.name @property def imageURL(self): try: url = self.image.url except: url = '' return url Product={'Telefon', 'TV'} class OrderItem(models.Model): product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True) quantity = models.IntegerField(default=0, null=True, blank=True) date_added = models.DateTimeField(auto_now_add=True) @property def get_total(self): total = self.product.price * self.quantity return total So, how can I use multiple models in Foreign Key field in my OrderItems model. -
How to upload form with input file using ajax
When i send the <input type='file' src='D:/.../image.png'>'s src throught Ajax to views.py in the views the src is not correct, It appears like D:/fakepath/imag.png the fakepath is some security thing made by browser But how I can upload the form's content when I can't get the path of the file input? -
Django forms.DateTimeField change input type
I want to change forms.DateTimeField input type to "d/m/y H:M". How can I do that? I tried this but didn't work: travel_on = forms.DateTimeField(input_formats='%m/%d/%y %H:%M') Here's my Ticket Model: User = settings.AUTH_USER_MODEL class Ticket(models.Model): from_station = models.CharField(max_length=30) to_station = models.CharField(max_length=30) purchased_on = models.DateTimeField(default=timezone.now) travel_on = models.DateTimeField() customer = models.ForeignKey(User,on_delete=models.CASCADE) def __str__(self): return f"Customer:{self.customer.username},From:{self.from_station},To:{self.to_station},Travel on:{self.travel_on},Purchased on:{self.purchased_on}" My TicketForm: from .models import Ticket from django import forms class TicketForm(forms.ModelForm): travel_on = forms.DateTimeField(input_formats='%m/%d/%y %H:%M') class Meta: model = Ticket fields = ('from_station','to_station','travel_on') -
How can I add new URLS to Django 3.2 under /admin?
I am working on upgrading an old Django project to 3.2. Previously, our urls.py for the main project included the following so that the urls from impersonate were below /admin url(r"^admin/", include(admin.site.urls)) url(r"^admin/impersonate/", include("impersonate.urls")), When I update this code to django 3.2, I don't seem to be able to include any urls beneath /admin. The following code: re_path(r"^admin/", admin.site.urls), re_path(r"^admin/impersonate/", include("impersonate.urls")), does not work, but it does work if I modify the impersonate line to: re_path(r"^impersonate/", include("impersonate.urls")), Basically, I want to preserve all of the impersonate urls to be beneath /admin, if this is still possible. I understand that this does not make them require admin permissions, rather this is just to group all the admin views of the project together. I have seen that I can write a custom ModelAdmin also, but this will still move the urls to under /admin/myapp/mymodel/my_view/. I do not want the extra part of the path mymodel here. -
Azure app service SSH connection refused. not using Docker. Django not installing from requirements
I followed the steps in https://docs.microsoft.com/en-us/azure/app-service/tutorial-python-postgresql-app?tabs=bash%2Cclone&pivots=postgres-single-server#4-deploy-the-code-to-azure-app-service to deploy my Django app to Azure. Issues: requirements are not installing so the app is not running. Unsure if this is because I used az webapp up instead of a git branch. I tried SSH in but connection error's out: SSH CONNECTION CLOSE - Error: connect EHOSTUNREACH 172.16.1.3:2222Error: connect EHOSTUNREACH 172.16.1.3:2222Error: Timed out while waiting for handshakeError: connect EHOSTUNREACH 172.16.1.3:2222 there are articles mentioning whitelisting port 2222 to go over 80*, but I can't seem to find where to do this on the portal. Again, I'm not using a docker image so I can't add a config. Used kudu file browser and see that requirements.txt is there and correct. this is the error from log stream: 2021-08-17T15:21:04.475206899Z File "<frozen importlib._bootstrap>", line 677, in _load_unlocked 2021-08-17T15:21:04.475210299Z File "<frozen importlib._bootstrap_external>", line 728, in exec_module 2021-08-17T15:21:04.475213499Z File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed 2021-08-17T15:21:04.475216699Z File "/home/site/wwwroot/backend/wsgi.py", line 12, in <module> 2021-08-17T15:21:04.475219999Z from django.core.wsgi import get_wsgi_application 2021-08-17T15:21:04.475222999Z ModuleNotFoundError: No module named 'django' -
Django @queryset on json field
select * from. table_name where id = 10 and name = 'xyz' and address::json->>'house_number' like '%"28735": true%'; can someone provide me or help me with how to write Django QuerySet for that. -
Error: The view didn't return an HttpResponse, when trying to send email
I want to manually approve reports for clients after they have agreed to terms. For this I want to email to be sent to myself when client clicks "accept". I get the following error instead: The view accounts.views.TermsView didn't return an HttpResponse object. It returned None instead. Have searched for the same error here, but failed to solve with these. Sorry, new programmer here. views.py class TermsView(TemplateView): template_name = "accounts/terms_of_service.html" ... def post(self, *args, **kwargs): self.request.user.terms_accepted = timezone.now() self.request.user.save(update_fields=["terms_accepted"]) def send_mail(self): messages.add_message( self.request, messages.SUCCESS, _("Thank you! We will contact you as soon as possible."), ) send_terms_agreed_reports(self.request.company, self.request.user) return redirect("stays:dashboard") emails.py def send_terms_agreed_reports(company, user): try: email_subject = "New company wants to use reports" return send_email( settings.TERMS_AGREED_ENABLE_REPORTS, email_subject, "emails/terms_agreed_reports.html", {"company": company.name, "reg_code": company.reg_code, "name": user.name, "email": user.email, "phone": user.phone}, ) except Exception: logger.exception("Could not send message") -
django password form field doesnt look other field.How can i fix it?
Although I specify a class in forms.py, the password fields do not appear as regular as the others. What is the reason for this and how can I fix it. forms.py class registerForm(UserCreationForm): class Meta: model = CustomUserModel fields=("first_name","last_name","email","phone_number","password1","password2") widgets = { "first_name" : TextInput(attrs={"class":"form-control floating"}), "last_name" : TextInput(attrs={"class":"form-control floating"}), "email" : EmailInput(attrs={"class":"form-control floating","type":"email"}), "phone_number" : TextInput(attrs={"class":"form-control floating"}), "password1" : PasswordInput(attrs={"class":"form-control floating"}), "password2" : PasswordInput(attrs={"class":"form-control floating"}), } In my template form looks like this -
How to perform an http post request to a device behind a router using DDNS & Python
For faster prototyping of my code, I would like to provide my laptop address as an endpoint to the http webhook API (Base URL) of the website cloud.thethings.network. For this, I setup a ddns on noip.com and connected my tp-link router with my noip-account. So right now, I have sth. like myneedddns.ddns.com that forwards to my router. I’ve also set port forwarding in my router to access my laptop and reserved a static IP for the laptop: However, I can not provide a format like xxx.ddns.com:801 on thethingsstack. From there I can probably handle how to receive the request with flask or django. How would you approach my goal? -
Unique Class or extend Class or Subclass in Python Django?
Unique Class or extend Class or Subclass in Python Django? In the following situation, I have a feeling I need to ?extend? the Migration class instead of re-stating it in the second module. Or is a child class needed? A goal here: To create a postgres table called venues. There is already a models/venues.py that seems to be set up ok. migrations/0001_initial.py: class Migration(migrations.Migration): initial = True dependencies = [('auth', '0012_alter_user_first_name_max_length'),] operations = [ migrations.CreateModel( name='User', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, ...)), ('password', models.CharField(max_length=128, ...)), ... migrations/0002_venue.py: class Migration(migrations.Migration): dependencies = [('app', '0001_initial'),] operations = [ migrations.CreateModel( name='Venue', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True...)), ('name', models.CharField(blank=True ...)), ('address', models.CharField(blank=True...)), ... Help? -
How to obtain a user instance using django rest framework
Perhaps the question is wrongly worded. I created user profile using Django through the following blocks of code: models.py class = Profile (models.Models): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) first name = models.CharField(max_length=50) ••• serializer.py class profile_serializer(serializers.ModerlSerializer) class Meta: model = Profile fields = '__all__' views.py class profile_view(generics.ListCreateAPIView) queryset = Profile.objects.all().filter(user=instance) urls.py urlspatterns = [path('profile', profile_view.as_view(), name='user_profile) I definitely do not know how to implement the filter method to ensure that only the logged in user is retrieved. Or is there a better approach to obtain a specific user? If I use Project.objects.all() without the filter I get all the registered user as expected. But I don't know how to retrieve a particular user. -
Problem with progress upload bar using XMLHttpRequest in Django
I have an issue with a progress upload bar in Django when the site is deployed to Heroku, when I click on the upload button the progress bar shows up at 10% then doesn't change or count up to 100%, when the upload is finished, it redirects as instructed in my views.py , the function runs fine locally, but after deploying to heroku it doesn't work. I think it may be something to do with the deployed url using 'https', but not sure and how to fix it? appreciate any help. custom.js function progressBar() { progressBox.classList.remove('not-visible') cancelBox.classList.remove('not-visible') const upload_data = input.files[0] const url = URL.createObjectURL(upload_data) // console.log(upload_data); const fd = new FormData() fd.append('csrfmiddlewaretoken', csrf[0].value) fd.append('track', upload_data) $.ajax({ type: 'POST', enctype: 'multipart/form-data', data: fd, beforeSend: function(){ }, xhr: function(){ const xhr = new XMLHttpRequest(); xhr.upload.addEventListener('progress', e=>{ // console.log(e); if (e.lengthComputable) { const percent = (e.loaded / e.total) * 100; // console.log(percent); progressBox.innerHTML = `<h5 style="text-align:center;">${percent.toFixed(1)}%</h5> <div class="progress" style="height: 30px;"> <div class="progress-bar bg-success" role="progressbar" style="width: ${percent}%" aria-valuenow="${percent}" aria-valuemin="0" aria-valuemax="100"></div> </div>` } }) cancelBtn.addEventListener('click', ()=>{ xhr.abort() progressBox.innerHTML="" cancelBox.classList.add('not-visible') window.location.reload(); }) return xhr; }, success: function(response){ // console.log(response); uploadForm.reset() cancelBox.classList.add('not-visible') }, error: function(error){ console.log(error); }, cache: false, contentType: false, processData: false, }) } -
How to set the default user as the current user object in django?
I have created a mini project called ToDoList App. I have used class based views for create, update and delete functions. There is MyTasks icon on navbar. What do I want? I want to set the default user as the current logged in user. Tasks of one person should not be seen by any another person. I have tried all the solutions but nothing seems to work. Here is my code in models.py file: class MyTasks(models.Model): user = models.ForeignKey(User, on_delete=CASCADE, related_name="mytasks") task_id = models.AutoField(primary_key=True, verbose_name="ID") task_title = models.CharField(max_length=100, default="", help_text="The title of the task", verbose_name="Task Title", blank=False) task_desc = models.TextField(default="", help_text="The description of task", verbose_name="Task Description", blank=False) task_time = models.DateTimeField(default=timezone.now(), verbose_name="Task Date & Time") task_completed = models.BooleanField(default=False, verbose_name="Task Completed") def save(self, *args, **kwargs): self.user = User super(MyTasks, self).save(*args, **kwargs) def __str__(self): return self.task_title When I used the save method to achieve the task, it is showing this error: ValueError: Cannot assign "<class 'django.contrib.auth.models.User'>" Please help me to achieve this task. Any help is much appreciated. -
New records not coming in the list call of Django DRF API using Redis cache
I have a Django REST API, and I am using Redis as the caching backend. Code @method_decorator(cache_page(60*60)) def dispatch(self, *args, **kwargs): return super().dispatch(*args, **kwargs) It caches the data on a get call, but when I insert a new record, that new record is not showing up in the list (Which is coming from cache). Any help? -
Granting access to other class views upon successful authentication Django REST
Here is my API in Django REST. Here is my code: from rest_framework.permissions import IsAuthenticated, AllowAny class CreateItems(generics.CreateAPIView): permission_classes = [IsAuthenticated] queryset = SomeModel.objects.all() serializer_class = SomeSerializer class AuthStatus(APIView): permission_classes = [AllowAny] def post(self, request, *args, **kwargs): token = self.request.data['itemsReturnedAuthAPI']['accessToken'] if(token): return Response({"Token":token}) else: return Response({"message":"No Token Found!"}) I have an authentication microservice that I get the JWT Token from for the user in order to have access to the views. In the AuthStatus class I am checking the token. My Question: I want to grant the user access to the CreateItems class, after the token is provided -
Django Rest Framework request unauthorized on all but one address
I'm trying to access django hosted at 192.168.x.x:8000 on a React frontend server on port 5002, when attempting to access the frontend with localhost, 127.0.0.1 or ip's outside of the home network, it gives following result in console: Unauthorized: /api/any_endpoint HTTP POST /api/any_endpoint 401 [0.03, 127.0.0.1:12345] However when accessing trough 192.168.x.x:5002, it just works. the /admin/ endpoint seems to work no matter the ip address (ip_address:8000), so it's either django-rest-framework or React that is causing this issue. I have no idea where to start debugging this, so any comment on what I should check would be appreciated -
Django (1045, "Access denied for user 'root'@'localhost' (using password: NO)")
I have come accross a strange issue, I have deployed a django site to an Ubuntu 20.04 LTS server. The problem is my django app can not connect to the database because It is doesn't using the db connection credentials that have identified in app settings.py. It is using root with no password. But when I can run manage.py db operations without any problem. This is my settings.py 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'pplus_db', 'USER': 'pplus_user', 'PASSWORD': 'dfa@4GL-5qQU', 'HOST': 'localhost', 'PORT':'3306', } } This is the screenshot of the error, I'm getting when I'm trying to login -
django.contrib.auth.urls change redirect path
I am coding a basic login and register page app in Django/Python Currently, after someone logs in, it redirects them back to the register page. I am trying to change the redirect path to "home/" Please see the following code: URLS.PY: from django.contrib import admin from django.urls import path , include from accounts import views as v from main import views as views urlpatterns = [ path('admin/', admin.site.urls), path('home/' , views.home , name = 'home'), path('', v.register , name='register'), path('' , include('django.contrib.auth.urls') , name = 'login'), ] Views.py: from django.shortcuts import render , redirect from .forms import RegisterForm # Create your views here. def register(response): if response.method == "POST": form = UserCreationForm(response.POST) if form.is_valid(): form.save() return redirect("/home") else: form = RegisterForm() return render(response, "registration/register.html", {"form":form}) Login.html {% extends "main/base.html"%} {% block title %} Login here {% endblock %} {% load crispy_forms_tags %} {% block content %} <form class="form-group" method="post"> {% csrf_token %} {{ form|crispy }} <p>Don't have an account ? Create one <a href="/register"></a></p> <button type="submit" class="btn btn-success">Login</button> </form> {% endblock %} Register.html {% extends "main/base.html"%} {% block title %}Create an Account{% endblock %} {% load crispy_forms_tags %} {% block content %} <form method="POST" class="form-group"> {% csrf_token %} {{ form|crispy …