Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Form not showing in template
I'm trying to make a login with a bootstrap dropdown. The problem is my form isn't showing up. I tried different things, I watched if my settings were correct and for me everything is good. I think the problem comes from my view. <!-- navbar.html --> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <a href="#" class="navbar-brand">Park<b>AUTO</b></a> <button type="button" class="navbar-toggler" data-toggle="collapse" data-target="#navbarCollapse"> <span class="navbar-toggler-icon"></span> </button> <div id="navbarCollapse" class="collapse navbar-collapse justify-content-start"> <div class="navbar-nav"> <a href="#" class="nav-item nav-link">Home</a> <a href="#" class="nav-item nav-link">About</a> <a href="#" class="nav-item nav-link">Contact</a> </div> <div class="navbar-nav action-buttons ml-auto"> <a href="#" data-toggle="dropdown" class="nav-item nav-link dropdown-toggle mr-3">Login</a> <div class="dropdown-menu login-form"> <form action= {% url 'account:login' %} method="post"> {{ form.as_p }}{% csrf_token %} <input type="submit" class="btn btn-primary btn-block" value="Login"> </form> </div> <a href="#" class="btn btn-primary">Get Started</a> </div> </div> </nav> #views.py from django.shortcuts import redirect, render from django.contrib.auth.forms import AuthenticationForm # Create your views here. def login(request): if request.method == 'POST': form = AuthenticationForm(data=request.POST) if form.is_valid(): user = form.get_user() login(request, user) return redirect("home:home") else: form = AuthenticationForm() return render(request, 'pages/home.html', {"form": form}) #urls.py from django.urls import path from .views import login app_name = 'account' urlpatterns = [ path('', login, name='login'), ] If someone could help me on that, it would be pretty nice. -
In a Django template, is it possible to send the whole variable document to a template tag?
If I render a template using this document: { "a": 1, "b": 2 } In Django templates, I can render html using the value of "a" like this: {{ a }} But is it possible to send the whole document to a template tag? ie, all this? { "a": 1, "b": 2 } So that my tag can access arbitrary elements? -
Unhandled Exception: type 'Null' is not a subtype of type 'int' in type cast
factory Account.fromJson(Map<String, dynamic> json) { return Account( json["id"], json["email"], json["description"], json["first_name"], json["last_name"], json["phone"], json["username"], json["image"], json["email_confirmed"], json["reviews_media"] != null ? double.parse(json["reviews_media"]) : (json["reviews_media"] as int).toDouble(), json["holiday_mode"], json["identity_code"], json["residency_city"], json["birthday"] != null ? DateFormat("yyyy-MM-dd").parse(json["birthday"]) : null); } -
How do I sort the movies according to their star ratings and filter the movies with lower rating than the specified threshold
I want to sort the movies according to their star ratings and filter the movies with lower rating than the specified threshold. I want to sort movie and TV information in descending order by stars, search by each ID, and display data.json format and socre. However, I get a'module' object does not support item assignment error. context ["movie"] = in movie_list class Movie(models.Model): id = models.CharField(primary_key=True, editable=False, validators=[alphanumeric],max_length = 9999) stars = models.FloatField( blank=False, null=False, default=0, validators=[MinValueValidator(0.0), MaxValueValidator(10.0)] ) def get_comments(self): return Comment_movie.objects.filter(movie_id=self.id) def average_stars(self): comments = self.get_comments() n_comments = comments.count() if n_comments: self.stars = sum([comment.stars for comment in comments]) / n_comments else: self.stars = 0 return self.stars class TV(models.Model): id = models.CharField(primary_key=True, editable=False, validators=[alphanumeric],max_length = 9999) stars = models.FloatField( blank=False, null=False, default=0, validators=[MinValueValidator(0.0), MaxValueValidator(10.0)] ) def get_comments(self): return Comment_tv.objects.filter(tv_id=self.id) def average_stars(self): comments = self.get_comments() n_comments = comments.count() if n_comments: self.stars = sum([comment.stars for comment in comments]) / n_comments else: self.stars = 0 return self.stars def Score_by(request): movies = Movie.objects.order_by('-stars') movie_list= [] if movies.exists(): for obj in movies: data = requests.get(f"https://api.themoviedb.org/3/movie/{obj.id}?api_key={TMDB_API_KEY}&language=en-US") movie_list.append(data.json()) context["movie"] = movie_list tv = TV.objects.order_by('-stars') tv_list = [] if tv.exists(): for obj in tv: data = requests.get(f"https://api.themoviedb.org/3/tv/{obj.id}?api_key={TMDB_API_KEY}&language=en-US") tv_list.append(data.json()) context["tv"] = tv_list return render(request, 'Movie/score_by.html', context) <div class="row"> … -
I am working on a djnago project and I am using django_bootstrap_icons, I have installed it using pip and done everything but they aren't showing
settings.py INSTALLED_APPS = [ ... 'myapp', 'django_bootstrap_icons', ] ... STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR,'static,'media') STATIC_ROOT = os.path.join(BASE_DIR,'static','static_root') STATICFILES_DIRS = ( os.path.join(BASE_DIR,'static','static_files') ) home.html ... {load static} <link rel="stylesheet" href="{% static 'bootstrap_icons/css/bootstrap_icons.css' %}"> ... {% load bootstrap_icons %} {% bs_icons 'alarm' %} Is there something I've done wrong. I installed the django bootstrap icons using pip and I even did the py manage.py collectstatic And still it's saying Icon does not exist However the icons appear if I connect to the Internet but since I've installed the django bootstrap icons, I want the icons to appear even when I'm offline because I don't have Internet access everytime... -
How to send mail (like noreply) with Django sendgrid
I am newbie! I want to create a django application that sends mail. it worked well on localhost, but when I deployed it, it stopped working because the host doesn't support smtp. He suggested using sendgrid, and I'm stuck here... enter image description here sorry i dont have permission to put pic only link views.py enter image description here error: enter image description here -
How to get multiple values from a model field into a form choice field?
I have a model called Listing that has a field called categories that stores all the different categories. There is also a form with a field called categories that should show a choice field to the user, where the choices should be the values stored in the Listing.categories model field. So I tried to loop through it but that is not possible as the choice field values are stored in a dict format. So how do I get the values from the model field into the choice field? models.py class Category(models.Model): name = models.CharField(max_length=50) class Listing(models.Model): ... category = models.ForeignKey(Category, on_delete=models.PROTECT, null=True) forms.py: from .models import Listing # example of what I was trying to do condition_choices = ( (1, 'New'), (2, 'Refurbished'), (3, 'Opened'), (4, 'Used'), ) ### for i in Listing.category: category_choices = ( (i, Listing.category) ) class NewListing(forms.Form): ... category = forms.ChoiceField(choices=category_choices) -
Django queryset annotation returning grouped counts
I am using Django 3.2 models.py class AwardCategory(models.Model) name = models.CharField(max_length=16) slug = models.SlugField(max_length=16, unique=True, db_index=True) class Award(models.Model): name = models.CharField(max_length=16) category = models.ForeignField(AwardCategory, on_delete=models.CASCADE) class CeremonyAward(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="awards", on_delete=models.CASCADE ) award = models.ForeignKey(Award, related_name="ceremonies", on_delete=models.CASCADE ) I want to write a query that returns for a specified user (or list of user_ids): award_category: name number_of_awards_in_category I know I have to use annotations, but I'm quite new to annotations. This is what I have so far: user_ids = (someuser.id,) CeremonyAward.objects.filter(user_id__in=user_ids).\ annotate(Count('award__category__slug', distinct=True)).\ prefetch_related('award','award_category') How do I create a query that groups by award__category and then counts the awards in each distinct category -
Django - Is there a difference between auth.models.User and .model.User (abstract)?
I have to import the User model in a file and I was wondering if there is any difference between the auth.models.User and an abstract user in .models.User: from django.contrib.auth.models import User or from .models import User -
POST http://127.0.0.1:8000/add-to-cart 500 (Internal Server Error)
Hi so I'm working on a ecommerce website using Django and my add to cart button keeps throwing this error. So when i click it before i've logged in it does its job and displays a "Log in to continue" message on the screen but after i login and click the "add to cart" button again it throws the error. I'm new to Django and i've been following https://www.youtube.com/watch?v=3YKXhdOGR-s&list=PL_99hMDlL4d2zsGU5nOgADmRc6A8msXyh&index=12&ab_channel=SharmaCoder this video for reference. this is my js file This the view.py file This is the html file urls.py AND ERROR -
ModelForm including ForeignKeys with multiple databases
Having two models in models.py such as: provider_name = models.TextField(primary_key=True, default=None) provider_address = models.TextField(null=False, blank=False, default=None) class PhoneNumber(models.Model): number = models.IntegerField(primary_key=True, default=None) provider = models.ForeignKey(PhoneProvider, on_delete=models.SET_NULL, default=None, null=False, blank=False) And then in forms.py I create two model forms: class Meta: model = PhoneProvider fields = "__all__" class FormPhoneNumber(forms.ModelForm): class Meta: model = PhoneNumber fields = "__all__" My question is, how to use the FormPhoneNumber (which has a ForeignKey) when using multiple databases with manual routing. Do I need to overwrite the field employing a query employing .using('database_name')? I am aware that Django does not support cross-referencing of Foreign keys along multiple databases, but I am talking about two tables placed in the same database. How can I let the ModelForm now the database from which it can extract the foreign key options? -
django oscar order app abstract models customization
I want to override django-oscar Order class which Inheritance from AbstractOrder class (in order apps and abstract_models.py file) but when i try to use migrate & makemigrations commands it says that model there is a problem in register_model function and i have no idea how i can solve it (i need to use basket_total_incl_tax property and currency field does anyone know where can i find these two in other classes?) if anyone knows what the problem is and what should i do to solve it please tell me. thank you. -
Render label names instead of integer fields in Django templates
As part of my models, I have an IntergerField "choices". These choices have been labelled. (Label 1 = Straw, Label 2 = Yellow...) However, the HTML renders the integer rather than the actual labels. What do I need to do return the labels and not the field's interger? Is it somethng I need to do in views? Or do I address it directly in the html file? Code below: Models CHOICE1=( ('',''), (1,'Straw'), (2,'Yellow'), ) class Model1(models.Model): user = models.ForeignKey(User,blank=True,on_delete=models.CASCADE) Choice_A = models.IntegerField(choices=Choice1,default=0) Views def account(request): review_list = Model1.objects.all return render(request,"main/account.html", {'review_list':review_list}) HTML <h6>Champagnes</h6> {% for Model1 in review_list%} <table class="table table-hover table-striped table-bordered "> {% if Model1.user == user%} <tr> <th>Text</th><th>{{Model1.Choice_A }}</th> </tr> {%endif%} </table> {% endfor %} -
Celery results not updating after dockerization
I'm currently putting my Django app on Docker. I successfully dockerized Django, gunicorn, nginx and Celery, however when I run a Celery task, even though it's executed (displayed in the logs), the results are not stored to my database. That worked before dockerizing everything so that probably comes from my docker configurations, but I didn't manage to find which part was incorrect/incomplete. Also, I'm using the default sqlite3 Django database as I don't need to store a huge amount of data. Here is my docker-compose.yml: version: '3.8' services: django_gunicorn: volumes: - db:/db.sqlite3 - static:/static - media:/media env_file: - env build: context: . ports: - "8000:8000" command: sh -c "python manage.py migrate && python manage.py collectstatic --no-input && gunicorn main.wsgi:application --bind 0.0.0.0:8000" nginx: build: ./nginx volumes: - static:/static - media:/media ports: - "80:80" depends_on: - django_gunicorn rabbitmq3: image: rabbitmq:3-alpine ports: - 5672:5672 celery: restart: always build: context: . command: celery -A main worker -P eventlet -c 100 -l INFO env_file: - env depends_on: - rabbitmq3 - django_gunicorn volumes: - db:/db.sqlite3 volumes: db: static: media: Dockerfile FROM python:3.10.5-alpine ENV PYTHONUNBEFFERED = 1 RUN pip install --upgrade pip COPY ./requirements.txt . RUN pip install -r requirements.txt COPY ./src /app WORKDIR /app celery.py import … -
Is Django able to handle PostgreSQL's truncated table names?
I am creating a Django application with PostgreSQL and some of my model names have become a bit long. Now, PostgreSQL is truncating the table name for such models to 63 characters. Please throw some light as to whether Django is able to handle such truncated table lengths on its own.. For example, consider a sample model with: App Name: MosaicApp Model Name: BeethovenBandLovedRockPopHipHopMetalReggaeLatinMetalCountryElectronicMusic Table Name created: MosaicApp_BeethovenBandLovedRockPopHipHopMetalReggaeLatinMe2dcf (or, something of this sort) Should I overlook this table name truncation? I am able to successfully apply-unapply my migrations. But it would be great if the experienced guys could throw some light as to whether this phenomenon can be overlooked. -
APScheduler not creating the job in AWS deployed Django Application
I have deployed an application which consists of a job like the following: from apscheduler.triggers.combining import OrTrigger from apscheduler.triggers.cron import CronTrigger from reports.views import AutoMails def start(): print("reached") scheduler = BackgroundScheduler() mail = AutoMails() trigger = OrTrigger([CronTrigger(hour=17, minute=9)]) scheduler.add_job(mail.get,trigger, seconds=10, id="test_mails_001", replace_existing=True ) scheduler.start() I tested this on the local server and it is working but upon deployment I didn't receive any email Is AWS bocking this somehow? -
How to create pdf file using Django template with proper CSS?
I am new to Django and stack overflow as well. I want to create Django template as a pdf file with all CSS styles .I used following code to create pdf file it renders file content properly but not CSS styles. Here is the code I have used : from io import BytesIO from xhtml2pdf import pisa from django.template.loader import get_template from django.http import HttpResponse from django.shortcuts import render def home(request): pdf = render_to_pdf("abc.html") return HttpResponse(pdf, content_type='application/pdf') def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') else return None -
Django CKEDITOR set max size of an image
how can I set the max size that an image can have in django-ckeditor? Here is the model's code: class Post(models.Model): ... text = RichTextUploadingField(max_length=1050,null=True,blank=True) I tried to use CKEDITOR_THUMBNAIL_SIZE but it didn't work. Also if I can't set the max size of an image is there any other way to resize the image? Thanks. -
Allow user website embed and export django
I am building a t $ c generator website with django. How do I allow user export files and website embed -
Why is google console shows anchor text as URL Django Template instead of actual text?
I have deployed a website using Django (https://www.pkelection.com/). This is my very first app so still trying to learn. So I was checking my SEO progress and ended up checking my google search console and saw this: Google search console results for top linking text The very first URL in top linking text pertains to (https://www.pkelection.com/by-election-p/provincial-assembly/1063-by-election-2022/). I am trying to figure out why google console is showing url text instead of actual anchor text. The same thing is happening with rest of the top linking text so I really fell that I am doing something wrong but can't figure our what. -
Unit testing with AWS Cognito and GraphQL
I'm currently writing tests for my software but got stuck at the point. I try to get data from my db with a normal GraphQL Query but my endpoint is first checking, if the idToken within the header is valid. For the user handling I'm using AWS Cognito but couldn't find a good way to mock the login to retrieve the valid token to query and mutate the data within various endpoints. Any idea how to handle this case? Here is my code from the graphene docs (https://docs.graphene-python.org/projects/django/en/latest/testing/): # Create a fixture using the graphql_query helper and `client` fixture from `pytest-django`. import json import pytest from graphene_django.utils.testing import graphql_query # https://docs.graphene-python.org/projects/django/en/latest/testing/ @pytest.fixture def client_query(client): def func(*args, **kwargs): return graphql_query(*args, **kwargs, client=client) return func # Test you query using the client_query fixture def test_some_query(client_query): response = client_query( ''' query GetAllProjectConfig{ getAllProjectConfig{ project{ id slug name } config{ id } } } ''', ) content = json.loads(response.content) assert 'errors' not in content -
How to get last six month data from date field - django
I do have a model as below class employee(models.Model): employee_name = models.CharField(max_length=100) joining_Date = models.DateField(blank=False, null=False) I want to get data for last six month(including current month) joined employee count month wise. Example: July : 12, June : 10, May : 8, April : 16, March : 13, February : 10, joining_Date storing like "2022-07-22".How to get done this by having date field. Thanks in advance. -
Pass multiple arguments to a custom filter Django
I have a custom filter that looks like this register = template.Library() @register.filter def makebreadcrumbs(value, arg): pass How can I pass multiple arguments to the filter? {% with request.resolver_match.namespace as name_space %} {{ request.path|makebreadcrumbs:name_space|safe }} {% endwith %} In the code above makebreadcrumbs is my custom filter, request.path is a variable (value), and name_space is an argument. -
Django: how to save form and perform math operation with along side saving the form in django?
i am trying to save a form, and after i want to get the new_balance and update the value, i have a function that would save a form, and the form have a field amount, so what i want is this, if i save the form i want to get the new_balance and substract the new_form.amount from the balance, it works but doesn't seems to be saving the new_balance when i refresh my page it shows this alert The page that you're looking for used information that you entered. Returning to that page might cause any action you took to be repeated. Do you want to continue?. views.py @login_required def withdrawal_request(request): user = request.user profile = Profile.objects.get(user=user) total_investment = PurchasedPackage.objects.filter(paid=True, user=request.user).aggregate(Sum("investment_package__price"))['investment_package__price__sum'] bonus_earning = profile.earning_point total_ref_earning = profile.referral_point indirect_ref_earning = profile.indirect_ref_earning daily_login_earning = profile.daily_login_earning bonus_point = profile.bonus_point social_share_points = profile.social_share_points pending_payout = WithdrawalRequest.objects.filter(user=request.user, status="pending").aggregate(Sum("amount"))['amount__sum'] if pending_payout == None: pending_payout = 0 total_payout = WithdrawalRequest.objects.filter(user=request.user, status="settled").aggregate(Sum("amount"))['amount__sum'] try: all_earning = total_investment + bonus_earning + total_ref_earning + bonus_point + social_share_points + indirect_ref_earning + daily_login_earning except: all_earning = bonus_earning + total_ref_earning + bonus_point + social_share_points + indirect_ref_earning + daily_login_earning try: new_balance = total_investment + bonus_earning + total_ref_earning + bonus_point + social_share_points + indirect_ref_earning + daily_login_earning … -
Yandex Oauth2 social_django 400 Unknown client with such client_id
When i used 'social_core.backends.yandex.YandexOAuth2', yandex returned it to me: 400 Unknown client with such client_id, what i can do? my setup settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_cleanup.apps.CleanupConfig', 'social_django', 'bootstrap5', ] AUTHENTICATION_BACKENDS = [ 'social_core.backends.yandex.YandexOAuth2', 'django.contrib.auth.backends.ModelBackend', ] SOCIAL_AUTH_URL_NAMESPACE = 'social' YANDEX_OAUTH2_CLIENT_KEY YANDEX_OAUTH2_CLIENT_SECRET my template file <a href="social/login/yandex-oauth2" class="btn btn-light col-2 m-2">