Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
CORS (Cross-Origin Resource Sharing) errors
I have two projects. The first one is a project with Django Rest Framework APIs, and the second one is a Django project where I will create HTML pages and handle all the frontend parts of the project. When I deploy both projects on the server and add CORS middleware properly in both, I still get a CORS error. I will run both project diffrent diffrent port. and i will try also decoreter concept. This is my second Project Setting.py This is my first restapi project Settings.py How to resolve this ? -
How to fetch data from the mysql into the frontend HTML, (Django project)? [closed]
I am making a project in which there are different casestudies, Now all these case study have some data related to it in the database. The data is stored into different tables in the database, all the casestudies have a unique ID as well. now i want if the user clicks on the particular case study it should redirect the user to the information page, where the data related to that particular casestudy appears in the different section of the page. I have made the whole UI of this project, but now i want to know how to setup the database and fetch results related to particular casestudy clicked by the user. for example, there are three case studies IRIS FLOWER CLASSIFICATION HOUSE PRICE PREDICTION NUMBER PLATE DETECTION preview of different casestudy now on the information page, there are different accordions -INTRODUCTION -DATA COLLECTION -DATA PREPROCESSING -FEATURE ENGINEERING -MODEL SELECTION/ TRAINING -RESULTS preview of the sections now in these parts there are different text fileds and the image/graph/video fields where i want to fetch -
How to not prefill a form fields with instance parameter django
I want to write a view function to edit a blog post. And I'm wondering how to tell Django what object to modify in the database using instance parameter without prefilling of a form. BlogPost model class BlogPost(models.Model): title = models.CharField(max_length=200) text = models.TextField() date_added = models.DateField(auto_now_add=True) def __str__(self): return self.title[:50] Form model class BlogPostForm(forms.ModelForm): class Meta: model = BlogPost fields = ["title", "text"] labels = {"title": "", "text": ""} The view function def edit_post(request, post_id): post = BlogPost.objects.get(id=post_id) if request.method != "POST": form = BlogPostForm(instance=post) else: form = BlogPostForm(instance=post, data=request.POST) if form.is_valid(): form.save() As far as I understood it, the instance parameter tells Django what object to modify in the database using form.save() method. But how to do it without prefilling of the form? -
Rendering a loading spinner before rendering another template
So I am trying to render a loading spinner page, for example on testview.html, before rendering my dynamically created report template, report.html. I was thinking of a fork, with one rendering the loading spinner and the other one loading and processing my data. Then, when the loading and processing is done, I want to use the context created with my data and inject it into my report template before initializing and rendering it. The problem is that I can't load report.html without the context since I need to initialize variables and functions in order to initialize the page. Here is an abstract of my report.html file: <body> <div class="navbar"> <p>{{eng_job}} - {{event_name}}</p> <a href="/index/"><i class="bx bxs-home" style="color:#ffffff"></i></a> {% for sheet in sheets %} {% if sheet == sheet_name %} <a class="selected" href="/{{eng_job}}/{{event_name}}/{{sheet}}/">{{ sheet }}</a> {% else %} <a href="/{{eng_job}}/{{event_name}}/{{sheet}}/">{{ sheet }}</a> {% endif %} {% endfor %} <div class="subnav"> <button class="subnavbtn">Save <i class='bx bxs-chevron-down' style='color:#ffffff' ></i></button> <div class="subnav-content"> <button type="submit" id="templateButton" form="templateForm">Save Template & Data</button> <button type="submit" id="saveButton" form="chartForm">Save Data</button> </div> </div> <div class="subnav"> <button class="subnavbtn">Add <i class='bx bxs-chevron-down' style='color:#ffffff' ></i></button> <div class="subnav-content"> <button id="addtablebutton" onclick="openFilterPopup()">Add Table</button> <button id="addimagebutton" onclick="toggleImageUpload()">Add Image</button> <button id="addchartbutton" onclick="addChart()">Add Chart</button> <button id="addtextbutton" onclick="addTextArea()">Add Text</button> </div> … -
Can't receive LiqPay callback
I'm trying to use LiqPay Checkout for my django website. Everything works great, I can see my test transactions on the LiqPay's admin panel, but I don't receive POST callback to the specified server_url. I can see all the attempts to send callback on the Liqpay's admin panel, but in the "HTTP Code" column it always says "Not Delivered". (url it tries to send request to is valid, and when I try to send request myself using curl I can see it in django's output). To make site global I used ngrok. Maybe this is a problem with some Django or ngrok firewall settings? -
extending django admin by a view without a model
I have a customized admin view - my app is called virtual: class VirtualAdminSite(admin.AdminSite): index_template = "virtual/admin_index.html" def index(self, request, extra_context=None): extra_context = extra_context or {} return super().index(request, extra_context) def get_urls(self): urls = super().get_urls() my_urls = path("virtual/info/", self.admin_view(self.info)) urls.append(my_urls) return urls def info(self, request): return HttpResponse("hello") and I want to be able to include the url in the newly created admin_index.html, so I did (please ignore I used HTMX to load this bc it's shorter than AJAX in vanilla JS): {% block content %} <div id="content-main"> {% include "admin/app_list.html" with app_list=app_list show_changelinks=True %} Info: <h3 hx-get="{% url 'info' %}" hx-trigger="load"> loading ... </h3> </div> {% endblock %} but I get a: Reverse for 'info' not found. 'info' is not a valid view function or pattern name error. I already tried adding admin/ in the path, and deleting virtual but everything fails. -
"TypeError: can not serialize 'ContentFile' object"
import base64 from django.core.files.base import ContentFile file = "data:image/png;base64,iVBORw0KGgoAAAANSUhEU..." format, imgstr = file.split(';base64,') ext = format.split('/')[-1] data = ContentFile(base64.b64decode(imgstr), name='temp.' + ext) somemodel.save(data) i want to save base64 file media in Django model file field i am expecting to save data but i got typeerror can not serialize 'ContentFile' object" please somebody tell me where i did wrong -
registering ModelAdmins with custom_admin_site does not show anything when split into multiple files
I overwrote the admin site to customize a little bit on the main page of the admin and now get_urls is never called. Note, that I defined the custom_admin.py: class TestAdminSite(admin.AdminSite): index_template = "Test/admin_index.html" def index(self, request, extra_context=None): extra_context = extra_context or {} print("test") # <-- this gets printed! return super().index(request, extra_context) def get_urls(self): urls = super().get_urls() print("test 2") # <-- not printed return urls custom_admin_site = TestAdminSite(name="custom_admin") admin.py: from .custom_admin import custom_admin_site in the projects urls.py I did: from testapp.admin import custom_admin_site urlpatterns = [..., path("admin/", custom_admin_site.urls), ... ] but as commented above, get_urls is never called. why? -
Making modelformset_factory editing forms
I have been learning django for the last few months, and have been working on an ecommerce project to further my learning, but I've been absolutely stumped by an issue I've been having recently. I'm using a ForeignKey to add multiple images to each product, and I currently have a form that allows me to create a post and add up to 20 images to it, I found some help online to make that form work and have studied it a lot to make sure I understand it, but when I tried to make it into an editing form I've gotten completely lost. Here is my code models.py from django.db import models from django.template.defaultfilters import slugify from users.models import User # Create your models here. def get_thumbnail_filename(instance, filename): title = instance.name slug = slugify(title) return "post_images/%s-%s" % (slug, filename) class Product(models.Model): seller = models.ForeignKey(User, on_delete=models.CASCADE, null=True) name = models.CharField(max_length=200) description = models.TextField() created = models.DateTimeField(auto_now_add=True) price = models.FloatField() thumbnail = models.ImageField(upload_to=get_thumbnail_filename, null=True) def __str__(self): return self.name def get_image_filename(instance, filename): title = instance.product.name slug = slugify(title) return "post_images/%s-%s" % (slug, filename) class Images(models.Model): product = models.ForeignKey(Product, default=None, on_delete=models.CASCADE, null=True) img = models.ImageField(upload_to=get_image_filename, verbose_name='Image') class Meta: verbose_name_plural = "Images" views.py @login_required def … -
object of type 'function' has no len() in django
I use the Django 4 book to learn Django, but I get errors during pagination views.py from django.shortcuts import render, get_object_or_404 from django.http import Http404 from .models import Post from django.core.paginator import Paginator def post_list(request): posts = Post.published.all() # Pagination with 3 posts per page paginator = Paginator(post_list, 3) page_number = request.GET.get('page', 1) posts = paginator.page(page_number) return render(request,'blog/post/list.html',{'posts': posts}) paginations.html file <div class="pagination"> <span class="step-links"> {% if page.has_previous %} <a href="?page={{ page.previous_page_number }}">Previous</a> {% endif %} <span class="current"> <p>Page {{ page.number }} of {{ page.paginator.num_pages }}.</p> </span> {% if page.has_next %} <a href="?page={{ page.next_page_number }}">Next</a> {% endif %} </span> </div> -
'NoneType' object has no attribute 'HTTP_200_OK' in Django Rest Framework
Am working on a certain project in drf and i have created a view for searching for job records but whenever i try out my endpoint, i get an error. Below are the relevant code blocks: models.py class Customer(models.Model): firstname = models.CharField(max_length=100, null=False, blank=False) othernames = models.CharField(max_length=100, null=True, blank=False) phonenumber_1 = models.CharField(max_length=15, null=False, blank=False) phonenumber_2 = models.CharField(max_length=15, null=True, blank=True) email = models.EmailField(blank=True, null=True) address = models.CharField(max_length=64, null=False, blank=False) passport_photo = models.ImageField(upload_to="passport_photos/", null=False, blank=False) file_upload = models.FileField(upload_to="uploaded_files/", null=False, blank=False) remarks = models.TextField() class Job(models.Model): job_title = models.CharField(max_length=64, null=False, blank=False) job_position = models.ForeignKey(JobPosition, null=True, on_delete=models.CASCADE) job_field = models.CharField(max_length=64, null=True, blank=True) job_description = models.TextField(null=True, blank=True) job_company = models.ForeignKey(EmployerCompany, null=True, blank=True, on_delete=models.CASCADE) class RecruitmentProcess(models.Model): STATUS_CHOICES = [ ('applied', 'Applied'), ("pending", "Pending"), ('interviewed', 'Interviewed'), ('not_hired', 'Not Hired'), ('hired', 'Hired'), ('rejected_offer', 'Rejected the Offer'), ] customer = models.ForeignKey(Customer, on_delete=models.CASCADE) job = models.ForeignKey(Job, on_delete=models.CASCADE) status = models.CharField(max_length=64, choices=STATUS_CHOICES, default='applied') application_date = models.DateTimeField(auto_now_add=True) urls.py urlpatterns = [ path('placements/search/', views.search_placement, name='placement_search'), ] serializers.py from rest_framework import serializers from.models import RecruitmentProcess from rest_framework.response import Response def create_standard_response(status, message, data=None): response = { 'status': status, 'message': message, } if data is not None: response['data'] = data return Response(response) class RecruitmentProcessSerializer(serializers.ModelSerializer): class Meta(object): model = RecruitmentProcess fields = "__all__" views.py from rest_framework.decorators … -
Google Cloud Storage Signed URL not Accessible in HTML but Works in Browser
`I'm using Python with the Google Cloud Storage library to generate signed URLs for my objects in a bucket. These URLs are meant to be embedded in HTML to display images on a webpage. However, while the signed URLs work fine when directly pasted into a browser, they do not display the images when used in the HTML code. from google.cloud import storage from datetime import timedelta def list_signed_urls(bucket_name, prefix, expiration_time=3600): storage_client = storage.Client() bucket = storage_client.bucket(bucket_name) blobs = bucket.list_blobs(prefix=prefix) signed_urls = [] for blob in blobs: signed_url = blob.generate_signed_url( expiration=timedelta(seconds=expiration_time), method='GET' ) signed_urls.append(signed_url) return signed_urls if request.session.get('file_processed'): bucket_name = 'datamedical' positive_images = list_signed_urls(bucket_name, 'positive/') negative_images = list_signed_urls(bucket_name, 'negative/') context = { 'positive_images': positive_images, 'negative_images': negative_images, } return render(request, 'image/index.html', context) **<img src="signed_url_here" alt="Image">** I've confirmed that the signed URLs are correct by testing them individually in a browser. However, when I use them in my HTML code like this: ` -
How to use existing db in django pytest?
I have default schema for my API, and existing schema for data search. This is db settings: DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql", "OPTIONS": {"options": "-c search_path=public"}, "NAME": config("DB_NAME", default=""), "USER": config("DB_USER_NAME", default=""), "PASSWORD": config("DB_PASSWORD", default=""), "HOST": config("DB_HOST", default="db"), "PORT": config("DB_PORT", default=""), }, "data": { "ENGINE": "django.db.backends.postgresql", "OPTIONS": {"options": "-c search_path=data"}, "NAME": config("DB_NAME", default=""), "USER": config("DB_USER_NAME", default=""), "PASSWORD": config("DB_PASSWORD", default=""), "HOST": config("DB_HOST", default="db"), "PORT": config("DB_PORT", default=""), }, } For "data" I used the comand python manage.py inspectdb --database=data > apps/data/models.py And got models.py like this: class Product(models.Model): id = models.AutoField(primary_key=True) ... class Meta: managed = False db_table = "Product" I've tried create some pytest: @pytest.mark.django_db(databases=["default", "data"], transaction=True) class TestSomeTestAPIView: view_name = "some-view-name" def test_some_test_name(self, auth_client): print(Product.objects.using("data").all()) And got the error "Product" table does not exists So I need use existing db schema "data" without creating migrations, and use default schema as usual. I've tried https://pytest-django.readthedocs.io/en/latest/database.html but it does not work in my case. Any ideas how to run pytests? -
Django messages not saved when a new request is called inside a view
I am trying to make a message/logging system where the user/front-end can get the progress status of the process currently running in a thread they initiated (what they started, where the process is currently at, did it successfully finished, or if its error, pass the error message). There is already a logging mechanism which saves the info to a .log file, but since I want it to be sent to the user who requested it, I used django.messages instead. I have set up my django settings as such: INSTALLED_APPS = [ ... 'django.contrib.messages', ... ] MIDDLEWARE = [ ... 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', ... ] TEMPLATES = [ { ... 'OPTIONS': { 'context_processors': [ ... 'django.contrib.messages.context_processors.messages', ... ], }, }, ] MESSAGE_STORAGE = 'django.contrib.messages.storage.session.SessionStorage' and I have this view: from django.contrib import messages from django.contrib.messages import get_messages from django.shortcuts import render, redirect from django.contrib.auth.models import User from threading import Thread from .logging_view_testing import try_catch import logging def index(request): if(True): thread = Thread(target=function_one, args=(request, )) thread.start() message_list = [] storage = get_messages(request) for message in storage: message_list.append(message) storage.used = False tag_filter = request.GET.get('tag', None) if tag_filter: message_list = [message for message in message_list if tag_filter in message.tags.split()] context = { 'username' : username, … -
response["X-Accel-Buffering"] = "no" in Django has no effect in Google App Engine
This works on my local (having Apache2) and on my Compute Engine having NGINX. My views.py : from django.shortcuts import render from django.http import StreamingHttpResponse import time def home(request): return render(request, 'home.html', {}) def automate_run(request): # content_type doesn't have to be application/json response = StreamingHttpResponse(automate_foo(), content_type="application/json") response['Cache-Control'] = 'no-cache' # prevent client cache response["X-Accel-Buffering"] = "no" # Allow Stream over NGINX server return response def automate_foo(): for i in range(1, 11): status = "Step %d" % i percentage = i * 10 json_string = f'{{"status": "{status}","percentage": "{percentage}"}}' print(json_string) yield json_string time.sleep(.5) But response["X-Accel-Buffering"] = "no" doesn't seem to have any effect on Google App Engine which I understand uses NGINX under the hood. Demo : https://cloudxchange.el.r.appspot.com (right-click > Inspect) -
Error module spyne.six.moves, execute serve django
I'm configuring a soap service in django, but when running runserver it gives me an error from the spyne.six.moves module, has anyone had this problem or similar that can help me? The version of my technologies Python 3.12 Spy 2.14 Execute server - response -
How to implement Email Verification on a Django Webapp?
I am building a web app with User Email verification and having trouble with user email verification. I am able to get my email to send, but unable to validate token once the newly created user clicks on the link. The following are my views.py. Email sends, but unable to validate token def signup_view(request): if request.method == 'POST': email = request.POST.get('email') password1 = request.POST.get('password1') password2 = request.POST.get('password2') if password1 != password2: messages.error(request, "Passwords do not match.") return redirect('signup') try: user = User.objects.create_user(username=email, email=email, password=password1, is_active=False) # Generate token for email confirmation token = generate_token.make_token(user) uidb64 = urlsafe_base64_encode(force_bytes(user.pk)) # Construct confirmation link confirmation_link = request.build_absolute_uri(f'/confirm-email/?uid={uidb64}&token={token}') email_body = render_to_string('email_confirmation.html', {'confirmation_link': confirmation_link}) # Send email with confirmation link send_mail( 'Confirm your email', email_body, 'contact@latamtravelservices.com', [user.email], fail_silently=False, ) messages.success(request, "An email has been sent to your email address. Please confirm your email to complete the registration.") return redirect('login') except Exception as e: messages.error(request, f"An error occurred during registration: {str(e)}") return redirect('signup') return render(request, 'signup.html') logger = logging.getLogger(name) def confirm_email(request): if request.method == 'GET': uidb64 = request.GET.get('uid') token = request.GET.get('token') try: uid = force_str(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except (TypeError, ValueError, OverflowError, User.DoesNotExist) as e: logger.error(f"Error decoding UID or retrieving user: {e}") user = None if … -
django url tag not receiving token correctly?
I am creating a web application where users can leave reviews for my company. Upon leaving a review, an email is sent to me with the review data and a link for me to easily click to approve the review to be shown on the page for all users. To do this, I used uuid to create a token for each review created. I know that the token is being passed to my review_email.html template because i can send the token as html text within the email, but for some reason i keep getting this error with the url tag: Reverse for 'approve_review' with keyword arguments '{'token': ''}' not found. 1 pattern(s) tried: ['reviews/approve/(?P[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\Z'] views.py: from django.shortcuts import render, redirect, get_object_or_404 from django.http import HttpResponse from django.urls import reverse from .models import Review from .forms import ReviewForm from django.core.mail import send_mail from django.conf import settings from django.template.loader import render_to_string import os import uuid # Create your views here. def submit_review(request): if request.method == 'POST': form = ReviewForm(request.POST) if form.is_valid(): review = form.save(commit=False) review.token = uuid.uuid4() review.save() print(review.token) send_review_email(review) return render(request, 'reviews/thank_you.html') else: form = ReviewForm() return render(request, 'reviews/submit_review.html', {'form': form}) def send_review_email(review): send_mail('New Review Submitted', 'A new review has been … -
Unsanitized input from an HTTP parameter flows into django.http.HttpResponse
In my python (django) project, I have following code snippet someError = request.GET.get('error', None) if someError is not None: self.logger.exception(f'Authorization failed with error: {someError}') return HttpResponse(f'Authorization failed with error: {someError}') The code is working fine, howevere when scheduled Snyk scan is run then it complains this Info: Unsanitized input from an HTTP parameter flows into django.http.HttpResponse, where it is used to render an HTML page returned to the user. This may result in a Cross-Site Scripting attack (XSS). I did some research and tried to convert someError object as string but it is still complaining about that. Can someone please let me know how to sanitize the error? Thanks in advance -
How to solve "detail": "Authentication credentials were not provided." Django REST Framework?
I'm encountering an issue with Django REST Framework where I'm receiving an "Unauthorized" error when trying to access a protected endpoint /api/user/ even though I've implemented token-based authentication. Here's an overview of my setup: I have a Django backend serving REST APIs using Django REST Framework. Token-based authentication is implemented using Django's built-in TokenAuthentication class. Frontend is developed using React and Axios for making API requests. Despite successfully logging in and receiving a token, subsequent requests to protected endpoints fail with an "Unauthorized" error. I've double-checked the following: The token is correctly stored in localStorage and is being sent with each request. URLs in the frontend (Axios requests) are relative to the base API URL (http://127.0.0.1:8000/api/). The Django server is running at the expected address and port (http://127.0.0.1:8000/). However, I'm still encountering the "Unauthorized" error. Here are relevant parts of my code: userApi.js: import api from './axiosConfig'; function getAuthToken() { return localStorage.getItem('token'); } export async function getUsers() { try { const response = await api.get('users/'); return response.data; } catch (error) { console.error('Error fetching users:', error.response || error.message || error); throw new Error('Failed to fetch users'); } } export async function updateUser(userId, updatedData) { const authToken = getAuthToken(); const url = … -
Ajax live search in header on wagtail
I recently just started learning Python, Wagtail and Django. There was a need to create a live search in the header of the site, but I just can’t get it to work correctly; as a result of the search, the entire page with search results is loaded. Here's the code I put a lot of effort into: in header.html: <div class="block_search"> <input type="text" class="search_input searchbox" id="search_header" value="" placeholder="Поиск товара..." name="q" > {% include "tags/header_search.html" %} </div> header_search.html: {% load static wagtailcore_tags header_tags %} <div id="search_box-result"> {% get_header_search as search_result%} {% for result in search_result %} {{result.title}} {% endfor %} </div> Jquery: <script> $(document).ready(function () { $('#search_header').on('input',function(e){ var search_result = $("#search_header").val(); $.ajax({ type: 'GET', cache: true, url: '', data: {"search": search_result}, success: function (response) { $("#search_box-result").replaceWith(response) } }); }); }); </script> header_tags.py: @register.simple_tag(takes_context=True) def get_header_search(context): request = context['request'] if request.method == 'GET': search_query = request.GET.get("search", None) print(search_query) if search_query: search_results = Page.objects.live().search(search_query) else: search_results = Page.objects.none() return search_results -
Django Rest Framework custom filter with default search and ordering filter
I have a project in Django Rest Framework where I need have endpoint where I'm able to search Document objects by title and text and possibility to search object is active and inactive, using to this url address. I am using to achive this django_filters package. Example: https://localhost:8000/?is_active=True. This is my model class Document(models.Model): title = models.CharField(max_length=100) text = models.TextField() date = models.DateField() account = models.ForeignKey( to=Account, null=True, blank=True, on_delete=models.CASCADE, related_name='documents', verbose_name='account', help_text='account', ) is_active = models.BooleanField(default=True) def __str__(self): return self.title **Serializer** class DocumentSerializer(serializers.ModelSerializer): class Meta: model = Document fields = ['id', 'title', 'text', 'date', 'account', 'is_active'] Custom FilterSet class DocumentBackendFilter(dfilters.FilterSet): is_active = dfilters.BooleanFilter(field_name='is_active', lookup_expr='exact') class Meta: model = Document fields = ['is_active'] View class DocumentsListView(viewsets.ModelViewSet): queryset = Document.objects.all() serializer_class = DocumentSerializer filterset_class = DocumentBackendFilter filterset_fields = ('is_active',) filter_backends = [filters.SearchFilter, filters.OrderingFilter] search_fields = ['title', 'text'] ordering_fields = ['title', 'text'] def get_queryset(self): qs = super().get_queryset() qs = qs.filter(account__users=self.request.user) return qs Problem: Under url: http://127.0.0.1:8000/?is_active=True I have elements where is_active is set on True and False. Default search is working OK. How can I get search, ordering and filter objects based on is_active? -
How to assert an exception that is logged and is not affecting the Response
I'm testing an API that can raise an exception, but eventually returns a response based on other calculations, not related to the exception that is raised (it only logs the exception): def get(self, request): #some code here try: #do something and create the response value except Exception as err: logger.exception(str(err)) return Response I tried the following to test if an exception is raised, but it didn't work as the final return value (API's response) doesn't care about the exception: with pytest.raises(RuntimeError): response = MyInfo.as_view( )(request) I get the following: > with pytest.raises(RuntimeError): E Failed: DID NOT RAISE <class 'RuntimeError'> even though a RuntimeError exception is logged. I think pytest only cares about the API's response and not an exception that has occurred inside the API. -
Django Table Will Not Create
I have an django app with many apps inside of it. One is a calendar model. I have tried to get this table created so many times without any response that I chose to go down the route of resetting everything. No matter how many times I reset the database or migrations, the table will not create. All other tables are completely fine. It is this sole table every time I try to migrate. I have tried many different solutions to no avail. calendar_event/models.py class CalendarEvents(models.Model): id = models.AutoField(primary_key=True) type = models.CharField(max_length=50, choices=EVENT_CHOICES, null=True, blank=True) name = models.CharField(max_length=145,null=True, blank=True) description = models.TextField(null=True, blank=True) location = models.CharField(max_length=100, null=True, blank=True) creator = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, on_delete=models.CASCADE, related_name='creator') guests = models.ManyToManyField(settings.AUTH_USER_MODEL, null=True, blank=True) start = models.DateTimeField(null=True, blank=True) end = models.DateTimeField(null=True, blank=True) event_last_date = models.DateField(null=True, blank=True) repeating = models.BooleanField(default=False, null=True, blank=True) repeat_interval = models.IntegerField(null=True, blank=True) repeat_frequency = models.CharField(max_length=20, choices= RECURRENCE_CHOICES, null=True, blank=True) repeat_by_weekdays = ArrayField(models.IntegerField(choices=WEEKDAY_CHOICES), default=list, null=True, blank=True) recurrence = RecurrenceField(null=True, blank=True, verbose_name="Recurrence") When I run makemigrations the table shows it's understood and ready to be created, but simply does not show up Solution Attempts I have tried resetting all migrations (keeping the init.py file) I have tried resetting the database and recreating from … -
Request for assistance in implementing a dynamic form with pigeon search in Django and HTMX
I am writing to request your assistance in implementing a dynamic form in my Django project. The main objective is to create a form that allows adding new pigeons to the database, with the ability to search and select existing parents, or register new parents if they are not found in the database, all without having to leave the current form. The current situation is as follows: I have a Pigeon model that represents pigeons, with fields such as name, ring number, color, gender, country of origin, among others. I need a form that allows entering the data of a new pigeon, including the selection of its parents (a father and a mother) from the existing pigeons in the database. If the parents of the new pigeon are not registered, it should be possible to create new records for them directly from the same form, without having to navigate to another page. Additionally, it is required to implement a dynamic search functionality to facilitate the selection of existing parents, using technologies such as HTMX and AJAX to avoid reloading the entire page. The traditional way of manually adding a father and mother for each new pigeon is becoming increasingly tedious …