Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django template tags in javascript
Display javascript tag inside django template. I want to add this code code = "images/" + item.student__stud_lname + "_" + item.bcode + ".png" inside the <td><img src="{% static "+'code'+" %}"</td> -
change / toggle web page theme with a button
trying various answers on 'toggle theme with button', i have a code, but it is not working from bootstrap 4, bootswatch themes 'flatly' and 'darkly' have been selected, since i want to offer user of my web page option to select his/her favorite theme, be it dark or light. i have put complete 'flatly.min.css' and 'darkly.min.css' into my static files folder (django project), and renamed them to 'light.css' and 'dark.css' i tried various answers from stack exchange, and currently i use this one: create switch for changing theme intead of browser page style html (thank you) by my amateur coding logic, my code should work, but it is not so (at all) in my base.html, i include: <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> ... {% include 'base/css.html' %} {% block base_head %} {% endblock %} </head> <body> ... {% include 'base/js.html' %} {% block javascript %} {% endblock %} </body> in css.html, i declare: <!-- custom styling --> <link rel="stylesheet" href="{% static 'css/base.css' %}"> <!-- light styling --> <link rel="stylesheet alternate" id="theme" href="{% static 'css/light.css' %}"> <!-- dark styling --> <link rel="stylesheet alternate" id="theme" href="{% static 'css/dark.css' %}"> when i use only 'css/dark.css' … -
I can't upload a file in Django and can't figure out why
I'm trying to upload a file like this: html: <form method="post" enctype="multipart/form-data" action="custom/"> {% csrf_token %} <input type="file" id="svg_upload"> <button type="submit">Submit</button> </form> views.py: print(request.FILES) print(request.POST) And I get the following output: <MultiValueDict: {}> <QueryDict: {'csrfmiddlewaretoken': ['ZC4JHfUkHSZ4WINRXRAXaA3Xd8osPYbHVLGBs2mZ702zRYTcmV7oBVzVsDE0sNFo']}> So the form works, but request.FILES is empty. I can't see what is wrong here, I've set the enctype and method correctly. Any ideas? -
How can I speed up regex querying in PostgreSQL database with django
I am trying to create regex query to my PostgreSQL database. I have already done it, but the problem is that the query with regex is up to 3 times slower than the query where I search by the name. Is there any way to accelarate regex query or any other option to get results faster? I use django to create queries to the database. My "normal" query where I search car by brand and model: object_db = Car.objects.filter(brand='Ford', car_model='Focus-RS') I create regex query like this: object_db = Car.objects.filter(brand__regex=r'^Ford$', car_model__regex='^Focus[-_]*RS$') I get the result that I want but it take to much time to get it. How can I improve the speed of regex query? -
How to Sort drop downs in alphabetical order in Django
I am trying to sort a drop down values in a form field in alphabetical order Drop down is the field = strategy I tried using the .order_by to solve this bug but it some how doesn't seems to solve it Below is the code i tried class AddForm(forms.ModelForm): class Meta: model = Line fields = ('analyst','strategy','conviction','startdate','startvalue','target','review','reason','rationale') def __init__(self, *args, **kwargs): self.user = kwargs.pop('user', None) super(AddForm, self).__init__(*args, **kwargs) self.fields['Strategy'].queryset = strategy.objects.order_by('name') I get a indentation error and the server stops running... i also tried using strategy = forms.ModelChoiceField(queryset=strategy.objects.order_by('name')) Didn't work!, where am i going wrong? -
Django update_or_create (get part) using related object as kwarg
I'm doing an update_or_create queryset operation, which internally uses the get queryset operation. I've read through the documentation on the update_or_create queryset method but I'm having some difficulty in understanding the parts relating to foreign keys and using objects as kwargs. Consider an example where I have models Book and Chapter and I do something like this: book = Book.objects.get(...) kwargs = {'book': book, 'name': 'Chapter 3'} defaults = {'text': '...'} Chapter.objects.update_or_create(defaults=defaults, **kwargs) Now the kwargs will be used in the 'get' method to check whether that chapter exists. But, since book is an object, how does Django know whether there is a chapter with a "matching" book? Does it check whether all fields of the book object match? Does it check only the unique field? Only the primary key of the book? If I have two books with the same fields but different primary key, could they match? Is it good practice to use an object in the kwargs in this way, or do I risk getting integrity error problems? Thank you. -
Django app switch from Mariadb to Postgresql
I have changed the Django Settings file database engine to postgres_psycopg2. When I run ./manage.py run server I get the following error numerous times: "[03/Apr/2019 18:40:09] code 400, message Bad request version ('error","name":"DatabaseError","code":"ECONNREFUSED","property":null,"redirect":null,"errno":"ECONNREFUSED","syscall":"connect","address":"127.0.0.1","port":3306,"fatal":true}}') For some reason it is trying to connect to port 3306, which is the Mariadb port and not port 5432, which is the port for Postgresql. I just upgraded my Mariadb to version 10.3.14 but the problem still exists. My Postgresql is version 11.2. I have been Googling for several days now and still have not found a solution. -
Django 'NoneType' object has no attribute 'filter'
The task: To assign a single user to the model at a time. The Error: Django 'NoneType' object has no attribute 'filter' The models.py is class Post(models.Model): post_tag = models.ForeignKey(ProjectUser, related_name="user_tag", blank=True, null=True,on_delete=models.CASCADE) Where ProjectUser is: from django.contrib.auth.models import AbstractUser class ProjectUser(AbstractUser): def __str__(self): return self.username The .html code is : % for post_user in objects %} <form method='POST' action="{% url 'a_tag' post_user.id %}"> {% csrf_token %} <input type='hidden'> {% if post_user.id in assigned_user %} <button type='submit'>Cancel</button> {% else %} <button type='submit'>Start</button> {% endif %} </form> The urls.py is path('<int:tag>', views.tag_analyst, name='a_tag'), The views.py function is <- Filter, add and remove attributes here are causing the errors def tag_analyst(request, tag): post = get_object_or_404(Post, id=tag) if request.method == 'POST': if post.post_tag.filter(id=request.user.id).exists(): post.post_tag.remove(request.user) else: post.post_tag.add(request.user) return HttpResponseRedirect(reverse('homepage')) The views.py class class View(LoginRequiredMixin, ListView): context_object_name = "objects" model = Post template_name = "page.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['assigned_user'] = self.request.user.user_tag.values_list('id', flat=True) return context -
How to select an option of choice field with a value which is rendered by render_field in django template? I'm using django-widget-tweaks package
I trying to render fields by looping form class field using django-widget-tweaks render_field. Fields are rendered as excepted, however, unable to select an option for combo box. Any Idea to make an option selected by value given. I have used value attribute to set the values of rendered fields which is working for charfield, but not for combo box. {% for field in form.visible_fields %} <div class="pan-sty"> <label class="th-color control-label font-normal">{{ attribute.1 }}</label> {% render_field field class+="form-control" value|option=records|get_attrs:field.name %} </div> {% endfor %} Excepted output the value "Indirect-retail" should be selected in combo box <div class="pan-sty"> <label class="th-color control-label font-normal">Sales Channel</label> <select name="sales_channel" class="form-control" id="id_sales_channel"> <option value="" selected="">---------</option> <option value="Direct-web">Direct - Web</option> <option value="Direct-in-store">Direct - In-store</option> <option value="Direct-sales-rep">Direct- Sales Representative</option> <option value="Indirect-wholesale">Indirect - Wholesale</option> <option value="Indirect-retail" selected>Indirect - Retail</option> <option value="Indirect-influencer">Indirect - Influencer</option> <option value="Indirect-affiliate">Indirect - Affiliate</option> </select> </div> but value getting added as "value" attribute in select tag <div class="pan-sty"> <label class="th-color control-label font-normal">Sales Channel</label> <select name="sales_channel" class="form-control" value="Indirect-retail" id="id_sales_channel"> <option value="" selected="">---------</option> <option value="Direct-web">Direct - Web</option> <option value="Direct-in-store">Direct - In-store</option> <option value="Direct-sales-rep">Direct- Sales Representative</option> <option value="Indirect-wholesale">Indirect - Wholesale</option> <option value="Indirect-retail">Indirect - Retail</option> <option value="Indirect-influencer">Indirect - Influencer</option> <option value="Indirect-affiliate">Indirect - Affiliate</option> </select> </div> -
Forloop on a json objects in template issue
I would like to render each row of a pandas DataFrame on my web app, so I convert it to a json object but my queries aren't displayed on my web page. I do not understand why. Can you help me on this? view.py def typeDetail(request,id,rt_id): normal_price=request.POST.get('normal_price') number_of_allotments=request.POST.get('number_of_allotments') property=get_object_or_404(Property,id=id) roomtype=get_object_or_404(RoomType,id=rt_id) dayList=Inventory.objects.filter( room_type=rt_id, date__gte= datetime.date.today() ).order_by('date') pd_frame=pd.DataFrame(list(dayList.values())) pd_frame['occupancy']=(int(number_of_allotments)-pd_frame['allotment'])/int(number_of_allotments) trueList=pd_frame.to_json(orient='records') # for day in dayList: # dateList.append(day.date) # price.append(day.pricing) # availability.append(day.allotment) return render(request,'livedb_model/typeDetail.html',{ 'property':property, 'roomtype':roomtype, # 'availability':json.dumps(availability), # 'price':json.dumps(price), # 'dateList':json.dumps(dateList,default=myconverter), 'trueList':trueList }) typeDetail.py <ul> {% for day in trueList %} {% if day.availability.room %} <li>{{day.date}}:{{day.allotment}}:{{day.pricing.room.actual_rate.amount}}:{{day.occupancy}} </li> {% else %} <li>{{day.date}}:0:{{day.pricing.room.actual_rate.amount}} </li> {% endif %} {% endfor %} </ul> -
Django Model value is NoneType why?
I'm making a simple app, calculation app. The user selects options and based on that options app calculate stuff need to. The problem is I can't edit numbers before they have been saved in the database. How can i accomplished that ? Thank you. I've tried to do a calculation in models.py, but i need when I call a 'def calculate()' from views.py it responds with Error (NoneType). Models.py class Video(models.Model): sirina = models.IntegerField(null=True) visina = models.IntegerField(null=True) roletne = models.IntegerField(null=True) okapnice = models.IntegerField(null=True) materijal = models.IntegerField(null=True) komore = models.IntegerField(null=True) krila = models.IntegerField(null=True) ks = models.IntegerField(default=True) kv = models.IntegerField(editable=False, null=True) ros = models.IntegerField(editable=False,blank=True, null=True) rov = models.IntegerField(editable=False,blank=True, null=True) proba = models.CharField(max_length=15,default='2') briner = models.CharField(max_length=15,default='2' def calculate(self): return self.sirina + self.visina total = property(calculate) def save(self,*args,**kwargs): self.ks = self.calculate() super(Video,self).save(*args, **kwargs) Views.py def showvideo(request): form = VideoForm(request.POST) if form.is_valid(): b = 5000 sirina = request.POST.get('sirina') visina = request.POST.get('visina') roletne = request.POST.get('roletne') #smejanje = sirina + 5000 s = sirina #k = sirina #b = k + 20 print(s) print(sirina) if sirina == '100' and roletne =='100': print(True) a = Video() ## a.save() ## From here it respond with error NoneType ## else: print(False) -
Python Manage.py and Pycharm
python manage.py runserver not working in pycharm and giving this error even I have put manage.py in settings of Django in Language & Framework Django Tab.. what it could be? (venv) C:\Users\ionezation\PycharmProjects\ecomesite\ecs>python manage.py runserver Traceback (most recent call last): File "manage.py", line 10, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 16, in main ) from exc ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? -
sent python object over rest api
I have created a rest api service and code is running fine over server. I was wondering if there is way through which we can send the python objects instead of the string, tuple, Response instance, or WSGI callable Here is code for reference: from flask import Flask , request , jsonify import requests app = Flask(__name__) def fun(path1): data = '' with open(path1) as f: data = f.read() return data @app.route('/client',methods=['POST']) def client(): data = request.get_json() path1 = data['loc'] return fun(path1) I was just wondering instead of data I should receive fun object. so that I can process in my local system in an application (pyqt) and do other task using this. -
How do I get data in nested format from django forms
I have a django project built using custom django admin and django forms. I'm trying to make a post request to an API. How do i get the data from the forms in a nested format. My forms currently looks like this, class CampaignForm(forms.Form): consumer = forms.CharField(max_length=200) startDate = forms.DateTimeField( input_formats=['%d/%m/%Y %H:%M']) endDate = forms.DateTimeField( input_formats=['%d/%m/%Y %H:%M']) referreeCredits = forms.IntegerField() referrerCredits = forms.IntegerField() maxReferreeCredits = forms.IntegerField() maxReferrerCredits = forms.IntegerField() message = forms.CharField(max_length=200) kramerTemplateId = forms.CharField(max_length=200) paymentMode = forms.CharField(max_length=200) eventName = forms.CharField(max_length=200) operator = forms.CharField(max_length=200) value = forms.IntegerField() mOperator = forms.CharField(max_length=200) mValue = forms.IntegerField() mReferrerCredits = forms.IntegerField() The json that the API takes looks like this: { "consumer": "FILING", "startDate": 0, "endDate": 0, "referreeCredits": 0, "referrerCredits": 0, "maxReferreeCredits": 0, "maxReferrerCredits": 0, "message": "string", "kramerTemplateId": "string", "eventRules": [ { "eventName": "string", "operator": "EQUAL", "value": 0 } ], "milestoneRules": [ { "operator": "EQUAL", "value": 0, "referrerCredits": 0 } ], "paymentMode": "PAYTM" } I've also tried hardcoding the json unsuccessfully(I'm getting a 400 bad request error), def campaign_add(self, request): form = CampaignForm() if request.method == 'POST': import ipdb; ipdb.set_trace() form = CampaignForm(request.POST) if form.is_valid(): dat = { "consumer": request.POST["consumer"], "startDate": self.datetime_to_epoch(request.POST["startDate"]), "endDate": self.datetime_to_epoch(request.POST["endDate"]), "referreeCredits": int(request.POST["referreeCredits"]), "referrerCredits": int(request.POST["referrerCredits"]), "maxReferreeCredits": int(request.POST["maxReferreeCredits"]), "maxReferrerCredits": int(request.POST["maxReferrerCredits"]), "message": request.POST["message"], "kramerTemplateId": … -
ERROR:- as_view() takes 1 positional argument but 2 were given
After running the server i am getting error as as_view() takes 1 positional argument but 2 were given please have a look on below code and suggest me. views.py from django.views.generic import View import json class JsonCBV(View): def get(self,request,*args, **kwargs): emp_data= {'eno':100,'ename':'pankhu','esal':300000,'eaddr':'pune'} return JsonResponse(emp_data) urls.py from django.contrib import admin from django.urls import path from testapp import views urlpatterns = [ path('admin/', admin.site.urls), path('jsonapi3/', views.JsonCBV.as_view), ] test.py import requests BASE_URL='http://127.0.0.1:8000/' ENDPOINT='jsonapi3' resp =requests.get(BASE_URL+ENDPOINT) data=resp.json() print('Data from django application') print('#'*50) print('Employee number:',data['eno']) print('Employee name:',data['ename']) print('Employee salary:',data['esal']) print('Employee address:',data['eaddr']) -
How to Implement an application with real time chat (audio,video,text,file support & tagging user in chat) system in dajngo
I am trying to implement chatting application using django-channels,but I have to implement many functionality as like slack in my app, such as file uploading, tagging user in chat etc. I have tried to implement file uploading by calling api & upload the file S3, then send the link to the socket. -
Django StopIteration issue
I would like to get your help according to my issue : StopIteration. Principe: I have a function which get as arguments a list of ids and a specific id. This list of ids corresponds to an array with pagination. This function is called when I create a new object in this array. Once my object is created, I'm redirected to the good page in my array. My function: def get_pagination(my_list_of_objects, pk): # if object doesn't exist, add id to list of objects if pk not in my_list_of_objects: my_list_of_objects.append(pk) # Get the list of objects code splitted by PAGE_LIMIT sorted by code (default) my_list_of_objects_code = MyModel.objects.values_list('code', flat=True).filter(id__in=my_list_of_objects) pagination = [my_list_of_objects_code[x:x + settings.PAGE_LIMIT] for x in range(0, len(my_list_of_objects_code), settings.PAGE_LIMIT)] # Get first and last page number first_page = 1 last_page = len(pagination) # Get sublist index (e.g page number for specific id) page_number = (next(index for index, value in enumerate(pagination) if pk in value)) + 1 return pagination, first_page, last_page, page_number Through this way : my_list_of_objects: list of objects id my_list_of_objects_code: list of objects sorted by code pagination: Split the list in sublists with n elements inside. n corresponds to pagination set in settings. first_page: first page number (e.g 1 as … -
How to properly pull from a database using Django and template tags
I'm trying to create a web application using Django that displays information about employees and schedules. I have the data for the employees stored in the Django database but when I try to pull from it and display information in a table nothing happens. I don't get an error so I'm not sure if I'm using the right methods or not. I haven't used Django before so I'm not sure if I'm doing this right. I'm currently writing the script to pull from the database and display in the html page it's supposed to show up in while using a python file to store the Django template tag. I tried before just pulling data from the database from the html file but was unable to since I needed to import my django model libraries and couldn't do that on html. I have the code split into two parts. The script that does the query is in my tag template labeled DatabaseQueryScript which is as follows: @register.filter(name='PullEmployees') def PullEmployeesFromDatabase(): AllEmployees = Profile.objects.all() return AllEmployees Then I call the function in the html file {% load DatabaseQueryScript %} {%for employee in PullEmployees%} ```printing data to a table on screen``` {%endfor%} I expect … -
Django with celery for a WSGI application, without any external message broker
Django integration is present in this repo: https://github.com/celery. But not clearly documented. Need a Simple Django with celery integration that can run as WSGI application, without any external message broker. Use case of django-celery-result is not clearly mention, and django-celery is out dated. Any alternative like django-celery with latest django and celery. -
Django 2.1 Best practice -> context processor or custom template tag or best way?
I have a common several links on footer HTLM for every website page. So I need to access a model with this common data. What's the best way using Django 2.1 ? How to do it ? -
how to login to graphql page(localhost:8000/graphql) with django
I want to use @login_required function like below code. and I want to check the query correctly works. import graphene from graphql_jwt.decorators import login_required class Query(graphene.ObjectType): user = graphene.Field(UserType) @login_required def resolve_me(self, info): user=info.context.user return types.UserProfileResponse(user=user) i put the code into graphql(localhost:8000/graphql) query{me{user{id}}}} the message is you do not have permission to perform this action I think maybe I have to give token to graphql. but i don't know how to give token. could you teach me? -
VsCode Exception has occurred: VariableDoesNotExist
VsCode throws exception when using debugger to run Django. I got same problem on two different project which was working fine before. I can't recall any changes that would lead to this exception. It occurs when I try to open Django admin page. Exception: Exception has occurred: VariableDoesNotExist Failed lookup for key [is_popup] in [{'True': True, 'False': False, 'None': None}, {'csrf_token': <SimpleLazyObject: '1XjSoBrvAaFZuOY9WTme5tXLO8awl43ORBO5YolUoHOlM0nOLDAfGd0atO3kh3dI'>, 'debug': True, 'sql_queries': <function debug.<locals>.<lambda> at 0x109638c80>, 'request': <WSGIRequest: GET '/login/?next=/'>, 'user': <SimpleLazyObject: <django.contrib.auth.models.AnonymousUser object at 0x1095d3908>>, 'perms': <django.contrib.auth.context_processors.PermWrapper object at 0x1095d3550>, 'messages': <django.contrib.messages.storage.fallback.FallbackStorage object at 0x1095d3c50>, 'DEFAULT_MESSAGE_LEVELS': {'DEBUG': 10, 'INFO': 20, 'SUCCESS': 25, 'WARNING': 30, 'ERROR': 40}}, {}, {'form': <AdminAuthenticationForm bound=False, valid=Unknown, fields=(username;password)>, 'view': <django.contrib.auth.views.LoginView object at 0x1095d3940>, 'site_title': 'Administration', 'site_header': 'Meridia ETL', 'site_url': '/', 'has_permission': False, 'available_apps': [], 'title': 'Log in', 'app_path': '/login/?next=/', 'username': '', 'next': '/', 'site': <django.contrib.sites.requests.RequestSite object at 0x1095d35f8>, 'site_name': 'localhost:8000', 'LANGUAGE_CODE': 'en-us', 'LANGUAGE_BIDI': False}] File "/Users/macbook/Development/MERIDIA/meridiaETLproject/env/lib/python3.7/site-packages/django/template/base.py", line 850, in _resolve_lookup (bit, current)) # missing attribute File "/Users/macbook/Development/MERIDIA/meridiaETLproject/env/lib/python3.7/site-packages/django/template/base.py", line 796, in resolve value = self._resolve_lookup(context) File "/Users/macbook/Development/MERIDIA/meridiaETLproject/env/lib/python3.7/site-packages/django/template/base.py", line 671, in resolve obj = self.var.resolve(context) File "/Users/macbook/Development/MERIDIA/meridiaETLproject/env/lib/python3.7/site-packages/django/template/defaulttags.py", line 875, in eval return self.value.resolve(context, ignore_failures=True) File "/Users/macbook/Development/MERIDIA/meridiaETLproject/env/lib/python3.7/site-packages/django/template/defaulttags.py", line 302, in render match = condition.eval(context) File "/Users/macbook/Development/MERIDIA/meridiaETLproject/env/lib/python3.7/site-packages/django/template/base.py", line 904, in render_annotated return self.render(context) File "/Users/macbook/Development/MERIDIA/meridiaETLproject/env/lib/python3.7/site-packages/django/template/base.py", … -
what is constants and why use constants in django?
I an new to Python-Django. What is the constants in django. I have seen lot of explanations in many websites. But i could't understand can any one explain the that thing with simple example. used that constant in django like in settings.py my_const='my_value' in views.py import django.conf import settings def my_site(request): return {'my_site':my_const} why use constants and what is exactly constants? -
How to write url pattern for primary key
I am having difficulty in Dynamic Url patterns in django can anyone give some reference for this path('/', views.SchoolDetailView, name='detail') -
How to Fix "The serializer field might be named incorrectly and not match any attribute or key on the `Model` instance in DRF
I'm using Django Rest Framework and I have attempted to add a custom field that does not exist in the HPIQuestionBank model to serializers.py file and so far the code is as below but I am getting and error. I'm aware the checkboxes and checkboxValues are not attributes of the model but my goal is to make them custom fields where am I going wrong? answer_type is a custom field and it's ok and working correctly. Got AttributeError when attempting to get a value for field `checkboxes` on serializer `TemplateQuestionBankSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `HPIQuestionBank` instance. Original exception text was: 'HPIQuestionBank' object has no attribute 'checkboxes'. serializer class TemplateQuestionBankSerializer(serializers.ModelSerializer): answer_type = serializers.CharField(write_only=True) checkboxes = serializers.ListField(child=serializers.CharField(write_only=True)) checkboxValues = serializers.ListField(child=serializers.CharField(write_only=True)) class Meta: model = HPIQuestionBank fields = ['id','label','answer_type','checkboxes','checkboxValues'] models class HPIQuestionBank(models.Model): label = models.CharField( max_length=200, db_index=True, blank=True, null=True) template = models.ForeignKey( HPIFilter, blank=True, null=True, on_delete=models.CASCADE, default='') organization = models.IntegerField(blank=True, null=True)