Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to truncate yyyy-mm-dd to mm-dd in xAxis of Django Chartit chart?
I want to remove the YYYY from the x-axis date YYYY-MM-DD, because the chart is showed in a small area. For example, 2018-09-04 should be 09-04. I'm not sure whether any existing method can be used for this, Could somebody help? I'm using Django version 2.0, django-chartit 0.2.9, and Python 3.7.0. def get_block_chart(self): blockpivotdata = DataPool( series=[{ 'options': { 'source': Block.objects .annotate(date=TruncDay('timestamp')) # Truncate to day and add to select list .values('date') # Group By day .annotate(num=Count('hash')) # Select the count of the grouping .values('date', 'num') # select day and num .order_by('date') }, 'terms': [ 'date', 'num' ] }] ) return Chart( datasource=blockpivotdata, series_options=[{ 'options': { 'type': 'line', 'stacking': False }, 'terms': { 'date': [ 'num', ] } }], chart_options={ 'title': { 'text': 'Block Count Chart'}, 'xAxis': { 'title': { 'text': 'Date'}}, 'yAxis': { 'title': { 'text': 'Block'}}, 'legend': { 'enabled': False}, 'credits': { 'enabled': False}}, ) -
Django Rest framework, how to include '__all__' fields and a related field using foreignkey_id field
So here is my files - Models.py class Model1(models.Model): user = models.ForeignKey(User) other_fields = models.CharField(max_length=40) Serializers.py class MySerializer(ModelSerializer): class Meta: model = Model1 fields = '__all__' Here json request {"user_id":1, "other_fields":"details"} and in views.py serializer = MySerializer(data=request.data) serializer.data **Throws keyerror "user"** When i try to change request parameter "user_id" to "user" it works for me . But I cant change request json. Is there any way to handle this issue in serializer? I can set all the fields inplace of '_all_' but it is not a good solution due to large number of fields . I also tried with - class MySerializer(ModelSerializer): user = serializers.CharField(source='user_id') class Meta: model = Model1 fields = '__all__' but it was not worked for me. -
"CSRF Failed: CSRF cookie not set after" Django upgrade
I've made a Django upgrade from 1.7.5 to 1.11.15. I'm also using Django Rest Framework verion 3.3.2. After this all PUT/POST (probably DELETE too) requests are denied with 403 Status code and message : {"detail":"CSRF Failed: CSRF cookie not set."} The middleware classes I employ in settings.py are : MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', #'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware' ) I noticed that if I enable the 'django.middleware.csrf.CsrfViewMiddleware' middleware class then everything works fine. However since I do not know clearly why this is class is currently disabled I would like to leave it as it is and look for another workaround. What would be the options in this scenario? -
How to automatically reload a Django app using django-livesync when a SCSS file changes?
I'm using https://github.com/fabiogibson/django-livesync to automatically refresh the Django page when some file changes. It works fine for any HTML or CSS file changed, however I'm now using https://github.com/jrief/django-sass-processor to compile SASS. Unfortunately, django-livesync doesn't work when a SCSS file is modified. Is there any way to make them work together? -
insert new field and value in nested json list with using recursion in Python Django rest framework
please any one tell me how to update/insert field and value in nested json list based on condition. like first my nested json list is like objlist= [{ "label": "1", "children": [{ "label": "2", "children": [{ "label": "3" }]}]}{"label": "4","children": [{ "label": "5"},{ "label": "6"}]}{"label":"7"},{"label":"8"}] after implement recursion and logic my output will like below\ objlist= [{ "label": "1", "children": [{ "label": "2", "children": [{ "label": "3" }]}], "checked":"true"}{"label": "4","children": [{ "label": "5", "checked":"true"},{ "label": "6"}]}{"label":"7"},{"label":"8", "checked":"true"}] and achieve this the code would be written below def get(self, request, format=None): queryset = models.Master_Industry.objects.filter(parent__isnull=True) serializer1 = masterserializer.IndustrySerializer(queryset, many=True) json_string = json.dumps(serializer1.data) stringobj = 2,5 my_dict = json.loads(json_string) for item in my_dict: if item["value"] in stringobj: item["checked"] = True continue for itemchild in item["children"]: if itemchild["value"] in stringobj: itemchild["checked"] = True continue for itemchildinner in itemchild["children"]: if itemchildinner["value"] in stringobj: itemchildinner["checked"] = True continue print(my_dict) return Response(serializer1.data) so please tell me how to resolve this? thanks -
Django TypeError: render() takes 2 positional arguments but 3 were given ?
i am sending an email to my drivers from my employee site but i am not able to send a driver id with the url link . and now it comes with the error render | join_message = template.render(ctx, request) TypeError: render() takes 2 positional arguments but 3 were given def rentacar_carapp_approve(request): if request.POST: try: args['driver'] = driver = Driver.objects.get(id=request.POST.get('driver_id')) subject = "Please Register Your Car" from_email = settings.EMAIL_HOST_USER to_email = 'bakrshk@gmail.com' if to_email is not None: template = Template("""Please hit the link and book a car {{ request.get_host }}{% url 'detail' driver_id=driver_id %}""") ctx = Context({'driver_id': driver.id}) join_message = template.render(ctx, request) send_mail(subject=subject, from_email=from_email, recipient_list=[to_email], message=join_message, fail_silently=False) print("email sent") except Driver.DoesNotExist: print("Driver doesn't exists") return HttpResponseRedirect('/mega-admin/rentacar/carapp-manager/') please tell me the solution i am newbie to django . -
django REST framework, validate json data
The server comes with json format: { "type": "string", "object": { "lead_id": int, "form_name": "string", "answers": [ { "key": "string", } ... ] }, "group_id": int, "secret": "string" } How to use django rest framework to validate this json? ru version -
Channels2 working on AWS Elastic Beanstalk
It works on my localhost. But when I deploy on AWS ElasticBeanstalk, I get this error: Traceback (most recent call last): File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response resolver_match = resolver.resolve(request.path_info) File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/urls/resolvers.py", line 523, in resolve raise Resolver404({'tried': tried, 'path': new_path}) django.urls.exceptions.Resolver404: {'tried': [[<URLPattern '^$' [name='home']>], [<URLPattern '^comunidade/'>]], 'path': 'socket/comunidade/'} During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 99, in get_exception_response response = callback(request, **dict(param_dict, exception=exception)) TypeError: handler404() got an unexpected keyword argument 'exception' My routing.py: application = ProtocolTypeRouter({ "websocket": OriginValidator( AuthMiddlewareStack( URLRouter([ # URLRouter just takes standard Django path() or url() entries. path("socket/", MyConsumer), url("socket/(?P<slug>[\w-]+)", MyConsumer), ]), ), [".mydomain.com.br", "localhost"] ), }) My JS connection: var ws_scheme = window.location.protocol == "https:" ? "wss" : "ws"; var connection = new WebSocket( ws_scheme + "://" + window.location.host + "/socket" + window.location.pathname ); In AWS config, WSGIPath is pointing to wsgi.py. It seems to be routing channels 2 to urls.py -
How to use CreateView with numeric fields and primary key
I am trying to create and object using CreateView, so I give django template name, model and fields. In my fields I have description, number of hours and primary key (hidden, as it is not obligatory to have it). I want to edit all the fields (including number of hours) but first of all, I cannot include field to enter hours in form, and secondly, I have the error ]Cannot insert the value NULL into column 'id'. But it should insert it automaticaly or at least let me edit it. -
Get Specific Length of String in jinja template
I have a CharField in model that can contains String of any length upto 1000... details = models.CharField(max_length=1000) How can I get the String of specific length(say 10) in my template? {{ details|10 }} -
dockerization of a project in python
I'm migrating a project to python on docker for a better "facility" for development. it's a project that runs with python 2.7, Django 1.6.8 and several RPC dependencies I find myself with a crash of the application with this stacktrace that I can't find the missing module (No module named coros). I'm thinking it should either be an addiction problem related to a version that is not good or an addiction installed on the default bone but not on the docker bone. Do you have any ideas or suggestions to correct this problem? app_1 | Traceback (most recent call last): app_1 | File "/usr/local/lib/python2.7/wsgiref/handlers.py", line 85, in run app_1 | self.result = application(self.environ, self.start_response) app_1 | File "/usr/local/lib/python2.7/site-packages/django/contrib/staticfiles/handlers.py", line 67, in __call__ app_1 | return self.application(environ, start_response) app_1 | File "/usr/local/lib/python2.7/site-packages/django/core/handlers/wsgi.py", line 187, in __call__ app_1 | self.load_middleware() app_1 | File "/usr/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 45, in load_middleware app_1 | mw_class = import_by_path(middleware_path) app_1 | File "/usr/local/lib/python2.7/site-packages/django/utils/module_loading.py", line 26, in import_by_path app_1 | sys.exc_info()[2]) app_1 | File "/usr/local/lib/python2.7/site-packages/django/utils/module_loading.py", line 21, in import_by_path app_1 | module = import_module(module_path) app_1 | File "/usr/local/lib/python2.7/site-packages/django/utils/importlib.py", line 40, in import_module app_1 | __import__(name) app_1 | File "/var/www/ofsdashboards/common/middleware/login_required.py", line 7, in <module> app_1 | compile(reverse('ofsdashboards.account.views.login').lstrip('/')), app_1 | File … -
How to hide the xAxis and yAxis title of Django Chartit chart?
I want to hide the x/y axis title in a small chart. I tried removing xAxis and yAxis fields from chart_options, but result is same. Could somebody help? return Chart( datasource=blockpivotdata, series_options=[{ 'options': { 'type': 'line', 'stacking': False }, 'terms': { 'date': [ 'num', ] } }], chart_options={ 'title': { 'text': 'Block Count Chart'}, 'xAxis': { 'title': { 'text': 'Date'}}, <<<< this one 'yAxis': { 'title': { 'text': 'Blocks'}}, <<<< and this one 'legend': { 'enabled': False}, 'credits': { 'enabled': False}}, ) BTW, I'm using Django version 2.0, django-chartit 0.2.9, and Python 3.7.0. -
How to upload list of files contained in a folder?
I am a python developer (python 3.6 in my pc), and as part of a project django (v==2.1) I want to upload list of files already in my folder and then empty it. I did several research on stackoverflow and on the Net most of the talk about the functions of the files in folders like walk, etc. What I want is to upload the files contained in a given folder in order to keep a reference of these in database. Thank you in advance. -
How add a html template as loading screen in AngularJS untill http response is recieved?
My project architecture is in this way .. I have a django-rest-api (api) in a django project and normal django app with TemplateView's , In django app templates I use both django template tags and angularJs tags and I differentiate them using {% verbaitm %} tag. I want to know the best way to show loading page . -
how to pass the dynamic variable in raw sql query using django mysql
How to archive the following... i need to pass two variable date which comes as long format and apply this variable in a subquery using raw sql django def duplicatephoneno(request): cursor = connection.cursor() payload = json.loads(request.body.decode('utf-8')) print(payload) if payload: startdate=payload['from'] enddate=payload['to'] with connection.cursor() as cursor: cursor.execute(MYSQLdb.escape_string("SELECT * FROM `allergy` WHERE `allergy`.`patient_n_key` IN (SELECT `patient_masters`.`patient_n_key` FROM `patient_masters` WHERE `patient_masters`.`created_on`between %s AND %s)",[startdate], [enddate])) row = dictfetchall(cursor) patientuser=serializers.serialize('json', row) return HttpResponse(patientuser, content_type='application/json;charset=utf8') -
TypeError: the first argument must be callable when I import a scheduler in my views.py file of django?
I am using Django 1.11. I want to use the scheduler in my application to run my script once in a day. This is my view.py file from __future__ import print_function from django.shortcuts import render from django.utils import timezone from django.http import HttpResponse from datetime import datetime, timedelta import requests import schedule import time def republic(request): return HttpResponse("<h1>Success Hindustan</h1>") def indiatv(request): return HttpResponse("<h1>Success Hindustan</h1>") def ndtv(request): return HttpResponse("<h1>Success NDTV</h1>") schedule.every().day.at("17:19").do(republic(requests)) schedule.every().day.at("17:19").do(indiatv(requests)) schedule.every().day.at("17:19").do(ndtv(requests)) while 1: schedule.run_pending() time.sleep(1) When I run the server I am getting following error File "/home/imsaiful/PiroProject/pironews/feed/urls.py", line 2, in <module> from . import views File "/home/imsaiful/PiroProject/pironews/feed/views.py", line 230, in <module> schedule.every().day.at("17:19").do(republic(requests)) File "/home/imsaiful/anaconda3/lib/python3.6/site-packages/schedule/__init__.py", line 385, in do self.job_func = functools.partial(job_func, *args, **kwargs) TypeError: the first argument must be callable But when I remove the scheduler lines then the application running properly. So, kindly help me to overcome this error? -
django-filter: How to concatenate columns
How to concatenate User.first_name and last_name in the same field when using django-filter? I'd like to have a single form field for querying something like John Smith. -
Using django prefetch_related()
Given the following: return Client.objects.filter(case=self.kwargs['case_pk'] ).prefetch_related('parent_set', 'children_set') This works correctly, although I think my filter is creating far too many queries. However, my problem is that there may be more than one Client. This results in: clienta parent1 clienta child1 clientb parent1 parent2 clientb child1 child2 I need to group the parents and children to the client, so I can produce something like this in a template: clienta parent: parent1 children: child1 clientb parents: parent1 parent2 children: child1 child2 Hope that makes sense. -
Django Rest Framework Get Additional related fields in one to many relation
Here's the problem Products have multiple sizes which is many to many relation Products |-------|---------| | ID | Title | |-------|---------| Sizes |-------|---------| | ID | Title | |-------|---------| Size Through |------|--------------|-----------|---------| | ID | Product ID | Size ID | Stock | |------|--------------|-----------|---------| I manage to get sizes in my product api using Django Rest Framework but i don't know how to get stock information as well. here is the code I've class SizeSerializer(serializers.ModelSerializer): class Meta: fields = ( 'id', 'title', ) model = Size class ProductsSerializer(serializers.ModelSerializer): sizes = SizeSerializer(many=True) class Meta: fields = ( 'url', 'id', 'title', "sizes", ) model = Products I would appreciate any help in this problem -
how i can fill my data on just one bootstrap table django 2.1
my picture i have problem with using table. i want to show one table my data but , it doesnt work, my program showing all my data different table but i dont want this. how i repair this situation ? my html codes thank u for your interest... <div class="container"> <div class="row"> <div class="col-3"> <a class="btn btn-warning" href="{% url 'ANASAYFA'%}"> ANASAYFA </a> <br> {% now "jS F Y H:i" %} </div> <div class="col-6"> {% for i in veriler %} <table class="table table-bordered table-dark"> <thead> <tr> <th scope="col">TARİH</th> <th scope="col">İSİM-SOYİSİM</th> <th scope="col">VARDİYA BÖLGE</th> <th scope="col">VARDİYA DÖNEM</th> </tr> </thead> <tbody> <tr> <th scope="i.row">{{ i.gun }}</th> <th>{{ i.personel }}</th> <th>{{ i.bolge }}</th> <td>{{ i.vardiya_donemi }}</td> </tr> </tbody> </table> {% endfor %} -
I cannot save image to mysql database on django with ImageField. (django version: 2.1)
When I am saving data with ImageField on django on sqlite db it's saving without any problem but when I am trying to save image on mySql database I am getting error like "expected str, bytes or os.PathLike object, not tuple". It's my code: Settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'dbname', 'USER': 'user', 'PASSWORD': 'password', 'HOST': 'localhost', } } ... MEDIA_URL = '/static/media/' MEDIA_ROOT = os.path.join(BASE_DIR, "static/media") models.py from django.db import models from subjects.models import Subjects class Course(models.Model): subject = models.OneToOneField(Subjects, on_delete=models.CASCADE) name = models.CharField(max_length=255) img = models.ImageField(upload_to="images", blank=True) def __str__(self): return self.name_en And I have also registered my model on admin.py to have permission. and I have also installed pillow to use ImageField. It's an error: Request Method: POST Request URL: http://127.0.0.1:8000/admin/course/course/add/ Django Version: 2.1 Python Version: 3.6.5 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'subjects', 'visit', 'course'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "/home/user/.virtualenvs/learneng/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/home/user/.virtualenvs/learneng/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 126. response = self.process_exception_by_middleware(e, request) File "/home/user/.virtualenvs/learneng/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 124. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/user/.virtualenvs/learneng/lib/python3.6/site-packages/django/contrib/admin/options.py" in wrapper 607. return self.admin_site.admin_view(view)(*args, **kwargs) File "/home/user/.virtualenvs/learneng/lib/python3.6/site-packages/django/utils/decorators.py" in _wrapped_view 142. response = view_func(request, *args, **kwargs) File "/home/user/.virtualenvs/learneng/lib/python3.6/site-packages/django/views/decorators/cache.py" … -
Is it possible to run locally even after deploying into AWS eb?
I'm a beginner and I've been working on Django project. Is it possible to run locally even after deploying into AWS? If so, what is the preferable way to do that? Also, is it possible to have multiple db so I can use both for development and production? -
Integrate Paho MQTT with Django
i am doing a project which use Django and MQTT. There is a situation that i want to re-subscribe all topics relating to models in database when my Django web server reconnect to the broker after disconnecting from some reason. I have the model Room as below: class Room(models.Model): building = models.ForeignKey(Building, on_delete= models.CASCADE) number = models.PositiveIntegerField() available = models.BooleanField(default=True) power = models.BooleanField(default=False) class Meta: ordering = ['building', 'number'] unique_together = ['building', 'number'] def __str__(self): return f"{self.building.bid}/{self.number}" def get_mqtt_topic(self): return f"{self.building.bid}/{self.number}" The method get_mqtt_topic() will return the MQTT topic associated to the room. MQTT client code mqtt/client.py: import paho.mqtt.client as mqtt from .tasks import * from .models import Room def on_connect(client, userdata, flags, rc): print("Connecting to CloudMQTT broker: "+ mqtt.connack_string(rc)) room_mqtt = [(room.get_mqtt_topic(), 1) for room in Room.objects.all()] client = mqtt.Client() client.on_connect = on_connect client.on_message = on_message Because I put the code below in init.py to run mqtt client in a different thread from the django app. from mqtt.client import client client.loop_start() so i got this error: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. If you have any idea to solve this problem. I appreciate very much. Thank you for spending your time read this! -
Why in this PDF file generated in this example not able to add watermark Pyhton3
Why in this PDF file generated in this example not able to add watermark . How can I fix it? (There is no error, just does not able to display "WATERMARK".). template_name = assign_custom_template(template_name) template_path = template_name e_library_list = Elibrary.objects.get(pk=e_library_id,) retrun_questionlist = {} for e_library_question_list in e_library_list.products.all(): questionlist = MCQAnswerFiled.objects.filter(group__pk=e_library_question_list.id) retrun_questionlist[e_library_question_list.id] = questionlist context = {'e_library_list': e_library_list,'retrun_questionlist':retrun_questionlist} # Create a Django response object, and specify content_type as pdf response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="report.pdf"' # find the template and render it. template = get_template(template_path) html = render_to_string(template_path, context) response = BytesIO() file = open('sheetstudentcopy.pdf', "w+b") pdf = pisa.pisaDocument(BytesIO(html.encode("UTF-8")), file,link_callback=link_callback) file.seek(0) pdf = file.read() file.close() return HttpResponse(pdf, 'application/pdf') -
Styles missing after CollectStatic
So...It's the first time I have to edit a Django project. I edited some css and after updating my filen in server I did: python manage.py collectstatic The problem is that now I have lost all the styles in the website. When inspecting I find there are some error about not finding some Cache Files (??) Fortunately, this was in my dev server but I had to perform changes in prod but I can't take the risk with this problem. Is there a way to revert back changes btw? anyone's willing to help a Django noob?