Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can i use tag user using @ in django
I am building a BlogApp and I am trying to add tag user system in creating post using @. I did't find any libraries to implement it in django app. What i am trying to do I am trying to build tagging user with @. So when user press @ and press of users(friends) appears. Same like stack overflow while someone add @ then user involved in that post appears. What have i tried I saw few answers on tagging user using @ but they didn't work for me. Like :- THIS. I also tried mark_down to tag immediately ( Like autocomplete ). BUT FAILED. :- THIS I don't know what to do. Any help would be appreciated. Thank You in Advance. -
How to validate and get nested serializer values in django rest framework?
I am using 2 serializers for validating this request: { "name":"Dade Waste Facility", "email":"example@mailinator.com", "mobile":"1234567", "street":"Street 1", "city":"Miami", "zipcode":"123456", "state":"Florida", "material_types": [{ "name": "Metal", "cost_per_ton": 20 }, { "cost_per_ton": 50, "name": "Food" }] } Django code: class MaterialTypeSerializer(serializers.Serializer): name = serializers.CharField( required=True, max_length=255, error_messages={ "required": "Material type name is required.", "max_length": "Material type name can be maximum 255 characters.", }, ) cost_per_ton = serializers.IntegerField( required=True, error_messages={"required": "Material type cost per ton is required.",}, ) class Meta: fields = "__all__" class WasteFacilityPostSerializer(serializers.ModelSerializer): name = serializers.CharField( required=True, max_length=255, error_messages={ "required": "Name is required.", "max_length": "Name can be maximum 255 characters.", }, ) contact_person_name = serializers.CharField( required=False, max_length=255, error_messages={ "max_length": "Contact person name can be maximum 255 characters.", }, ) email = serializers.EmailField( required=False, max_length=255, error_messages={ "invalid": "Email address not valid.", "max_length": "Email can be maximum 255 characters.", }, ) mobile = serializers.CharField( required=True, validators=[ RegexValidator( regex=r"^\d{10,14}$", message="Phone number must be entered in format: '+999999999'. Up to 14 digits allowed.", ) ], max_length=15, error_messages={ "required": "Mobile is required.", "max_length": "Mobile can be maximum 14 digits.", }, ) street = serializers.CharField( required=True, max_length=255, error_messages={ "required": "Street is required.", "max_length": "Street can be maximum 255 characters.", }, ) suite = serializers.CharField( required=False, max_length=255, error_messages={"max_length": "Suite … -
Is it better to have several different tables for similar objects, or one big table?
I have an optimisation problem for my tables : I have Items that can have a price by one, by ten and by hundred. Right now i have three tables for that : class Prix_x1(models.Model): def __str__(self): return self.item.name prix = models.IntegerField(null=True) saved_at = models.DateTimeField() item = models.ForeignKey(Item, on_delete=models.CASCADE) class Prix_x10(models.Model): def __str__(self): return self.item.name prix = models.IntegerField(null=True) saved_at = models.DateTimeField() item = models.ForeignKey(Item, on_delete=models.CASCADE) class Prix_x100(models.Model): def __str__(self): return self.item.name prix = models.IntegerField(null=True) saved_at = models.DateTimeField() item = models.ForeignKey(Item, on_delete=models.CASCADE) But often i need to check which of these prices is the lowest on a per unit basis. So i have to check each price table for each Item every time i need to do that. So my question is : Is it a better way to optimse that ? For exemple, is it better to have one big table Price with a field number_of_unit that can take 1, 10 or 100 as value ? Thanks for your help !! -
how to filter the foreignkey objects if exists in the manytomany django
i have to make a queryset for only returns that object which is in the M2M field class Item(models.Model): items = models.CharField(max_length=20) class Main(models.Model): admin = models.ForeignKey(User,on_delete=models.CASCADE) items = models.ManyToManyField(Item,on_delete=models.CASCADE) #others class TestModel(models.Model): admin = models.ForeignKey(User,on_delete=models.CASCADE) items = models.ForeignKey(Item,on_delete=models.CASCADE) i have to make query to filter in TestModel to only the items which is in the Main model! i tried this in my views.py get_id_from_user = request.GET.get('user_input') main_obj = Main.objects.get(id=get_id_from_user) test_objects = TestModel.objects.filter(items__in=main_obj.items.all() but test_objects still returns all the Item object! is it possible please thank you -
MultiValueDictKeyError while submitting Django form
I am new to Django and I am working on a site which should take user input and use it for further operations. I am using a simple text field and I am trying to access the input using request.POST method, however this is giving MultiValueDictKeyError on the name of the text field. Kindly help me out in this. PFA my codes. views.py from django.shortcuts import render from django.http import HttpResponse import openpyxl import math def index(request): if "GET" == request.method: return render(request, 'index.html') else: excel_file = request.FILES["excel_file"] wb = openpyxl.load_workbook(excel_file) # getting a particular sheet by name out of many sheets # USING TEXT BOX sheet_id = request.POST["leadtime"] sheet_name = str(sheet_id) + "_Day_Lead" worksheet = wb["Observed"] worksheet1 = wb[sheet_name] index.html <div class="md:flex flex-col w-full items-center"> <div class="relative mb-4"> <form action="index" method="POST"> {% csrf_token%} <label for="full-name" class="leading-7 text-sm text-gray-600">Duration of Lead Time in Day(s)</label> <input type="text" id="full-name" placeholder="1 to 5 or ALL" name="leadtime" class="w-full bg-white rounded border border-gray-300 focus:border-green-500 focus:ring-2 focus:ring-green-200 text-base outline-none text-gray-700 py-1 px-3 leading-8 transition-colors duration-200 ease-in-out"> </form> </div> <div class="relative mb-4"> <form action="index" method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="file" title="Upload excel file" name="excel_file" style="border: 3px solid green ; padding: 5px;" required="required"> </div> <button type = … -
How to turn off pagination for a particular viewset in Django Rest Framework?
This is a snippet of the code that I tried to disable pagination as suggested in answers to similar questions. But this is not working for me. I even tried overriding the default paginate_queryset method but ended up observing that it wasn't even getting called(maybe I am doing it the wrong way) class TestViewSet(viewsets.ModelViewSet): queryset = Test.objects.all() serializer_class = TestSerializer filter_backends = (django_filters.DjangoFilterBackend, SearchFilter) filterset_fields = {'status': ('exact', 'in'), } search_fields = ['=id', ] pagination_class = None Below is also the code I tried to override paginate_queryset def paginate_queryset(self, queryset, request, view=None): if 'no_page' in request.query_params: return None return super().paginate_queryset(queryset, request, view) -
How to get in Javascript specific Object of iteration done in a Django template
I have the next iteration in a Django template. This shows me a group of images and their title. {% for i in blogs %} <div class="content__blog"> <h4 class="content__blog__h4">{{i.title}}</h4> <img class="content__blog__img" src="{{i.image.url}}" onclick="clickImage()"> </div> {% endfor %} What i want to do by adding JavaScript is that when clicking on an Image it'll resize. But only the image clicked. How do i specify in the JS file which image i'm clicking on? -
global variable in Django views.py
I am new to Django. In views.py I want to use variable defined in one function in anothe function. But when even after defining a variable as global it returns error. views.py def index(request): data = {'Price':[100,200], 'Sale':[30,40]} global df df = pd.DataFrame(data) def corr(request): correlation = corr.df() print(correlation) Error: name 'df' is not defined -
Django MPTT - can't update TreeForeignKey data (lft, rgth... etc)
my model class Category(MPTTModel, models.Model): api_uuid = models.UUIDField(null=False, blank=False, unique=True) department = models.ForeignKey(Department, on_delete=models.DO_NOTHING, related_name='categories', to_field='api_uuid', db_column='department_api_uuid', blank=True, null=True, db_constraint=False) parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True, on_delete=models.DO_NOTHING, help_text=_("Parent's UUID")) name = JSONField(blank=True, null=True, default=dict) code = models.IntegerField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: db_table = "category" category section from the view: for category_data in categories_data[1:]: category_api_uuid = category_data.pop('uuid', None) category_data['api_uuid'] = category_api_uuid department_uuid = category_data.pop('department_uuid', None) department = departments.filter(api_uuid=department_uuid).first() category_data['department'] = department parent_uuid = category_data.pop('parent', None) parent_category = Category.objects.filter(api_uuid=parent_uuid).first() category_data['parent'] = parent_category category = Category.objects.filter(api_uuid=category_api_uuid).first() if category: instance = Category(category.id, **category_data) instance.save() else: instance = Category(**category_data) instance.save() I am getting data from the API and can successfully create instances in the database on the first try. Whenever I try to update instances in the databases everything except 'parent' related fields get updated. fields that does not update: (leftt, rightt, level, parent, parent_id) can anyone help with this one?? Appreciate any help -
How to get coverage report 100% in my Django project
I have written test cases for all my views in my Django project views.py. For example I have written test case for coupons page here is my code snippet in views.py def coupons(request): try: email = request.session.get('email') # From 'master_table' model filtering items by type_of_product 'C' and getting query set. coupon = master_table.objects.filter(type_of_product='C').order_by('-rebate') couponBMC = vk_master_table.objects.filter(type_of_product='BMC').order_by('-rebate') # Counting no.of objects from query set. count_c = master_table.objects.filter(type_of_product='C').order_by('-rebate').count() countBMC = master_table.objects.filter(type_of_product='BMC').order_by('-rebate').count() count = count_c + countBMC # Pagination by using query set and count(counting number of objects in query set). coupons = random.sample(list(chain(coupon, couponBMC)), k=count) # First page by default. page = request.GET.get('page', 1) # Per page we are setting 40 objects. paginator = Paginator(coupons, 40) coupons = paginator.page(page) except PageNotAnInteger: coupons = paginator.page(1) except EmptyPage: coupons = paginator.page(paginator.num_pages) except Exception as e: logging.error(e) return render(request, "coupons.html", {'error': error, 'banners': bestDeals(), 'form': HomeForm(), 'ClassifiedBar': Extras.ClassifiedBar(request), 'time': settings.SESSION_IDLE_TIMEOUT, 'name': first_last_initial(email), 'fullname': fullname(email), 'CategoriesBar': Extras.CategoriesBar(request), 'AdvertiserBar': Extras.AdvertisersBar(request), 'KA_Banner': advertiser_banners.KA_Banners(request), 'LA_Banner': advertiser_banners.LA_Banners(request), 'id': request.session.get('id'), 'BB_Banner': advertiser_banners.BB_Banners(request)}) return render(request, "coupons.html", {'Coupons': coupons, 'banners': bestDeals(), 'form': HomeForm(), 'ClassifiedBar': Extras.ClassifiedBar(request), 'time': settings.SESSION_IDLE_TIMEOUT, 'name': first_last_initial(email), 'fullname': fullname(email), 'CategoriesBar': Extras.CategoriesBar(request), 'AdvertiserBar': Extras.AdvertisersBar(request), 'id': request.session.get('id'), 'KA_Banner': advertiser_banners.KA_Banners(request), 'LA_Banner': advertiser_banners.LA_Banners(request), 'BB_Banner': advertiser_banners.BB_Banners(request) }) Here is my test case for above snippet @pytest.mark.django_db … -
Delete Image on Cloudinary via Django Admin
I am not sure what code to paste here, but I am using CKEditor in Django Admin and Cloudinary as the image storage server. CKEditor has this problem that when a post is deleted the accompanying images are not deleted. I thought there could be a way to manually delete pictures using a file browser. But https://django-filebrowser.readthedocs.io/en/latest/ does not support cloudinary. Is there any file-browser that can seamlessly work with cloudinary? -
Django: Show logging WITHOUT creating mysite.log file
I don't want the mysite.log file with my basic Django logging setup because the file typically ends up being massive and I don't use it. How can I still have the error messages show up when running python manage.py runserver and in my Heroku logs WITHOUT having a mysite.log file created? My logging settings in my settings.py file are below (note: these settings were copy & pasted from another stackoverflow post): DEBUG_PROPAGATE_EXCEPTIONS = True LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format' : "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s", 'datefmt' : "%d/%b/%Y %H:%M:%S" }, 'simple': { 'format': '%(levelname)s %(message)s' }, }, 'handlers': { 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': 'mysite.log', 'formatter': 'verbose' }, }, 'loggers': { 'django': { 'handlers':['file'], 'propagate': True, 'level':'DEBUG', }, 'MYAPP': { 'handlers': ['file'], 'level': 'DEBUG', }, } } -
Videos in Django didn't go forward in the duration
Videos in Django didn't go forward in the duration, is this a public problem in Django or just because I working in the virtual environment, I road a lot about this problem and this is a lot of opinions, some problem because the problem in HTTP and another because I Working in the virtual environment, so I tried my website in the all kind of the browsers and didn't work finally except the Firefox, that only one I able to going forward in the video duration. So my question is when I deploy my website is this will continue or Not? -
Django model saves when it shouldn't
I'm trying to set custom validation rules on my Django models. I have the following code: Entity.py from django.core.exceptions import ObjectDoesNotExist, PermissionDenied from django.db import models class Entity(models.Model): TYPE_CHOICES = [ ('asset', 'asset'), ('company', 'company') ] entity_type = models.CharField(max_length=25, choices=TYPE_CHOICES) ... class Asset(Entity): ... class Company(Entity): ... Security.py from django.core.exceptions import ObjectDoesNotExist, PermissionDenied, ValidationError from django.db import models from .Entity import Entity class Security(models.Model): ... entities = models.ManyToManyField(Entity) def clean(self, *args, **kwargs) -> None: try: # Check that object has already been saved Security.objects.get(name=self.name) print("All entities:", self.entities.all()) if len([e for e in self.entities.all() if e.entity_type == 'company']) > 1: raise ValidationError("A security can only be related to one company") except ObjectDoesNotExist: pass return super(Security, self).clean(*args, **kwargs) def save(self, *args, **kwargs): try: self.full_clean() return super(Security, self).save(*args, **kwargs) except ValidationError: raise ValidationError("A security can only be related to one company") class Bond(Security): ... class Equity(Security): ... What I'm trying to do is to prevent a Security from being saved if its field entities holds more than 1 company. The entities field is a ManyToMany relationship with Entity, as it can hold multiple Asset objects but only one Company. This is my test file class EntityTestCase(TestCase): def test_multiple_companies_fail(self): b = Bond.objects.get(name='Bond 1') c1 … -
Django app extremely slow when using MYSQL database
I have developed my first Django application which runs fine locally when using a sqlite database however when I change my settings to use a RDS MYSQL database (hosted in the same region on AWS) each page takes up to 40 seconds to load as apposed to 0.4 seconds before. I expected performance to decrease using a remote database but a 95%% drop has me thinking I may be doing something wrong. Below are the performance stats loading my homepage using Django-debug-toolbar. MYSQL SQL: 2752.0 ms (5 queries ) CPU: 824.7ms Request: 7910.2ms Local SQLite SQL: 1.8ms (3 queries) CPU: 340.9ms Request: 360.0ms -
using raw sql join querry with pyodbc mssql django
hey guys am back again. So now i am trying to perform some raw join statements but they are not working. All the examples i see are either with php admin. i am using ms sql. I dont want do do the joins using the the django models instead i want to use raw querries to perform the join and render it to my html page. Plesa can someone tell me how to do the same. Here are my codes models.py from django.db import models class Company(models.Model): name = models.CharField(max_length=100) contact_name = models.CharField(max_length=100) address = models.TextField(max_length=255) ph_no = models.CharField(max_length=17) tele = models.CharField(max_length=17) mail = models.EmailField(max_length=150) is_active = models.BinaryField(default=0) class Client(models.Model): company_id = models.IntegerField() first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) ph_no = models.CharField(max_length=17) tele = models.CharField(max_length=17) mail = models.CharField(max_length=100) is_active = models.BinaryField(default=1)``` views.py from django.shortcuts import render from .models import Company, Client import pyodbc import datetime import pytz con = pyodbc.connect('Driver={SQL server};' 'Server=;' 'Database=Shipping;' 'Trusted_Connection=True;') cursor = con.cursor() con.autocommit = False sql_join_client = ''' select Client.Client_id,Company.name,Client.first_name,Client.last_name, Client.ph_no,Client.tele,Client.mail,Client.IsActive,Client.last_update from Client join Company on Client.company_id=Company.company_id ''' #some names in model differ from the actual names in the db tables def showclient(request): cursor.execute(sql_join_client) # join result = cursor.fetchall() return render(request, 'client.html', {'Client': result}) client.html … -
Access webapp (django) externally cors?
I did follow some tutorial to create a webapp with django which hosts a bot widget.. When running locally (0.0.0.0:8000) everything works and the communication to the bot works perfectly ...When accessing the webapp via 192.xxx.xxx.xxx:8000 i get the website but the bot internally does not response... When i inspect the site....i get in the console an error Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:5005/webhooks/rest/webhook. (Reason: CORS request did not succeed)." in django in the setting.py file i do start django with source venv/bin/activate . && python manage.py runserver 0.0.0.0:8000 What do i miss....i guess the problem has to be in the communicaiton with the widget... I just wonder why it works if i run it locally... -
How to make this simple calendar example add remove and edit events
I need help converting this calendar to one that can add, remove, and edit events. I am using django through visual studio, so I need to know how to add the events to the database and how to manipulate them. I am thinking of using an add event button that will pull up a form created from django that you can submit and then it shows up on the calendar and if you refresh the page it stays there. This is the js code ;(function ($, window, document, undefined) { "use strict"; // Create the defaults once var pluginName = "simpleCalendar", defaults = { months: ['january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december'], //string of months starting from january days: ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'], //string of days starting from sunday displayYear: true, // display year in header fixedStartDay: true, // Week begin always by monday or by day set by number 0 = sunday, 7 = saturday, false = month always begin by first day of the month displayEvent: true, // display existing event disableEventDetails: false, // disable showing event details disableEmptyDetails: false, // disable showing empty date details events: [], // List … -
Django with HAPROXY -Session cookie setup - set_cookie('haproxy_cookie_name, 'new_value') doesn't set the new value
I have a Django app with a HAPROXY load-balancer. I am using the Session cookie setup by the Load-Balancer to make the user go always for the same server to provide persistence as shown in this link: [https://www.haproxy.com/blog/load-balancing-affinity-persistence-sticky-sessions-what-you-need-to-know/#session-cookie-setup-by-the-load-balancer][1] for some reason I am wanting to be able to set the cookie So I can choose which server to access each time but reaponse.set.cookie('haproxy_cookie_name, 'new_value') doesn't set the new value I have also checked the reaponse.set.cookie works on other cookie and it works fine. Do anyone have any idea why this doesn't work? Is there other option to set the cookie value (from the server) -
UnboundLocalError while submitting radio button form in django
I am new to Django and I am working on a site which should take user input from Radio Button and use the selected value for further operations. I have seen some ways using Database, but I want to use a simple way to directly get the value of the selected radio button from the template. I am using Django forms and I am getting UnboundLocalError when submitting the form in HTML. It shows that local variable 'selected' referenced before assignment. I understand that the form is not valid, but I do not know why kindly help me out. PFA my codes. views.py (Only the part where value of selected radio button is accessed) def index(request): if "GET" == request.method: return render(request, 'index.html') else: excel_file = request.FILES["excel_file"] wb = openpyxl.load_workbook(excel_file) form = CHOICES(request.POST) if form.is_valid(): selected = form.cleaned_data.get("NUMS") else: form = CHOICES() worksheet = wb["Observed"] worksheet1 = wb[selected] forms.py from django import forms NUMS= [ ('one', 'one'), ('two', 'two'), ('three', 'three'), ('four', 'four'), ('five', 'five') ] class CHOICES(forms.Form): NUMS = forms.ChoiceField(widget=forms.RadioSelect, choices=NUMS) index.html (Only the part of Radio buttons) <form action="index" method="POST"> {% csrf_token %} {{form.NUMS}} <input type="radio" id="NUMS" name="NUMS" value="1 Day Lead"> <label for="NUMS">1 Day Lead</label> <input type="radio" id="NUMS" … -
Unable to use and set up django-instagram package
I'm following the exact instructions in here https://github.com/marcopompili/django-instagram but I keep getting the error: django_instagram.templatetags.instagram_client - WARNING - variable name "instagram_profile_name" not found in context! Using a raw string as input is DEPRECATED. Please use a template variable instead! although I added to my urls.py the following: path('', TemplateView.as_view(template_name='index.html', extra_context={ "instagram_profile_name": "amd" })), I can't find any other resource to learn how to use this package, any help? -
How to subtract/Compare Date obtained from Query params and Django TimeZone?
I have certain date obtained from query params and I want to compare the date with Django timezone.now().date() but I am getting error as '<' not supported between instances of 'str' and 'datetime.date' I know query params date have come in str format and timezone.now().date() is in datetime.date format. here is my code so far def _validate_departure_date(self): print('-------') print(type(timezone.now().date())) if self._query_params.get('departure_date') < timezone.now().date(): raise ValidationError({'departure_date': 'Departure date should not be in past.'}) How to compare these dates? -
Difference Between Model , AbstractUser in Django
1>> Here we can create a News model from django.db import models class News(models.Model): title = models.CharField(max_length=180) slug = models.CharField(max_length=254) author = models.CharField(max_length=100) 2>> how this is different from above model from django.contrib.auth.models import AbstractUser class User(AbstractUser): name = models.CharField(max_length=70, null=True, blank=True) country = models.CharField(max_length=70, null=True, blank=True) region = models.CharField(max_length=70, null=True, blank=True) 3>> and django already create model with this name is it different from above two? can we add field what ever we like in this User Model instead of first_name,last_name,email(which django already provide) from django.contrib.auth.models import User -
Django QuerySet ordering by related fields length
I am beginner at django and trying to build a project with it. So I have 'Question' and 'Tag' models. I used ManytoMany relation between two. Like this: models.py class Question(models.Model): title = models.CharField(max_length=200) tags = models.ManyToManyField(Tag, blank=True) Here is my question: I'm using class based views for listing tags. At get_queryset() method, I want to return all 'Tag' objects ordered by number of questions they related. Shortly, I want to order data by another related datas lenght. How can i do that? Thanks for answers. -
V- model on input texbox on key up updates text on other v model input text in django for loop
I have this Django for loop where i have this form with input textbox that has v model. When i type a text on it , on key up it updates text on ther input texbox inside this django for loop : {% for drama in theatre %} <div class="comment-input" id="postcomment-{{tweet.id}}"> <form v-on:submit.prevent="submit0comment({{tweet.id}})" id="comment-{{tweet.id}}" > <input id=".input_1" type="text" v-model="comment_body" class="form-control"> <div class="fonts"> <button class="btn-share">Post</button> </div> </form> </div> <br> <div class="d-flex flex-row mb-2" v-for="comment in comments"> <img :src="comment.avatar" width="40" class="rounded-image"> <div class="d-flex flex-column ml-2"> <span class="name">[[comment.commenter]]</span> <small class="comment-text">[[ comment.comment_body]]</small> <div class="d-flex flex-row align-items-center status"> <small>Like</small> <small>Reply</small> <small>[[ comment.created_at ]]</small> </div> </div> </div> {% endfor %}