Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Does Zappa support Djangos recently added async functionality?
I'm starting to learn Django's new native async support: https://docs.djangoproject.com/en/4.0/topics/async/ Is it supported by Zappa? I've tried creating a basic async view but when I deploy it using Zappa the view just runs in normal sync mode. I'm aware that Zappa has it's own async functionality (wish I knew about it earlier), but I'd prefer to use the Django async. -
Many to Many table of MYSQL database in django
I connected my Django project to an existing MySQL database. Migration worked well and I can see the new Django-generated tables in the MySQL database. I have some many-to-many relationship tables in the MySQL database, without primary keys, since it is not necessary for MySQL. The Django documentation specifically states that every model needs a primary key and that Django might auto-generate a primary key column. When running inspectdb, I don't see that Django added anything to my database. An example table "countries" the columns: country_id and country_name many-to-many table "country_neighbors" the columns: country_id and neighbor_country_id(which is a country_id in the countries table) Question: Can I just use my database as is and use the inspectdb-generated foreign keys in the many-to-many model as I did when I only worked directly with the mysql database? many thanks! -
Django render not working and stays on the same page
import json from django.shortcuts import render, redirect from django.views import View from django.core.mail import send_mail from .models import MenuItem, Category, OrderModel class Index(View): def get(self, request, *args, **kwargs): return render(request, 'customer/index.html') class About(View): def get(self, request, *args, **kwargs): return render(request, 'customer/about.html') class Order(View): def get(self, request, *args, **kwargs): # get every item from each category appetizers = MenuItem.objects.filter( category__name__contains='Appetizer') entres = MenuItem.objects.filter(category__name__contains='Entre') desserts = MenuItem.objects.filter(category__name__contains='Dessert') drinks = MenuItem.objects.filter(category__name__contains='Drink') # pass into context context = { 'appetizers': appetizers, 'entres': entres, 'desserts': desserts, 'drinks': drinks, } # render the template return render(request, 'customer/order.html', context) def post(self, request, *args, **kwargs): name = request.POST.get('name') email = request.POST.get('email') street = request.POST.get('street') city = request.POST.get('city') state = request.POST.get('state') zip_code = request.POST.get('zip') order_items = { 'items': [] } items = request.POST.getlist('items[]') for item in items: menu_item = MenuItem.objects.get(pk__contains=int(item)) item_data = { 'id': menu_item.pk, 'name': menu_item.name, 'price': menu_item.price } order_items['items'].append(item_data) price = 0 item_ids = [] for item in order_items['items']: price += item['price'] item_ids.append(item['id']) order = OrderModel.objects.create( price=price, name=name, email=email, street=street, city=city, state=state, zip_code=zip_code ) order.items.add(*item_ids) # After everything is done, send confirmation email to the user body = ('Thank you for your order! Your food is being made and will be delivered soon!\n' f'Your total: {price}\n' 'Thank … -
Django Q object is adding extra - IS NOT NULL
for the below raw query, I want to build Django ORM query Select * from employee WHERE (address_id is not null OR address_id<>'*') AND (xyz_id is null OR xyz_id='*') AND (abc_id is null OR abc_id='*') So I have build ORM query as below data = Employee.objects.filter(~Q(employe_id="23") | Q(employe_id__isnull=False), Q(xyz_id__isnull=False) | Q(xyz_id='*'), Q(abc_id__isnull=True) | Q(abc_id=‘*’)) and when i print the query, it is showing as below SELECT "employee"."id", "employee"."xyz_id", "employee"."abc_id" FROM "employee" WHERE ((NOT ("employee"."address_id" = 23 AND "employee"."address_id" IS NOT NULL) OR "employee"."address_id" IS NOT NULL) AND ("employee"."xyz_id" IS NOT NULL OR "employee"."xyz_id" = *) AND ("employee"."abc_id" IS NULL OR "employee"."abc_id" = *)) my question is why Q object in Django is adding bolded line in above generated query ? which is not solving for above raw sql criteria. i am using Django 2.2 version Kindly advise -
Issues with NGINX / SSL Certificate when running docker-compose with NGINX, Django & Acme companion
I have a problem that's been bugging me for a couple of days, and I'm not sure if it's a pure NGINX issue or have something to do with SSL certificates, so I'll explain the issue I'm facing in hope of that someone can help me weed out where the issue is coming from. I'm running the following docker-compose file consisting of a Django application, a Nginx-proxy and a container using let's-encrypt to generate a SSL certificate, I have got the inspiration for it from the docs on the Docker image for the let's-encrypt container and a tutorial: https://github.com/nginx-proxy/acme-companion/blob/main/docs/Docker-Compose.md https://testdriven.io/blog/django-lets-encrypt/ docker-compose.yml version: '2' services: web: container_name: web restart: always labels: - "com.centurylinklabs.watchtower.enable=true" image: index.docker.io/username/myreponame:latest command: gunicorn myreponame.wsgi:application --bind 0.0.0.0:8000 volumes: - static_volume:/home/dockeruser/web/staticfiles - media_volume:/home/dockeruser/web/mediafiles expose: - 8000 env_file: - ./.env.prod logging: driver: "json-file" options: max-size: "100m" network_mode: bridge nginx-proxy: image: nginxproxy/nginx-proxy container_name: nginx-proxy ports: - "80:80" - "443:443" volumes: - conf:/etc/nginx/conf.d - vhost:/etc/nginx/vhost.d - html:/usr/share/nginx/html - certs:/etc/nginx/certs:ro - /var/run/docker.sock:/tmp/docker.sock:ro network_mode: bridge acme-companion: image: nginxproxy/acme-companion container_name: nginx-proxy-acme volumes_from: - nginx-proxy volumes: - certs:/etc/nginx/certs:rw - acme:/etc/acme.sh - /var/run/docker.sock:/var/run/docker.sock:ro network_mode: bridge volumes: conf: vhost: html: certs: acme: static_volume: media_volume: If I run the containers I can access the website via the browser and … -
How to get the full url in reverse function
I appreciate help with the following issue. In models.py (I use the app django-payments) class Payment(BasePayment): def get_failure_url(self): return "http://127.0.0.1:8000/collaborate/donate/payment-failure" return reverse('payment_failure') def get_success_url(self): return "http://127.0.0.1:8000/collaborate/donate/payment-success" In urls.py urlpatterns = [ path("donate/payment-failure/",views.payment_failure, name='payment_failure'), In views.py def payment_failure(request): template_name = 'collaborate/payment_failure.html' return render(request, template_name) In models.py, I override the method "get_failure_url" in order to redirect to the error url, but the sample code (django-payments) has a hard-coded url (http://127.0.0.1:8000/collaborate/donate/payment-failure). In my case, I want to use other expression calling a View name 'payment_failure', but I don't know how to obtain the full url. I have tried using "return reverse('payment_failure')", but it doesn't work, because the path is "https://sis-t.redsys.es:25443/", and not the url of my web. thanks, -
how can i schedule expo notifications from python
native expo for application and python[django] for backend , i have created an app and successfully sent notification from python to my app [i am using expo notifications for sending notifications] but i want to schedule them , its possible in react native directly but i want to do it from python for some other purpose. can someone help me with this this is my code for generating notification @api_view(['GET']) def sendNotification(request): token = StoreToken.objects.all().last() print(token) if token == None: return Response({'detail':'something went wrong'}, status=status.HTTP_400_BAD_REQUEST) message = { 'to' : token.token, 'title' : 'hello', 'body' : 'this is body' } return r.post('https://exp.host/--/api/v2/push/send', json = message) -
Django redirect user to shopping cart after item is added
In a Django / python website, I have a button that adds the selected item to the shopping cart but I need the user to then be redirected to the cart, but nothing I've tried has worked. Any help would be appreciated. I'm a novice at this. The button code: <button data-product="{{product.id}}" data-action="add" class="btn button button--primary add-btn update-cart"> Book this event </button> -
how to automatically update daily datetime in django
Hi I want to automatically update datetime daily in my database and put the today date as now then it show the subtract the start day and no and give me the delta is there any way to do this? -
django HttpResponseRedirect broken when accessing external url
I'm experiencing strange behaviour with my django app. I'm trying to use basic HttpResponseRedirect() but redirect to url outside of my application. This works flawlessly on django development server but is broken in my production environment. Namely, it does not redirect to external url but only applies relative path of the url to base url of my app (trying to redirect from facebook.com to google.com/maps, ends up in facebook.com/maps). I gutted my backend but there is nothing suspicious, therefore combined with issue appearing only in production env I suspect its problem of apache config. I inherited this app and have very little insight into server configuration, so I'm posting what seems important and will be grateful for any of your insights. I replaced some lines which seemed confidential with "// removed before sending to public". fyi rule in RewriteEngine does not trigger it LoadModule expires_module modules/mod_expires.so LoadModule ssl_module modules/mod_ssl.so LoadModule proxy_module modules/mod_proxy.so LoadModule proxy_http_module modules/mod_proxy_http.so LoadModule rewrite_module modules/mod_rewrite.so LoadModule socache_shmcb_module modules/mod_socache_shmcb.so Listen 443 SSLPassPhraseDialog builtin SSLSessionCache shmcb:/var/cache/mod_ssl/scache(512000) SSLSessionCacheTimeout 300 Mutex default SSLRandomSeed startup file:/dev/urandom 256 SSLRandomSeed connect builtin SSLCryptoDevice builtin <VirtualHost *:80> ServerName // removed before sending to public Redirect / // removed before sending to public </VirtualHost> <VirtualHost *:443> … -
Why Do I Need Cors Headers For One App But Not For Another Identical App?
I have two (almost) identical Angular PWA apps that are inside ASPNET wrappers. One is hosted at port 5000 and the other is hosted at 5002. location /app1/ { proxy_pass http://localhost:5000/; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection keep-alive; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } location /app2/ { proxy_pass http://localhost:5002/; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection keep-alive; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } The app downloads data from a Django server at /home/apps/djangoapp/media/JSON: ### Upload App ### MEDIA_ROOT = '/home/apps/djangoapp/media' MEDIA_URL = '/media/' JSON_URL = 'JSON/' DATA_UPLOAD_MAX_NUMBER_FIELDS = 100000 CORS_ALLOW_ALL_ORIGINS = True DATA_UPLOAD_MAX_MEMORY_SIZE = 10242880 The file is created with a post request and is owned by www-data after creation, no matter which app creates the file. For some reason, I can't download on the app2 (at port 5002) without passing Access-Control-Allow-Origin' '*' from NGINX for the media folder. location /media { alias /home/apps/djangoapp/media; add_header 'Access-Control-Allow-Origin' '*'; } It doesn't seem like this is the way to do it, especially since the other app apparently doesn't need the cors headers. And to further complicate things, app1 doesn't even complain about the headers being there when I put … -
How to render my formset using django-formtools?
I am using a form that will appear in multiple steps and in some cases with the formset button, everything was fine until I put django-formtools and if several forms appear in multiple steps. The problem is that what I had in JS does not appear to me, for example I had an "add form" button that when I clicked, the forms I wanted to add appeared, and now with django-formtools it no longer appears. I don't know if it's more because of the template, maybe I'm not rendering it as it should new-customer.html (this is how it looks with form-tools) <p>Step {{ wizard.steps.step1 }} of {{ wizard.steps.count }}</p> <form action="" method="post">{% csrf_token %} <table> {{ wizard.management_form }} {% if wizard.form.forms %} {{ wizard.form.management_form }} {% for form in wizard.form.forms %} {{ form }} {% endfor %} {% else %} {{ wizard.form }} {% endif %} </table> {% if wizard.steps.prev %} <button name="wizard_goto_step" type="submit" value="{{ wizard.steps.first }}">first step</button> <button name="wizard_goto_step" type="submit" value="{{ wizard.steps.prev }}">prev step</button> {% endif %} <input type="submit" value="submit"/> </form> new-customer.html (example of what it looks like without formtools and what works) <tbody> {{ manoObra_formset.management_form }} {% for form in manoObra_formset %} <div class="form-rows"> <tr> <td> {{form.codigo}} </td> … -
in Django how do I make my product page display only the variations in stock, when a user has selected 1 variation?
I am new to Django and trying to create an e-commerce website as a learning project. I am building the page for viewing the details of a single product and my problem is this: -the product has two variation types for users to select (size and color). These are HTML elements, showing the different ProductVariations as options. One has the options of small, medium, large and the other has red, green. blue. -when the user selects one variation (Color: Red), then I want the other select element to ONLY display the sizes in stock for that product, in that color. And likewise, if the user chooses Size: Medium then I want the Select element for color to only show the colors available in medium. Here are my models: class Product(models.Model): category_fk = models.ForeignKey(to=Category, on_delete=models.CASCADE) subcategory_fk = models.ForeignKey(to=SubCategory, on_delete=models.CASCADE) product_name = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200,unique=True) description = models.TextField(max_length=500, blank=True) price = models.IntegerField() image = models.ImageField(upload_to='photos/products') class VariationCategory(models.Model): name = models.CharField(max_length=50,unique=True) class ProductVariation(models.Model): product_id = models.ForeignKey(to=Product, on_delete=models.CASCADE) variation_category = models.ForeignKey(to=VariationCategory,on_delete=models.CASCADE,null=True) variation_value = models.CharField(max_length=100,) date_created = models.DateTimeField(auto_now_add=True) class ProductStock(models.Model): product_fk = models.ForeignKey(to=Product,on_delete=models.CASCADE, related_name="productstock") variation_mtm = models.ManyToManyField(to=ProductVariation,blank=True,) quantity = models.IntegerField() date_created = models.DateField(auto_now_add=True,null=True) date_updated = models.DateField(auto_now=True) for clarity: examples of VariationCategory would be … -
UUID breaking the ws connect
I've been using a websockets connection with django-channels for a chatroom app with the following routing: re_path(r'ws/chat/(?P<room_name>\w+)/participant/(?P<user>\w+)/$', consumers.ChatConsumer.as_asgi()) So if the id of my chatroom is 1, to connect to WS I would use the following url with 2 being the id of the participant that wants to enter the room: ws/chat/1/participant/1/ Now i changed the id of my room model to UUID so now to connect to a room I need to use the following url ValueError: No route found for path 'ws/chat/84f48468-e966-46e9-a46c-67920026d669/participant/1/ where "84f48468-e966-46e9-a46c-67920026d669" is the id of my room now, but I'm getting the following error: raise ValueError("No route found for path %r." % path) ValueError: No route found for path 'ws/chat/84f48468-e966-46e9-a46c- 67920026d669/participant/1/'. WebSocket DISCONNECT /ws/chat/84f48468-e966-46e9-a46c-67920026d669/participant/1/ [127.0.0.1:50532] My consumers: class ChatConsumer(WebsocketConsumer): def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.user = self.scope['url_route']['kwargs']['user'] self.room_group_name = 'chat_%s' % self.room_name # Join room group async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() def disconnect(self, close_code): delete = delete_participant(self.room_name, self.user) if delete == 'not_can_delete_user': pass else: # Leave room group channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)( f'chat_{self.room_name}', { 'type': 'receive', 'message': "USER_DISCONNECT", 'body': { 'participant': delete, 'idParticipant': self.user } } ) async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name ) def receive(self, text_data=None, type='receive', **kwargs): if isinstance(text_data, dict): text_data_json = text_data message = text_data_json['message'] … -
Django js tabs keep selected tab on page refresh
I'm working with js tabs (https://www.w3schools.com/howto/howto_js_tabs.asp) in Django and they work fine but I'd like to keep the selected tab active on that moment on page refresh. Is there an easy way to do it? I found similar questions but they are not valid for my case... This is the script I'm using: function openTab(evt, tabName) { var i, tabcontent, tablinks; tabcontent = document.getElementsByClassName("tabcontent"); for (i = 0; i < tabcontent.length; i++) { tabcontent[i].style.display = "none"; } tablinks = document.getElementsByClassName("tablinks"); for (i = 0; i < tablinks.length; i++) { tablinks[i].className = tablinks[i].className.replace(" active", ""); } document.getElementById(tabName).style.display = "block"; evt.currentTarget.className += " active"; } -
How to fix css in django cycle?
I want to do div titleblog and do magrin-top:100px,but it isnt working in django cycle..Idk why.I tried to do <a class='titleblog',but it wasnt working). P.S css file is attached at html file.CSS file is working,because navigation panel is displaying. blog.html <div class="titleblog"> {% for i in objects %} <a href="{{i.id}}">{{i.titleblog}}</a> <b>{{i.message | lower}}</b> {% endfor %} </div> home.css .titleblog{ margin-top: 100px; } -
Exposing simple types on WSDL with Spyne
We are trying to build a SOAP app with Django + Spyne building specific required endpoints. The exposed WSDL has to precisely match a predetermined XML file, including the custom simpleType definitions. We're currently failing to show the simple type definitions on our WSDL, everything else matches up precisely. A simple example is the following hello world app: import logging logging.basicConfig(level=logging.DEBUG) from spyne import Application, rpc, ServiceBase, \ Integer, Unicode, SimpleModel from spyne import Iterable from spyne.protocol.xml import XmlDocument from spyne.protocol.soap import Soap11 from spyne.interface.wsdl import Wsdl11 from spyne.server.django import DjangoApplication from django.views.decorators.csrf import csrf_exempt class IdType(SimpleModel): __type_name__ = "IdType" __namespace__ = 'spyne.examples.hello' __extends__ = Unicode class Attributes(Unicode.Attributes): out_type = 'TxnIdType' class HelloWorldService(ServiceBase): @rpc(IdType, Integer, _returns=Iterable(Unicode)) def say_hello(ctx, TxnIdType, times): for i in range(times): yield 'Hello, %s' % TxnIdType application = Application([HelloWorldService], tns='spyne.examples.hello', interface = Wsdl11(), in_protocol=Soap11(validator = 'lxml'), # out_protocol=XmlDocument(validator='schema') out_protocol=Soap11() ) hello_app = csrf_exempt(DjangoApplication(application)) Which yields the following WSDL: <wsdl:definitions xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:plink="http://schemas.xmlsoap.org/ws/2003/05/partner-link/" xmlns:wsdlsoap11="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:wsdlsoap12="http://schemas.xmlsoap.org/wsdl/soap12/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:soap11enc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:soap11env="http://schemas.xmlsoap.org/soap/envelope/" xmlns:soap12env="http://www.w3.org/2003/05/soap-envelope" xmlns:soap12enc="http://www.w3.org/2003/05/soap-encoding" xmlns:wsa="http://schemas.xmlsoap.org/ws/2003/03/addressing" xmlns:xop="http://www.w3.org/2004/08/xop/include" xmlns:http="http://schemas.xmlsoap.org/wsdl/http/" xmlns:tns="spyne.examples.hello/types" xmlns:s0="spyne.examples.hello" targetNamespace="spyne.examples.hello/types" name="Application"> <wsdl:types> <xs:schema targetNamespace="spyne.examples.hello/types" elementFormDefault="qualified"> <xs:import namespace="spyne.examples.hello" /> <xs:complexType name="say_helloResponse"> <xs:sequence> <xs:element name="say_helloResult" type="xs:string" minOccurs="0" nillable="true" /> </xs:sequence> </xs:complexType> <xs:complexType name="say_hello"> <xs:sequence> <xs:element name="IdType" type="s0:IdType" minOccurs="0" nillable="true" /> <xs:element name="times" type="xs:integer" minOccurs="0" … -
Django - Pathing Issue (I think!)
I've created a restuarant booking system using Django. Trying to achieve full Crud functionality. Just trying to sort out the update and delete. So basically when i open the user account it comes up with the reservations they've made and the option to edit or Delete them. Where my issue is is when i have my url paths as follows: urlpatterns = [ path('', views.ReservationsFormView.as_view(), name='reservations'), path('edit/<slug:pk>/', EditReservationView.as_view(), name="edit_reservation"), path('view/<slug:pk>/', ReservationCompleteView.as_view(), name="reservation_complete"), path('reservations_account/', ReservationAccountView.as_view(), name="reservations_account"), path('delete/<slug:pk>/', DeleteReservationView.as_view(), name="delete_reservation"), ] It won't load the account screen as it says: error screen 1 and when I change my paths to as follows: urlpatterns = [ path('', views.ReservationsFormView.as_view(), name='reservations'), path('edit_reservation', EditReservationView.as_view(), name="edit_reservation"), path('view_reservation/', ReservationCompleteView.as_view(), name="reservation_complete"), path('reservations_account/', ReservationAccountView.as_view(), name="reservations_account"), path('delete_reservation/', DeleteReservationView.as_view(), name="delete_reservation"), ] It does load the account screen but when i hit the Edit or Delete button i get the following: error screen 2 Relatively new to Django so any help is grealy appreciated. Thanks in adance -
RuntimeError: Model class mainpage_authentication.models.User doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS
Before applying models to my project everything was okay. But when I just applied them, the system crushed. I'm a freshmen learning Django, so will be grateful for an explanation, and a solution, if possible. My code: admin.py from django.contrib import admin from .models import User admin.site.register(User) apps.py from django.apps import AppConfig class AuthenticationPageConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'mainpage_authentication' forms.py from django import forms from .models import User class AuthenticationLoginForm(forms.Form): class Meta: model = User fields = ['username', 'password'] models.py from django.db import models class User(models.Model): username = models.CharField(max_length=100) password = models.CharField(max_length=100) settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'mainpage_authentication', ] views.py from django.shortcuts import render from django import views from mainpage_authentication.forms import AuthenticationLoginForm class MainPageView(views.View): def get(self, request): return render(request, 'mainpage.html') class AuthenticationLoginPageView(views.View): def get(self, request): form: AuthenticationLoginForm = AuthenticationLoginForm() return render(request, 'authentication-page.html', {"form": form}) -
how to upload all type of file to cloudinary using django with filefield
hello guys i want to upload all type of file to cloudinary this is my model i don't want to upload a specific kind of file but all type pleaze help me class post(models.Model): titre=models.CharField(unique=True,null=True,max_length=100) description=models.TextField(null=True,blank=True,max_length=400) T=models.CharField(default="image",blank=True,max_length=50) image=models.FileField(null=True) cat=models.ForeignKey(categorie,on_delete=models.CASCADE,null=True) datepost=models.DateTimeField(auto_now_add=True,blank=True) user=models.ForeignKey(myuser,on_delete=models.CASCADE,null=True) vue=models.IntegerField(default=0,blank=True) def __str__(self): return self.titre def save(self, *args ,**kwargs): #cette partie permet de generer un identifiant unique f=self.image.read(1000) self.image.seek(0) mime=magic.from_buffer(f,mime=True) if "video" in mime : self.T="short" super(post,self).save(*args,**kwargs) thanks for your helps and sorry for my bad english -
How can i join two prefetch related in Django query
i have to do a django filter with complex form query and i don't have experience with select_related and prefetch_related methods. models.py: class User(models.Model): class Park(models.Model): class Plot(models.Model): owner = models.ForeignKey(get_user_model(), verbose_name=_('Owner'), on_delete=models.SET_NULL, null=True, related_name='plots') park = models.ForeignKey('Park', verbose_name=_('Park'), on_delete=models.SET_NULL, null=True, related_name='plots') class Building(models.Model): plot = models.ForeignKey('Plot', verbose_name=_('Plot'), on_delete=models.SET_NULL, blank=True, null=True, related_name='plot_buildings') owner = models.ForeignKey(get_user_model(), verbose_name=_('Owner'), on_delete=models.SET_NULL, blank=True, null=True, related_name='owner_buildings') tenant = models.ForeignKey(get_user_model(), verbose_name=_('Tenant'), on_delete=models.SET_NULL, blank=True, null=True, related_name='tenant_buildings') I need to get all de user that are owner of a plot or a building or tenant of a building. i have this for now... filters.py: class UserApiFilter(filters.FilterSet): park_id = filters.CharFilter(method='filter_by_park') def filter_by_park(self, queryset, name, value): params = {name: value} result = queryset.prefetch_related(Prefetch('plots', queryset=app_models.Plot.objects.filter(**params))) Anybody could help me please? Thanks in advance. -
AttributeError at /media/.. when requesting file in media folder Django development stage
When I am reqeuesting media files (.png in this case) in the media folder in development I get this error: AttributeError at /media/test.png This FileResponse instance has no content attribute. Use streaming_content instead. Request: http://localhost:8000/media/test.png I added below to the url patterns: urlpatterns += staticfiles_urlpatterns() urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) And below to the settings: STATIC_ROOT = BASE_DIR / 'static' STATIC_URL = '/static/' MEDIA_ROOT = BASE_DIR / 'media' MEDIA_URL = '/media/' Static files are working just fine. What do I overlook? Thanks! -
Django How to display either an image or pdf
I have a model with file upload field where users can upload either an image or a pdf. What is the best way to display the upload in a template when it can be either an image or a pdf. I have seen a fairly complex ajax based solution. Is there a better way? -
django error: The value of 'ordering[0]' refers to 'username', which is not an attribute of 'accounts.clinic_staff'
I extended my accounts custom user model using a one-to-one field and it worked fine. But when I tried customizing it to display more info such as the staff_number and location, the following error is returned: <class 'accounts.admin.staffAdmin'>: (admin.E033) The value of 'ordering[0]' refers to 'username', which is not an attribute of 'accounts.clinic_staff'. the staffAdmin class doesn't have username listed as a list_display and the clinic_staff is just returning the username. I'm stuck on what to do? this is my accounts>models.py code: from datetime import date import email import imp from pyexpat import model from tkinter import CASCADE from tkinter.tix import Tree from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class MyAccountManager(BaseUserManager): def create_user(self, email, username, password=None,): if not email: raise ValueError('Email address is required') if not username: raise ValueError('Username is required') user = self.model( email=self.normalize_email(email), username = username, ) user.set_password(password) user.save(using = self.db) return user def create_superuser(self, email, username, password): user = self.create_user( email=self.normalize_email(email), password = password, username = username, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using = self.db) return user class Account(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) is_admin = … -
How can I migrate my existent sqlite db to postgres on heroku?
I deployed my django app on heroku and I can't see my database on the site(users, posts..). If i create a new superuser(couldn't log in with my old superuser so I had to create another one) or any other user, content disappears after some time.. Correct me if I'm wrong I thought heroku converts that for me automatically when I deploy my app, anything I missed? And I did migrate from the heroku CLI Setting: import os import django_heroku from decouple import config # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = secretkey # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ["network50web.herokuapp.com"] # Application definition INSTALLED_APPS = [ 'crispy_forms', 'network', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'import_export' ] 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', 'whitenoise.middleware.WhiteNoiseMiddleware', ] ROOT_URLCONF = 'project4.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': (BASE_DIR, 'network/templates'), 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'project4.wsgi.application' # Database # https://docs.djangoproject.com/en/3.0/ref/settings/#databases …