Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases
I am trying to implement multiple inheritance with Partitioned model and Aggregate Model class AdAgencyLocationPurposeAggregate(PostgresAggregateModel,PostgresPartitionedModel): PostgresAggregateModel: class PostgresAggregateModel(PostgresModel,metaclass=PostgresAggregateModelMeta ): PostgresPartitionedModel class PostgresPartitionedModel( PostgresModel,metaclass=PostgresPartitionedModelMeta ): -
Celery Scheduler not starting
I'm trying to setup scheduler but I got the following error "Unrecoverable error" from __future__ import absolute_import import os from celery import Celery from django.conf import settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core.settings.prod') app = Celery('core') app.config_from_object("django.conf:settings") app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) @app.task(bind=True) def debug_task(self): print("Request: {0!r}".format(self.request)) # CELERY STUFF BROKER_URL = 'redis://localhost:6379' CELERY_RESULT_BACKEND = 'redis://localhost:6379' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = 'America/Chicago' I was guided by https://realpython.com/asynchronous-tasks-with-django-and-celery/ Here are two photos of my errors -
Django static files deployed from AWS S3
My sidebar navbar doesn't get the right styles user/main.css ul.no-bullets { list-style-type: none; margin: 0; padding: 0; } home.html {% extends 'base.html' %} {% block title %}Home{% endblock %} {% block content %} {% if user.is_authenticated %} <div class="container"> <div class='row'> <div class="col-xs-12 col-md-3"> {% block sidebar %} {% include 'sidebar.html' %} {% endblock %} </div> <div class="col-xs-12 col-md-9"> Some page </div> </div> </div> {% else %} <p>You are not logged in</p> <a href="{% url 'login' %}">Log In</a> {% endif %} {% endblock %} sidebar.html {% block content %} <nav id="sidebar"> Hi {{ user.username }}! <img class="profile-pic" src="{{request.user.profile_pic.url}}" > <ul> <li><a href="/">Dashboard</a></li> <li><a href="/">Messages</a></li> <li><a href="/">Documents</a></li> <li><a href="{% url 'logout' %}">Log Out</a></li> </ul> </nav> {% endblock %} base.html <!DOCTYPE html> {% load static %} <html> <head lang="en"> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!--Css Style --> <link rel="stylesheet" href="{% static 'user/main.css' %}" type="text/css"> <!-- Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous"> <!--Font Link--> <title>{% block title %}Base{% endblock %}</title> </head> <body> <main> {% block content %} {% endblock %} </main> </body> </html> -
How to serialize class into json (class is not in model)
I have simple class class City: def __init__(self, key): self.key = key def distance(self): distance = Distance.objects.get(id=self.key).distance return distance def __repr__(self): return "(" + self.key + ")" And in my view class as API def get_route(request): res = {} res['cities'] = [City(1),City(2),City(3)] return Response(res) it returns the list of class City However this shows the error Object of type City is not JSON serializable __repr__ could be used for representing class. However, it's not work for json. How can I solve it ?? -
Django Custom Admin Users
So I want 3 types of users: Admins, Doctors, and Patients They should possess the following attributes and only admins shall access the /admin routing so they should possess is_staff, is_superuser to determine if it's a patient or doctor. name, pw, email, phone, profile_pic, and date_created are other attributes they should possess. So I need to add parameters to the existing auth in admin.py from django.contrib.auth.models import User class Patient(models.Model): user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=200, null=True) phone = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) profile_pic = models.ImageField(default="", null=True, blank=True) date_created = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return self.name -
username with `james i. adams` not accepted with django routers
I have registered routers for user model, which has viewset that has lookup_url as username. The username james adams is accepted by the router, but getting below error for james i. adams django.urls.exceptions.NoReverseMatch: Reverse for 'user-detail' with keyword arguments '{'username': 'james i. adam', 'version': 'v1'}' not found. 4 pattern(s) tried: ['(?P<version>(v4))/users/(?P<username>[^/.]+)/?\\.(?P<format>[a-z0-9]+)/?$', '(?P<version>(v4))/users/(?P<username>[^/.]+)/?$', '(?P<version>(v1))/users/(?P<username>[^/.]+)/?\\.(?P<format>[a-z0-9]+)/?$', '(?P<version>(v1))/users/(?P<username>[^/.]+)/?$'] Can someone guide me, how can I allow such username for url patterns with routers registered? Thanks in Advance -
How to Filter foreign key related models using datetime range
I'm trying to create a reservation system and I want to query all available tables. So, what I did is as follows, ... date_time = request.data.get('date_time') date_time = datetime.strptime(date_time, '%b %d %Y %I:%M%p') num_of_attendees = request.data.get('num_of_attendees') tables = Table.objects.filter(~Q( tablereservation__date_time__range=[date_time, date_time + timedelta(hours=2)]), num_of_chairs__gte=num_of_attendees ) ... But it returns all the table objects. My models, class Table(models.Model): """ Holds table details """ num_of_chairs = models.PositiveSmallIntegerField(default=1) def __str__(self): return str(self.id) class TableReservation(models.Model): """ Holds table reservation details """ date_time = models.DateTimeField() table = models.ForeignKey(Table, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return '{}-{}'.format(self.table, self.user) But I want is to get only the table objects that aren't reserved in the given date-time range. Any help is greatly appreciated. -
Django-Import-Export assign Field to specific column
I have a working form which exports all data to xls using Resource and Fields from the django-import-export package. But now I need to go a bit further and make it a bit more advanced. I need to export all data to an existing Excel template, assigning each field to a specific column, as in, for instance: Field 1 needs to be filled in B3, Field 2 in C4 etc. etc. I'm thinking after_export() can be used here but the docs dont go into detail how to use this method. Does anyone have some experience with this package? I'm not using the admin integration. -
ListCreateAPIView is not letting post data
I'm trying to create an API where I will upload image throw API end point, My Model has only one imageField. Please checkout the code below Model: class Image(models.Model): image = models.ImageField(upload_to="media", default="default.png", blank=True, null=True) def __str__(self): id = self.id return f'image-{id}' Serializer: class ImageSerializer(serializers.ModelSerializer): class Meta: model = Image fields = ['image'] Views: from rest_framework.generics import CreateAPIView, ListCreateAPIView from home.models import Image from .serializers import ImageSerializer class ImageListCreateView(ListCreateAPIView): queryset = Image.objects.all() serializer_class = ImageSerializer Urls: from django.urls import path from .views import ImageListCreateView urlpatterns = [ path('image/', ImageListCreateView.as_view(), name='image'), ] But if I visit the url '127.0.0.1:8000/api/image/' It only shows the data. not letting me post new data. -
How to integrate django to Elastic App Search
I have doing a project of e-commerce and I need to integrate Django and Elastic App Search. How to integrate -
django many to many queriying
I am building an e-commerce website using Django, my models is like bellow : class ProductAttribute(models.Model): product=models.ForeignKey(Product,on_delete=models.CASCADE) attributes_values = models.ManyToManyField(AttributeValue,verbose_name="Liste des attributs") stock = models.PositiveIntegerField() price = models.PositiveIntegerField(verbose_name="Prix") image = models.ImageField(blank=True,null=True,upload_to="products") class AttributeValue(models.Model): attribute=models.ForeignKey(Attribute,on_delete=models.CASCADE,verbose_name="Attribut") value = models.CharField(max_length=50,verbose_name="Valeur") class Attribute(models.Model): name = models.CharField(max_length=50,verbose_name="Nom") my view.py def getatts(request,product_id): products_with_attributes=ProductAttribute.objects.filter(product__id=product_id) res=#..... missing code to get attributes with values return res In the front end i want to retrieve attributes of a particular product to get them by order, to use them in select (ex:size,color choices) , for example if the query set of ProductAttribute is like: [{id:1,product:1,attributes_values:[3,4],...},{id:1,product:1,attributes_values:[5,6],...}] the result in JSON would be like so: { result:[ { key: "color", values: [ {id: 1, value: "Red", choices:{ key:"size", values:[{id:3,value:"L"},{id:4,value:"XL"}] } }, {id: 2, value: "Black", choices:{ key:"size", values:[{id:5,value:"M"},{id:6,value:"XXL"}] } }, ] } ] } -
Problem while trying to create dynamic html
Why don't I get the dynamic text that used in the views.py? My views.py code: from django.shortcuts import render from django.http import HttpResponse # Create your views here. def index(request): context = { 'name' : 'Amlan', 'age' : 23, 'nationality' : 'Indian' } return render(request, 'index.html', context) My index.html code: <h1> Hello {{name}}<br>You are {{age}} years old<br>You are {{nationality}} </h1> When I run the server I get: Hello You are years old You are -
DRF - from django.conf.urls import url in Django 4.0
I've a project in django 3.2 and I've updated (pip install -r requirements.txt) to version 4.0 (new release) and I've currently the below error when I run the server in a virtual environment. I use DRF. Can't import => from rest_framework import routers in urls.py from django.conf.urls import url ImportError: cannot import name 'url' from 'django.conf.urls' -
Disable querying a field in Django Rest Framework
Here is the model class. Where categories is a nested mptt model tree. class MyModel(models.Model): categories = models.ManyToManyField(Category) # to another nested model (self referncing tree) The serialzier is a simple one class MyModelSerializer(serializers.ModelSerializer): class Meta: model = MyModel exclude = ['categories', ] When serializing the Model object, on sql queries are executed to fetch categories. I dont want the categories field in the response, so I excluded it in the serializer but the categories table is queried when serializing. serializer = MyModelSerializer(MyModel.objects.first()) How can I disable queries to that table when doing this particular operation? Thanks. -
Applying date filter on a char-field that stores the date-time in string in django?
I have this field on a model X: class Details(models.Model): start_time = models.CharField(max_length=25, null=True, blank=True) Now, one problem arises that I need to apply the date filter on this. is there any way to solve this. I want to do something like this Details.objects.filter(start_time__time=some_time) -
How to return back to the same page when we use user_passes_test decorator in Django
When I sign in or log in to my account, I do not want to go back to the login page or registration page by giving the URL in the address bar. What I want is to stay on the same page even after giving the registration or login page URL. For that, I have used the user_passes_test decorator in the views.py file. Also, I set login_url in the user_passes_test decorator as return redirect(request.META['HTTP_REFERER']). At that time I got a Page not found (404) error. views.py from django.contrib.auth.decorators import user_passes_test @user_passes_test(user_is_not_logged_in, login_url="return redirect(request.META['HTTP_REFERER'])", redirect_field_name=None) def register(request): if request.method == 'POST': form = UserForm(request.POST) if form.is_valid(): form.save() return redirect('login') else: form = UserForm() return render(request, 'register.html', {'form': form}) Can anyone suggest a solution to solve this issue? -
style.css file is not working nor any error message is displaying in terminal in django
I have looked around on this site as well as others and still have not found a solution that works for why django is not loading my css file even not showing any error in terminal even in debug console. my settings.py file: STATIC_URL = 'static/' my html file: {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}" /> My file tree: App -static -css -style.css -templates -index.html INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'App', ] Any help would be greatly appreciated. I tried using the STATIC_ROOT as shown on a different thread but there was no change with that. -
Database data is not updating on my apache2 website unless I restart apache2 service
I have Django installed and am using Apache2 to host the website (using WSGI). I have checkboxes on my website and when I click a checkbox and then click submit it saves the change to the SQLite3 database and refreshes my website. If I log out of my website and then back in the checkbox is no longer clicked but the related database item is showing TRUE in the Django admin site. If I restart Apache2 using "sudo service apache2 restart" and refresh the website it then has the proper boxes checked. I am brand new to Django/Apache2 so I apologize if this is a stupid mistake, but restarting apache2 every time I make a change seems wrong. my views.py from django.shortcuts import render from django.http import HttpResponse from .models import RelayList from .forms import RelayControl from django.contrib.auth.decorators import login_required # Create your views here. @login_required def index(response): curList = RelayList.objects.get(id=1) #retrieves the database object and places it into a variable if response.method == "POST": form = RelayControl(response.POST) if form.is_valid(): curList.relay1 = form.cleaned_data["relay1"] curList.relay2 = form.cleaned_data["relay2"] curList.relay3 = form.cleaned_data["relay3"] curList.save() else: form = RelayControl() # creates an instance of the for defined in class RelayControl in forms.py #return HttpResponse('<h1>Hello World, … -
How can I render a Django Formset with some data for update process?
I am using Dajngo formset with inlineformset_factory What I need it when the user click in the update like It should render formset with the value. This is the code I did but nothing works: This is how I create a formset OrderItemFormset = inlineformset_factory( Order, OrderItem, fields='__all__', extra=1, can_delete=False) And here how I tried to render the formset with the queryset=my_query_set. if 'id' in kwargs.keys(): order = Order.objects.get(id=kwargs.get('id')) order_items = OrderItem.objects.filter(order_id=kwargs.get('id')) else: order = None order_items = None order_form = OrderForm(instance=order) print(order_items) order_item_form = OrderItemFormset(queryset=order_items) When I click in the update link Django render the Parent form with the data I need, but this does not work with formset it just give me one row with empty data. -
TemplateDoesNotExist at /product/1/ productDetail.html
I am making an about page for every item. There is a problem that occurred when I am pressing 'View' on my store page: TemplateDoesNotExist at /product/1/ productDetail.html I have tried specifying the directory by putting {{% extends store/main.html %}}, it did not help. Please assist me. store/views.py from django.shortcuts import render, redirect from django.http import JsonResponse import json import datetime from django.urls import reverse from .forms import CommentForm from .models import * from .utils import cookieCart, cartData, guestOrder def store(request): data = cartData(request) cartItems = data['cartItems'] order = data['order'] items = data['items'] products = Product.objects.all() context = {'products': products, 'cartItems': cartItems} return render(request, 'store/store.html', context) def cart(request): data = cartData(request) cartItems = data['cartItems'] order = data['order'] items = data['items'] context = {'items': items, 'order': order, 'cartItems': cartItems} return render(request, 'store/cart.html', context) def checkout(request): data = cartData(request) cartItems = data['cartItems'] order = data['order'] items = data['items'] context = {'items': items, 'order': order, 'cartItems': cartItems} return render(request, 'store/checkout.html', context) def updateItem(request): data = json.loads(request.body) productId = data['productId'] action = data['action'] print('Action:', action) print('Product:', productId) customer = request.user.customer product = Product.objects.get(id=productId) order, created = Order.objects.get_or_create(customer=customer, complete=False) orderItem, created = OrderItem.objects.get_or_create(order=order, product=product) if action == 'add': orderItem.quantity = (orderItem.quantity + 1) elif action … -
Django admin login page redirects to same page on login credentials
i hosted Django app in AWS sever properly and there no error in server. after login from Django admin login page redirects to same page on correct login credentials. but it works on local server. MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', # 'debug_toolbar.middleware.DebugToolbarMiddleware', # AxesMiddleware should be the last middleware in the MIDDLEWARE list. # It only formats user lockout messages and renders Axes lockout responses # on failed user authentication attempts from login views. # If you do not want Axes to override the authentication response # you can skip installing the middleware and use your own views. 'axes.middleware.AxesMiddleware', ] AUTHENTICATION_BACKENDS = [ # AxesBackend should be the first backend in the AUTHENTICATION_BACKENDS list. 'axes.backends.AxesBackend', # Django ModelBackend is the default authentication backend. 'django.contrib.auth.backends.ModelBackend', ] can anyone help me??? -
Deploy React and Django, same domain but different sub-domains, while on the same server
I am building a React js Application with the Django backend. with API integration I have one server and 1 Domain, and using nginx I suppose to do Run my React app on www.my-domain.com and Django backend on services-api.my-domain.com which scenario should I choose? Should I go with 2 Different Domains and Different servers? or I can do on this way what I discussed above & guide me how I can do this. How i can setup React and Django on the same server with same domain but in different sub-domain -
How to solve TypeError: Object of type HttpResponse is not JSON serializable?
I am trying to return a model.pkl file using postman from an API made in django rest framework. However the response I get is TypeError: Object of type HttpResponse is not JSON serializable. The following code is what I am using to return the file, but I cannot understand what is going wrong (this was inspired by this post). from rest_framework.status import HTTP_200_OK import pickle from django.http import HttpResponse from wsgiref.util import FileWrapper # views.py ... model_pickle_path = f'/path/model_state.pkl' #model_pickle_trained = pickle.load(open(model_pickle_path, 'rb')) model_pickle_trained = open(model_pickle_path, 'rb') response = HttpResponse(FileWrapper(model_pickle_trained), content_type='application/octet-stream') response['Content-Disposition'] = 'attachment; filename=%s' % model_filename_defined return Response(data=response, status=HTTP_200_OK) Traceback: TypeError: Object of type HttpResponse is not JSON serializable -
Get MIME type of file that is in memory - Python Django
I have a form where users can upload files. I only want them to be able to upload images. I have added that in the HTML form but need to do a server side check. I would like to do this check before I save the file to AWS S3. Currently I have this: from .models import cropSession, cropSessionPhoto import magic def crop(request): if request.method == 'POST': data = request.POST images = request.FILES.getlist('photos') crop_style = data['style'] if len(images) <= 0: messages.error(request, "At least one photo must be uploaded.") return redirect(reverse('crop-form')) crop_session = cropSession(crop_style=crop_style) crop_session.save() for image in images: mime = magic.Magic(mime=True) mime.from_file(image.file) upload = cropSessionPhoto(crop_session=crop_session, photo_file_name=image, photo_file_location=image) upload.save() else: messages.error(request, "An error has occured.") return redirect(reverse('crop-form')) return render(request, 'crop/crop.html') However, I get this error: TypeError: expected str, bytes or os.PathLike object, not BytesIO How do I properly pass the image to magic? Thank you -
Why fetch does not include credentials everytime with option {credentials: "include"}?
I have been trying to fetch data from my djangorestframework api verifying through cookies. Before reaching to the main problem, My computer IP on LAN: 192.168.1.50 Running localhost at port 80: 127.0.0.1 Running django at port 8000: 192.168.1.50:8000 - (tried vice versa as well: 127.0.0.1:8000) Now, assuming my django is running on 192.168.1.50:8000, I figured out that if I send fetch request to djangorestframework from 192.168.1.50 the cookies are attached with the request. Django's settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', "corsheaders", 'users', ] MIDDLEWARE = [ "corsheaders.middleware.CorsMiddleware", 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CSRF_COOKIE_SAMESITE = None SESSION_COOKIE_SAMESITE = None CSRF_COOKIE_HTTPONLY = True SESSION_COOKIE_HTTPONLY = True CORS_ALLOWED_ORIGINS = [ "http://192.168.1.50", "http://127.0.0.1", ] CORS_ALLOW_CREDENTIALS = True CORS_ALLOW_HEADERS = [ "accept", "accept-encoding", "authorization", "content-type", "dnt", "origin", "user-agent", "x-csrftoken", "x-requested-with", ] Fetch method from JS, fetch("http://192.168.1.50:8000/user/auth/", { method: "GET", credentials: "include", headers: { 'Content-Type': 'application/json', }, }).then(r => { console.log(r.json()); }) Sending request from 192.168.1.50, From 192.168.1.50's (from chrome browser), Response Header: Access-Control-Allow-Credentials: true Access-Control-Allow-Origin: http://192.168.1.50 Allow: OPTIONS, GET Content-Length: 5 Content-Type: application/json Cross-Origin-Opener-Policy: same-origin Date: Wed, 15 Dec 2021 #:#:# GMT Referrer-Policy: same-origin Server: WSGIServer/0.2 CPython/3.8.10 Vary: Accept, Cookie, Origin X-Content-Type-Options: nosniff X-Frame-Options: DENY Request Header: …