Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
[python][django]Uploading files in Django
I have a form.py including Floatfield and Charfield. Now I want to add a new Filefield to upload a text file. But I fail. The float var is submitted successfully and I could see they are changed with the change of the input, but I cannot find the file in located folders. And also, how could I check whether file extensions are correct? Shoudl I achieve it in view or model? Could someone help me? I truly struggled with it. model.py file = models.FileField(upload_to='/Folder', null = True) form.py file = forms.FileField(label='data', required=False) view.py is followed the structure in Django official document. def handle_uploaded_file(f): with open('./test_temp_file.txt', 'wb+') as destination: for chunk in f.chunks(): destination.write(chunk) def file_upload(request): if request.method=='POST': form = input_form(request.POST,request.FILES) if form.is_valid(): handle_uploaded_file(request.FILES['file']) name = request.FILES['filename'].name time = cleaned_data(timezone.now()) form = { 'name' : name, 'time' : time } return render(request, 'home/results.html',{'form':form}) else: form = input_form() return render(request, 'home/input.html', {'form': form}) Thanks. -
How to send value from HTML form into a general context of Django Project
I need to send a value from a html file into a Django View. I need to get user.id_aadgroup.idcustomer.uuid from permissions.html (which is linked to the view PermissionsListView) passed into the context of a brand new view, ApplicationListView() which has the url name applications when I click on the submit button. Here is the code: permissions.html in the django app permissions <form action="{% url 'applications' user.id_aadgroup.idcustomer.uuid %}" method="get"> <button type="submit" class="btn btn-outline-primary" value="go to manage permissions">Accéder au contrat</button> </form> view.html in the django app applications class ApplicationListView(ListView): model = ViewDevpermissionapplicationuser template_name = 'applications/applications.html' def get_context_data(self, **kwargs): kwargs.update( user= self.request.session.get('user', {'is_authenticated' : False}) ) context = super().get_context_data(**kwargs) return super().get_context_data(**kwargs) Think I can do it with a form but don't know how, any suggestions ? -
Method \"POST\" not allowed
I am getting error as Method \"POST\" not allowed. urls.py from django.conf.urls import url from . import views urlpatterns = [ url('', views.listTutorials), url('create/', views.createTutorial), url('<str:pk>/update/', views.updateTutorial), ] views.py from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework import status from .serializers import TutorialSerializer from .models import Tutorial @api_view(['POST']) def createTutorial(request): serializer = TutorialSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) @api_view(['PUT']) def updateTutorial(request, pk): tutorial = Tutorial.objects.get(pk=pk) serializer = TutorialSerializer(tutorial, data=request.data) if serializer.is_valid(): serializer.save() return Response(status=status.HTTP_204_NO_CONTENT) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) @api_view(['GET']) def listTutorials(request): tutorials = Tutorial.objects.all() serializer = TutorialSerializer(tutorials, many=True) return Response(serializer.data) serializers.py from rest_framework.serializers import ModelSerializer from .models import Tutorial class TutorialSerializer(ModelSerializer): class Meta: model = Tutorial fields = '__all__' models.py from django.db import models class Tutorial(models.Model): title = models.CharField(max_length=70, blank=False, default='') description = models.CharField(max_length=200,blank=False, default='') published = models.BooleanField(default=False) def __str__(self): return self.title project urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), url('tutorials/', include('tutorials.urls')) ] Now I am using POST request as http://localhost:8000/tutorials/create/ with body { "title": "Django framework", "description": "Learning django framework" } But I am getting error { "detail": "Method \"POST\" not allowed." } -
Django: combine ListView and DeleteView to use with HTMX?
I’m using Django with HTMX to manage a CRUD table in which I want to list and delete objects. For this, I have a ListView which displays a table (using django-tables) with pagination, sorting, and text search features. It works as expected with HTMX: for example, if you go to the next page, the whole page is not reloaded: HTMX gets the table and upload a specific part of the DOM. It looks like this: The code of the ListView looks like: class Proposals(SingleTableMixin, SearchableMixin, ListView): table_class = ProposalTable # for django-tables2 ordering = "id" model = Proposal paginate_by = 5 search_filters = ["title__icontains"] # custom text search def get_template_names(self): # Trick to chose between loading the whole page (first time user goes to the page) or just the table via HTMX (when user uses pagination or sorting, it reloads the table only in the DOM) if self.request.htmx: return "fragments/proposals_fragment.html" return "proposals.html" Now, I’m trying to add a delete feature, with the best UX. I have explored multiple ways until now: Just by removing the row from the DOM once the object is actually removed from the DB → bad: while it’s fast, it makes the pagination wrong/inconsistent, and with … -
Django - Easiest way to translate just 1 page
I want to translate only 1 page (1 Django template) to 2 different languages. After reading a bit about Django internationalization, seems quite complex and probably an overkill for my use case (it's just 1 page and not even a public website, just an internal report). It would be great if I could use the same view for different 2 templates (one template for each language), but I don't know how to do that. Currently, I'm using something like this to send the info to the template (the list is actually much longer): context = { 'campaigns' : campaigns, 'data_campaigns' : data_campaigns, 'manual_changes' : manual_changes, 'groups_bad' : groups_bad, } return render(request, 'english.html', context) It would be great if I could create a "spanish.html" template and just translate the text directly in that template. Is it possible? Are there better (and not very complex) solutions? Also, maybe using "context" like this is not a best practice. I'm learning Django, it was the easiest option I found and it works. I'm open to change it. Thanks! -
i have an error when installing django with docker even though it is in accordance with the documentation
how can I get to run django correctly by using docker? i have followed the documentation but have an error like thisPicture of error -
Template input isn't in POST
I added an input field in template to a POST form, but it isn't getting passed in the request. <form method='post' id="data_form"> {% csrf_token %} {{ form.as_p}} ... {% if part_formset %} <p> Parts:</p> <input type="checkbox" name="assigned_only" id="assigned_only" class="filter-button" {% if assigned_only %}checked{% endif %}><label for="assigned_only" class="filter-button">Assigned only</label> {{ part_formset.management_form }} <table> <tbody> {% for form in part_formset %} <tr> <td> {{ form.part }}{{ form.part.errors }} </td> <td> x {{ form.amount }}{{ form.amount.errors }}</td> </tr> {{ form.id }} {{ form.non_field_errors }} {% endfor %} </tbody> </table> {{ part_formset.non_form_errors }} {% endif %} </form> But the POST request returns every other field except this one. What am I missing? -
Django, Do I have to use is_valid() when I get request.FILES?
I wanted to save the images, so I wrote the code like this. def test_form(request): if request.method == "POST": for key in request.FILES.keys(): for img in request.FILES.getlist(key): f = Image() f.image = img f.save Can't I save it after validating it like this? def extension_filter(filename): filter = ['png','jpeg','jpg',...] extenstion = filename.split('.')[-1] if extenstion in filter: return True else : return False ... for key in request.FILES.keys(): for img in request.FILES.getlist(key): if extenstion_filter(img): f = Image() f.image = img f.save else: continue ... -
Send different attachment files such as picture, pdf, audio files, video files and zip files via email in Django
I have a platform (e-commerce website) where I do upload different types of files and then I send them to users based on requests via email. I did try but get the following error: FileNotFoundError at /some-url/[Errno 2] No such file or directory: 'http://127.0.0.1:8000/media/book_file/selfish_gene.jpeg' I got some help regarding sending pdf files via email but that one is not working as well. I do appreciate any guidance and help in advance regarding sending other files such as audio, picture, and video via email in Django. Below I do provide a snippet of the code. Hope it helps. Model: class Book(models.Model): title = models.CharField(max_length=255) author = models.CharField(max_length=255) isbn = models.CharField(max_length=255) page = models.IntegerField(null=True, blank=True) class BookFiles(models.Model): book = models.ForeignKey(Book, null=True, on_delete=models.SET_NULL) file = models.FileField(upload_to='book_file/', null=True, blank=True) View: def send_book(request): message = 'body of this email' subject= 'the subject of this email' recipient_email = 'customer@example.com' from_email = 'platformemail@example.com' email=EmailMessage(subject,message,from_email,[recipient_email]) email.content_subtype='html' the_domain = request.build_absolute_uri('/')[:-1] book_object = Book.objects.get(title='Selfish Gene').bookfiles_set.all().first().file.url the_file=open(f'{the_domain}{book_object}',"r") email.attach("file_name.pdf", the_file.read(),'application/pdf') email.send() -
AttributeError at /basic_app/ Generic detail view SchoolDetailView must be called with either an object pk or a slug in the URLconf
views.py from django.views.generic import View, TemplateView, ListView, DetailView from basic_app import models class IndexView(TemplateView): template_name = 'index.html' class SchoolListView(ListView): context_object_name = 'schools' model = models.School class SchoolDetailView(DetailView): context_object_name = 'school_detail' model = models.School template_name = 'basic_app/school_details.html' urls.py(app_urls.py) from django.urls import path from basic_app.views import SchoolDetailView app_name = 'basic_app' urlpatterns = [ path('',SchoolDetailView.as_view(),name='list'), ] (project)urls.py from django.contrib import admin from django.urls import path,include from basic_app import views urlpatterns = [ path('admin/', admin.site.urls), path('',views.IndexView.as_view()), path('basic_app/',include('basic_app.urls',namespace='basic_app')) ] Help me I am not able to find the problem. -
Looking for the right Tools for developing a website with SPA components in Django
i am a new Webdeveloper and im struggeling to find the right tools and frameworks to use for the specific site i am building. Its a site for managing all kind of information and documents about clients my firm cares for. It consists of general information (like statistics etc.) that should be served synchronously and a client specific part that should be a SPA (mainly because i want to have a list of all clients on the side, so that the main part of the page updates when you click one). My problem is , that there is so much information about that kind of stuff (but not specificly a project comparable to mine), so that i can't decide what the best approach would be. I found those options so far: Just serve everything with django and update reactive parts of the page with Ajax building a dedicated Frontend and with Frameworks like Svelte or React and using Django as API. Using these Frameworks just for the critical components that have to be reactive and serving everything with django If i understand correctly, the cleanest way would be Nr. 2, but i would lose access to djangos form rendering with … -
Why isn't my picture loading from my static folder?
I am working with the Django framework and am having some problems with referencing the source of an image from my HTML page. I continuously get this error in my terminal Not Found: /bread.jpg "GET /bread.jpg HTTP/1.1" 404 2445 although the last 4 digit string is different with every attempt I make to fix it. My project (YeOldeShoppe) has an app (Shoppe) and is laid out like this YeOldeShoppe Shoppe migrations templates index.html urls.py views.py YeOldeShoppe static bread.jpg settings.py urls.py manage.py The code I'm having an issue with is in my index.html {% load static %} ... <div style="width: 25%; display: table-cell; text-align: center;"> <img src="{{STATIC_URL}}bread.jpg" alt="Great Value Bread"/> <h2>Bread</h2> <h5>$0.99</h5> </div> In my settings.py I've already set STATIC_URL STATIC_URL = '/static/' In my urls.py of Shoppe I tried to add it to urlpatterns urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) So far, I've tried to have the static folder be in the root directory of YeOldeShoppe (eg. with manage.py), I've tried it in the YeOldeShoppe subdir (with settings.py) and in my Shoppe subdir (with views.py). I tried having the both templates dir with the static dir in the root (with manage.py), and I tried to use the command python manage.py collectstatic. I've … -
Django getting NoneType error when querying tags using TaggableManager
I am creating a blog with Django and using TaggableManager to fetch similar posts. I get int() argument must be a string, a bytes-like object or a number, not 'NoneType' when I request a post (PostDetail view) which has only one tag that has not been used in other posts. If the post has a tag which was used before or two tags, one new and one used before, all is fine. The issue might be because I'm querying a reverse foreign key, so 'None' appears for tags not having any post (source Django documentation on values_list) models.py class Post(models.Model): tags = TaggableManager( help_text="We suggest to use no more than 3 tags to improve search results") views.py class PostDetail(View): def get(self, request, slug, *args, **kwargs): # fetch post by similarity post_tags_ids = post.tags.values_list('id', flat=False) similar_posts = Post.objects.filter(tags__in=post_tags_ids)\ .exclude(id=post.id) similar_posts = similar_posts.annotate(same_tags=Count('tags'))\ .order_by('-same_tags') I'm following the example shown in the book Django by Example here's the repository. I'd like my detailed view of the post to be shown anyways, how can I avoid getting 'NoneType'? Thanks in advance for any help. -
How to save url <str:> part in Django Class Based View context
I am struggling to get the value uuid_contrat in my url into my views' context. This is what I have got so far: urls.py from django.contrib import admin from django.urls import path, include from applications.views import * from . import views urlpatterns = [ path('<str:uuid_contrat>/', ApplicationListView.as_view(), name="applications") , ] views.py class ApplicationListView(ListView): model = ViewDevpermissionapplicationuser template_name = 'applications/applications.html' def get_context_data(self, *args, **kwargs): kwargs.update( user= self.request.session.get('user', {'is_authenticated' : False}) ) context['uuid_contrat'] = self.request.GET.get('uuid_contrat') return context I tried using request.GET.get but it isn't working, any suggestions ? -
DjangoRestFramework - pass partial flag to nested serializer
How do I pass partial flag to nested serializers ? for example , serializers.py class ASerializer(serializers.Serializer): name = serializers.CharField() def validate(self, data): print("A", self.partial) return data class BSerializer(serializers.Serializer): a = ASerializer(read_only=False) def validate(self, data): print("B", self.partial) return data views.py class TestView(APIView): def get(self, request, format=None): content = {} return Response(content) def post(self, request, format=None): bsr = BSerializer(data=request.data, partial=True) # <- I want to pass the partial flag to the nested serializer as well if bsr.is_valid(raise_exception=True): return Response(bsr.data) else: return Response(bsr.error) passing {"a":{"name":"test"}} to TestView prints A False B True In this example how do I pass the partial flag to ASerializer from BSerializer ? -
Django channels websocket "Sending and Receiving Messages" fails
I am following the course Developing a Real-Time Taxi App with Django Channels and Angular . I cannot proceed as the test in Part 1 of the course, and in particular the websocket "Sending and Receiving Messages" fails. Please find in the following the error message:FAILED trips/tests/test_websocket.py::TestWebSocket::test_can_send_and_receive_messages - concurrent.futures._base.TimeoutError Here the complete failure log: _____________________________________________________ TestWebSocket.test_can_send_and_receive_messages _______________________________________________________ *self = <channels.testing.websocket.WebsocketCommunicator object at 0x7f31d75e64e0>, timeout = 1 async def receive_output(self, timeout=1): """ Receives a single message from the application, with optional timeout. """ # Make sure there's not an exception to raise from the task if self.future.done(): self.future.result() # Wait and receive the message try: async with async_timeout(timeout): > return await self.output_queue.get() env/lib64/python3.6/site-packages/asgiref/testing.py:74: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <Queue at 0x7f31d75e6550 maxsize=0 tasks=1> @coroutine … -
Django form.is_valid returning False where request.POST contains data from two forms
I am using the Django Provided User Model and along with that, I have also made a second model by the name of Account, in which I am storing the User's Profile Picture and Name. All this data is provided in a Single Form in the HTML file and both forms are dealt in a single View Function. This is my models.py file, from django.db import models from django.contrib.auth.models import User # Create your models here. class Account(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=255, null=True) profile_pic = models.ImageField(null=True, blank=True) ratings = models.FloatField(default=1000) date_joined = models.DateTimeField(auto_now_add=True, null=True) This is my forms.py file, from django.forms import ModelForm from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django import forms from .models import Account class UserForm(UserCreationForm): class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] class AccountForm(ModelForm): class Meta: model = Account fields = ['name', 'profile_pic'] Here's the complete register.html Template file, {% load static %} <!DOCTYPE html> <html> <head> <title>Register Account</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.1/css/all.css" integrity="sha384-gfdkjb5BdAXd+lj+gudLWI+BXq4IuLW5IT+brZEZsLFm++aCMlF1V92rMkPaX4PP" crossorigin="anonymous"> <style> body, html { margin: 0; padding: 0; height: 100%; background: #7abecc !important; } .user_card { width: 350px; margin-top: auto; margin-bottom: auto; background: #74cfbf; position: … -
What is the proper way to change custom user password?
I am working on my Django (DRF) application. A have a CustomUser model class CustomAccountManager(BaseUserManager): def create_superuser(self, email, user_name, password, **other_fields): ... def create_user(self, email, user_name, password, **other_fields): if not email: raise ValueError(_('You must provide an email address')) email = self.normalize_email(email) user = self.model(email=email, user_name=user_name, **other_fields) user.set_password(password) user.save() return user class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) user_name = models.CharField(max_length=150, unique=True) # Full name phone_number = models.CharField(max_length=20, unique=True) ... I have created a custom way to change password. I am sending current_password, new_password_verify and new_password_verify in body parameter. What is the proper way to implement password change in Django? class CustomUserViewSet(viewsets.ModelViewSet): def update(self, request: Request, *args, **kwargs): instance: CustomUser = self.get_object() serializer = self.get_serializer( instance, data=request.data, partial=True ) serializer.is_valid(raise_exception=True) self.perform_update(serializer) if getattr(instance, "_prefetched_objects_cache", None): instance._prefetched_objects_cache = {} return Response({ "is_password_updated": self.update_password(request, instance), # <-------UPDATE "result": serializer.data }) def update_password(self, request, instance): """update password if 'new_password_verify' and 'new_password' are in request""" if "current_password" in request.data and instance.check_password(request.data["current_password"]) and \ "new_password" in request.data and "new_password_verify" in request.data and \ request.data["new_password"] == request.data["new_password_verify"]: instance.set_password(request.data["new_password"]) instance.save() return True return False -
TimeoutError: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, .... Django
I currently develop a Django project and want to send email for email verification. Here is My Code settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST_USER = 'co******@gmail.com' EMAIL_HOST_PASSWORD = '***********' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = 'co******@gmail.com' SERVER_EMAIL = 'co******@gmail.com' views.py template = render_to_string('mail.html', {'email': email, 'code': temp_code}) send_mail( 'Email Verification', '', settings.EMAIL_HOST_USER, [email], fail_silently=False, html_message=template ) -
Pass Django's "to_field" argumento in model, two fields that have a UniqueConstraint
What I'm trying to accomplish is to have the "dependencia" field on Puesto model as Charfield, in order to use the natural keys and pass for example this "[NTRA. SRA. DE LA ASUNCION,Capital]" and that can be mapped to the Dependencia Model. I'm passing this arguments from a JSON fixture. Because the "descripcion" and "departamento" fields in "Dependencia" can't have the argument unique= True, I can't use them to point to those fields and finally get "dependencia" on Puesto model converted from int (because is pointing to the id field in dependencia which is the PK), to Charfield. Is there a way of use the constraint "unico_nombre_pordpto", or pass the field descripcion and departamento to "to_field"? What suggestions do you have? Thanks in advance. MODEL DEPENDENCIA class DependenciaManager(models.Manager): def get_by_natural_key(self, descripcion, departamento): return self.get(descripcion=descripcion, departamento=departamento) class Dependencia(models.Model): descripcion = models.CharField(max_length=300, blank=False, null=False) cod_institucion = models.PositiveIntegerField( blank=True, null=True, ) departamento = models.ForeignKey( Departamento, on_delete=models.PROTECT, blank=False, null=True, to_field="descripcion", ) objects = DependenciaManager() class Meta: constraints = [ models.UniqueConstraint( fields=["descripcion", "departamento"], name="unico_nombre_pordpto" ) ] def natural_key(self): return (self.descripcion, self.departamento) def __str__(self): return f"{self.descripcion}" MODEL PUESTO class Puesto(models.Model): numero = models.PositiveIntegerField(blank=False, null=False, primary_key=True) cargo = models.ForeignKey( Cargo, on_delete=models.PROTECT, blank=False, null=True, to_field="descripcion_cargo", ) dependencia = … -
how can I add sum rows in django import-export library?
How can I add sum row on the bottom of my table in exported xlsx file? I don't see anything like that in their doc but maybe you did something similar. I'd like to summarize only the total_price column. My resource looks like this: class CERequestResource(resources.ModelResource): related_component__service = Field(attribute='related_component__service') related_product__title = Field(attribute='related_product__title'') related_component__component_name = Field(attribute='related_component__component_name') related_component__task_description = Field(attribute='related_component__task_description') related_component__position = Field(attribute='related_component__position') number_of_units = Field(attribute='number_of_units', column_name='# of Units') related_component__margin = Field(attribute='related_component__margin') total_price = Field(attribute="total_price") model = CERequest fields = ('id', 'related_component', 'related_product', 'number_of_units', 'total_price', 'margin') -
updated cash page in Django
When is changed a record in the database , how to identify all the pages (url) related to this change, so that we can remove these cached pages from the server's cache with a signal. -
Django kubernetes connection Max retries exceeded with url
I'm trying to create a kubernetes job inside google cloud using django and when I call my rest_api view I'm getting this error: ConnectionRefusedError: [Errno 111] Connection refused During handling of the above exception, another exception occurred: urllib3.exceptions.NewConnectionError: <urllib3.connection.HTTPConnection object at 0x7fc745e58580>: Failed to establish a new connection: [Errno 111] Connection refused During handling of the above exception, another exception occurred: urllib3.exceptions.MaxRetryError: HTTPConnectionPool(host='localhost', port=80): Max retries exceeded with url: /apis/batch/v1/ (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7fc745e58580>: Failed to establish a new connection: [Errno 111] Connection refused')) Here is my kubec-config.yaml: apiVersion: v1 kind: Config clusters: - cluster: certificate-authority-data: DATA+OMITTED server: --- name: gke_---_europe-west1_cluster-1 users: - name: cluster-1 current-context: gke_---_europe-west1_cluster-1 contexts: - context: cluster: gke_---_europe-west1_cluster-1 user: gke_---_europe-west1_cluster-1 name: gke_---_europe-west1_cluster-1 spec: jobTemplate: spec: template: spec: containers: - name: cluster-1 image: cluster-1:v5 env: imagePullPolicy: IfNotPresent command: ['./Renderer'] args: ['project.json'] restartPolicy: OnFailure I got many of the information here by running kubectl config view inside google cloud and just copy and pasted them here. And this is my APIview: class ProjectExportView(APIView): def get(self, request, uuid): jobs = ["", "", ""] try: project = Project.objects.get(uuid=uuid) from utils.gke import kube_test_credentials, kube_cleanup_finished_jobs, kube_delete_empty_pods, kube_create_job import os # Testing Credentials kube_test_credentials() # We try to cleanup dead jobs … -
Django - CreateView form_valid() how can I access foreign key objects
I think I complicate this more because what I am using for the Foreign Key has a Choice setting and I have the Foreign Key set to show the human readable choice. Which seems to be what it is searching on. Strikes me as strange though because when I look at the return data it appears to be passing the primary key. Anyways maybe some code will help so: (as a caveat this is the 9 millionth view iteration and at this point I was at least kind of experimenting with different thing) views.py model = Ship fields = ['hull', 'name', 'debt'] template_name = 'crew/ship.html' success_url = reverse_lazy('crew_app:ship_list') def form_valid(self, form): hul = form.instance.hull hp = get_object_or_404(ShipHull, hull=hul) form.instance.hull_points_max = hp.hull_points form.instance.hull_points_cur = hp.hull_points return super().form_valid(form) models.py class ShipHull(models.Model): SHIP_TYPE = ( ('WF', 'Worn Freighter'), ('RTT', 'Retired Troop Transport'), ('SAV', 'Strange Alien Vessel'), ('UPS', 'Upgraded Shuttle'), ('RSS', 'Retired Scout Ship'), ('RSV', 'Repurposed Science Vessel'), ('BMV', 'Battered Mining Ship'), ('UMC', 'Unreliable Merchant Cruiser'), ('FDV', 'Former Diplomatic Vessel'), ('ALC', 'Ancient Low-Tech Craft'), ('BSW', 'Built from Salvaged Wrecks'), ('RMS', 'Retired Military Patrol Ship'), ) hull = models.CharField(max_length=200, choices=SHIP_TYPE) traits = ArrayField(models.CharField(max_length=200), blank=True) hull_points = models.IntegerField() debt = models.CharField(max_length=200) roll = IntegerRangeField(null=True) def __str__(self): … -
Display of Django ModelForm field validation errors in crispy forms
I am using the following ModelForm: class ListingQuoteForm(forms.ModelForm): author_phone = forms.CharField(validators=[validate_phone_number]) content = forms.CharField( label='Your message', min_length=50, widget=forms.Textarea(attrs={'rows': 4}), help_text='Please provide a few details about your race and your requirements', ) def __init__(self, *args, **kwargs): user = kwargs.pop('user', None) super().__init__(*args, **kwargs) if user.is_authenticated: self.fields['author_name'].initial = user.full_name(strict=True) self.fields['author_email'].initial = user.email self.fields['author_email'].disabled = True class Meta: model = QuoteRequest fields = ('author_name', 'author_email', 'author_phone', 'content') labels = { 'author_name': 'Your name', 'author_email': 'Your email', 'author_phone': 'Your phone number', } and rendering it in the following template: {% load crispy_forms_tags %} <div class="listing-section" id="quote-form"> <div class="listing-section-header"> {% if primary_category.quote_request_type == 'quote' %} <h2>Request a quote</h2> {% elif primary_category.quote_request_type == 'info' %} <h2>Request more info</h2> {% endif %} </div> <div class="listing-section-body"> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ quote_form.author_name|as_crispy_field }} {{ quote_form.author_email|as_crispy_field }} {{ quote_form.author_phone|as_crispy_field }} {{ quote_form.content|as_crispy_field }} <div class="form-group"> <button class="standard-button standard-button--submit" type="submit">Send</button> </div> </form> </div> </div> When the content field min length validation fails, a message is displayed like so: But when my custom phone number validation fails, the error displays under the field like so: How can I get my phone number validation error to display the same way the in-built min length validation does for the CharField?