Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to automatically choose related model using field value
Assume, we have model class BaseModel(models.Model): is_a = models.BooleanField() and two models related to this one: class A(models.Model): value_1 = models.IntegerField() base = models.ForeignKey(BaseModel, related_name='a') class B(models.Model): value_1 = models.IntegerField() value_2 = models.IntegerField() base = models.ForeignKey(BaseModel, related_name='b') What I need is to refer to A or B depending on is_a property. For example, base = BaseModel.objects.get(id=1) if base.is_a: obj = A.objects.create(value_1=1, base=base) else: obj = B.objects.create(value_1=1, value_2=2, base=base) return obj or if base.is_a: queryset = base.a.all() else: queryset = base.b.all() return queryset i.e., every time I have to check the is_a property. Is there more graceful way? There are two only related models, A and B, no other ones will appear in the nearest future. Part of the problem can be solved with django-polymorphic, e.g.: class A(PolymorphicModel): ... class B(A): ... This allows to retrieve all A's and B's with one request like base.b.all(), but the problem here is that every B creates instance of A, which is unwanted. I've considered GenericForeignKey as well. As far as I understood it has a number of limitations like "1) You can't use GenericForeignKey in query filters ; 2) a GenericForeignKey won't appear in a ModelForm" (from GenericForeignKey or ForeignKey). -
How to return manytomanyfield as object in Django RestFramework API
I tried to create an API with Django RestFramework, so i created 2 models Note and Task and have a ManyToManyField in Note model so i can put many Task in a Note but the API i created don't return full object feature but just the id. Here is my code: class NoteAPI(ListAPIView): serializer_class = NoteSerializer queryset = Note.objects.all() Here is my models: class Task(models.Model): task = models.CharField(max_length=255, null=False, blank=False) detail = models.CharField(max_length=255, null=True, blank=True) completed = models.BooleanField(default=False) priority = models.IntegerField(default=0) def __str__(self): return self.task class Note(models.Model): title = models.CharField(max_length=255, null=False, blank=False) priority = models.CharField(max_length=1, choices=PRIORITY_CHOICES, default="B") detail = models.CharField(max_length=255, null=True, blank=True) completed = models.BooleanField(default=False) task = models.ManyToManyField(Task, related_name="note_task", blank=True) process = models.IntegerField( default=0, validators=[max_int_value]) def __str__(self) -> str: return self.title + " is "+ str(self.process) + "% completed" And i want the out put can looks like: [ { "id": 2, "title": "Sleep", "priority": "F", "detail": "Don't do it, stay awake and do your job", "completed": false, "process": 0, "task": [ { "id": 1, "task": "Go to bed", "completed": false }, { "id": 2, "task": "Start counting", "completed": false } ] } ] But it actually be like this [ { "id": 2, "title": "Sleep", "priority": "F", "detail": "Don't … -
ran into error while building Django/PostgreSQL app with docker-compose
While trying to create Django/PostgreSQL app as mentioned in here I'm getting following error : db_1 | db_1 | PostgreSQL Database directory appears to contain a database; Skipping initialization db_1 | db_1 | 2021-12-19 14:50:52.192 UTC [1] LOG: starting PostgreSQL 14.1 (Debian 14.1-1.pgdg110+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 10.2.1-6) 10.2.1 20210110, 64-bit db_1 | 2021-12-19 14:50:52.193 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432 db_1 | 2021-12-19 14:50:52.193 UTC [1] LOG: listening on IPv6 address "::", port 5432 db_1 | 2021-12-19 14:50:52.199 UTC [1] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432" db_1 | 2021-12-19 14:50:52.231 UTC [26] LOG: database system was interrupted; last known up at 2021-12-19 14:49:29 UTC web_1 | Watching for file changes with StatReloader web_1 | Performing system checks... web_1 | web_1 | System check identified no issues (0 silenced). db_1 | 2021-12-19 14:50:53.782 UTC [27] FATAL: the database system is starting up web_1 | Exception in thread django-main-thread: web_1 | Traceback (most recent call last): web_1 | psycopg2.OperationalError: FATAL: the database system is starting up web_1 | web_1 | web_1 | The above exception was the direct cause of the following exception: web_1 | web_1 | Traceback (most recent call last): web_1 | File … -
How to create an array inside an object when working with MongoDB using Django?
I am working on a project where I want my user model to have this structure. structure { "_id":{ "$oid":"61bf3e026ffc7993a082773e" }, "email":"user@domain.com", "role":"student", "type":"t1", "fname":"ABC", "from":{ "org-user":[ "83bf3e026ffc7993a0827731", "78bf3e026ffc7993a0827731" ] } } In this model, "from" is the object which has one key "org-user". This "org-user" is an array of mongodb object IDs. This is the code I have written so far. from djongo import models class User(models.Model): class Meta: db_table = "users" _id = models.ObjectIdField() email = models.EmailField( max_length=255, unique=True, ) role = models.CharField(max_length=255, default="student") type = models.CharField(max_length=255, default="internal") fname = models.CharField(max_length=255) any idea on how I can achieve this in Django? -
how to update only the file field in model using django rest..i use angular as frontend
I want to update only specific fields in my model. This is my models.py class CheckinQnResult(models.Model): client = models.ForeignKey(User, on_delete=models.CASCADE,null=True, blank=True,related_name='client_create') appt = models.ForeignKey(Appointment, null=True, blank=True, on_delete=models.SET_NULL, related_name='appt_qn') is_first_visit = models.BooleanField(default=False) document = models.FileField(upload_to='documents', null=True, blank=True) duration_of_sickness = models.CharField(max_length=100, null=True, blank=True) age_noticed = models.CharField(max_length=100, null=True, blank=True) first_sought_age = models.CharField(max_length=100, null=True, blank=True) med_treated = models.CharField(max_length=1000, null=True, blank=True) I want to update only specific fields in my model. This is my view.py class DocumentView(ViewSet): model = CheckinQnResult serializer_class = DocumentAlldataSerializer permission_classes = [IsAuthenticated] authentication_classes = [BasicAuthentication, TokenAuthentication, JSONWebTokenAuthentication] def create(self,request): serializer = self.serializer_class(data=request.data) if serializer.is_valid(): ch_qn = serializer.save() appt = Appointment.objects.get(id=request.data.get('appt_id')) appt.save() ch_qn.appt = appt ch_qn.save() return Response({'status': 'success', 'message': 'Check in questions submitted successfully'}, status=status.HTTP_200_OK) else: return Response(serializer.errors) def getdocument(self,request): queryset = CheckinQnResult.objects.filter(client=request.user) serializer = DocumentAlldataSerializer(queryset,many=True) return Response({'status':'success','data':serializer.data},status=status.HTTP_200_OK) ) def update(self, request, *args, **kwargs): partial = kwargs.pop('partial', False) instance = CheckinQnResult.objects.get(id=request.data['id']) serializer = self.serializer_class(instance, data=request.data, partial=partial) serializer.is_valid(raise_exception=True) self.perform_update(serializer) return Response({'status': 'success', 'data': serializer.data}, status=status.HTTP_200_OK) def delete(self, instance): instance = CheckinQnResult.objects.get(id=self.request.GET.get('id')) instance.delete() return Response({'status': 'success', 'message': 'Document Deleted successfully'}, status=status.HTTP_200_OK) I want to update only specific fields in my model. This is my serializer.py class DocumentAlldataSerializer(serializers.ModelSerializer): appt = AppointmentSerializer() client=UserSerializer() class Meta: model = CheckinQnResult fields = '__all__' extra_fields = ['appt','client'] Here … -
refresh_from_db in proxy model at Django, Process finished with exit code -1073741571 (0xC00000FD)
In Django project, I have a class, "ClassName" that has a table in postgresql. I also have Proxy class, inherit from "ClassName", with name "ProxyClassName". if run refresh_from_db() on instance of "ProxyClassName", everything is fine, but if I specify any fields, refresh_from_db(fields=['field1', 'field2', 'field3']), code will crash with error "Process finished with exit code -1073741571 (0xC00000FD)" I see it has something to do with stack overflow and stack size (Process finished with exit code -1073741571 (0xC00000FD) in Python), but how should I prevent this from happening? -
How to make my edit function redirect to the Post option. Django
I am creating an edit option for my entry. But instead of redirecting to the entry page, it is taking me to the addpage to create a new form. How do I redirect to the edit page. Also, how do I make sure that the users previous input would reflect when they click on the edit button. I used initials - is this the best way to do it since I'm not using models but rather forms.Form. VIEWS.PY class AddPageForm(forms.Form): title = forms.CharField(max_length=20) content = forms.CharField(widget=forms.Textarea( attrs={ "class": "form-control", "placeholder": "Tell us more!" }) def edit_page(request, title): entry = util.get_entry(title) if request.method == "POST": form = AddPageForm(request.POST, initial={ "title": title, "content": content }) if form.is_valid(): util.save_entry(title, content) return redirect('encyclopedia:entrypage', title=title) else: form = AddPageForm() return render(request, "encyclopedia/editpage.html", {"form":form}) EDIT PAGE {% block body %} <h1>Edit {{ title }}</h1> <form action="" method="post"> {% csrf_token %} {% form %} <input type="submit" value="Submit" class="btn btn-secondary"> </form> ENTRY PAGE {% block body %} {{ content|safe }} <a href="{% url 'encyclopedia:editpage' title=title %}" class="btn btn-primary">Update</a> <!-- <input="text" name="title" value="{{game.title}}" /> <input="text" name="genre" value="{{game.genre}}" /> --> {% endblock %} URLS.PY app_name = "encyclopedia" urlpatterns = [ path("add_page", views.add_page, name="addpage"), path("edit_page/<str:title>", views.edit_page, name="editpage") ] -
how to return FileResponse AND reload form in Django
I'd like to have two buttons: [save] and [save and generate PDF] for now i have a condition: if show_pdf: return HttpResponseRedirect('/show_pdf_page/') else: return render(request,'project/edit.html', context) And if I press save it reloads project/edit.html, if save and generate - it opens adobe reader with my pdf. As expected. But if i return to browser I can see the edit.html before pressing button - and I can't use it anymore - NoReverseMatch at /edit/ Which is also correct, because I didn't run render(request,'project/edit.html', context) But maybe it is possible to do both? First generate pdf page, then render? Or generate in second tab and render in this? No ideas for now And I don't want to use target="_blank", because I have to validate form before (if show_pdf) -
Django - Returning full exception trace to front-end on a 400
So just for closed beta and internal testing purposes I'm trying to return the exception with the 400 error in my Django server. Here is an example below of how I am doing this in Django code. I have a partner working on the front-end and they said they can't get the error out of the 400 response. I assumed it'd be in like response.body['error']. How can I send back a 400 with the full error trace in a way that can be pulled out by the front-end? except Exception as e: return Response(dict(error=str(e), user_message=error_message_generic), status=status.HTTP_400_BAD_REQUEST) -
error occured while reploying django app on heroku
2021-12-19T13:18:18.028596+00:00 app[web.1]: File "", line 953, in _find_and_load_unlocked 2021-12-19T13:18:18.028635+00:00 app[web.1]: File "", line 219, in _call_with_frames_removed 2021-12-19T13:18:18.028675+00:00 app[web.1]: File "", line 1006, in _gcd_import 2021-12-19T13:18:18.028714+00:00 app[web.1]: File "", line 983, in _find_and_load 2021-12-19T13:18:18.028764+00:00 app[web.1]: File "", line 965, in _find_and_load_unlocked 2021-12-19T13:18:18.028834+00:00 app[web.1]: ModuleNotFoundError: No module named 'home' 2021-12-19T13:18:18.292460+00:00 heroku[web.1]: Process exited with status 1 2021-12-19T13:18:18.370187+00:00 heroku[web.1]: State changed from starting to crashed 2021-12-19T13:21:06.146372+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=aai-mes.herokuapp.com request_id=2b6669e7-58ca-4754-a66e-ccd32ef5e49b fwd="152.57.134.21" dyno= connect= service= status=503 bytes= protocol=https 2021-12-19T13:21:06.532523+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=aai-mes.herokuapp.com request_id=d2c98d53-350b-4f79-84db-93cf40fb1104 fwd="152.57.134.21" dyno= connect= service= status=503 bytes= protocol=https -
Django downloading a file
i have a db i made it with Django, and with the models.CharField I created the path how the users going to upload a file in their post. in MEDIA_URL = "/media/" but i tried to let the user download the content (the file) throw a link or just a click. how can i do that! i have a multiple files name in my models.py like this: files_Tensile = models.FileField(blank=True, null=True, upload_to="chapters/%Y/%m/%D") files_Charpy = models.FileField(blank=True, null=True, upload_to="chapters/%Y/%m/%D") files_Modulus = models.FileField(blank=True, null=True, upload_to="chapters/%Y/%m/%D") Diagramm_Hohen_Temp = models.ImageField(blank=True, null=True, upload_to="chapters/%Y/%m/%D") files_Metallo = models.FileField(blank=True, null=True, upload_to="chapters/%Y/%m/%D") Gefüge = models.ImageField(blank=True, null=True, upload_to="chapters/%Y/%m/%D") Diagramm_Wärmebehandlung=models.ImageField(blank=True,null=True,upload_to="chapters/%Y/%m/%D") files_Density = models.FileField(blank=True, null=True, upload_to="chapters/%Y/%m/%D" the views.py: def download(request, path): file_path = os.path.join(settings.MEDIA_ROOT, path) if os.path.exists(file_path): with open(file_path, 'rb') as fh: response = HttpResponse(fh.read(), content_type="application/vnd.ms-excel") response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path) return response raise Http404 in the html: <td><a href="media/files_Density/download"> Download Files</a></td> I get the error, Page not found (404). can anyone please explain how to fix this? -
I want to write an a-cinch export report using python- django
I have an heavy data which I want to export, I have problem that because it's heavy it is timeout and fail. Do you know I can I write an a-cinch report using django? -
How to connect two applications and hit the API of the first application1 from application2
How can I connect two applications with the scenario below? Application1: Our infrastructure was created on AWS with python-django and react, its a private VPC that i can only access via SSH to the EC2 bastion instance (as far as to be able to write codes into)and the way the backend was deployed to create the backend URL api.mywebsite.com (which has multiple endpoints) was through cloudfront and Route53. (www.mywebsite.com was built via s3 and can talk to the backend api.mywebsite.com). Application2: (This is a client infrastructure) At this time i haven't met the client to know what their system is made of but regardless i need to find a way write some codes on this system when a specific event is triggered to send data to an API endpoint of Application1. What would be the best way to implement such an API to connect Application1 and Application2? This is pretty much the same way that someone would use an API like STRIPE...I guess, but i am not sure how to achieve such result... thank you in advance -
Iterating over queryset of dictionary
I have a queryset dict which I want to access in template, I have following queryset: <QuerySet [{'membership__name': 'm1', 'membership_count': 2}, {'membership__name': 'm2', 'membership_count': 1}]> I have tried some options but can't seem to get what I want. {% for key, value in reports_data %} {{key}} : {{value}} {% endfor %} Can anyone please help me how can I do it. -
Increment value in while-loop based on rank
I am currently working on a Django application where a user can track played golf rounds and compare them to friends. Some background on this: Every player has a handicap which gives them a number of extra strokes on each course they are playing. These extra strokes are distributed over all holes depending on the difficulty of the hole (called HCPI, the number of the hole is not equal to its HCPI). E.g. you are playing an 18 hole course. If you get 18 extra strokes, they are equally added to the par of every hole. If you get 20 extra strokes, you get one stroke added to the par of hole 1-18 and one stroke added to the hole ranked 1 and 2. And so on. I am currently stuck in adding the extra strokes on the current par. The problem itself seems to need a while-loop and some javascript. But I wonder if my whole set-up is wrong? As I want to add the whole table to a database later on, it might be a better solution to add the extra strokes there. Any input is appreciated as I would like to have a solution where the user … -
Using aggregation on subquery in Django ORM
I have a table like this Category Subcategory Sub_subcategory Cat_1 Subcat_1 Sub_subcat_1 Cat_1 Subcat_1 Sub_subcat_2 Cat_1 Subcat_2 Sub_subcat_3 Cat_2 Subcat_2 Sub_subcat_4 Cat_3 Subcat_3 Sub_subcat_5 And I need to find in how many categories each subcategory appears. So my expected output based on above table would be: Subcategory Total Subcat_2 2 Subcat_1 1 Subcat_3 1 So I can get that by running following SQL query: SELECT subcategory, count(*) total FROM ( SELECT DISTINCT subcategory, category FROM table_1 ) as temp_table GROUP BY subcategory ORDER BY total DESC I spent a lot of time trying to get the same result with Django ORM but wasn't able to get it done. I expected this code to work: subquery = Table1.objects.values('subcategory', 'category').distinct() results = subquery.annotate(total=Count('*')).values('subcategory', 'total').order_by('-total') But it works exactly the same as without 'distinct()' in subquery, so it counts all categories for every subcategory. I also tried to find similar case in other questions, but those with subqueries usually relate to JOINing tables and using OuterRef, here it is more like getting results based on temporary table that is created by subquery. Does anyone know how can I achieve that (or if it's even possible)? -
retrieve data from views to html in template in django
from django.shortcuts import render from django.http import HttpResponse mList=[ { 'id':1,'title':'ECOMMERCE WEBSITE','description':"ECOMMERCE IS GOOD" },{ 'id':2,'title':'Graphic WEBSITE','description':"graphic IS GOOD" },{ 'id':3,'title':'PORTFOLIO WEBSITE','description':"portfolio IS GOOD" }, ] def single(request,pk): projectObj = None for i in mList: if i['id'] == pk: projectObj = i return render(request,'appone/single-project.html', {'pobj': projectObj }) and in html in template folder I use: <h1> {{pobj.title}}--{{pobj.description}}</h1> but nothing appears there:( whats the problem ? It should work fine -
Django admin chained select using django-select2
I have a standard model City with a Foreign Key to Country. In my django admin, I want to implement the so-called chained select, i.e. first we pick the country and then based on that we pick the city. It would be perfect if I could also pick the city first and then get the country on the spot. Also, what makes this case more complicated is that we pick cities and countries in an inline. How do I do this? -
Django - Ensure ordering of response data is newer first
So I have some code below that returns posts that are newer than a post with post_uuid given. This is ensured because I force an ordered uuid scheme where each Post is given a uuid in order of creation. I want to enforce that that the returned serializer.data is ordered by Post creation data, with the newest best first or index=0 and oldest being last. How do I ensure this? view.py def query_to_full_post_data_serializer(request, post_query_set: QuerySet): query_set_annotated = post_query_set.annotate( creator_username=F('creator__username'), creator_avatar_url=F('creator__avatar') ) return FullPostDataSerializer(query_set_annotated, many=True) @api_view(['GET']) def get_newer_posts(request, post_uuid, count): query = generate_followee_or_join_goal_follow_query(request) query = query & Q(uuid__gt=post_uuid) serializer = query_to_full_post_data_serializer(request=request, post_query_set=Post.objects.filter(query).order_by('uuid')[:count]) return Response(serializer.data, status=status.HTTP_200_OK) serializer.py class FullPostDataSerializer(serializers.ModelSerializer): creator_username = serializers.SlugField() creator_avatar_url = serializers.SlugField() class Meta: model = Post fields = ( 'body', 'created', 'creator_username', 'uuid', 'creator', 'creator_avatar_url') Tried Solutions serializer.data.reverse() doesn't reverse the list for some reason. -
View not returning ID
I have a view that requires two args to be provided. Project_id and Questionnaire_ID There is a Project and Questionnaire model. class Questionnaire(models.Model): title = models.CharField(max_length=50, blank=False, unique=True) class Project(models.Model): project_name = models.CharField(max_length=50, blank=False, unique=True) project_website = models.URLField(max_length=50, blank=True) project_description = models.TextField(blank=True) I have a project details page, which is basically just a project landing page and from there I have a link to the questionnaire. the link is formed via a For loop {% for item in questionnaire %} <a class="dropdown-item" href="{% url 'questions' project.id questionnaire.id %}?next={{ request.path|urlencode }}">Questionnaire</a> {% endfor %} and my url conf is path('questions/<int:project_id>/<int:questionnaire_id>', view=add_fundamental_answers_view, name="questions"), but when i load the project_details page i get an error Reverse for 'questions' with arguments '(1, '')' not found. 1 pattern(s) tried: ['questions/(?P<project_id>[0-9]+)/(?P<questionnaire_id>[0-9]+)$'] So it looks like the questionnaire_id is not being past in, but i'm not sure why? def add_fundamental_answers_view(request, project_id, questionnaire_id): project = get_object_or_404(Project, pk=project_id) questionnaire = Question.objects.filter(questionnaire_id=questionnaire_id) next = request.POST.get('next', '/') if request.method =='POST': formset = AnswersForm()(request.POST) if formset.is_valid(): answer = formset.save(commit=False) answer.project_name = project answer.save() return HttpResponseRedirect(next) else: form = AnswersForm() return render(request, 'pages/formset.html', {'project': project, "form": form,'questionnaire':questionnaire}) Any ideas where I'm going wrong? Thanks -
I am getting TemplateDoesNotExist error in Django version 4.0
urls file from django.urls import path from django.urls.resolvers import URLPattern from . import views urlpatterns = [ path('hello/', views.say_hello), path('name/', views.name), path('tp/', views.tp) ] #views file def tp(request): return render(request, 'TP.html') -
What to use: Provide canvas frontend using backend api
I am thinking about a web page providing some 2d-like animations based on backend data. The animations/action change frequently based on the backend data. . Currently I am thinking about using React and combine with canvas So my thinking was to provide the data via some end point as json and using react to build the frontend.But using canvas in react found me only a few links. [1]: https://thibaut.io/react-canvas-components The most similar question I found on stack was this [2]: Mixing HTML5 Canvas and Python. But the answers are almost a decade old. Can someone provide me some basic approach / links so I am not starting totally off? Thank you in advance! cheers! hobo -
Django form error: django.db.utils.IntegrityError: UNIQUE constraint failed: legal_useragreedtolegal.user_id
Whenever, I call form.save() I get "django.db.utils.IntegrityError: UNIQUE constraint failed: legal_useragreedtolegal.user_id" I think this might be because I have a oneToOneField and Django is trying to save to UserAgreedToLegal and User Model but the User model already has that ID, so the unique constraint fails, but not sure. I am wondering how I can fix this issue. I listed my model, form, and view code below models.py import uuid from django.contrib.auth.models import User from django.db import models from django.utils import timezone as django_timezone class UserAgreedToLegal(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) agreed_first_terms_of_service = models.BooleanField(default=False, blank=False, null=False) date_agreed = models.DateField(null=True, default=django_timezone.now) uuid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) def __str__(self): return self.user.username forms.py from django import forms from legal.models import UserAgreedToLegal class TermsOfServiceAgreementForm(forms.ModelForm): class Meta: model = UserAgreedToLegal fields = [ 'agreed_first_terms_of_service' ] views.py if request.method == 'POST': form = TermsOfServiceAgreementForm(request.POST) if form.is_valid(): form.clean() terms_of_service_agreement = form.save(commit=False) terms_of_service_agreement.user = request.user terms_of_service_agreement.save()``` -
http://localhost:8000/token/ 400 (Bad Request)
in django, i have the jwt module for drf (it is called simple-jwt), and i have set up the urls as instructed in the docs, how do i fix the error, in backend side, the whole login process is supposed to be POST request: urls.py urlpatterns = [ path('token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), now for react part (frontend): function Login(){ let [login,setLogin] = useState({ email: '', password:'' }); let cookie = Cookies.get('csrftoken'); const { email, password } = login; function handleChange(e){ console.log(e.target.value); setLogin({ ...login, [e.target.name]: e.target.value }); } function handleSubmit(e){ const token = localStorage.getItem('token'); e.preventDefault(); axios.post('http://localhost:8000/token/',login,{withCredentials:true},{headers: {'Content-Type': 'application/json', 'X-CSRFToken': cookie,'Access-Control-Allow-Origin':'*','Authorization': `Bearer ${token}`}}) .then(res => { console.log(res.data); } ) .catch(err => console.log(err)) } return ( <div className="container"> <form method='post' onSubmit={handleSubmit}> <h1>Login</h1> <label> Email: <input type='text' name = 'email' value={email} onChange={e=>handleChange(e)} required/> </label> <label> Password: <input type='password' name = 'password' value={password} onChange={e=>handleChange(e)} required/> </label> {isLoggedin = true} <button type='submit'>Login</button> </form> <p className='mt-3'> Don't have an Account? <Link to='/signup'>Sign Up</Link> </p> </div> ); }; export default Login; ``` this is login component, I am getting bad request (400) error, but I cant find out why, and how to fix it? if there is anything else (more code, or more information) to add, … -
How do I override Django's default form error templates - at the project level?
I know this topic has been asked a few times before on StackOverflow, and the docs seem pretty clear about how to do it, but it's not working for me and I'm stumped. Overriding at the project level makes the most sense to me so I created a templates directory outside my app directories - at the same level as manage.py - and I added that directory path to my TEMPLATES['DIRS'] setting TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'APP_DIRS': True, 'DIRS': [BASE_DIR / 'templates'], # Allow overriding of other apps templates 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] I checked where the form is getting its error template by printing the path in the View print(form.errors.template_name) The print statement printed django/forms/errors/dict/default.html so I put a new custom default.html file inside mydjangoproject/templates/django/forms/errors/dict/. This doesn't work however. My new default.html template file isn't being used. Any ideas for what I'm doing wrong?