Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Bootstrap 5 site header works on desktop but not on mobile
I am following the great Django series by Corey Schafer (https://www.youtube.com/playlist?list=PL-osiE80TeTtoQCKZ03TU5fNfx2UY6U4p). Given that Bootstrap 5 has emerged since it's creation, i'm attempting to utilize it for my modified creation. The problem I am finding is that the header below is functioning properly desktop site (note: I've only activated the register.html link so far as I progress through the course), but the "hamburger" that should be created is inactive and unclickable on the mobile site. Here is the relevant file creating the header: base.html {% load static %} <!DOCTYPE html> <html> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"> <link rel="stylesheet" type="text/css" href="{% static 'The6ixDjango/main.css' %}"> {% if title %} <title>{{ title }}</title> {% else %} <title>The6ixClan</title> {% endif %} </head> <body> <header class="site-header"> <nav class="navbar navbar-expand-md navbar-dark bg-steel fixed-top"> <div class="container"> <a class="navbar-brand mr-4" href="{% url 'The6ixDjango-home' %}">The6ixClan</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarToggle" aria-controls="navbarToggle" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarToggle"> <div class="navbar-nav mr-auto"> <a class="nav-item nav-link" href="{% url 'The6ixDjango-home' %}">Home</a> <a class="nav-item nav-link" href="{% url 'The6ixDjango-about' %}">About</a> </div> <!-- Navbar Right Side --> <div class="navbar-nav"> <a class="nav-item nav-link" href="#">Login</a> <a class="nav-item nav-link" href="{% … -
File not in request.FILES but in request.POST I'm using htmx to make post request
I have snippet of inputs that I render to the html page when a condition is met, everythings works appropriately except for the input with type file, I want to upload the files when a change has occured but the file object is not in request.FILES, it's in request.POST now I don't mind it being request.POST but the files is displayed as 'multiple': ['[object File]'] My partial template <div class="my-2"> <div id="uploaded"></div> <p class="lead">{{question.prompt}}</p> <input name="multiple" type="file" accept="image/*, .pdf" id="image_{{question.id}}" {% if question.required %}required{% endif %} {% if question.disabled %}disabled{% endif %} class="form-control" placeholder="{{question.placeholder}}" hx-post="{% url 'survey:file_multiple' %}" hx-trigger="change"> <input type="hidden" name="filemultipleId" value="{% if question.form_input_type == 'file-multiple' %}{{question.id}}{% endif %}"> </div> I am not rendering the form with django form as it will be difficult and near impossible to achieve the dynamicity I am looking for request.POST QueryDict <QueryDict: {'csrfmiddlewaretoken': ['TiLZFEWw88cqItD8MABv6lZKYDrNaVxGF4ZMDOV3sK43540z6uOcrx5uQO6iYldA', 'date': [''], 'dateId': ['20', '5'], 'multiple': ['[object File]'], 'filemultipleId': ['18'], 'fileId': ['17']}> Traceback Internal Server Error: /file-multiple/ Traceback (most recent call last): File "/home/tomms/.local/share/virtualenvs/web-app-QB9eq0sY/lib/python3.9/site-packages/django/utils/datastructures.py", line 83, in __getitem__ list_ = super().__getitem__(key) KeyError: 'multiple' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/tomms/.local/share/virtualenvs/web-app-QB9eq0sY/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/tomms/.local/share/virtualenvs/web-app-QB9eq0sY/lib/python3.9/site-packages/django/core/handlers/base.py", line … -
Deploy Django app with Nginx, Gunicorn, uvicorn, PostgreSQL
My app works on development mode (I run from a container with specified variable RTE=dev docker-compose up) I need to deploy the app to my domain and I have all settings in place for it (Nginx, Gunicorn, uvicorn, PostgreSQL). When I docker-compose up in Production mode I do not get any errors and I can't seem to find out where the issue is. settings.py class RuntimeEnvironment(Enum): """docstring: environment variables""" dev = 1 test = 2 prod = 3 RTE = RuntimeEnvironment[os.environ['RTE']] (...) if RTE is RuntimeEnvironment.dev: SECRET_KEY = 'django-insecure-l)lj4%c6(3v5r!0b9eac&0%%_500%ct4x1nbf5j5qsarmtn0#d' else: SECRET_KEY = os.environ['DJANGO_SECRET_KEY'] (...) if RTE is RuntimeEnvironment.dev: DEBUG = True ALLOWED_HOSTS = [] else: DEBUG = False ALLOWED_HOSTS = ['pbstyle.dk', 'https://pbstyle.dk/'] nginx.conf upstream app_upstream { server app:8080; } server { listen 80; listen 443; server_name pbstyle.dk; location /static/ { alias /static/; } location /media/ { alias /media/; } location / { proxy_set_header Host $host; proxy_pass http://app_upstream; } } docker-compose version: "3.8" services: db: image: postgres:13-alpine volumes: - db_data:/var/lib/postgresql/data - ./dbscripts/:/dbscripts/ env_file: - db_${RTE}.env app: build: . ports: - 8000:8000 - 8080:8080 env_file: - db_${RTE}.env volumes: - .:/app/ - static:/static/ - media:/media/ depends_on: - db nginx: build: nginx/ ports: - 443:443 - 80:80 volumes: - ./ngin/${RTE}/conf.d/:/etc/nginx/conf.d/ - ./certs/:/etc/letsencrypt/ - static:/static/ … -
Django is not recongizing a users password when login is attempted
When trying to create a simple web page with login and sign up i ran into the issue of django not recognzing the created user. In views.py i created a simple message that displays "Incorrect password or email" if user does not exist. I created a user and made sure that the password was correct when i inputed it into the login form however it still gave me the message of "Incorrect password or email". Instead of redirecting to home like a created user should it errored and i could not figure out why it is not accepting the password/email in the form. views.py from django.shortcuts import redirect, render from django.contrib.auth import authenticate, login, logout from django.contrib import messages from django.contrib.auth.models import User def home(request): return render(request, 'home.html') def signup(request): if request.method == "POST": email = request.POST['email'] password = request.POST['password'] myuser = User.objects.create_user(email, password) myuser.email = email myuser.password = password myuser.save() messages.success(request, "Your account has been successfully created ") return redirect('signin') return render(request, 'signup.html') def signin(request): if request.method == "POST": email = request.POST['email'] password = request.POST['password'] user = authenticate(request, email = email, password = password) if user is not None: login(request, user) email = user.email messages.success(request, "Successfully Logged In") return … -
Page not found, my template is there but I see an Page Not Found error
I saw different Q&A about this error, but I couldn´t find one similar to my case. I´m trying to create "read templates" from two classes, but I can´t. I already created the views and the models, but the templates don´t work. views: def readCoberturas(request): cobert = Coberturas.objects.all() dicCoberturas = {"Coberturas": cobert} return render(request, "AppURC/readCoberturas.html", dicCoberturas) Model (Coberturas): class Coberturas(models.Model): tipo = models.CharField(max_length=20) numeroPoliza = models.IntegerField() fechaContratacion = models.DateField() fechaVigencia = models.DateTimeField() detalle = models.CharField(max_length=40) def __str__(self): return f"Tipo de Cobertura: {self.tipo} | Poliza n°: {self.numeroPoliza} | Fecha alta: {self.fechaContratacion} | Vigencia hasta: {self.fechaVigencia} | Detalle: {self.detalle}" Url: path('readCoberturas/',views.readCoberturas, name='ReadCoberturas'), Template: {% load static %} {% block contenido %} {% for C in Coberturas %} <li>{{ c }}</li> {% endfor %} {% endblock %} I hope I have made this sufficiently clear. Thanks to all! -
Django - See exact value of foreign key import export
I have some models and some foreign keys assigned to them. What I want is to get the Foreign keys exact content rather than the ID of the foreign key. What I can do ? my models from django.db import models class MonkAttributes(models.Model): id = models.AutoField(primary_key=True) head = models.CharField(max_length=55) cloth = models.CharField(max_length=55) mouth = models.CharField(max_length=55) skin = models.CharField(max_length=55) eyewear = models.CharField(max_length=55) background = models.CharField(max_length=55) class MonkFiles(models.Model): id = models.AutoField(primary_key=True) uri = models.CharField(max_length=255) type = models.CharField(max_length=25) class MonkCreators(models.Model): id = models.AutoField(primary_key=True) address = models.CharField(max_length=255) share = models.IntegerField() class MonkProperties(models.Model): id = models.AutoField(primary_key=True) files = models.ForeignKey(MonkFiles, on_delete=models.CASCADE) category = models.CharField(max_length=55) creators = models.ForeignKey(MonkCreators, on_delete=models.CASCADE) class MonkDetailsModel(models.Model): id = models.AutoField(primary_key=True) dna = models.CharField(max_length=25) name = models.CharField(max_length=50) symbol = models.CharField(max_length=10) description = models.CharField(max_length=255) seller_fee_basis_points = models.IntegerField() image = models.CharField(max_length=255) external_url = models.URLField() attributes = models.ForeignKey(MonkAttributes, on_delete=models.CASCADE) properties = models.ForeignKey(MonkProperties, on_delete=models.CASCADE) def __str__(self): return self.name or '' exported json file is like this: I want to get the exact content of attributes and properties [ { "id": 1, "dna": "010001001110", "name": "Decentralized Monks Test Item", "symbol": "SYM", "description": "This image shows the true nature of Monks.", "seller_fee_basis_points": 100, "image": "https://ipfs.io/ipfs/QmNjsxLtyK5ZpmoyZFaPKFTXeDAmGQDq2vSSCfNXA279SB", "external_url": "http://0xmonks.com", "attributes": 1, "properties": 1 } ] -
Production web app - Django with Djongo or Flask with Mongo?
I am working on a new web app that will store data about transactions of multiple companies. As companies from various industries sell various products they need different columns (attributes) to describe each product. For example, food products require Best before date column, but books don't require it and instead they need Author and Genre columns. My way of thinking is that it is hard and inefficient to store this kind of data in relational, SQL database. Instead, I think that NoSQL such as MongoDB will be perfect for this case. Please correct me if I'm wrong. My question is: for such web app, which from the below options should I use? Django app with Djongo, which is an unofficial connector between Django and MongoDB Flask with MongoEngine Flask with PyMongo Other NoSQL technology. Maybe NoSQL is a bad choice in my case and should be avoided? My concerns are: Not sure if Djongo should be used in production, as support for it can be dropped any time (I expect this web app to last a few years) and I don't know if Djongo is reliable Not sure if Flask isn't too 'poor' and 'simple' for an app that is … -
Annotate QuerySet with the maximum of a date field and a manually created date
I have the following model: class Item(models.Model): last_used = models.DateTimeField() created_at = models.DateTimeField() I'm trying now to look at the average "lifetime" of items per month. Lifetime is how many days items are used, on average. I can calculate the overall average with the following: from django.db.models import IntegerField, F, Avg from django.db.models.functions import Cast, ExtractDay, TruncDate items = Item.objects.annotate(days_used=Cast(ExtractDay(TruncDate(F('last_used')) - TruncDate(F('created_at'))), IntegerField())+1) avg = items.aggregate(Avg('days_used'))['days_used__avg'] Now when I want to calculate this per month, I would like to annotate the query with a new field that is the maximum of created_at or the beginning of the month in question. This is needed so that the maximum lifetime value for all months is the number of days in that month. There's a function, Greatest that I think could be used for this, but I'm not sure how. Assuming we're interested in December, 2021, this is what I have at the moment: target_month = 12 items = items.annotate(created_max=Greatest(TruncDate(F('created_at')), TruncDate(F(timezone.datetime(2021, target_month, 1))) But using timezone.datetime is causing an error: AttributeError: 'datetime.datetime' object has no attribute 'split' NOTE: I'm aware that last_used may cause the value to go over the number of days but that's another issue we're tackling. -
How to get around the django Error : raw query must include primary key
Is there a way to run a query on Django without using the Primary key of the table? in the following code, I have a query that, at least I think, must be used only with SELECT DISTINCT p.type without adding the primary key of the table - in this case, the PK is NAME. Every time I run the code I get the same Error - raw query must include primary key is there a way to get around that? Code: def Query_result(request): AttackThreshold_res = request.POST.get('AttackThreshold') PokemonCount_res = request.POST.get('PokemonCount') sql_threshold_res = Pokemons.objects.raw(""" SELECT DISTINCT p.type FROM pokemons p INTERSECT SELECT DISTINCT p1.type FROM pokemons p1 WHERE p1.attack > %s INTERSECT SELECT DISTINCT p2.type FROM pokemons p2 GROUP BY ( p2.type ) HAVING Count(p2.type) > %s """, [AttackThreshold_res, PokemonCount_res]) return render(request, 'queries.html', {'sql_threshold': sql_threshold_res}) -
Django Stripe Invalid signature Azure Deployment
I'm trying to deploy a Django(3.2.9) app with payments using Stripe(2.61.0). Works well using the Stripe CLI locally. But soon as I deploy on Azure and try to a test mode webhook to test if it's working properly I keep receiving the result of been Invalid. I've made tests about if it's different webhook secret when deploy in anyway but the result is that the one on Stripe Dashboard. I wanna know if there's any possibility I'm oblivious to this issue? -
Django model related to self
How to create object to object relation suchwise that when i add this relation to parent and relaton to child added automatically? class Object(models.Model): name = models.CharField(max_length=150) description = models.TextField(blank=True) is_published = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) relation = models.ForeignKey('self', related_name="related", on_delete=models.DO_NOTHING, blank=True, null=True) def __str__(self): return self.name When I appoint some relation in django-admin for example to 'Spider Man' object related to 'Peter Pen' object I don't have relation 'Peter Pen' -> 'Spider Man' when I open 'Peter Pen' object -
Django models: How do I check that a decorartor property exists
I have a Profile model with a decorator property @property def primary_phone(self): When I query for the primary phone for a given id like this it works x = Profile.objects.get(id=3) x.primary_phone outputs Out[3]: '+256771000022' However filtering for the same like this Profile.objects.filter(primary_phone="+256771000022").exists() outputs FieldError: Cannot resolve keyword 'primary_phone' into field. Choices are: _created_at, _modified_at, apierror, business,...) -
django how to create object and add many to many best way or best practice
how can I make this code much more effective or faster def handle(self, *args, **kwargs): shops = MyShop.objects.all() for shop in shops: month_invoice = shop.shop_order.annotate(year=TruncYear('created'), month=TruncMonth('created')).values( 'year', 'month', 'shop_id' ).annotate(total=Sum(ExpressionWrapper( (F('item_comission') / 100.00) * (F('price') * F('quantity')), output_field=DecimalField())), ).order_by('month') for kv in month_invoice: a = ShopInvoice.objects.create(shop_id=kv['shop_id'], year=kv['year'], month=kv['month'], total=kv['total']) test = shop.shop_order.filter(created__month=kv['month'].month, created__year=kv['year'].year) for t in test: a.items.add(t.id) -
I am getting "token_blacklist.0008_migrate_to_bigautofield...Not implemented alter command for SQL ALTER TABLE "token_blacklist_blacklistedtoken"
Anyone please tell me what type of error is it? on django rest_framework I am getting this error after running "python manage.py migrate" I am using simple_jwt library for authentication and the migrations stop here Applying token_blacklist.0008_migrate_to_bigautofield...Not implemented alter command for SQL ALTER TABLE "token_blacklist_blacklistedtoken" ALTER COLUMN "id" TYPE long (env) D:\inductionplan\django-api\backend>python manage.py migrate Operations to perform: Apply all migrations: admin, api, auth, authtoken, contenttypes, sessions, token_blacklist Running migrations: Applying token_blacklist.0008_migrate_to_bigautofield...Not implemented alter command for SQL ALTER TABLE "token_blacklist_blacklistedtoken" ALTER COLUMN "id" TYPE long Traceback (most recent call last): File "D:\inductionplan\django-api\env\lib\site-packages\djongo\cursor.py", line 51, in execute self.result = Query( File "D:\inductionplan\django-api\env\lib\site-packages\djongo\sql2mongo\query.py", line 784, in __init__ self._query = self.parse() File "D:\inductionplan\django-api\env\lib\site-packages\djongo\sql2mongo\query.py", line 876, in parse raise e File "D:\inductionplan\django-api\env\lib\site-packages\djongo\sql2mongo\query.py", line 857, in parse return handler(self, statement) File "D:\inductionplan\django-api\env\lib\site-packages\djongo\sql2mongo\query.py", line 889, in _alter query = AlterQuery(self.db, self.connection_properties, sm, self._params) File "D:\inductionplan\django-api\env\lib\site-packages\djongo\sql2mongo\query.py", line 425, in __init__ super().__init__(*args) File "D:\inductionplan\django-api\env\lib\site-packages\djongo\sql2mongo\query.py", line 84, in __init__ super().__init__(*args) File "D:\inductionplan\django-api\env\lib\site-packages\djongo\sql2mongo\query.py", line 62, in __init__ self.parse() File "D:\inductionplan\django-api\env\lib\site-packages\djongo\sql2mongo\query.py", line 441, in parse self._alter(statement) File "D:\inductionplan\django-api\env\lib\site-packages\djongo\sql2mongo\query.py", line 500, in _alter raise SQLDecodeError(f'Unknown token: {tok}') djongo.exceptions.SQLDecodeError: Keyword: Unknown token: TYPE Sub SQL: None FAILED SQL: ('ALTER TABLE "token_blacklist_blacklistedtoken" ALTER COLUMN "id" TYPE long',) Params: ([],) Version: 1.3.6 The above exception was … -
how do i render text put into a django textfield with a its original format?
im building a site with django and i would like to output some text that I put into a text field from my model but when i do so in the html it loses all the form that i give it (spacing and new lines, etc.) does anyone have a solution?. so instead of coming out as: enter image description here it comes out as just a line without the proper spacing enter image description here -
How to get a user with 'django-microsoft-authentication' code?
I'm using the library django-microsoft-authentication. The application for microsoft was created, all the codes were received by me. I did everything according to the documentation. MICROSOFT = { "app_id": "<my app id>", "app_secret": "my app secret id", "redirect": "http://localhost:8000", "scopes": ["user.read"], "authority": "https://login.microsoftonline.com/common", "valid_email_domains": ["<list_of_valid_domains>"], "logout_uri": "http://localhost:8000/admin/logout" } Add 'microsoft_authentication' to INSTALLED_APPS LOGIN_URL = "/microsoft_authentication/login" LOGIN_REDIRECT_URL = "/admin" and urls.py from django.urls import path, include urlpatterns = [ ..... path('microsoft_authentication/', include('microsoft_authentication.urls')) ] And everything goes well, and without errors. I authenticate and get returned to the home page. But there is no new user in the admin area. Or I need to do create a new user manually? Or is callback not working? In my address bar I get some this: http://localhost:8000/?code=0.Awfwjhey79kyt4fe..........feky5hmj (random code). I understand that this is some kind of user token grant. According to the documentation, I checked the decorator @microsoft_login_required(), and it working when I was logged in, and it did not work when I was NOT logged in. So everything is going well. But I only get the code=..... above. But I don't see the user anywhere. How do I get a user? How do I create and save a user? Please, any help will … -
Django-taggit: how to save after adding tags in save()
def save(self, *args, **kwargs): super(Flow, self).save(*args, **kwargs) if self.pk: self.tags.add(str(date.today().year)) self.save() This doesn't work in my model Flow. How can I save the newly added tag into tags of my flow instance successfully? Thanks. -
making a new table in django for database by user from frontend
I am writing a web application by Django and Reactjs. It should be able that the user creates a new project in application with a specific name and, the project should have its table in the database. I need a tool to create a model and migrate it automatically in the database. -
ValueError: invalid literal for int() with base 10: in Django 3.0
I have updated my project from Django 1.8 to Django 3.0 Here when i am trying display items using autocomplete i am getting this error Here is my views.py def autocomplete_items(request, flag=None): client = request.user.client q = request.GET.get('term') category = request.GET.get('category', '') job_items = JobItems.objects.filter(client_id=client) if category: job_items = job_items.filter(category_id=category) if flag: job_items = job_items.filter(stock='Variety Master') else: if client.horticulture: job_items = job_items.exclude(stock='Variety Master') products = job_items.filter(Q(item_name__icontains=q)|Q(soil_type__icontains=q)|Q(height__icontains=q)|Q(pot_size__icontains=q)|Q(form__contains=q)|Q(unit_price__contains=q)|Q(supplier_one__supplier_name__icontains=q)|Q(part_number__icontains=q)|Q(batch_number__icontains=q),is_deleted=False, is_one_of_item=False) res = [] for c in products: #make dict with the metadatas that jquery-ui.autocomple needs (the documentation is your friend) dict = {'id':c.id, 'label':c.__str__()+ ' ('+ str(c.part_number)+')' if c.part_number else c.__str__() , 'label2':c.__str__()+ ' ('+ str(c.batch_number)+')' if c.part_number else c.__str__(), 'value':c.__str__(), 'partnumber': c.part_number} res.append(dict) return HttpResponse(json.dumps(res[:15])) Here is my models.py class JobItems(models.Model): description = models.TextField(blank=True) item_name = models.CharField(max_length=512) part_number = models.CharField(max_length=32, null=True, blank=True, verbose_name='Stock number') batch_number = models.CharField(max_length=200, blank=True, null=True) client = models.ForeignKey("core.Client", related_name="job_items",on_delete=models.CASCADE) is_deleted = models.BooleanField(default=False, help_text="Deleted tasks will not display in the UI.") is_checked = models.BooleanField(default=False, help_text="Save item into item details") created_at = models.DateTimeField(auto_now_add=True) modified_at = models.DateTimeField(auto_now=True) quantity = models.DecimalField( max_digits=10, decimal_places=2, default=0.00, verbose_name='Quantity In Stock') unit_price = models.DecimalField(null=True, max_digits=10, decimal_places=2, default=0.00, verbose_name='Retail price') def __str__(self): return self.item_name class Meta: ordering = ("quantity", ) here is my error traceback Traceback (most … -
Django: how to search for the most similar entry
There are many ways I can query for information in a database, mine being PostgreSQL, such as __contains, __icontains, unnaccent__icontains, __unaccent__lower__trigram_similar, and so on. Though these are very handy, none of these helped my really reach the goal I have in mind: searching for the most similar entry. Trigram similarity got pretty close, but it no longer worked for longer strings. Is there any operation that can get the closest value, also working for longer strings? -
Django: How to rewrite raw SQL into queryset
The raw SQL was rewritten because the issue time of the following queryset was very slow. # queryset Video.objects.annotate( is_viewed=Exists(History.objects.filter(user=user, video=OuterRef("pk"))), is_favorited=Exists( Favorite.objects.filter(user=user, video=OuterRef("pk")) ), is_wl=Exists( Track.objects.filter( playlist__user=user, playlist__is_wl=True, video=OuterRef("pk") ) ), ).filter( Q(title__contains=value) | Q(tags__name__contains=value), is_public=True, published_at__lte=timezone.now(), ).order_by("-published_at").distinct()[:20] SELECT DISTINCT "videos_video"."id", "videos_video"."title", "videos_video"."thumbnail_url", "videos_video"."preview_url", "videos_video"."embed_url", "videos_video"."duration", "videos_video"."views", "videos_video"."is_public", "videos_video"."published_at", "videos_video"."created_at", "videos_video"."updated_at", EXISTS (SELECT (1) AS "a" FROM "videos_history" U0 WHERE (U0."user_id" IS NULL AND U0."video_id" = "videos_video"."id") LIMIT 1) AS "is_viewed", EXISTS (SELECT (1) AS "a" FROM "videos_favorite" U0 WHERE (U0."user_id" IS NULL AND U0."video_id" = "videos_video"."id") LIMIT 1) AS "is_favorited", EXISTS (SELECT (1) AS "a" FROM "videos_track" U0 INNER JOIN "videos_playlist" U1 ON (U0."playlist_id" = U1."id") WHERE (U1."is_wl" AND U1."user_id" IS NULL AND U0."video_id" = "videos_video"."id") LIMIT 1) AS "is_wl" FROM "videos_video" LEFT OUTER JOIN "videos_video_tags" ON ("videos_video"."id" = "videos_video_tags"."video_id") LEFT OUTER JOIN "videos_tag" ON ("videos_video_tags"."tag_id" = "videos_tag"."id") WHERE ("videos_video"."is_public" AND "videos_video"."published_at" <= '2022-01-03 05:20:16.725884+00:00' AND ("videos_video"."title" LIKE '%word%' OR "videos_tag"."name" LIKE '%word%')) ORDER BY "videos_video"."published_at" DESC LIMIT 20; I have sped up the above query to look like the query below. But how can I reproduce this in Django's querieset? SELECT DISTINCT "t"."id", "t"."title", "t"."thumbnail_url", "t"."preview_url", "t"."embed_url", "t"."duration", "t"."views", "t"."is_public", "t"."published_at", "t"."created_at", "t"."updated_at", EXISTS (SELECT (1) AS … -
Django Session Is not working with Heroku when changing views (but works locally)
The sessions work perfectly while changing views when working locally, but when deployed to Heroku it is as if the session was refreshed and all the information it contains is deleted upon every view change. I am using Heroku's Postgres Database. I have already taken a look at: Django Session Not Working on Heroku but the problem still persists Here is my current settings file. Any help would be appreciated import os from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = 'e488a0185303170daa47fe1de243823fbb3db60f045e6eae' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['127.0.0.1', 'here goes the heroku host'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', '....', '....', ] ASGI_APPLICATION = 'System.asgi.application' MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', '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', ] ROOT_URLCONF = 'System.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR / '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 = 'System.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } import dj_database_url db_from_env = dj_database_url.config() DATABASES['default'].update(db_from_env) SESSION_ENGINE= 'django.contrib.sessions.backends.cached_db' AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 'OPTIONS': {'min_length': 8} }, … -
Django Rest Framework - Nested List Inside JSON Response
I'm very new to both Django and the Django Rest Framework, and I'm struggling with building up a particular JSON response. I have two models, like so: class Artist(models.model): artist_id = models.CharField( max_length=256, primary_key=True, ) name = models.CharField( max_length=256, null=False, blank=False, ) birthplace = models.CharField( max_length=256, null=False, blank=False, ) class Album(models.Model): artist = models.ForeignKey( Artist, on_delete=models.DO_NOTHING, db_constraint=False, null=True, ) name = models.CharField( max_length=256, null=False, blank=False, ) label = models.CharField( max_length=256, null=False, blank=False, ) I'm trying to build a JSON response that looks like this, where the albums are nested inside the artist: { "artist_id": "A123", "name": "Bob Dylan", "birtplace": "Duluth, Minnesota", "albums": [ { "id": 123, "name": "Bob Dylan", "label": "Columbia" }, { "id": 123, "name": "The Freewheelin' Bob Dylan", "label": "Columbia" } ] } Is this even possible? I was looking into select_related, but that doesn't seem to work as I feel like I need to 'hit' the Artist table first, and there is no relationship defined in the direction of Artist to Album. Any help would be greatly appreciated. -
I need save info + User.id or username to database in Django
I have some problem with save info about authentificate user with info. I didnt have some id but django have exception. My model.py from django.contrib.auth.models import User from django.db import models from hashlib import md5 from django.conf import settings # Create your models here. class Url(models.Model): long_url = models.CharField(unique=True,max_length=500) short_url = models.CharField(unique=True, max_length=100) user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) id = models.BigAutoField(primary_key=False, null=True) @classmethod def create(self, long_url, user, id): tmp = md5(long_url.encode()).hexdigest()[:6] tmp = '127.0.0.1:8000' + '/' + tmp try: obj = self.objects.create(id=id,long_url=long_url, short_url=tmp, user=user) except: obj = self.objects.get(long_url=long_url, user=user) return obj My views.py from django.contrib.auth.models import User from django.shortcuts import render, redirect from .forms import UserRegistration, UserLogIn from .models import Url from django.http import HttpResponse from django.contrib.auth import authenticate, login # Create your views here. def register(request): if request.method == 'POST': user_form = UserRegistration(request.POST) if user_form.is_valid(): new_user = user_form.save(commit=False) new_user.set_password(user_form.cleaned_data['password']) new_user.save() return render(request, 'register.html', {'new_user': new_user}) else: user_form = UserRegistration() return render(request, 'register.html', {'user_form': user_form}) def shorter(request): if request.method == 'POST': long_url = request.POST.get('long_url') obj = Url.create(long_url, User) return render(request, 'short.html', { 'short_url': request.get_host() + '/' + obj.short_url[-6:]}) return render(request, 'shorter.html') My forms.py from django.contrib.auth.models import User from django import forms class UserRegistration(forms.ModelForm): password = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField(label='Repeat … -
Django: How do I create separate instances of the same model object?
I have two classes that need to relate to each other. an Item class and an Order class. An Item object has several attributes: name, cost, quantity etc. I want the same item to be able to belong to several different Order objects and white doing so, having different attributes inside that Order object. (Like different orders can have different amounts of the same Item on order) Is this possible? Here's what I've got so far: class Item(models.Model): description = models.CharField(max_length=200) cost = models.FloatField() order_quantity = models.IntegerField(null=True, blank=True) def __str__(self): return str(self.description) @property def line_total(self): return self.cost * self.order_quantity class Order(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('issued', 'Issued'), ('closed', 'Closed'), ) reference = models.AutoField(primary_key=True) location = models.ForeignKey( Location, null=True, blank=True, on_delete=models.CASCADE) author = models.ForeignKey(User, on_delete=models.CASCADE) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) item = models.ManyToManyField(Item, blank=True) class Meta: ordering = ('location',) def __str__(self): return str(self.reference) This setup allows me to have the same item in different orders, which is great, however I can't figure out how to make some Item attributes 'independent', based on which order they belong to.