Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ModelAdmin autocomplete_fields
I did not use the admin.py but can I use the autocomplete fields in the frontend like a webshop search field? regards Christopher. -
form submission not working when trying to send an email in Django
I have created a simple system to keep patient records. I have added a patient to the system and now i have created a view to retrieve patient name and email address from the system (GET method) and is working. The challenge is sending an email to the selected patient using the patient's registered email address with some additional information that is Subject and Body of the email from a form on form submission (POST method) is not working. the form is not being submitted. I have send some emails before using the same EmailForm from forms.py in a different view and is working. here is my views.py def send_client_mail(request, pk): patient = Patient.objects.get(id=pk) address = patient.email if request.method == "POST": form= EmailForm(request.POST) if form.is_valid(): name = form.cleaned_data.get('subject') address = address message = form.cleaned_data.get('email_body') send_mail( name, message, 'myemailaddress@gmail.com', [address, ], fail_silently=False) messages.info(request, 'Email was sent successfully !!') else: form = EmailForm(None) return render(request, 'client_email.html', {'title': 'send email to ', 'form': form, 'patients': patient) here is my forms.py class EmailForm(forms.Form): subject = forms.CharField(required=False, label='Email subject', widget=forms.TextInput(attrs={'size':'40', 'style':'font-size:medium'})) email_address = forms.CharField(required=False, label='Recepient Email Address', widget=forms.TextInput(attrs={'size':'40', 'style':'font-size:medium'})) email_body = forms.CharField(required=False, label='Email body/message', widget=forms.Textarea(attrs={'size':'10', 'style':'font-size:medium;', 'rows' :4})) def clean_subject(self): subject = self.cleaned_data.get('subject') if subject … -
NoReverseMatch Reverse for 'ux' not found. 'ux' is not a valid view function or pattern name
I am getting below error only when i am trying to access the website via domain name. When i access my website using ip address (by running python manage.py runserver) it doesn't throw an exception. Please check using below: https://adhocdevices.com/ Please help me in resolving this issue. My urls.py is as below: path('category/<int:pk>/',views.CategoryShow), path('about/',views.about,name='about'), path('contact/',views.contact,name='contact'), path('product/',views.product,name='product'), path('ux/',views.ux,name='ux'), path('webservices/',views.webservices,name='webservices'), path('iotdevices/',views.iotdevices,name='iotdevices'), path('digitaloceanhosting/',views.digitaloceanhosting,name='digitaloceanhosting'), path('devops/',views.devops,name='devops'), path('dataanalytics/',views.dataanalytics,name='dataanalytics'), path('chatmessanger/',views.chatmessanger,name='chatmessanger'), path('azurecloudsupport/',views.azurecloudsupport,name='azurecloudsupport'), -
Making Django admin and using rest API for data accessing and posting , front end using html css
I'm pretty confused and making and making new admin thing from the start using start bootstrap admin template but how do I authenticate the admin login on my admin model with session and cookies record and everything using rest api Any help will be appreciated? -
I implemented a star rating system for delivery man in django by users but i am stuck at how to calculate the average
I have a model name Ratings and its connected to custom user model through foreignkey relationship.i used javascript to post data and get ratings in the backend by get method using id but the problem is rating process works fine but it just upgrades the current queryset when ever regarded delivery man gets rated. so how do i calculatye the average as it does not store the previous querysets rather its just upgrades the queryset of that particular deliveryman views.py def rate_user(request): if request.method == 'POST': el_id = request.POST.get('el_id') val = request.POST.get('val') print(val) obj = Ratings.objects.get(id=el_id) obj.rated_number = val obj.save() return JsonResponse({'success':'true', 'score': val}, safe=False) return JsonResponse({'success':'false'}) models.py class Ratings(models.Model): rated_user = models.ForeignKey(User,on_delete=models.CASCADE,blank=True,null=True) avg_rating = models.CharField(max_length=5,null=True,blank=True,default=0) # count = models.CharField(max_length=100000,blank=True,null=True,default=0) rated_number = models.IntegerField(blank=True,null=True,default=0, validators = [ MaxValueValidator(5), MinValueValidator(1), ] ) def __str__(self): return str(self.pk) @receiver(post_save, sender=User) def create_ratings(sender, instance, created, **kwargs): if created: if instance.is_delivery_man or instance.is_driver: Ratings.objects.create(rated_user=instance) js <script> const one = document.getElementById('first') const two = document.getElementById('second') const three = document.getElementById('third') const four = document.getElementById('fourth') const five = document.getElementById('fifth') // get the form, confirm-box and csrf token const form = document.querySelector('.rate-form') const confirmBox = document.getElementById('confirm-box') const csrf = document.getElementsByName('csrfmiddlewaretoken') const handleStarSelect = (size) => { const children = form.children … -
Multiple Models and Forms in Django Class Based View
Is it possible to have multiple forms and retrieve data from four models in one Django class based view? For example we are creating a booking app and on the Admin management page we want the page to be able to show: Data from four separate models Allow editing of the data (e.g. update / delete) Adding of new records (Post - Only from one form at a time) Here is an example of what I have tried. If I include both functions get_context_data they overwrite one before. Thanks in advance for anyone that can help me with this, still fairly new to Django. # ADMIN PAGE VIEWS. class ASPAdminListView(ListView): # creates a context dictionary to return a named list of asp_bookings. context_object_name = 'asp_bookings' model = ASPBookings template_name = "vistours/admin_bookings.html" # creates another dictionary to retun the BFBWBookings data. def get_context_data(self, **kwargs): # Call the base implementation first to get a context context = super().get_context_data(**kwargs) # Add in a QuerySet of all the books context['bfbw_bookings'] = BFBWBookings.objects.all() return context # creates another dictionary to retun the Athlete data. def get_context_data(self, **kwargs): # Call the base implementation first to get a context context = super().get_context_data(**kwargs) # Add in a QuerySet … -
django-Preview the photo after selecting the file in Django
models.py class Banner(models.Model): banner_photo = models.ImageField(null=True, blank=True) As the answer below, I would like to preview the image selection before saving the banner image in django-admin. I am a beginner about HTml. How do I override it? I want to preview the banner picture to be registered with Admin like the captured image. I don't know how to apply it even if I see the answer. onchange file input change img src and change image color -
How to pass static js file in django template script?
I want to load the staticfile json that is present in the code into the js to host the swagger. My index.html: <HTML> <head> {% load staticfiles %} </head> <body> <script src="{% static "js/script1" %}"></script> <script> var json_contents = // Use the static json `js/json1.json` in here? </script> </body> </html> How to do the above? -
Django reverse relationship (with annotate and filtering)
I want to get players with less than 5 records in the "MatchSup" table for specific matches Player.objects.filter('age="25"',matchsup__match__in='matchlist').annotate(numviews=Count('matchsup__player__lt=5',)) (like this that's wrong i know) class Player(models.Model): name= models.CharField(max_length=64, null=True, blank=True) class MatchSup(models.Model): player= models.ForeignKey(Player, null=True, blank=True, on_delete=models.SET_NULL) match = models.ForeignKey('Match', on_delete=models.CASCADE) -
Django Validators.py
please your help. I have the next code: form.py from .validators import MaxSizeFileValidator class ProductForm(forms.ModelForm): name = forms.CharField(min_length=5, max_length=50) image = forms.ImageField(required=False, validators=[MaxSizeFileValidator(max_file_size=2)]) validator.py from django import forms from django.core.exceptions import ValidationError class MaxSizeFileValidator: def __init__(self, max_file_size=5): self.max_file_size = max_file_size def __class__(self,value): size = value.size max_size = self.max_file_size * 1048576 if size > max_size: raise ValidationError(f"Not permitted size image, must be: {self.max_file_size}MB") return value When a run the code, the page show the next: TypeError at /add-product/ 'MaxSizeFileValidator' object is not callable Request Method: POST Request URL: http://127.0.0.1:8000/add-product/ Django Version: 3.1.5 Exception Type: TypeError Exception Value: 'MaxSizeFileValidator' object is not callable Thanks!!! -
How to create Django custom admin page? (Not overriding list or object page)
I want to add "upload image" page to django model admin. So I add "upload image" action button to image list page. when click "upload image" button, redirect to upload image page. In this case, there are not url navigation (breadcrumbs) and login information on header bar. How to show these items? Which class should I use? I already tried TemplateView, ModelAdmin, but I cannot implement what i want. Or, How to pass the model and the model admin to custom templage page? here is example of my admin template. {% extends "admin/app_index.html" %} {% load i18n admin_urls static admin_list %} {% block breadcrumbs %} <div class="breadcrumbs"> <a href="{% url 'admin:index' %}">{% trans 'Home' %}</a> &rsaquo; <a href="{% url 'admin:app_list' app_label=opts.app_label %}">{{ opts.app_config.verbose_name }}</a> &rsaquo; {% if has_view_permission %}<a href="{% url opts|admin_urlname:'changelist' %}">Images</a>{% else %}Images{% endif %} </div> {% endblock %} I copied this code from templates/admin/change_form.html for showing breadcrumbs. In this case, how to get opts, app_label and/or app_list? -
Image is showing twice after upload
I ma building a Social Media Webapp and I build a story feature. What i am trying to do :- I am trying to save images in stories, BUT when i select and save image then it shows twice . BUT when i check in admin then there is only one photo. I don't know where is the problem. models.py class Story(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE,default='',null=True) images = models.FileField(null=True) views.py def new_story(request,pk): form = NewStoryForm(request.POST,request.FILES) requested = request.user if request.method == 'POST': form = NewStoryForm(request.POST,request.FILES) if form.is_valid(): new_video = form.save() new_video.user = request.user new_video.save() return redirect('story') else: form = NewStoryForm() context = {'form':form,'requested':requested} return render(request, 'new_story.html', context) new_story.html <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button name="Submit">Add Story</button> </form> story.html <script> var currentSkin = getCurrentSkin(); var stories = new Zuck('stories', { backNative: true, previousTap: true, skin: currentSkin['name'], autoFullScreen: currentSkin['params']['autoFullScreen'], avatars: currentSkin['params']['avatars'], paginationArrows: currentSkin['params']['paginationArrows'], list: currentSkin['params']['list'], cubeEffect: currentSkin['params']['cubeEffect'], localStorage: true, stories: [ // {% for story in stories %} Zuck.buildTimelineItem( '{{ story.user.id }}', '{{ user.profile.file.url }}', '{{ story.user }}', 'https://{{story.id}}.codes', timestamp(), [ [ '{{story.user.id }}-1', 'photo', 3, '{{ story.images.url }}', '', false, false, timestamp(), ], ] ), // {% endfor %} ], }); </script> I don't know what am i … -
How can i add multiple queries in my List View Django
My View class profit_loss(generic.ListView): model = PartyCompleteLedgers template_name = 'report/Profit_Loss/profit_loss_show.html' context_object_name = 'all_profit' def get_queryset(self): a = PartyCompleteLedgers.objects.values('party_category').order_by("party_category").annotate(debit = Sum('party_debit_amount'),credit= Sum('party_credit_amount'),balance = (Sum('party_debit_amount')+Sum('party_credit_amount'))) for item in a: item['party_category'] = CategoryMaster.objects.get(id=item['party_category']) return a success_url = reverse_lazy('financial_accounting_app:profit_loss-detail') Using this for loop inside this view helps me to render actual data according to their id but i am unable to add more queries in the same view. Remenber both (PartyCompleteLedgers) and (CategoryMaster) has a foreign key relation. -
Send notification by firebase cloud messaging on a topic by django
I have implemented a firebase cloud messaging app which sends a notification to an android device based on its device token which works fine. I've used django-fcm module. But, storing device registration code for each user device is a little difficult in the practical application as I've to modify the front end source code which I don't want to. Therefor I decided to go with topic messaging. I cannot find any useful documentation regarding this. view.py def send_notification(registration_id,message_title, message_body): try: push_service = FCMNotification(api_key=FCM_DJANGO_SETTINGS['FCM_SERVER_KEY']) result=push_service.notify_single_device(registration_id=registration_id, message_title=message_title, message_body=message_body) return result except: pass def send_noti(request): device_token = "dEMspOwATpiFVumQGi1QOS:APA91bEZsTu7SbRTYRDGJjhNhHRErYd_UHs43rrPY6uN4yXe5_UHnPpepocFP60wnnU2IImCBXcem0rVuEUj7PCPc9EfkC0W4cLrNSmBCoWM5mz8jp9YgYF-VurJ1JyoRH627IH5Ujxn" send_notification(device_token,"title","body") return JsonResponse({"status": "success"}, safe=False) urls.py urlpatterns = [ path('noti/', views.send_noti, name='send_noti'), ] Can anyone help to send notification on topic using django? -
RUN command not executed in dockerfile image building
I have following file structure Django/ - IoT.yml - Dockerfile_Build_Django - requirements.txt My dockerfile (Dockerfile_Build_Django) for budiding image is as below: FROM python:3.10.0a7-alpine3.13 ENV PYTHONUNBUFFERED 1 RUN mkdir /code/ WORKDIR /usr/src/app COPY . . RUN pip install -r requirements.txt My docker-compose file as below: Django_2.2: build: context: ./ dockerfile: Dockerfile_Build_Django # Give an image name/tag image: python:3.10.0a7-alpine3.13 container_name: Django_2.2 depends_on: - Django_Mongo_4.2.12 tty: true after "docker-compose -f IoT.yml up" to setup and run container, then I use "docker exec -it Django_2.2 /bin/sh" to SSH access the Django_2.2 container, I found: no folder "/code" was created according to "RUN mkdir /code/" in docker file nothing was copied over to working directory according to dockerfile. Django was not installed according to above dockerfile. it makes me feel whether Docker.Inc tested properly before they release the software/product, they can not rely on users to do testing and raising bugs/defects for them. or, the Docker official document was truely poorly written, which resulted in a huge waste of time from developers all over the world. https://docs.docker.com/compose/compose-file/compose-file-v3/#build Following official guide just does not work out for you, was that on purpose? so that enterprise needs to hire Docker Specialist or buy professional service from Docker … -
How does django decide which transaction to choose on transaction.on_commit()
I had to use transaction.on_commit() for synchronous behaviour in one of the signals of my project. Though it works fine, I couldn't understand how does transaction.on_commit() decide which transaction to take. I mean their can be multiple transactions at the same time. But how does django know which transaction to take by using transaction.on_commit() -
Change HTTP Response message Django
I am using http response to handle exception in my website. I want to show proper message / validation during create and update data. But It shows HTTP responses like Bad Request , Internel server error. Here is my code: from django import http from rest_framework import viewsets class SaleViewSet(viewsets.ModelViewSet): def create(self, request, *args, **kwargs): data = request.data try: // Some code return http.JsonResponse(response) except Exception as e: logger.error(e) return http.HttpResponseBadRequest(content=e) In dialog box message it shows ,"Bad Request". Instead of "Bad Request" in dialog box message I want to show custom message. I want to do , except Exception as e: logger.error(e) return http.HttpResponseBadRequest(My message) -
TypeError: 'list' object is not callable in Django Channes
HTTP POST /room/ 200 [0.01, 127.0.0.1:59330] WebSocket HANDSHAKING /ws/chat/100/ [127.0.0.1:59334] Exception inside application: 'list' object is not callable Traceback (most recent call last): File "/usr/lib/python3.9/site-packages/channels/staticfiles.py", line 44, in call return await self.application(scope, receive, send) File "/usr/lib/python3.9/site-packages/channels/routing.py", line 71, in call return await application(scope, receive, send) File "/usr/lib/python3.9/site-packages/channels/sessions.py", line 47, in call return await self.inner(dict(scope, cookies=cookies), receive, send) File "/usr/lib/python3.9/site-packages/channels/sessions.py", line 254, in call return await self.inner(wrapper.scope, receive, wrapper.send) File "/usr/lib/python3.9/site-packages/channels/auth.py", line 181, in call return await super().call(scope, receive, send) File "/usr/lib/python3.9/site-packages/channels/middleware.py", line 26, in call return await self.inner(scope, receive, send) TypeError: 'list' object is not callable I have been having this error in django channels and i have no clue on how to go about it -
how do I fix PEP fields.E339 in django models through/through_fields?
I am trying to link vulnerability cve models with products via intermediate models to link/match each vulnerability based on the product / cve class Vulnerability(models.Model): cveid = models.CharField(max_length=32, null=True, blank=True) affected_products = models.ManyToManyField( Product, through='ProductVulnerability', through_fields=("product", "vulnerability") ) class ProductVulnerability(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) vulnerability = models.ForeignKey(Vulnerability, on_delete=models.CASCADE) class Meta: unique_together = [("product", "vulnerability")] service | ERRORS: service | api.Vulnerability.affected_products: (fields.E339) 'ProductVulnerability.product' is not a foreign key to 'Vulnerability'. service | HINT: Did you mean one of the following foreign keys to 'Vulnerability': vulnerability? service | api.Vulnerability.affected_products: (fields.E339) 'ProductVulnerability.vulnerability' is not a foreign key to 'Product'. service | HINT: Did you mean one of the following foreign keys to 'Product': product? service | SystemCheckError: System check identified some issues: -
Django/Python - Comparing 2 lists of dictionaries and adding a key,value when a common key is identified
I have two lists of dictionaries. The first list will contain significantly more dictionaries than the second list. There could be up to 200-300 dictionaries in list1 and no more than 10-15 dictionaries in list2. For example, any dictionary in list1 that has the same 'g': h key/value as that of list2 needs to add key/value 'j': k to list 1. list1 = [{'a': b, 'c': d, 'e': f, 'g': h}, {'a': b, 'c': d, 'e': f, 'g': h}, {'a': b, 'c': d, 'e': f, 'g': h}, {'a': b, 'c': d, 'e': f, 'g': h} ] list2 = [{'g': h, 'j': k}] I'm struggling on finding any previous examples of this type and cannot figure out a function of my own. -
How to do a quick user registration & CRUD on simple app
I have been asked to perform a simple task where I can do the following User can register and login as a doctor or patient Doctor has many clinics. clinic include (name, price, date, start_time, end_time) Patients can reserve doctor clinics Display doctors and patients reservations Use Python, django, django rest framework and relational database to complete the task. I participate in a big project for creating an app for doctor clinics where I'm responsible for creating the previous tasks. class User(AbstractUser): ... # fields objects = MedicalUserManager() class MedicalUserManager(models.UserManager): def create_user(self, username, email=None, password=None, **extra_fields): # pop all fields you want to use for `Doctor` or `Patient` from `extra_fields` doctor_pin = extra_fields.pop('doctor_pin', None) pid = extra_fields.pop('pid', None) user = super().create_user(username, email, password, **extra_fields) if doctor_pin: doctor = Doctor.objects.create(user=user, upin=doctor_pin) user.is_doctor = True # not needed if `is_doctor` is in `extra_fields` because it would have been saved when creating the `User` user.save() elif pid: patient = Patient.objects.create(user=user, pid=pid) user.is_patient = True user.save() return user or the following: class User(AbstractUser): is_doctor = models.BooleanField(default=False) is_patient = models.BooleanField(default=False) class Patient(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) user.is_patient = True pid = models.AutoField(unique=True, primary_key=True) #patient identification class Doctor(models.Model): upin = models.AutoField(primary_key=True) #unique physician identification number user … -
How to make subdomain in Django?
I want to make subdomains for every django apps in my project. I know that there are third party apps like django-hosts & django-subdomains but I don't want to use them when I can create subdomain without using them. While I was searching about creating subdomain in django, I found that we have to do something with the middleware. I don't know much about coding so please try to give me specific code to create subdomains in django. -
How to change button from drop down to manual input python django
I am making an attendance web app and after I made the relationship of the database one to many, the button changed from manual input to drop down type like so: this is my html code: <form method="post"> {% csrf_token %} <div class="input-group mb-2"> <div class="input-group-prepend"> <label for="name">Enter Your Full Name:</label> {{form.name}} <button type="submit" name="checkName" value="checkName" class="btn btn-outline-success">Submit</button> </div> </div> </form> models.py: class employeeName(models.Model): employee = models.CharField(max_length=200) def __str__(self): return self.employee class Name(models.Model): name = models.ForeignKey(employeeName, null=True,on_delete=models.CASCADE) timeIn = models.TimeField() timeOut = models.TimeField(default=datetime.now()) date = models.DateField(auto_now=True) def __str__(self): return str(self.name) -
Getting CSRF session cookie from Django while using React for frontend
Background I've been trying to make a POST request to my application's backend (written in Django) from my React frontend, but the request fails because the request does not include a CSRF token. Here is the code I use to setup and send my request: const formData = new FormData() // 'image' is a user uploaded image formData.append( "myImage", image, image.name ) const data = await axios.post("http://localhost:8000/myendpoint", formData) return data My application is very simple in that there is no log-in/session-keeping that I need to do and to use the app the user simply needs to give some data (upload an image to be precise) to my Django API's endpoint and then get some results. For reference, here is what I see on my Django server logs: Forbidden (CSRF cookie not set.): /myendpoint And here is the error I see in the browser's console: POST http://localhost:8000/myendpoint 403 (Forbidden) Based on some questions that appear similar to mine, the suggestion seems to be to retrieve this CSRF token from the csrftoken cookie that Django sends and then including it in subsequent POST requests (for instance, this answer). I didn't think this would work since I did not see any cookies in … -
I've been working on my blog app and everything was going smoothly until I try to add a new field to my Post model
I've been working on my blog app and everything was going smoothly until I try to add a new field to my Post model. It's giving me an error of no such table: blog_post_likes. Is there something about the django models that I need to know like anything going on behind the scenes that I am not aware of? from django.db import models from django.urls import reverse from django.contrib.auth.models import User # Create your models here. STATUS = ( (0, 'Draft'), (1, 'Published'), ) class Post(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(blank=False, unique=True, default='travel-blog-post') author = models.ForeignKey(User, on_delete=models.CASCADE) date_created = models.DateTimeField(auto_now_add=True) body = models.TextField() status = models.IntegerField(choices=STATUS, default=0) # meta descrption for SEO benifits metades = models.CharField(max_length=300, default="new post") category = models.CharField(max_length=200, default='uncategorized') likes = models.ManyToManyField( User, related_name='post_like', blank=True) class Meta: ordering = ['-date_created'] def __str__(self): return self.title def get_absolute_url(self): return reverse('article-detail', kwargs={'slug': self.slug}) class Category(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name def get_absolute_url(self): return reverse('index') **