Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to submit a form and display output without refreshing
I'm trying to create a simple calculator which gets an input number from the user and shows the calculated output below it. The code works fine but it redirects and reloads the page, obviously. I don't want that I want the output to be displayed as soon as the user fills the form. I have 0 knowledge of js and ajax so I would appreciate you guys helping me with that part. I searched a lot but couldn't understand what to do. this is my form: <form id="myform" method="POST"> {% csrf_token %} Enter first number: <input type="text" name="num1"><br><br> <input type="submit"> </form> and this is the output bellow the form I want: <h1>congrats!</h1> as simple as that. fill the form, submit and display a simple message without refreshing -
Ajax POST to an url then redirect to it
I'm building a web app where user can create markers on a leaflet map. Marker's details are saved in a backend with Django. My goal is to redirect the user to a detail page to fill marker's detail after clicking on the map. Here the js code to redirect to url create with an Ajax post. window.location.href = {% url 'create' %}; $.ajax({ url: {% url 'create' %}, data: { markers: markers_dict}, type: "POST" }).done(function (response) { console.log(response); }); but I'm struggling in the views.py because this redirect and AJAX post create two request one GET and another POST: def create_marker(request): if request.method == "POST": r = request.POST.get("markers") print(r) return JsonResponse({"response":"succeed"}) else: return JsonResponse({"response":"failed"}) It always returns the failed response even if it prints r in the console. How can I send these frontend data to the create url while redirect to this url and create a django from with these data ? -
How can I apply base.html file for extending to every template in django
Is there a way to extend base.html file in python django by default, I want it because I am overwriting {% extends %} tag in every html file -
Django ManytoMany Field Queryset for Exact and Similar Match
I have the following models: class Disease(models.Model): name = CICharField("Disease Name", max_length=200, unique=True) symptoms = models.ManyToManyField(Symptom, through='DiseaseSymptom', related_name='diseases') class Symptom(models.Model): name = CICharField("Symptom Name", max_length=200, unique=True) On the front-end, I have multiple select boxes where users can select multiple Symptoms to find disease and that will pass to Disease model as symptoms_selected params. I have the following get_queryset on Disease > views.py def get_queryset(self): params = self.request.query_params query_symptoms = self.request.GET.getlist('symptoms_selected') if query_symptoms: i = 0 queryset = Pattern.objects.all() while i < (len(query_symptoms)): symptom = [query_symptoms[i]] queryset = queryset.filter(symptoms__id__in=symptom) i=i+1 else: queryset = Pattern.objects.all() For eg: Disease Data: Disease A: Got Symptoms: A, B, C, D Disease B: Got Symptoms: A, D, P, Q Disease C: Got Symptoms: A, Q, X, Y Currently, if Users select 3 symptoms: A, D, Y. It returns Null. Instead of Null, I want to show users some similar matches with 2 and 1 symptoms. I want queryset will return: Exact match diseases i.e. 3 Symptoms matched diseases 2 Symptoms matched diseases 1 symptom matched diseases Can anyone tell me how can I achieve this? -
Input type file (multiple) not working in Django
I got a form with an input <form method="POST" enctype="multipart/form-data"> <input type="file" multiple> </form> When I upload files in that input, I'm trying to get those files with: request.FILES But I'm getting null object. Why is this happening? -
Django class based views: page "GET" content disappears after "POST" request is executed
I am building a homepage that has a dynamically updated blogs section and a BMI calculator section. Initially, the page loads perfectly fine. But the problem is that when I calculate the BMI (POST request) the page refreshes and the blogs section (GET) disappears. my urls.py urlpatterns = [ path('', HomeViews.as_view(), name='home_page'), my views.py class HomeViews(ListView, View): template_name="home_page.html" def get(self, request, *args, **kwargs): posts_diet = BlogModel.objects.filter(cat__title='Healthy Diet').order_by('-created_at')[:1] return render(request, 'home_page.html', { 'posts_diet' : posts_diet, }) def post(self, request, *args, **kwargs): if request.method == "POST": # get input height_metric = request.POST.get("height-metric") weight_metric = request.POST.get("weight-metric") #----bmi Formula----- if height_metric: bmi = float(weight_metric) / (float(height_metric)**2) else: bmi = 0 return render(request, 'home_page.html', { 'bmi': bmi, }) my home_page.html <div> {% for pst in posts_diet %} <div> <img src="uploads/{{ pst.blog_main_image }}" /> <div> <p>{{ pst.cat | striptags | slice:':50' }}</p> <p>{{ pst.created_at | date:"M d, Y" |striptags | safe }}</p> </div> <div> <h1>{{ pst.title | striptags | slice:':150' }}</h1> <button> </button> </div> </div> </div> {% endfor %} my terminal: # initial homepage request (everything loads perfectly fine) [24/Dec/2021 14:34:21] "GET /static/css/dist/styles.css HTTP/1.1" 200 30992 [24/Dec/2021 14:34:21,606] - Broken pipe from ('127.0.0.1', 65275) # on submitting POST request GET gets executed but GET content is … -
Django: Complex query sets take longer to execute
If I do an OR search filter on the fields of the model and the m2m model associated with it, the annotate, the query will take a long time to execute.(1500-2000ms) If I remove Q(tags__name__icontains=value) from the filter in the following queryset It works in about 30-50ms, so I think the cause is a problem with m2m. Filtering the m2m field from the model that is tied to m2m will loop through the entire through table, which in my opinion is time consuming. How can I rewrite the queryset to improve this? Video: 300k rows, Tag: 5k rows, video_tag_through: 1.3m rows # models.py class Tag(models.Model): name = models.CharField(unique=True, max_length=30) created_at = models.DateTimeField(default=timezone.now) ... class Video(models.Model): title = models.CharField(max_length=300) tags = models.ManyToManyField(Tag, blank=True) updated_at = models.DateTimeField(auto_now=True) ... class History(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) video = models.ForeignKey(Video, on_delete=models.CASCADE) ... class Favorite(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE video = models.ForeignKey(Video, on_delete=models.CASCADE) ... class Playlist(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) is_wl = models.BooleanField(default=False, editable=False) ... class Track(models.Model): playlist = models.ForeignKey(Playlist, on_delete=models.CASCADE, null=True) video = models.ForeignKey(Video, on_delete=models.CASCADE) ... This may sound complicated and confusing, but the query set looks like this # query Video.objects.annotate( is_viewed=Exists(History.objects.filter(user=user, video=OuterRef("pk"))), is_favorited=Exists( Favorite.objects.filter(user=user, video=OuterRef("pk")) ), is_wl=Exists( Track.objects.filter( playlist__user=user, playlist__is_wl=True, video=OuterRef("pk") ) ), … -
how to make all letters lowercase in Django model?
I want to make both the integer choices uppercase in my models.py, but even though I write them uppercase (CASE1, CASE2), they don't change in browser? Why? class Cases(models.IntegerChoices): CASE1 = 1, CASE2 = 2, -
Django UpdateView not loading forms with styles
I created a form using Django's UpdateView class, however, when the form loads it seems like the text boxes and text areas are not styled (looks like form.as_p style). Here is an example of exactly what I did. Views.py class UpdatePostView(UpdateView): template_name = 'Post/UpdatePost.html' model = Post fields = ['Title', 'Body'] success_url = reverse_lazy('BlogApp:main') def form_valid(self, form): form.instance.Title = form.cleaned_data['Title'] form.instance.Body = form.cleaned_data['Body'] form.instance.save() return super().form_valid(form) Here is how I loaded the form in UpdatePost.html: <form id="UpdatePostForm" method="POST"> {% csrf_token %} <div class="form-group"> <label for="PostTitle">{{form.Title.label}}</label> {{form.Title}} </div> <div class="form-group"> <label for="PostBody">{{form.Body.label}}</label> {{form.Body}} </div> <input class="btn btn-primary" type="submit" for="UpdatePostForm" value="Update"> </div> </form> -
How to design django model for different products features of buyerSeller App
I am new to django and trying to make buyerSeller djangoApp in which they can list their products them self from single submit form. I have to lots of products features to be in one form but i want seperate model and also i have used Javascript to show/hide specific form fields with category selection. I am stuck to design model and link them, So please help me how to design model and link each other. class Category(models.Model): name = models.CharField(max_length=40,blank=True, null=True) created = models.DateTimeField(auto_now_add=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True) def __str__(self): return self.name class Subcategory(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) name = models.CharField(max_length=40) created = models.DateTimeField(auto_now_add=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True) def __str__(self): return self.name class Listingproducts(models.Model): #Needs to be shown in all Category selections owner = models.ForeignKey(User, null=True, on_delete=models.SET_NULL) category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True) subcategory = models.ForeignKey(Subcategory, on_delete=models.SET_NULL, null=True) title = models.CharField(max_length=200,null=True) price = models.IntegerField(null=True) isnegotiate = models.CharField(max_length=200, choices=negotiate, null=True) adsexpiry = models.CharField(max_length=200, choices=ads_expiry, null=True) deliverycharges = models.CharField(max_length=200,blank=True,null=True) isdeliver = models.CharField(max_length=200, choices=isdeliver, null=True) deliveryarea = models.CharField(max_length=200, choices=delivery_area, null=True) conditions = models.CharField(max_length=200, choices=condition_type, null=True) userfor = models.CharField(max_length=200, blank=True, null=True) descriptions = models.TextField(max_length=200,null=True) featured_image = models.ImageField(null=True, default='default.jpg') # --------- Vechicles Features list -------------------- lotno = models.CharField(max_length=200,null=True) enginecc = models.IntegerField(blank=True,null=True) kilometersrun = … -
JS gives me POST 404 (Not Found) when I try to update my models in django with fetch - even though the same code works for other function
I'm working on a small project and I'm trying to use JS fetch to delete an item (called script) from the read later for a specific user (ReadLater is a separate model in Django). Prior to writing this function, I also wrote the same function for adding and deleting notes of users (where Note is also a separate model) and the same code works as it should, but for some reason, when I try to remove from Read Later, in fetch I get Post 400 - not found. I've been busting my head for over an hour now, just looking at the code, but I don't see where I'm mistaken. What am I missing? URLs: urlpatterns = [ ... # API path("add_note/<int:script_id>", views.add_note, name="add_note"), path("delete_note/<int:note_id>", views.delete_note, name="delete_note"), path("read_later/<int:script_id>", views.read_later, name="read_later"), ... ] View: @csrf_exempt @login_required def read_later(request, script_id): """Removing selected script from read_later""" if request.method == "POST": try: script = Script.objects.get(pk=script_id) user = request.user data = json.loads(request.body) # Double-checking if remove is what we want if data.get('action') == 'remove': rl = ReadLater.objects.get(user=user, script=script) rl.delete() return JsonResponse({"message":"Removed from Read Later successfully."}, status=201) except Script.DoesNotExist: return JsonResponse({"error": "Script not found"}, status=404) else: return HttpResponseRedirect(reverse('index')) JS: document.addEventListener('DOMContentLoaded', function() { document.querySelector('#mp_read_later_view').addEventListener('click', function(e) { const … -
Login with custom css with Django
So i have a django web and i want in the login page to custom a background image by static files. I tried to do it but it seems that it doesn't read my static filed. settings.py: STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static')] TNX! -
How to display data on Piechart from MYSQL database using django?
I am trying to extract data from the database and view the results on a pie chart, the charts should change dynamically when the values in the database change. But I am getting error in my script. Here is my view.py: def pie_chart(request): labels = [] data = [] queryset = Persons.objects.order_by('-id')[:3] for city in queryset: labels.append(city.firstname) data.append(city.salary) return render(request, 'breedingherdsummary.html', { 'labels': labels, 'data': data, }) Model.py: class Persons(models.Model): id = models.IntegerField(primary_key=True) firstname = models.CharField(max_length=100) lastname = models.CharField(max_length=100) address = models.CharField(max_length=100) dob = models.CharField(max_length=100) salary = models.IntegerField doj = models.DateField class Meta: db_table = "test" Here is my script: <script> var config = { type: 'doughnut', data: { datasets: [{ data: {{ data|safe }} , backgroundColor: [ '#FFA07A', '#E9967A', '#FA8072', '#F08080', '#CD5C5C' ], label: 'Salary' }], labels: {{ labels|safe }} }, options: { responsive: true, innerRadius: "40%" } }; window.onload = function() { var ctx = document.getElementById('pie-chart').getContext('2d'); window.myPie = new Chart(ctx, config); }; </script> Any help will be highly appreciated. Thank You! -
Understand `clean()` for customized form-wide data cleaning
In the source code of django/forms/forms.py class BaseForm(RenderableFormMixin): ... def clean(self): """ Hook for doing any extra form-wide cleaning after Field.clean() has been called on every field. Any ValidationError raised by this method will not be associated with a particular field; it will have a special-case association with the field named '__all__'. """ return self.cleaned_data If We want to perform additional form validation, we normally have below codes: class ContactForm(forms.Form): ... def clean(self): cleaned_data = super(ContactForm, self).clean() name = cleaned_data.get('name') email = cleaned_data.get('email') message = cleaned_data.get('message') if not name and not email and not message: raise forms.ValidationError('You have to write something!') Q: super().clean() does not perform any actual validation except return cleaned_data, how could ContactForm.clean() perform the basic data validation which is supposed to be invoked by super().errors or super().is_valid() or super.full_clean(). -
DjangoAdmin: POST data is empty when saving a model with a filefield
My application has been setup on AWS lambda, together with API gateway, S3, cloudfront, RDS. I'm having some troubles saving my model in DjangoAdmin that makes use of imagefield or filefields. For some reason, when I submit my model, my POST data is empty. This problem only comes forward upon saving a model that has a Filefield or Imagefield and when working online. So on localhost this isn't a problem at all and I can save images to my S3 bucket without a problem. The reason why I found out is because I got a csrftoken is missing error at first. So I made a custom csrf error view and printed out the request.POST data, where my csrfmiddleware token should be in. Any ideas why this only happens when I have a filefield or imagefield in my model? -
AbstractUser object has no attribute 'model'
Below is my model.py class CustomUser(AbstractUser): email = models.EmailField(unique=True, primary_key=True) I override the default user model by providing a value for the AUTH_USER_MODEL setting.py AUTH_USER_MODEL = 'home.CustomUser' But When I run server, I got AttributeError: 'CustomUser' object has no attribute 'model' What's problem in my code?? My django version = 4.0 -
I have a model Job with a manytomany field benefit. How will I make it accept pk value and str value?
How will I make the many-to-many field benefit in the job model which has a field name accept string also? If the new value is given it has to create a new instance also. now I'm getting the error "Incorrect type. Expected pk value, received str." { "benefit": [ 1 ], } what I have to input is { "benefit": [ 1,"new_instance" ], } and create new instance as the name in the benefits model. -
Is it possible to have generic a field in django models?
I am currently trying to work on designing a DB schema for a chat application. And I am having some confusion pertaining to the field type in which I should store the content of each message. Here is the partially completed DB schema of a chat message: ... ... ... # types of chat messages available TEXT = 'text' IMAGE = 'image' ... MESSAGE_TYPE = [ (TEXT, _('Chat message type : Text')), (IMAGE, _('Chat message type : Image')), .... ] # User class represents a user of the application class ChatMessage(models.Model): """ Class for storing chat messages between `Users` """ # type of the message message_type = models.CharField(choices=MESSAGE_TYPE, null=False) # user who created the text message sender = models.ForeignKey(User, on_delete=models.CASCADE, null=False) # user who is supposed to receive the message recipient = models.ForeignKey(User, on_delete=models.CASCADE, null=False) # timestamp at which the message was created created_at = models.DateTimeField(default=timezone.now) # whether the recipient has seen the message seen = models.BooleanField() # content of the chat message content = ..... I am planning to use encoder/decoder utilities to interpret the content for different types of chat messages using the message_type field. But I am having difficulty in specifying the field which is suitable to … -
Pre filled form data using id in Django?
Actually Everything is working fine and Id is also coming in URL but Data is not coming in fields when I click on Update button Here is my Code This is models that I have created #Models.py from django.db import models class User(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) mobile_number = models.IntegerField() cnic = models.CharField(max_length = 13) blood_group = models.CharField(max_length= 10) last_donation = models.DateTimeField(auto_now_add=True) This is MY views #views.py from django.shortcuts import render,redirect from .models import * from .forms import UserForm from django.urls import reverse def home(request): data = User.objects.all() #This function display All data on homePage context = { 'data': data } return render(request, 'home.html',context) def donor(request): if request.method == "POST": userform = UserForm(request.POST) #This Add New User if userform.is_valid(): userform.save() else: userform = UserForm() return render(request, 'donor.html',{'userform':userform,}) def Update(request,pk): context = {} if request.method == "POST": p_id = User.objects.get(pk = pk) form = UserForm(request.POST or None, instance= p_id) if form.is_valid(): form.save() return redirect(reverse('home')) context['form'] = UserForm() return render(request, 'update.html',context) #urls.py from django.urls import path from blood import views urlpatterns = [ path('',views.home, name='home'), path('donor/', views.donor, name = 'donor'), path('update/<int:pk>', views.Update, name='update'), ] This is Forms that I have created and check validation #forms.py from django.forms import ModelForm from … -
Django ModelField custom attribute
Very simple question: can you make a custom attribute for a Field? I have a Customer model with a bunch of Fields. Charfields, ForeignKeys,IntegerFields, BooleanFields etc. etc. When the form gets submitted for a new customer I want to export the data to an existing excel template, where cell names are B1 and value B2 for instance. So I was thinking to just give every field an 'cell position' attribute so I can just loop through the cells and easily assign each column their value, something like name = models.CharField(verbose_name='Name',max_length=30,'cell position' = 'B2'), Would that be possible? If so or not, how would I go about doing this? -
Unexpected FieldError, "Cannot resolve keyword 'conducted_by' into field. Choices are:..." while getting a queryset in Django
I have this model: class CTScan(models.Model): patient=models.ForeignKey(Patient, on_delete=CASCADE) amount=models.DecimalField(max_digits=10, decimal_places=2, default=0) date=models.DateField(default=datetime.date.today) conducted_by=models.CharField(max_length=4, default=None) remarks=models.TextField(max_length=500, blank=True, default=None) ctscan_date=models.DateTimeField(auto_now_add=True) And I have turned the conducted_by field into a radioselect field in forms.py: class CTScanForm(ModelForm): PARTY_SELECT = ( ('k', 'KCC'), ('o', 'OOPL'), ) conducted_by=forms.CharField(widget=forms.RadioSelect(choices=PARTY_SELECT, attrs={'class': 'form-check-inline'})) class Meta: model=CTScan fields='__all__' labels={ 'conducted_by':'Conducted By', } widgets={ 'date': DateInput(attrs={'type': 'date'}), } When I make a query in views.py like: ct_kcc=IpdReport.objects.filter(ctscan__date__range=(prev1, prev2), conducted_by='k') It throws a FieldError: Cannot resolve keyword 'conducted_by' into field. Choices are: approvedpackage, approvedpackage_id, claimedpendingcases, ctscan, ctscan_id, discharge, discharge_id, id, lockdata, lockdata_id, ongoingreport, package, package_id, patient, patient_id, radiations, radiations_id, realization, realization_id, reclaimedrepudiation, repudiatedclaims, unclaimedpendingcases What is wrong with my code? -
Typerror: object is not subscriptable Django test
I have some problems with my tests in Django. The ide is that I create questions for my learning platform, and I want to verify that the questions are actually created. The problem is that (from what I understand) I try to put a list, objects that in a list cannot fit. Do you have any ideas how I can correct this? Thank you very much! Error: response.context['latest_question_list'], TypeError: 'NoneType' object is not subscriptable The test: def test_two_types_questions(self): """ The questions index page may display multiple questions. """ lab1 = Lab.objects.create(lab_name="test lab past question", pub_date=datetime.now(), lab_theory="test lab past question") question1 = QuestionMultipleChoice.objects.create(lab=lab1, question='This is a test question', option1='1', option2='2', option3='3', option4='4', answer='1') question2 = QuestionFillText(lab=lab1, text1='1', text2='2', answer='1') response = self.client.get(reverse('labs:index')) print(response) self.assertQuerysetEqual( response.context['latest_question_list'], [question1, question2], ) -
Understand `_html_output()` from Django Forms Source Code
Below source code is from django/forms/forms.py class BaseForm(RenderableFormMixin): def _html_output(self, normal_row, error_row, row_ender, help_text_html, errors_on_separate_row): "Output HTML. Used by as_table(), as_ul(), as_p()." How is this private method _html_output() used / invoked by as_table(), as_ul(), as_p() please ? I did not find out from the source code. -
MultiValueDictKeyError while trying to add image to my blog post
I am trying to add image to my blog post but when i added this to my code image = request.Post['image'] And i keep getting errors. -
Django: Unable to save the model instance
I have models defined like the below: class Device(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=50) owner = models.ForeignKey(Customer, null=True, on_delete=models.CASCADE) def __str__(self): return self.name class DeviceReadings(models.Model): device = models.ForeignKey(Device, on_delete=models.CASCADE) reading = models.FloatField() timestamp = models.DateTimeField() And I am trying to save models like below: device = Device.objects.get(pk=device_id) r = DeviceReadings(device_id=device, reading=reading, timestamp=timestamp) r.save() It gives an error that Invalid UUID format. It works if I set device.pk. I am not so well-versed in Django, unable to understand why the instance is not being saved.