Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to make input boxes' width same with each other in django-crispy-forms?
I'm rewriting my website with Django, and I would like to utilize Django forms since it's really easier than writing every form by hand in HTML. I looked at crispy-forms documentation and found out there is something called Layout. I don't know if I'm using as intended or if I'm repeating myself over and over, but here is what I got: from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, Fieldset, Submit, HTML, Div from django import forms from .models import Member class EnrollForm(forms.ModelForm): message = forms.CharField(widget=forms.Textarea) def __init__(self): super().__init__() self.helper = FormHelper() self.helper.form_show_labels = False self.helper.layout = Layout( Fieldset( '', input_with_icon('bi bi-person', 'first_name'), input_with_icon('bi bi-person', 'last_name'), input_with_icon('bi bi-123', 'student_id'), input_with_icon('bi bi-building', 'department'), input_with_icon('bi bi-list-ol', 'degree'), input_with_icon('bi bi-envelope', 'email'), input_with_icon('bi bi-telephone', 'mobile_number'), input_with_icon('bi bi-chat-left-text', 'group_chat_platform'), input_with_icon('bi bi-send', 'message'), ), Submit('submit', 'Üye Ol', css_id='signup-btn') ) class Meta: model = Member fields = ['first_name', 'last_name', 'student_id', 'department', 'degree', 'email', 'mobile_number', 'group_chat_platform'] def input_with_icon(icon_class, field_name): return Div( Div( HTML( f"""<span class="m-3"> <i class="{icon_class} fs-2" style="color: #ff4100;"></i> </span>""" ), css_class='input-group-prepend' ), field_name, css_class='input-group mb-3' ) {% extends "base/boilerplate.html" %} {% load crispy_forms_tags %} {% block content %} <div class="container-sm align-items-center"> <div class="py-2 mt-4 align-items-center"> <div class="ml-5 pt-3 align-items-center form-container"> <h1 class="text-center mb-5">Topluluğumuza Katılın</h1> <form method="POST" … -
how do i do a image display form
I want an image found referring to the person that was searched for (in the people table) to be presented in the html, but at the same time I want it so that if the user wants to change the photo, he just needs to click on it of the image already presented and then the file explorer is opened so that a new image can be chosen. Once the new image has been chosen, the new image must be displayed in the html in place of the old one temporarily. the program is opening the file explorer, i choose the new image but the old image isn't change and the new image isn't displayed in any place of the html too my code: <script> // Quando a imagem da pessoa for clicada document.getElementById("imagem-pessoa").addEventListener('click', function() { // Abrir o explorador de arquivos ao clicar no campo de arquivo oculto document.getElementById("input-imagem").click(); }); // Quando uma nova imagem for selecionada document.getElementById("input-imagem").addEventListener('change', function(event) { // Capturar a nova imagem selecionada const novaImagem = event.target.files[0]; // Atualizar temporariamente a imagem no HTML const urlNovaImagem = URL.createObjectURL(novaImagem); document.getElementById("imagem-pessoa").src = urlNovaImagem; }); </script> and the html <img class="rectangle" id="imagem-pessoa" src="{{ pessoa.imagem.url }}" alt="Imagem da Pessoa">> <input … -
Pytest --no-migrations throws "relation already exists"
I have a fairly large django app that I usually test using pytest --no-migrations (as the migrations take ages), but since I added a ManyToMany relationship this way: class Object(models.Model): # ... collections = models.ManyToManyField(Collection, through=Collection.products.through, blank=True) class Collection(models.Model): # ... products = models.ManyToManyField("objects.Object", blank=True) Running pytest works fine, but running pytest --nomigrations throws this error on every test: self = <django.db.backends.utils.CursorWrapper object at 0xffff91150820> sql = 'CREATE TABLE "brand_collections_collection_products" ("id" bigserial NOT NULL PRIMARY KEY, "collection_id" bigint NOT NULL, "object_id" bigint NOT NULL)', params = None ignored_wrapper_args = (False, {'connection': <django.db.backends.postgresql.base.DatabaseWrapper object at 0xffff94ed1330>, 'cursor': <django.db.backends.utils.CursorWrapper object at 0xffff91150820>}) def _execute(self, sql, params, *ignored_wrapper_args): self.db.validate_no_broken_transaction() with self.db.wrap_database_errors: if params is None: # params default might be backend specific. > return self.cursor.execute(sql) E django.db.utils.ProgrammingError: relation "brand_collections_collection_products" already exists /usr/local/lib/python3.10/site-packages/django/db/backends/utils.py:82: ProgrammingError I have no idea what this error means in this context, or why it suddenly triggers, and I could not find an easy answer online... -
What is the most optimize way to use annotate with Count function with many filter in django query
For example in school, there is many data to store example "Class", "Student", "Book", etc. Also, the model used softdelete(softdelete refers to action when delete just change the is_deleted to True in the model). In each model, there are create_time, update_time, is_delete, etc. In my code now I use the method below, it spent at least 30s to run sql. So what is the most optimised way to query Count with the filter that contains many conditions? Also sometimes we need to count the same model but using the different filter Here is an example of code in Django (Check count data for each school). # In this code, each model already implements softdelete manager query. School.objects.annotate( number_of_class=Count( "class", filter=Q(class__is_deleted=False, class__create_time__lte=datetime, ...more filter), distinct=True ), number_of_student=Count( "student", filter=Q(student__is_deleted=False, student__create_time__lte=datetime, ...more filter), distinct=True ), number_of_public_book=Count( "book", filter=Q(book__is_deleted=False, book__create_time__lte=datetime, book__create_time__gte=datetime, book__type=1, ...more filter), distinct=True ), number_of_private_book=Count( "book", filter=Q(book__is_deleted=False, book__create_time__lte=datetime, book__create_time__gte=datetime, book__type__in=[2,3], ...more filter), distinct=True ) more_count... ) Please help give all code queries that you know and what you think can be optimised for counting with many counts and filters. -
Seeking advice on the architecture of a Django project
I'm currently developing a project in Django split into 4 applications for managing stock, creating a quote, managing production and a Djangorestframework API for generating quotes. All for a printing company. The production management interface must include all the production information as well as the quote information. The quote information contains the stock information as well as some additional information. To explain in more technical terms, the production management models inherit from the quotes models, which inherit from the stock models. How can I design my models to avoid redundancies in the database and make design simpler? I'm looking for good practice in application design. I looked at how to do inheritance between applications and how this is interpreted in the database. -
Unable to view my django and react website on ec2
So I have been trying to host my react and django application on AWS EC2. The approach I was following is that to deploy both the servers and be able to access them by http://ec2publicip:3000 for react and http://ec2publicip:8000 for django. I want to be able to test my website on the ec2 website before I purchase a domain and have both my servers as subdomains. I launched the ec2 instance and then git cloned my repo, which contains both the react and django applications. I successfully installed all the requirements and when I run my django server, on the terminal it shows that its been activated, but when I go to http://ec2publicip:8000 I just get that it took to long to respond on my web browser I have followed the following guide [https://www.programink.com/django-tutorial/django-deployment.html] but I have had no success Attaching my git hub repo link just in case since I don't think there is a problem with the code as I have been running the same on my local machine, and its working fine Any help or pointers would be appreciated -
how to setup stripe webhook in django
I am working on a project where buyer will make the payment and the payment will be transferred to multiple users is this the right way to do the split payment how can i run my webhook here is my code class AuctionPayment(View): def get(self, request, *args, **kwargs): if not request.user.is_authenticated: return redirect('/') else: user = request.user customer_id = user.stripe_customer_id if customer_id == "": customer_id = stripe.Customer.create(email=user.email)["id"] user.stripe_customer_id = customer_id user.save() user = request.user mode = request.GET.get('mode', 'auction') auction_id = self.kwargs["auction_id"] courier_id = self.kwargs["courier_id"] if mode == 'auction': auction = Auction.objects.get(pk=auction_id) seller_id = auction.user seller_account_id = seller_id.stripe_connect_id referrals = Referral.objects.filter(referred_user=seller_id).first() # referred_by = referrals.referred_by courier = CourierService.objects.get(auction=auction, courier_id=courier_id) if auction.current_bid is not None: price = int(round(float(auction.current_bid) * 100.0)) if auction.auction_status == "Ongoing": price = int(round(float(auction.product.nail_buy_now_price) * 100.0)) buyer_address = auction.buyer_address else: event = SpecialEvent.objects.get(pk=auction_id) courier = CourierService.objects.get(event=event, courier_id=courier_id) seller = event.selected_seller seller_request = SellerRequest.objects.get(event=event, user=seller) price = int(round(float(seller_request.price) * 100.0)) buyer_address = event.buyer_address taxes = 0 if buyer_address.state.lower() == 'alabama' or buyer_address.state.lower() == 'al': taxes = int(round(float(price * 0.08))) shipping_charges = courier.price total_charges = price + taxes # if referrals: admin_amount = int((total_charges) * 0.2) seller_amount = total_charges - admin_amount referral_amount = int(admin_amount * 0.02) stripe.api_key = "sk_test_EI5Kddsg2MCELde0vbX2cDGw" charge_id = … -
Django Filter Consolidate data using Aggregate
I want to populate dynamic data using Django Filter Date Range, I have achieved this. In this there is a consolidated data which I am collecting of a single column, which is also working using aggregate. Now I want the consolidated to change as per the records which gets selected when date range is applied in Django filter form. I am able to consolidate data in the column and get a total out of it in “manual_total” [when I pre-define the date field]. But when I filter using the Django Filter Date range field using Form and filters, I am not getting total as per the columns being fetched. How do I achieve it? When I filter as per date in the form, the total should be as per the records showing post filter. For example, I have 2 records from March 1st to March 31st and 1 record for April 1st. If I filter March 1st to 31st, it shows only total of 2 records, but total it shows including the 3rd record. Below are my code and pls guide me to join the queryset and aggregate together to retrieve data as per the date range filter I select. … -
Sometimes I can't send a file
I am using django-channels with daphne and I know that there are strong restrictions on the size of the file or message I can send. But as it turned out, with a message limit of 1 MB, I can send a 2.5 MB image in the message and at the same time there are situations when images with a much smaller size do not want to load, as a result of which I do not get any error, and my client-side method, which should receive a new message from the socket for all users, shows nothing. This is my method that sends messages from the client side. The file is loaded into the input.: document.querySelector('#chat-message-submit').onclick = function (e) { e.preventDefault(); const messageInputDom = document.querySelector('#chat-message-input'); const message = messageInputDom.value; const fileInput = document.querySelector('#chat-file'); const file = fileInput.files[0]; if (file) { const reader = new FileReader(); reader.onload = function (event) { const fileData = event.target.result.split(',')[1]; const fileExtension = file.name.split('.').pop(); const fileObject = { name: file.name, type: file.type, extension: fileExtension, data: fileData }; chatSocket.send(JSON.stringify({ 'message': message, 'username': userName, 'slug': slug_info, 'media_file': fileObject, })); }; reader.readAsDataURL(file); } else { chatSocket.send(JSON.stringify({ 'message': message, 'username': userName, 'slug': slug_info, })); } messageInputDom.value = ''; fileInput.value = ''; … -
Can transaction.on_commit() be used to
I have a function that delete an object from a group of objects bound together and that are ordered by a "order" value they have like this: `{id:23, name:name1, order:1} {id:12, name:name2, order:2} {id:46, name:name3, order:3}` After deleting other objects order should change to represent the deletion, like if i delete the object with id 12 the object with id 46 should become "order:2" This i can make easy with a function that get the others objects and lowers every object with more than order 2 by one but if i update those objects sometimes happens that they are reordered in the database before the delete has ended. So, can i use transaction.on_commit() so the reorder function does not execute after the delete has ended? Or there is something i am missing? Trying it does not appear to be a problem, but i don´t now if i am not doing anything to resolve my problem or i am misreading something of the correct usage of this function -
Django throws the duplicate key value violates unique constraint error
I study the Django framework and there is that exercise that asks you to create a simple blog web application. This app has simple models and forms to handle the data a theoretical user would save in the project's db. Here are the models: from django.db import models class Blog(models.Model): text = models.TextField() date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return self.text class Post(models.Model): blog = models.ForeignKey(Blog, on_delete=models.CASCADE) text = models.TextField() date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return self.text Here are the forms: from django import forms from . models import Blog, Post class BlogForm(forms.ModelForm): class Meta: model = Blog fields = ['text'] labels = {'text': ''} class PostForm(forms.ModelForm): class Meta: model = Post fields = ['text'] labels = {'text': ''} So, let's say I add a Blog instance via the db. This is how I do it: INSERT INTO learning_logs_topic (id, text, date_added) VALUES (1, 'A blog #1', now()::timestamptz); This data appears on the Django admin site and on the html template. It happens almost instantly, which means that Django actually is aware of the new date has been added to the db. But when I'm trying to add a Blog instance via the admin site or by the saving the html … -
Docker Celery configuration - For Django/React/Redis/Celery project. No Celery logo and background task log appearing
I have created a project github repository that has Docker, Django, React, Redis, Celery: https://github.com/axilaris/dockerize-django-react-celery-redis. My goal is to get celery working correctly with the logo appearing and background task log prints. This is based from this Docker - React and Django example tutorial code: https://github.com/dotja/authentication_app_react_django_rest And trying to use Docker - Celery & Redis from this tutorial code: https://github.com/veryacademy/docker-mastery-with-django/tree/main/Part-4%20Django%20Postgres%20Redis%20and%20Celery <-- Part 4 tutorial for Celery & Redis Here is the docker-compose.yaml for the redis & celery part: # Redis redis: image: redis:alpine container_name: redis ports: - "6379:6379" # celery celery: restart: always build: context: ./backend command: celery -A backend worker -l DEBUG volumes: - .:/django container_name: celery depends_on: - redis - backend my project should work if you need to check: docker-compose build docker-compose up However, there is no celery logo (1) and I dont see the logs print on the background process (2). I think it is executing as result.ready returns. But I want these 2 for completeness. (eventhough result.ready maybe be working with celery executing background task) It did not print this celery logo. celery | -------------- celery@b755a7cdba8d v5.3.6 (emerald-rush) celery | --- ***** ----- celery | -- ******* ---- Linux-6.6.12-linuxkit-aarch64-with 2024-03-02 20:48:06 celery | - *** … -
Seeking Feedback on Map Optimization in Django App
I'm currently working on a Django app involving maps and would appreciate some guidance on my approach. Here's what I'm doing in simpler terms: Receiving Trip Details: When a user makes a post call, I receive details about their trip. Fetching Coordinates: Depending on whether it's a pickup or drop trip: For pickups: We have multiple pickup locations and one common drop-off point. For drops: We have multiple drop-off points and one pickup location. Optimizing Trip Order: Using the TomTom API, I optimize the order of these coordinates to find the most efficient route. For example: If the trip type is "Pickup" and we have coordinates [0,1,2,3], and the optimized order is [0,2,1,3], we'll calculate the route geometry for pairs like 0,2 then 2,1 then 1,3. Calling TomTom APIs: With the optimized order, we call the TomTom Route API, passing consecutive pairs of optimized coordinates to get a complete optimized route geometry. Adding Route Layer to Map: Finally, using these optimized geometries, we add a route layer to the map for visualization. I'm wondering if this approach makes sense and if there are any potential improvements or better ways to achieve this. Any insights or suggestions would be greatly appreciated! -
django framework 404 error page not found
i don't understand were i was doing wrong i'm getting this again and again i'm getting error like this Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/ Using the URLconf defined in sitaram.urls, Django tried these URL patterns, in this order: members/ [name='members'] admin/ The empty path didn’t match any of these. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. wanted to know were i'm i doing wrong -
In my webpage add to cart button (from homepage) is not working
I created a add-to-cart button for my website so, In Index.html: <button class="btn-action add-to-cart-btn" data-index="{{p.id}}" id="add-to-cart-btn"> <input type="hidden" value="1" id="product-quantity" class="product-quantity-{{p.id}}"> <input type="hidden" class="product-pid-{{p.pid}}" value="{{p.pid}}" name=""> <input type="hidden" class="product-image-{{p.id}}" value="{{p.image}}" name=""> <input type="hidden" class="product-id-{{p.id}}" value="{{p.id}}" name=""> <input type="hidden" class="product-title-{{p.id}}" value="{{p.title}}" name=""> <ion-icon name="bag-add-outline"></ion-icon> </button> This is the add-to-cart button and in function.js: $(".add-to-cart-btn").on("click",function(){ let this_val=$(this) let index= this_val.attr("data-index") let quantity=$("#product-quantity-" + index).val() let product_title=$(".product-title-" + index).val() let product_id=$(".product-id-" + index).val() let product_price = $("#current-product-price-" + index).text() let product_pid = $(".product-pid-" + index).text() let product_image=$(".product-image-" + index) console.log("Quantity:", quantity); console.log("Id:", product_id); console.log("Pid:", product_pid); console.log("Image:", product_image); console.log("Index:", index); console.log("Title:", product_title); console.log("Price:", product_price); console.log("Current Element:", this_val); The problem is that: When I am clicking on the add-to-cart button, in the console no values are displaying Note: The javascript is taking value from home page(index) and from an another page........... and if you need my views.py: def add_to_cart(request): cart_product={} cart_product[str(request.GET['id'])]={ 'title': request.GET['title'], 'qty': request.GET['qty'], 'price': request.GET['price'], } if 'cart_data_obj' in request.session: if str(request.GET['id']) in request.session['cart_data_obj']: cart_data= request.session['cart_data_obj'] cart_data[str(request.GET['id'])]['qty']=int(cart_product[str(request.GET['id'])]['qty']) cart_data.update(cart_data) request.session['cart_data_obj']=cart_data else: cart_data=request.session['cart_data_obj'] cart_data.update(cart_product) request.session['cart_data_obj']=cart_data request.session['total_cart_items'] = len(cart_data) else: request.session['cart_data_obj']=cart_product request.session['total_cart_items'] = len(cart_product) return JsonResponse({"data":request.session['cart_data_obj'],'totalcartitems': request.session['total_cart_items']}) But views.py is working perfectly well -
Output to Django template from EAV model
I can’t figure out how to display the value of the characteristics into a template from the model, where the characteristics are compared with the values. I got the value from the Product table, but how do I get it from the ProductProperty table? class Product(models.Model): name = models.CharField(verbose_name='Наименование', max_length=128) name_eng = models.CharField(verbose_name='Наименование (англ.)', max_length=128) slug = models.SlugField(verbose_name='Слаг', max_length=128, unique=True, db_index=True, editable=False) category = models.ForeignKey(verbose_name='Категория', to=Category, on_delete=models.CASCADE) class Property(models.Model): name = models.CharField(verbose_name='Наименование', max_length=128) class ProductProperty(models.Model): product = models.ForeignKey(verbose_name='Продукт', to=Product, on_delete=models.CASCADE) property = models.ForeignKey(verbose_name='Характеристика', to=Property, on_delete=models.CASCADE) value_string = models.CharField(verbose_name='Текстовое значение характеристики', max_length=250, null=True, blank=True) value_integer = models.IntegerField(verbose_name='Числовое значение характеристики', null=True, blank=True) value_genres = models.ManyToManyField(verbose_name='Жанры', to=Genre, null=True, blank=True) I tried to implement this through a for loop, but it didn't work -
Need Authorization Header in test DRF
I try to test some views by the url but seems I'm blocked with the credentials, I see other post with the same problem and try to follow them but I'm still as the sane point test_web_share_file_folder_view_set.py class WebShareFileFolderViewSetTestCase(TestCase): def setUp(self): self.factory = APIRequestFactory() self.user = User.objects.create_user(username='my_user', password='my_password') headers = web_backend_api_access_headers() self.token = headers['Authorization'] self.client = APIClient() def test_list_with_search(self): WebShareFileFactoryBoy(name="file_with_search", path="path_with_search") url = reverse('web-share-file-folders-list') request = self.factory.get(url, {'search': 'file_with_search'}) request.user = self.user self.client.credentials(HTTP_AUTHORIZATION='Bearer' + self.token) response = self.client.get(url, headers={'Authorization': 'Bearer ' + self.token}) print(response.data) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertTrue('file_with_search' in response.data['results'][0]['name']) here the error when I start the test FAIL: test_list_with_search (tests.test_web_share_file_folder_view_set.WebShareFileFolderViewSetTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "-\tests\test_web_share_file_folder_view_set.py", line 32, in test_list_with_search self.assertEqual(response.status_code, status.HTTP_200_OK) AssertionError: 401 != 200 and here the print of response.data {'detail': ErrorDetail(string='Need Authorization Header', code='authentication_failed')} If anyone has an idea :? thank you I try to access to the view to make a test -
How to setup two Google Storage Buckets for a Django application, one for MEDIA files and the other for STATIC files?
Here is the error I am getting at the home page of my app. Your default credentials were not found. To set up Application Default Credentials, see https://cloud.google.com/docs/authentication/external/set-up-adc for more information. #settings.py from google.oauth2 import service_account from google.cloud import storage try: # Load service account info from environment variables service_account_info = { "type": env("TYPE"), "project_id": env("PROJECT_ID"), "private_key_id": env("PRIVATE_KEY_ID"), "private_key": env("PRIVATE_KEY"), "client_email": env("CLIENT_EMAIL"), "client_id": env("CLIENT_ID"), "auth_uri": env("AUTH_URI"), "token_uri": env("TOKEN_URI"), "auth_provider_x509_cert_url": env("AUTH_PROVIDER_X509_CERT_URL"), "client_x509_cert_url": env("CLIENT_X509_CERT_URL") } # Create credentials from the service account info credentials = service_account.Credentials.from_service_account_info(info=service_account_info) # Initialize the Google Cloud Storage client with your credentials client = storage.Client(credentials=credentials, project=env("PROJECT_ID")) # List all buckets -> this works buckets = list(client.list_buckets()) print("Buckets in {}:".format(client.project)) print(buckets) except Exception as e: print("Error initializing Google Cloud credentials: ", e) #also settings.py DEFAULT_FILE_STORAGE = 'fly_io_test.gcloud.GoogleCloudMediaFileStorage' STATICFILES_STORAGE = "storages.backends.gcloud.GoogleCloudStorage" GS_STATIC_BUCKET_NAME = env("DEV_STATIC_FILES_BUCKET_NAME") GS_MEDIA_BUCKET_NAME = env("DEV_MEDIA_FILES_BUCKET_NAME") STATIC_URL = f"https://storage.googleapis.com/{GS_STATIC_BUCKET_NAME}/admin/" MEDIA_URL = f"https://storage.googleapis.com/{GS_MEDIA_BUCKET_NAME}/" I have have run gcloud auth login , gcloud config set project <project_id>. and then gcloud auth application-default-login in the container seemingly successfully. I'm getting the ADC error I don't know if this will write media files to the MEDIA bucket and STATIC files to the static bucket. -
Django Python Email Subject end of text white space not showing
I have this email to send out with email subject + current date. msg = MIMEMultipart('alternative') msg['Subject'] = Header("Email Subject for " + str(today.strftime("%d/%m/%y"))) msg['From'] = me msg['To'] = you When receive the email, the email subject shows Email Subject forDD/mm/yy. Tried add space after "for" as above but it wont show at Gmail. Is there any way to add a space between for and DD/mm/yyyy? -
Debugging in Django REST Framework
How to correctly catch breakpoints in Django REST Framework debugging session after an HTTP request? When debugging a DRF project breakpoints trigger upon initiating the debug process rather than after sending an HTTP request. i set "justMyCode": false rather than to true When I begin the debugging process, all steps are debugged up to the point where the WSGI server starts, as indicated by the following output: sql Copy code ... System check identified no issues (0 silenced). March 13, 2024 - 02:36:24 Django version 5.0.3, using settings 'tuto.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. However, after sending an HTTP request, I immediately receive the response, with no breakpoints being hit during the process. -
autofill html form w/ multiple different fields, including: Checkbox and Dropdown selections
Part of the html form I want to autofill: <div h2 class="display-6 text-uppercase mb-3"> Service</h2> <span class="question">Select Service(s):</span><br> <input type="checkbox" id="car_wash" name="car_wash" value="car_wash"/> <label for="car_wash"> Car Wash</label><br> <input type="checkbox" id="window_cleaning" name="window_cleaning" value="Window Cleaning" autocomplete="name"> <label for="window_cleaning"> Window Cleaning</label><br> <input type="checkbox" id="power_wash" name="power_wash" value="Power Wash" autocomplete="name" <label for="power_wash"> Powerwashing</label><br> <input type="checkbox" id="curb_address" name="curb_address" value="Curb Address Painting" autocomplete="name" <label for="curb_address"> Curb Address Painting</label><br> </div> <div id="dropdownHolder" class="col-lg-12 mb-3"> <select id="carwash_type" name="carwash_type" class="form-select form-control" aria-label="Default select example" value="ON"> <option selected> Car Type</option> <option value="1">Coupe / Sedan / Hatchback</option> <option value="2">Suv / Crossover</option> <option value="3">Mini Van</option> <option value="4">Pickup Truck</option> <option value="5">I'm not sure</option> </select> </div> <div id="dropdownHolder" class="col-lg-12 mb-3"> <select id="carwash_type" name="carwash_type" class="form-select form-control" aria-label="Default select example" value="ON"> <option selected> Car Wash Package</option> <option value="1">Express Interior</option> <option value="2">Express Exterior</option> <option value="3">Full Service Wash</option> </select> </div> There are several pages linking to this form, each of which have a service selected and if it's a car wash, the extras as well, including car type and wash package. Here is the html of the car wash selection - before the form page, trying to link to it w/autofilled selections. <div class="services-content text-center border py-3 py-md-5 px-3"> <iconify-icon class="service-icon" icon="fa6-solid:car-on"></iconify-icon> <h4 class="my-3">Auto Detailing</h4> <a href="booking.html" class="icon-link my-3"> … -
Django form submition Problem with Submit button
Im encountering a problem with an html template that i created using bootstrap so my problem is that i have a javascript working dynamically to add rows to a django form with 4 specific fields but whenever i add a row the submit button stops submitting results and instead adds more product fields to fill and they are initialized to None here is the code for my html template {% block createlist %} <form id="form-container" method="POST"> {% csrf_token %} <div class="card"> <div class="form-group" id="form-group"> <div class="row mt-3"> <h4 class="card-title md-2 m-2">List Name</h4> <div class="m-2">{{ listform.name}}</div> </div> <div id="button_row" class="row mt-0 no-gutters"> <!-- Apply .row class here --> <div class="row"> <h2 class="col-md-2 md-2 m-2">Products</h2> <div id="add-form" class="col-md-1 md-2 m-2"><button type="button" class="btn btn-primary">+</button></div> </div> <div class="col-md-2 m-2">Product Name</div> <div class="col-md-2 m-2">Quantity</div> <div class="col-md-2 m-2">Weight</div> <div class="col-md-2 m-2">Price</div> </div> {{ productformset.management_form }} {% for form in productformset %} <div id="form-row" class="row mt-0 no-gutters"> <!-- Apply .row class here --> <div class="col-md-2 m-2"><input type="text" name="{{ form.prefix }}-product_name" value=""></div> <div class="col-md-2 m-2"><input type="text" name="{{ form.prefix }}-quantity" value="{{ form.quantity.value }}"></div> <div class="col-md-2 m-2"><input type="text" name="{{ form.prefix }}-weight" value="{{ form.weight.value }}"></div> <div class="col-md-2 m-2"><input type="text" name="{{ form.prefix }}-price" value="{{ form.price.value }}"></div> </div> {% endfor %} </div> </div> … -
(WAGTAIL) How to add a button, or something similar, items per page to a model listing in the wagtail administrative area?
I'm trying to add an items button per page in the wagtail administrative area, but I didn't find anything in the documentation. Is there any way to customize and create a button to choose the number of items per page? -
Why is the email still not being sent even though all steps have been fulfilles?
I'm trying to send a confirmation email every time a user signs up for my service. I followed tutorials but while the user is getting signed up, the email is not being sent. This is my views.py def signup_view(request): if request.method == "POST": first_name= request.POST.get('first_name') last_name = request.POST.get('last_name') email = request.POST.get('email', 'default user') phone = request.POST.get('phone') password1= request.POST.get('password1') password2= request.POST.get('password2') userHash= email.replace('@','') # userHash =~ s/'@'//g #new =User.objects.filter(username = userHash) if password1 != password2: return render(request, 'signup.html',{'error_message': ' Passwords Different'}) else: user = User.objects.create_user((userHash, password1)) user.save() login(request, user) current_site = get_current_site(request) user = request.user email = request.user.email subject = "Verify Email" message = render_to_string('account/verify_email_message.html', { 'user': user, 'domain': current_site.domain, 'uid':urlsafe_base64_encode(force_bytes(user.pk)), 'token':account_activation_token.make_token(user), }) email = EmailMessage( subject, message, to=[email] ) email.send() return HttpResponse("Please Confirm your email address to complete the registration") and render(request,'account/landing.html') else: form = CreateUserForm() context = { 'form': form } return render(request, 'account/signup.html', context) def activate(request, uidb64, token): try: uid = force_str(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except(TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): user.is_active = True user.save() return HttpResponse("Thank you for this confirmation") and redirect('account/index.html') else: messages.warning(request, 'The link is invalid.') return render(request, 'account/index.html') def home(request): return render(request, 'account/index.html') This is … -
Create List of Blank Forms on Submit
I am working with Django and have one form for each employee that expires every two weeks. For example, last weeks timesheets are now expired and I need to create a list of new timesheets. How can I create multiple blank forms, based on creation of new time period? Context: class TwoWeekPeriod(models.Model): start_date = models.DateField(_("Start Date")) end_date = models.DateField(_("End Date")) week_number = models.IntegerField(_("Week Number")) class CreateNewTimesheet(models.Model): employee = models.ForeignKey(Employee, on_delete=models.CASCADE) start_date = models.DateField(_("Start Date")) end_date = models.DateField(_("End Date")) two_week_period = models.ForeignKey(TwoWeekPeriod, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def save(self, *args, **kwargs): week_number = (self.start_date - timezone.now().date()).days // 14 + 1 two_week_period, _ = TwoWeekPeriod.objects.get_or_create( start_date=self.start_date, end_date=self.end_date, defaults={'week_number': week_number} ) self.two_week_period = two_week_period super().save(*args, **kwargs) Employee Timesheet example: class Foo(model.Models) employee = models.ForeignKey(Employee, on_delete=models.CASCADE) time_in = ### time_out = ### How can I use CreateNewTimesheet, let’s say 14 (each employee) blank forms using model Foo for each employee in order to input new time, for each employee, for the next two week period, without having to create each individual timesheet manually?