Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get a customer ID from event object (webhooks) in stripe using Django?
I can't find where is the the customer id when I receive an avent from Stripe webhooks after a transaction was made: @csrf_exempt def StripeWebhookView(request): CHECKOUT_SESSION_COMPLETED = "checkout.session.completed" payload = request.body sig_header = request.META["HTTP_STRIPE_SIGNATURE"] endpoint_secret='whsec_o0T4qLvSeI0kjhpUs2JcHq9F0Ik9VUeY' try: event = stripe.Webhook.construct_event( payload, sig_header, endpoint_secret ) if event["type"] == CHECKOUT_SESSION_COMPLETED: **customer_id_stripe = event["data"]["object"]["customer"]** print('customer_id:', customer_id_stripe) I have tried to fetch the customer id by using this line of code: **customer_id_stripe = event["data"]["object"]["customer"]** but when I print customer_id_stripe it print None and to be honest, when I check out the full object I recieved from Stripe this is what I get: { "id": "evt_1MqMKgESXHNK1nmVaYJeR1PX", "object": "event", "api_version": "2022-11-15", "created": 1679947678, "data": { "object": { "id": "cs_test_a1A15S4eEOZc3WPfyTT5aJeGhhXRi5DK8xQiRnbgs8iG16rZ8oN032V8rm", "object": "checkout.session", "after_expiration": null, "allow_promotion_codes": null, "amount_subtotal": 50, "amount_total": 50, "automatic_tax": { "enabled": false, "status": null }, "billing_address_collection": null, "cancel_url": "http://127.0.0.1:8000/discovery/", "client_reference_id": null, "consent": null, "consent_collection": null, "created": 1679947653, "currency": "usd", "custom_fields": [ ], "custom_text": { "shipping_address": null, "submit": null }, # **"customer": null,** "customer_creation": "if_required", "customer_details": { "address": { "city": null, "country": "IL", "line1": null, "line2": null, "postal_code": null, "state": null }, "email": "anon@gmail.com", "name": "asdasd", "phone": null, "tax_exempt": "none", "tax_ids": [ ] }, "customer_email": null, "expires_at": 1680034053, "invoice": null, "invoice_creation": { "enabled": false, "invoice_data": { "account_tax_ids": … -
When using Django's Prefetch object, it makes one query per related object
So I've been developing with Django for a while. I am familiar with prefetch_related and was noticing some strange behavior today when working with Prefetch objects. I was under the impression that a queryset executed with prefetch_related would make 2 queries, 1 for the parent objects, and another for the children filtering on the parent object ids. However, when I print the queries being executed using pretch_related with a Prefetch object, I noticed that one query was being made per related object which diminishes the desired effect of prefetch_related. Can anyone fill me in to why this is happening based on the following code and returned SQL. Schedule.objects.prefetch_related("shifts") # SQL returned [{"sql": 'SELECT "schedule"."id" FROM "schedule" LIMIT 21', "time": "0.033"}, { "sql": 'SELECT "shift"."id" FROM "shift" WHERE "shift"."shift_id" IN (1, 2) ORDER BY "shift"."order" ASC', "time": "0.062", } ] The above is what I expected Now the problem queryset Schedule.objects.prefetch_related( Prefetch( "shifts", queryset=Shift.objects.filter( state__in=[StopPointStates.COMPLETED, StopPointStates.PENDING] ) .order_by("assigned_at", "priority", "order") .only("id"), ) ).only("id") # SQL returned [{"sql": 'SELECT "schedule"."id" FROM "schedule" LIMIT 21', "time": "0.009"}, { "sql": 'SELECT "shift"."id" FROM "shift" WHERE ("shift"."state" IN (\'completed\', \'pending\') AND "shift"."shift_id" IN (1, 2)) ORDER BY "shift"."assigned_at" ASC, "shift"."priority" ASC, "shift"."order" ASC', "time": "0.015", … -
Uploading Django project to Heroku - blank page showing Internal server error
So I've deployed my first project to Heroku using PostgresQL. To my excitement, I managed to upload my files to both Github and Heroku. But to my disappointment, when I open the website, I only see a page showing "Internal Server Error". Why does this error show and how can I resolve it? I've been spending 9 month learning, HTML, CSS, Java, Python, Django, React, Bootstrap. This is the last step before I have a page online. So I appreciate all help! My project settings: """ Django settings for my_portfolio_project project. Generated by 'django-admin startproject' using Django 4.1.2. For more information on this file, see https://docs.djangoproject.com/en/4.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.1/ref/settings/ """ from pathlib import Path import os import django_heroku import dj_database_url from dotenv import load_dotenv BASE_DIR = Path(__file__).resolve().parent.parent load_dotenv() # env = environ.Env() # # Reading the .env-file # environ.Env.read_env("\my_portfolio_project\.env") # Build paths inside the project like this: BASE_DIR / 'subdir'. # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! # Make sure your SECRET_KEY setting is set to a unique, strong, and secure value. Don't use the default value … -
gdal required on django but why?
I imported 3 tables on to my postgresql. These tables have the names of countries, regions, cities and then IP to countries. They are pretty old but very exhaustive. In my models I have not created any geo field or any point field, the latitude and longitude were expressed as float fields and I did that precisely to avoid having to install libraries. Yet, when I was writing makemigrations, I got an error that I needed to install gdal library. Reluctantly I did, but then it asked me that I needed to install GLIBCXX_3.4.30 library. It turns out they are not available for Fedora. What is this lousy break? I am using Fedora 37 and I am pretty annoyed at this, because, why would django tell me that I have to install that? Has it detected that the tables in postgresql have city names, latitude and longitudes? they are expressed as float fields in the table cells. -
Djano page with two views
Mockup of page with two views How can I make a page like the one in the URL above? I tried to do it using a partial for the form, but I need help figuring out how to handle the URL routing. Is there a better way to do this? The first view is a Folium map. The second view in a ModelForm. I'm open to suggestions. I tried to make the form a partial. -
How can I use a property inside another property? Django
I have the following model with three properties to know the consumption according to the reading: class ConsElect(models.Model): pgd = models.ForeignKey(TipoPGD, on_delete=models.CASCADE, related_name='consumoelect') data= models.DateField(default=datetime.now) read_morning = models.IntegerField(default=0) read_day = mod def get_rm(self): c_m = list(ConsElect.objects.filter(data__gt=self.data).values('read_morning')[0:1]) return ((c_m[0]['read_morning '] - self.read_morning )) cons_m= property(get_rm) def get_rd(self): c_d = list(ConsElect.objects.filter(data__gt=self.data).values('read_day')[0:1]) return ((c_d[0]['read_day'] - self.read_day)) cons_d= property(get_rd) def get_total(self): #It's not correct, I don't know how to implement it return cons_d + cons_m #I need to get the sum of the above two properties I need a third property in the model to store the sum of the two previous properties, how can I call the two previous properties inside the new property -
Django/react authenticated user not being returned
I am trying to show user profile page when user is logged in.I tested it with postman and printed in terminal and it is working.I can login and a user object is returned and when I go to the user profile route it returns the posts of the logged in user.However,it is not working properly with react.I can login with react and the user is authenticated in in the backend but when I go to the user profile route the user id is retuned none and no post is showing even in the terminal. Here in postman it logs in and then for myprofile route is shows the user id and a list of his posts. Here I login with the same user using react and I can login successfully but when going to myprofile it returns none for user id and so empty queryset for posts. Django: urls.py from django.urls import path,include from . import views # from .views import ChangePasswordView urlpatterns = [ path('register/', views.register, name='register'), path('login/', views.custom_login, name='login'), path('logout/', views.custom_logout, name='logout'), path('myprofile/', views.user_profile, name='user_profile'), path('edit_user/', views.edit_user_profile, name='edit_user_profile'), path('activate/<uidb64>/<token>', views.activate, name='activate'), path("passwordreset/", views.password_reset_request, name="password_reset1"), path('reset/<uidb64>/<token>/', views.passwordResetConfirm, name='password_reset_confirm'), path('password_reset/', include('django_rest_passwordreset.urls', namespace='password_reset')), ] views.py from django.contrib.auth.decorators import login_required from django.shortcuts … -
How can I implement authentication and authorization in a Django REST API using JSON Web Tokens (JWT)?
I am building a Django REST API and I want to add authentication and authorization to it. I have researched and found that JSON Web Tokens (JWT) is a popular solution for this purpose. However, I am having trouble implementing it in my Django API. Can someone please provide a step-by-step guide or code example on how to implement JWT authentication and authorization in a Django REST API? Thank you in advance for your help. I tried to implement JWT authentication and authorization in my Django REST API following several online tutorials and articles. I installed the necessary packages, such as Django Rest Framework JWT and PyJWT, and attempted to follow the provided code examples to configure my API for JWT authentication and authorization. -
I have an issue rendering image from database using django
``Images are rendering from other pages but nit rendering new page views.py def hotels(request): mhtl = Hotel.objects.all() context = { 'my_rms': mhtl, } return render(request,'affiliate/hotels.html', context) type here models.py class Hotel(models.Model): title = models.CharField(null=True, blank=True, max_length=100) price = models.CharField(null=True, blank=True, max_length=100) card_img = models.ImageField(null=True, blank=True, upload_to="images/") def __str__(self): return self.title` The html page {% extends 'affiliate/base.html' %} {% load static %} {% block content %} <h2>Find your next stay</h2> <h3>HERE</h3> <h5>--- WIDGET WIDGET WIDGET WIDGET ---</h5><hr> <!--CARDS--> {% for m in my_rms %} <img src="{{ m.card_img }}"> <h5>{{m.title}}</h5> <p>${{ m.price }}</p> {% endfor %} <hr> {% endblock content %} other datas are rendering except the image and the message from the terminal is: [28/Mar/2023 10:17:48] "GET /hotels/images/ht7.jpg HTTP/1.1" 404 2991 Not Found: /hotels/images/ht7.jpg I am trying to find a way to resolve this please I tried a for lood to retrieve data from a specific model otherdatas are rendering only image is not.` -
AJAX performs its function, but the page refreshes
My django web application has a form to add an item to the cart. I wrote ajax code so that when adding a product, the page is not refreshed. It turns out that the product adds to the cart but the page with the json-response opens {"success": true}. I see that in views.py 'product_id' is written twice but I don't know which is better. views.py def add_to_cart(request, product_id): if request.method == 'POST': product_id = request.POST.get('product_id') quantity = 1 user = request.user cart_item = CartItem.objects.create(product_id=product_id, quantity=quantity, user=user) cart_item.save() data = {'success': True} return JsonResponse(data) else: data = {'success': False, 'error': 'error'} return JsonResponse(data, status=400) urls.py path('add_to_cart/<int:product_id>/', views.add_to_cart, name='add_to_cart'), product_detail.html <form action="{% url 'add_to_cart' single_product.id %}" method="POST" id="add-to-cart-form"> {% csrf_token %} <input type="hidden" name="product_id" value="{{ single_product.id }}"> <button type="submit" class="btn btn-primary">Add</button> </form> script.js $(document).ready(function() { $('#add-to-cart-form').on('submit', function(event) { event.preventDefault(); var url = $(this).attr('action'); var data = $(this).serialize(); $.ajax({ url: url, method: 'POST', data: data, success: function(response) { console.log(response); }, error: function(xhr, status, error) { console.log(error); } }); }); }); Nothing is written in the console. JQuery is working, I checked this script. <script src="{% static '/js/jquery-3.6.4.min.js' %}" type="text/javascript"></script> <script> $(document).ready(function() { console.log('jQuery is working!'); }); </script> -
When search Django rest framework instead of showing all records, I want only first record
I have setup django rest framework which is working fine. I can see list of my record or when search it also working. I want to make a change that if I do search it only give me first record instead of all searched record. Here is the example of my code which i tried but not working. Please guide. Thanks class PhoneNumberModelViewSet(viewsets.ModelViewSet): queryset = PhoneNumbers.objects.all() serializer_class = PhoneNumbersSerializer filter_backends = [SearchFilter] search_fields = ['area_code'] I want to make a change that if I do search it only give me first record instead of all searched record. Here is the example of my code which i tried but not working. Please guide. Thanks class PhoneNumberModelViewSet(viewsets.ModelViewSet): queryset = PhoneNumbers.objects.all() serializer_class = PhoneNumbersSerializer filter_backends = [SearchFilter] search_fields = ['area_code'] def get(self): queryset = super().get() area_code = self.request.query_params.get('area_code') if area_code: try: queryset = queryset.filter(area_code=area_code)[0:1] except IndexError: queryset = PhoneNumbers.objects.none() return queryset -
Form is submitted but not saving value in database
When I submitted this form, instead of saving the value it takes and save it to the database, it submitted the form but the value is none when I check admin page, the form is submitted and redirected me to home page, but the value that a form takes is none when I check my admin: Model: class Column(models.Model): user = models.OneToOneField(User, on_delete= models.CASCADE) name = models.CharField(max_length=100) select_type = models.ForeignKey(Type, on_delete= models.CASCADE) views: class CreateColumn(CreateView): model = Column template_name = 'column_create.html' form_class = ColumnForm success_url = 'home' def get_context_data(self, **kwargs): context = super(CreateColumn, self).get_context_data(**kwargs) context['formset'] = ColumnFormSet(queryset=Column.objects.none()) return context def form_valid(self, form): form.instance.user = self.request.user return super(CreateColumn, self).form_valid(form) Form: class ColumnForm(forms.ModelForm): class Meta: model = Column fields = ['name', select_type'] ColumnFormSet = modelformset_factory(Column, fields=('name' 'select_type'), extra=30) template: <form method='post'> {% csrf_token %} {{ formset.management_form}} {% for form in formset %} {{form.as_p}} {% endfor %} <button type='submit'>Save<button/> <form/> -
Create Django custom 404 error template page affects navigation bar
I am creating a custom 404 error page but it affects my navigation bar. Before creating a custom 404 error page: After creating a custom 404 error page: main's urls.py handler404 = "audioJournaling.views.error_404" setting.py DEBUG = False ALLOWED_HOSTS = ['*'] views.py def error_404(request, exception): return render(request, '404.html') 404.html <h1>404 Page Not Found</h1> <p>My Custom 404 Page Not Found!</p> The first code I have followed is https://levelup.gitconnected.com/django-customize-404-error-page-72c6b6277317 And the second is https://studygyaan.com/django/django-custom-404-error-template-page The only difference between the two code is the views.py. The first code example place the code in main's views.py. The second code example place the code in app's views.py. However, both of them shows the same problem. -
admin.display with mark_safe
Is there any chance I can put HTML in the <th> of change_list.html, other than going down the ugly road of overriding the admin_list template tags? I want to style the text in the table head a little bit for viewing pleasure but it is quite tricky to access the table header in django. I have something in mind like: @admin.display(description = mark_safe("<b class='bg-danger'>status</b>")) def get_status(self, obj): return obj.status -
django display nested loop foreignkey in template
I have 3 models Course course_name = models.CharField(max_length = 200, unique=True) Module module_name = models.CharField(max_length = 200, unique=True) course = models.ForeignKey(Course, on_delete=models.PROTECT) Sesion sesion_name = models.CharField(max_length = 200, unique=True) course = models.ForeignKey(Module, on_delete=models.PROTECT) Lesson lesson_name = models.CharField(max_length = 200, unique=True) sesion = models.ForeignKey(Sesion, on_delete=models.PROTECT) I need show in ul, ol html Course name Module 1 Sesion 1 Lesson 1 Lesson 2 Sesion 2 Lesson 1 Lesson 1 Module 2 Sesion 1 Lesson 1 How I can display this queryset? I try prefetch... and dict = [zip(mod, ses, tem)] but i Dont understand how display or how set the queryset -
Getting ModuleNotFoundError while running the Django app with embedded python distro but its working fine with python installer version in Windows
I am trying to run a Django app in windows. Case A: (with python Windows embeddable package) Downloaded python Windows embeddable package (64-bit) installed Django by executing python -m pip install Django created a Django app by running django-admin startproject testDjango1 executing in command line: python manage.py runserver getting error: D:\program_files\python\testDjango1>python manage.py runserver Traceback (most recent call last): File "D:\program_files\python-3.10.10-embed-amd64\Lib\site-packages\django\core\management\base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "D:\program_files\python-3.10.10-embed-amd64\Lib\site-packages\django\core\management\commands\runserver.py", line 74, in execute super().execute(*args, **options) File "D:\program_files\python-3.10.10-embed-amd64\Lib\site-packages\django\core\management\base.py", line 448, in execute output = self.handle(*args, **options) File "D:\program_files\python-3.10.10-embed-amd64\Lib\site-packages\django\core\management\commands\runserver.py", line 81, in handle if not settings.DEBUG and not settings.ALLOWED_HOSTS: File "D:\program_files\python-3.10.10-embed-amd64\Lib\site-packages\django\conf\__init__.py", line 92, in __getattr__ self._setup(name) File "D:\program_files\python-3.10.10-embed-amd64\Lib\site-packages\django\conf\__init__.py", line 79, in _setup self._wrapped = Settings(settings_module) File "D:\program_files\python-3.10.10-embed-amd64\Lib\site-packages\django\conf\__init__.py", line 190, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "importlib\__init__.py", line 126, in import_module File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 992, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1004, in _find_and_load_unlocked ModuleNotFoundError: No module named 'testDjango1' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "D:\program_files\python\testDjango1\manage.py", line 22, in … -
Hide specific URI in URL using htaccess
The hosted site is located in a subdirectory and can only be accessed through the URI /public/, i.e., https://test.myapp.com/myapp1/public. However, I want to make the site accessible directly through the URI https://test.myapp.com/myapp1/. This is Symfony 5.4 PHP project. -
Django Rest Framework nested serializer returns empty list
I have two models which are related by one to many relationship. I want to use the first model called Return to post data and another one called Assessment to retrieve data. My models are as follows:- from django.db import models class Return(models.Model): room_type = models.CharField(max_length=50) number_of_rooms = models.PositiveSmallIntegerField() price_per_night = models.DecimalField(max_digits=10, decimal_places=2) actual_turnover = models.DecimalField(max_digits=10, decimal_places=2) created_at = models.DateField(auto_now=True) class Meta: verbose_name = 'Return' verbose_name_plural = 'Returns' def __str__(self): return f'{self.room_type}' # A function that return number of days in a month def days_in_month(self): # Get the year and month from the date field year = self.created_at.year month = self.created_at.month # Use calendar.monthrange() to get the number of days in the month num_days = monthrange(year, month)[1] return num_days @property def potential_turnover(self) -> float: return float(self.days_in_month()) * float(self.number_of_rooms) * float(self.price_per_night) @property def total_number_of_rooms(self) -> float: total = 0 for obj in Return.objects.all(): total += obj.number_of_rooms return total @property def total_potential_turnover(self) -> float: total = 0 for obj in Return.objects.all(): total += obj.potential_turnover return total @property def gross_amount(self) -> float: total = 0 for obj in Return.objects.all(): total += obj.actual_turnover return total class Assessment(models.Model): return = models.ForeignKey(Return, related_name = "returns", on_delete=models.CASCADE) created_at = models.DateField(auto_now=True) class Meta: verbose_name = 'Assessment' verbose_name_plural = … -
How do I pass in a variable inside a HTML link which will then pre populate different parts of a fields in my Django model form
Please bare with me as this is my first post on here and I may have made some formatting erros in the way the question is presented and someone might have already answered my question. But I just can't find the answer. Thank you very much for your help in advance. So I have a Django project that shows a weekly calender with items that people will be working on. Next to each day on the calender there is a button to add items on to the list but i want to make that button dynamic so it only takes in the current date that it is being showed next to and only takes the user that it is being showed under. Then i want that link to prepopulate two fields of a scheduleCreationForm. Please see below the view of the html page and the code for the html page view of html page # html file <section class="section"> <div class="row"> {% for profile in profiles %} <div class="col-6 col-md-12 col-lg-6"> <div class="card"> <div class="card-content"> <div class="card-body"> <h4 class="card-title">{{profile.name}}</h4> {% for date in ldates %} <div class="d-flex justify-content-between"> <p>{{date}}</p> <a href="#" ><i class="bi bi-plus-circle"></i></a> </div> <hr style="margin-top: 0px; margin-bottom: 0px; … -
How to make a form which adds data to a through table in django
I have two models, Place and Species, with a many-to-many relationship, which are joined by a through table called Sighting which has some extra fields: class Place(models.Model): coordinates = models.TextField() class Sighting(models.Model): place = models.ForeignKey(Place, on_delete=models.PROTECT) species = models.ForeignKey(Species, on_delete=models.CASCADE) uploaded_by = models.ForeignKey(User, on_delete=models.PROTECT) description = models.TextField(blank=True, null=True) class Species(models.Model): name = models.TextField() places = models.ManyToManyField(Places, through=Sighting) here is the view for creating instances of the Species model, which adds the uploaded_by attribute automatically to the Sighting through table: class SpeciesCreateView(CreateView): model = Species form_class = SpeciesCreateForm template_name = "species_form.html" def get_success_url(self): messages.success(self.request, "Species Created Successfully") return reverse("add_species") def form_valid(self, form): self.object = form.save(commit=False) self.object.save() for place in form.cleaned_data["places"]: sighting = Sighting() sighting.uploaded_by = self.request.user sighting.place = place sighting.species = self.object sighting.save() response = super().form_valid(form) return response here is the form for that CreateView, where a user can select multiple places to link to the species: class SpeciesCreateForm(forms.ModelForm): class Meta: model = models.Species fields = [ "name", "places", ] name = forms.CharField() places = forms.ModelMultipleChoiceField( queryset=models.Species.objects.all(), help_text="Places this species has been sighted", ) and for good measure the form template: {% extends "base.html" %} {% block content %} <h1>Upload Species</h1> <div> <form method="POST" action="" enctype="multipart/form-data"> {% csrf_token %} {% include … -
how to create a custom user registration form without using django's forms
I work on a project of which I do the back-end, another developer works the front-end. he created a registration page with html forms, it gives me a hard time because I have never used html forms I only use django forms. so I can't save the forms he created in the database. help me please I tried the django forms method but it doesn't work. views files from django.shortcuts import render, redirect from user.forms import * # Pour importer tous les elements du fichiers forms.py # on import View pour utiliser la vue basée des classes. from django.views.generic import View from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required from django.conf import settings from command.models import Command,CommandProduct from main.utils import get_command_data from main.models import Cart from user.forms import * class Loginpage(View): template_name = 'user/loginpage.html' form_class = 'LoginForm' def get(self, request): form = self.form_class() message = '' print('-----------LOgiN GET-----------') return render(request, self.template_name, {'form': form, 'message': message}) def post(self, request): form = self.form_class(request.POST) print('-----------LOgiN-----------') print(form) if form.is_valid(): user = authenticate(email=form.cleaned_data['email'], password=form.cleaned_data['password']) if user is not None: login(request, user) return redirect('main/home') else: message = 'Identifiants invalides' return render(request, self.template_name, {'form': form, 'message': message}) def connect(request): form = LoginForm() error = '' … -
How to create filter form page with Django filters with object count per category shown in the option labels
I am new to Django and trying to create a page that shows a list of products with couple of filters. The page works fine using standard method and shows filter and update the page as selected. What I want to do is to add a count of products available based on the seelcted filters in; in this case just for category. models.py class Category(index.Indexed, models.Model): name = models.CharField(max_length=1024) class Meta: verbose_name = "Category" verbose_name_plural = "Categories" class Product(models.Model): title = models.CharField(max_length=1024, verbose_name="Product title") last_modified = models.DateTimeField(null=True, blank=True) category = models.ForeignKey("Category", on_delete=models.SET_NULL, null=True, blank=True) filters.py class ProductFilter(django_filters.FilterSet): category = django_filters.ModelChoiceFilter( queryset=Category.objects.annotate(num_product=Count("product")) ) last_modified = django_filters.DateRangeFilter(label="Date_Range") class Meta: model = Product fields = ["category", "last_modified"] views.py def product_explorer_view(request): products = Product.objects.all() product_filter = ProductFilter(request.GET, queryset=products) products = product_filter.qs context = { "products": products, "product_filter": product_filter, } return render(request, "/products_index.html", context) products_index.html <form class="mb-1"> <div class="row g-2"> <div class="col-md-2 col-sm-4"> Category: <div class="form-floating"> <!-- <label for="searchTerm" class="form-label">Category</label> --> {{ product_filter.form.category }} </div> </div> <div class="col-md-2 col-sm-4"> Date: <div class="form-floating"> <!-- <label for="searchTerm" class="form-label">Category</label> --> {{ chart_filter.form.last_modified }} </div> </div> <div class="col-md-1 col-sm-4 pt-1"> </br> <button class="btn btn-secondary btn-lg" type="submit">Search</button> </div> </div> Number of available products: {{ products|length }} </form> Right now this … -
What does the u in a Django DateTimeField refer to?
In the source code for the DateTimeField (Python 3.8), it has the following error handling: default_error_messages = { 'invalid': _('“%(value)s” value has an invalid format. It must be in ' 'YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format.'), 'invalid_date': _("“%(value)s” value has the correct format " "(YYYY-MM-DD) but it is an invalid date."), 'invalid_datetime': _('“%(value)s” value has the correct format ' '(YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ]) ' 'but it is an invalid date/time.'), } What is the uuuuu referring to? -
django rich text field data in email
I want to send Post data of a RTF Field (Rich text field) or a HTML Field data in a email, below are my code and it seems to be not happening, please guide me. models.py class Servicereport(models.Model): name = models.CharField(max_length=255, blank=True, null=True) email = models.CharField(max_length=255, null=True, blank=True) report = RichTextField(default='<p><b>sample data .... </b>') forms.py class ServicereportForm(ModelForm): class Meta: model = Servicereport fields = '__all__' widgets = { 'report': RichTextFormField() } views.py def createServicereport(request): form = ServicereportForm() if request.method == 'POST': form = ServicereportForm(request.POST) if form.is_valid(): subject = "SERVICE REPORT" html_message = render_to_string('report') message = EmailMessage(subject, html_message, 'from@email.com', [request.POST.get('email')]) message.content_subtype = 'html' message.send() form.save() return redirect('/') context = {'form': form} return render(request, 'service_report.html', context) I want to send POST data of RTF Field 'report" via email and the code will be in HTML, but I am unable to send, it is showing below error: TemplateDoesNotExist at /create_service_report/ report Request Method: POST Request URL: http://127.0.0.1:8000/create_service_report/ Django Version: 3.2.4 Exception Type: TemplateDoesNotExist Exception Value: report Exception Location: D:\development\website\venv\lib\site-packages\django\template\loader.py, line 19, in get_template Python Executable: D:\development\website\venv\Scripts\python.exe Python Version: 3.7.9 -
What is difference between explicit pk and auto pk in Django, which one is preferred?
→ Shows warning when using auto pk. (Auto-created primary key used when not defining a primary key type, by default) → Problem get saved pk in explicit defined: 19 class Post(models.Model): 20 id = models.IntegerField(primary_key=True) 21 timestamp = models.DateTimeField(auto_now_add=True) 22 content = models.TextField(max_length=4096) 23 user = models.ForeignKey(User, on_delete=models.PROTECT, related_name="userPosts") The problem in: post = Post.objects.create( content = data.get("post"), user = request.user ) print(post.pk) Returns: None If comment line 20 above, Returns: 82 Why using auto-pk has warnings? While the explicit cant returns after saving the object? (Are there any solution?)