Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is it necessary to use 'related_name' if one is using a through table in django?
I get errors telling me to change related names because of using a through table, so it it necessary to use a related name, if one will still use one in the through table? -
Django ORM Group By ID
I am trying to get some information from my table; total price, total trip etc between two dates. Here is my query start_date = Utils.subtract_day(datetime.datetime.today(), 30) end_date = datetime.datetime.today() trips = TbPastTrips.objects.filter(identity=identity, creation_time__range=(start_date, end_date), status=TripStatus.PAYMENT_COMPLETED)\ .annotate(total_price__=Sum('price'), total_tip=Sum('tip_amount'), total_additional_fees=Sum('additional_fees'), total_trip=Count('price')) \ .values('total_price__', 'total_tip', 'total_additional_fees', 'total_trip') print(trips.query) This is the raw sql query that I expect from above queryset: SELECT SUM(`tb_past_trips`.`PRICE`) AS `total_price__`, SUM(`tb_past_trips`.`TIP_AMOUNT`) AS `total_tip`, SUM(`tb_past_trips`.`ADDITIONAL_FEES`) AS `total_additional_fees`, COUNT(`tb_past_trips`.`PRICE`) AS `total_trip` FROM `tb_past_trips` WHERE (`tb_past_trips`.`IDENTITY` = 44444444444 AND `tb_past_trips`.`CREATION_TIME` BETWEEN '2017-08-29 10:36:19.446371' AND '2017-09-28 10:36:19.446405' AND `tb_past_trips`.`STATUS` = 4) But it adds below extra query: GROUP BY tb_past_trips.ID ORDER BY NULL to end of the query. But I don't want to group it. So what is the wrong thing that i am doing? Django version :(1, 11, 5, 'final', 0) Python 3.6.2 -
Custom function inside a Django model
How do I calculate the total with the existing model fields class Book(models.Model): school_id = models.ForeignKey(School) name = models.CharField(max_length=100, default=None, blank=None, unique=True) class_name = models.CharField(max_length=50) category = models.ForeignKey(Category) bundle = models.CharField(max_length=20, unique=True) particulars = models.CharField(max_length=50) tax_code = models.CharField(max_length=50, default=None) amount = models.FloatField() tax_CGST = models.FloatField(default=0) tax_SGST = models.FloatField(default=0) total = models.FloatField() def total(self): return ((self.tax_SGST+self.tax_CGST)*self.amount)/100 def __str__(self): return self.name In the above code, I want the total function to calculate the total from the Tax and amount fields and add it to the total field in the database -
Send OpenCV image in POST response
I wish to send image through POST response after perform some processing on image. cv2.putText(img,text, (x,y-15), font, 1,(255,0,0),2,cv2.LINE_AA) I got data in img. How do I encapsulate the image in the post request? I tried with return HttpResponse(img, content_type='image/jpg') It shows nothing in Postman. -
Django: mini-groups of permissions
I'd like to compose authorization groups picking preset configurations of permissions (one set of permissions for each area the user has access) instead of selecting manually hundreds of different permissions: I have a lot of models, many of which are extension of other models, and this results in having hundreds of similar permissions. I've found no solution ready (except for django-tabular-permission which helps in readability). Any hint? -
What's the best to make a tree of comments in django
I've made a model of comments with a prarent field to store a comment as a child of other one. My question is how to display it in template -
Error transferring django project from windows to linux
My project with py3 and django worked well in win10. But when I tried to make it work in linux, a 404 eror of static file appeared. The error message is below. [28/Sep/2017 09:32:57] "GET /static/home/cys/prj/.../cls_demo/static/c73f33679ff4328816dee4450044174e.jpg HTTP/1.1" 404 1955 ** Settings.py ** STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'collected_static') STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), os.path.join(BASE_DIR, "clsapp", "static"), ] STATICFILES_FINDERS = ( "django.contrib.staticfiles.finders.FileSystemFinder", "django.contrib.staticfiles.finders.AppDirectoriesFinder" ) **Sample of how I call static files through my templates** {% load staticfiles %} <div class="img" style="background-image: url('{% static img_path %}')"> </div> There is different code between win10 version and linux version. Why did this error appear? How to fix it... -
Django Translation - Translate dynamic strings
We are using Django as our backend REST API server. I am looking to translate text being sent as push notifications to our app. I am new to translations. The text resides in a config file and varies for each user. NOTIFICATION_TEXT = { 'access_request': '%(user_name)s has requested to access your document %(story_name)s, please review '} I saw the google translate feature and it perfectly translates if given the final sentence understanding the user_name and story_name are constant. I was looking for a similar magic band functionality in Django where I can just wrap final message before sending to user in the locale received in the Accept-language header of the REST call. But this doesn't seem possible. As I understand I would need to pre-mark the text which needs to be translated with ugettext and define language and middleware settings. Then generate locale specific files using django-admin makemessages -l de and then in the generated django.po file for that specific locale give the translated text manually for django to refer. But I am stuck how to mark given my message is dynamic, inside a dic. Or is there other way round? -
Gunicorn ImportError: No module named application
hi I'm following this tutorial https://semaphoreci.com/community/tutorials/dockerizing-a-python-django-web-application on how to deploy on docker a Django project,at some point you have to start using gunicorn my start.sh is like this. #!/bin/bash #start gunicorn processes echo "starting gunicorn for wrappers" exec gunicorn sparqlwrapper.wsgi.application --bind 0.0.0.0:8000 --workers 5 but when i run the start.sh I get this error starting gunicorn for wrappers [2017-09-28 12:47:05 +0000] [28740] [INFO] Starting gunicorn 19.7.1 [2017-09-28 12:47:05 +0000] [28740] [INFO] Listening at: http://0.0.0.0:8000 (28740) [2017-09-28 12:47:05 +0000] [28740] [INFO] Using worker: sync [2017-09-28 12:47:05 +0000] [28745] [INFO] Booting worker with pid: 28745 [2017-09-28 12:47:05 +0000] [28746] [INFO] Booting worker with pid: 28746 [2017-09-28 12:47:05 +0000] [28747] [INFO] Booting worker with pid: 28747 [2017-09-28 12:47:05 +0000] [28745] [ERROR] Exception in worker process Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/gunicorn/arbiter.py", line 578, in spawn_worker worker.init_process() File "/usr/local/lib/python2.7/dist-packages/gunicorn/workers/base.py", line 126, in init_process self.load_wsgi() File "/usr/local/lib/python2.7/dist-packages/gunicorn/workers/base.py", line 135, in load_wsgi self.wsgi = self.app.wsgi() File "/usr/local/lib/python2.7/dist-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/usr/local/lib/python2.7/dist-packages/gunicorn/app/wsgiapp.py", line 65, in load return self.load_wsgiapp() File "/usr/local/lib/python2.7/dist-packages/gunicorn/app/wsgiapp.py", line 52, in load_wsgiapp return util.import_app(self.app_uri) File "/usr/local/lib/python2.7/dist-packages/gunicorn/util.py", line 352, in import_app __import__(module) ImportError: No module named application [2017-09-28 12:47:05 +0000] [28745] [INFO] Worker exiting (pid: 28745) [2017-09-28 12:47:05 +0000] [28746] … -
Page not found (404) error happens I did not write the url
I got an error,Page not found (404) Request Method: GET Request URL: http://localhost:8000/app/test.html?prop=value . I wrote index.html like <body> <form method="post" action=""> <select id="mainDD" data-placeholder="Choose" class="chzn-select" style="width:600px;"> {% for i in json_data.items.values %} <option value="{{forloop.counter}}">{{ i }}</option> {% endfor %} </select> {% for key, values in preprocessed %} <select name="type" id=type{{forloop.counter}}> {% for counter, value in values %} <option value="{{forloop.counter}}">{{ value }}</option> {% endfor %} </select> {% endfor %} </form> <script type="text/javascript"> $(document).ready(function () { $('#mainDD').on('change', function() { var thisType = "type" + $(this).val(); for(i=1; i<6; i++) { var thisId = "type" + i; if(thisType !== thisId) { $("#"+thisId).hide(); } else { $("#"+thisId).show(); } } }).trigger('change'); }); </script> <form id="postform" action="http://localhost:8000/app/test_view" method="POST"> {% csrf_token %} <input type="submit" value="SEND"> </form> <script type="text/javascript"> let key = "prop"; let value = "value"; var array1 = []; var array2 =[]; document.querySelector("input[type=submit]").onclick = e => { const test = window.open(`test.html?${key}=${value}`, "_blank"); } </script> </body> This part const test = window.open(test.html?${key}=${value}, "_blank"); causes error because I did not regist url http://localhost:8000/app/"test.html?prop=value" .I only regist http://localhost:8000/app/test_view. But I wanna send selected i & value's values to test.html,so I wrote this like. I wrote in test.html like <body> <h2>RESULT</h2> <script type="text/javascript"> onload = () => { document.body.appendChild( document.createTextNode([...new … -
django datetimefield filter not working
I m trying to filter the date from the mysql table. if i dont put the date filter in ...my search form works fine...when i put that date filter it basically fails the form.is_valid() statement. It works fine without the filter created_at I have tried all the filter type for the created_at some of them gives this error the other doesnt give no error but, the none of the search filter give any results... this is the error that i get: ValueError: Cannot use None as a query value forms.py class AllTablesForm(forms.Form): title = forms.CharField(label='', max_length=250, required=False, widget=forms.TextInput(attrs={'placeholder': 'Title'})) url = forms.CharField(label='', max_length=250, required=False, widget=forms.TextInput(attrs={'placeholder': 'Url'})) description = forms.CharField(label='', required=False, widget=forms.TextInput(attrs={'placeholder': 'Description'})) created_at = forms.DateTimeField(label='', required=False, widget=forms.TextInput(attrs={'placeholder': 'Created At'})) where i do my search forms views.py def search_form_table(request, pk): table_name = Crawledtables.objects.get(id=pk) t = create_model(table_name.name) if request.method == 'GET': form = AllTablesForm(request.GET) if form.is_valid(): cd = form.cleaned_data title = cd['title'] url = cd['url'] description = cd['description'] created_at = cd['created_at'] # print created_at query = t.objects.filter(title__icontains=title, url__icontains=url, description__icontains=description, created_at__gte=created_at) return render(request, 'search/search_table.html', {'tbl_name': table_name, 'form': form, 'details': query}) else: form = AllTablesForm() return render(request, 'search/search_table.html', {'form': form}) right now i have created_at__gte and i get that error. it basically says that … -
Celery task - Inserting records into database does not work
This is my first days with Celery (Celery 4.1, Python 3, Django 1.10). And I am playing with a simple task that inserts records into my main database. The odd think is that I get no error messages, but the records are just not inserted in the database. Here's the code: views.py: def test_view(request): test.delay() return HttpResponse() tasks.py from __future__ import absolute_import, unicode_literals from celery import task from main.models import EmailDialog @task() def test(): a = EmailDialog() a.save() If I remove the .delay() and call test() as standard python function, I see the records appear in the database. But after adding back the .delay() part, the records are not added. I am wondering what direction to dig. P.S. I saw a similar question, but it did not help solve the issue either. -
Python telegram bot: Access to contact information
Following code requests location and contact from user: def contact(bot, update): dp = DjangoTelegramBot.dispatcher con_keyboard = KeyboardButton(text="send_contact", request_contact=True) loc_keyboard = KeyboardButton(text="send_location", request_location=True) custom_keyboard = [[ con_keyboard ,loc_keyboard]] reply_markup = ReplyKeyboardMarkup(custom_keyboard) bot.sendMessage(update.message.chat_id, text="Would you mind sharing your location and contact with me", reply_markup=reply_markup) My question is how can I access to phone number after user click on send_contact button? PS: I am using python-telegram-bot and django-telegrambot -
How to debug django with `heroku logs --tail` in detail?
I am new to Django. I've deployed my django site on Heroku. What I would like to know is how to display logs at production environment as same as that of development environment. Of course, I googled it but I just found tips about how to use logger, and this should be triggered by logger.info('str') at view, right? what I want to achieve is: display traceback as same as development environment display print method at every view, without logger (I mean, without defining logger.info to each locations. I know using print for debugging purpose at production is far from best practice, but it is okay, because I will delete it at once by using vim command after fixing all of the bugs. I am using: Django 1.11.5 Python 3.6.1 WSGI -
Object of type date is not JSON Serializable
I have a table in MySQL with name, period, indicator, value as the column names. Period stores date. I am trying to get the object from django using the following code def get_table(request): tab = list(table.objects.values('name', 'period' , 'indicator', 'value')) json_data = json.dumps(tab) return HttpResponse(json_data) I receive an error saying date is not JSON Serializable. How do I convert it to string before getting the object? Can anyone help me with the code? -
Django - modify css in result list item
I have simple result list in my admin panel. For example it is something like that: id name description category In my admin panel there is result list with classes "row1", "row2". I would like to add another class depending of obj value (obj.group_id which is not listed). I mean: if obj.group_id == 2: add class "premium" to result list item # whole row with this item I would like to simply distinguish some rows in my django admin panel. I don't have any idea how can I achieve that. Any clues? -
django admin cascade dropdownlist
model.py class CaseTitle(BaseModel): Description = models.CharField(max_length=500) def __str__(self): return self.Description class CaseCategory(BaseModel): Description = models.CharField(max_length=500) CaseTitle = models.ManyToManyField(CaseTitle) my scenario is when select casetitle dropdown, CaseCategory must be fill according to CaseTitleID -
Can I use the python object directly in template?
in the views.py I pass the data to the template: data = { "net_title":"private", "server_data":OneObject, } return render(request, "index.html", {"data":data}) In the index.html template, I want to use the data.net_title as the key to get value. I don't know whether it is feasible: {{ data.server_data.THE_NET_TITLE }} # THE_NET_TITLE should be `data.net_title`. Can realize this requirement? -
How can I run a background-task in django and when it's done, I can push information to front end.
Since one of my tasks in views.py is time-consuming, so I think I'd better put it in the background. But also, I want to make sure when this task finished, I'll receive something in the front end. How can I achieve this? I've searched and found django-channels, but still, I can't combine the two goals together. Hope someone will help me. -
defining multiple variabless within a form issue
Hi guys I have something that I do not know how to make it work. I am working on a questionnaire like, where on a page will show up the questionn and a radio like form list of answers that the user can select. I gave it a try but I do not know how to link a question to my form, could you please help ? models.py: from django.db import models # Create your models here. class Questionnaire(models.Model): question = models.CharField(max_length=600) multiple_answer = models.BooleanField(default=False) def __str__(self): return self.question class Answers(models.Model): question_id = models.ForeignKey('Questionnaire', on_delete=models.CASCADE) answer = models.CharField(max_length = 600) def __str__(self): return self.answer class Test(models.Model): user = models.ForeignKey('registration.MyUser') created_at = models.TimeField(auto_now_add=True) closed = models.BooleanField(default=False) class UserAnswer(models.Model): test_id = models.ForeignKey('Test') question = models.ForeignKey('Questionnaire') answer = models.ForeignKey('Answers') views.py: def AnswerChoiceSelect(request): #import pdb; pdb.set_trace() if request.method == "POST": answer_form = QuestionChoices(request.POST) if answer_form.is_valid(): print("working") else: print('Non Valid form') else: answer_form = QuestionChoices(request.user) return render(request,'question_template.html', {'answer_form':answer_form }) forms.py: from django import forms from django.contrib.auth.models import User from registration.models import MyUser from .models import Questionnaire, Answers, Test, UserAnswer from django.contrib.auth import get_user_model User = get_user_model() class QuestionChoices(forms.Form): question_choice = forms.ModelChoiceField(widget=forms.RadioSelect, queryset=None) def __init__(self,questionnaire, *args, **kwargs): super(QuestionChoices, self).__init__(*args, **kwargs) current_question = Questionnaire.objects.get(id = question_id) self.fields['question_choice'].queryset … -
Uncaught TypeError: Cannot set property 'onclick' of null- I moved the script upper now code
I got an error,Uncaught TypeError: Cannot set property 'onclick' of null. I wrote <body> <form method="post" action=""> <select id="mainDD" data-placeholder="Choose" class="chzn-select" style="width:600px;"> {% for i in json_data.items.values %} <option value="{{forloop.counter}}">{{ i }}</option> {% endfor %} </select> {% for key, values in preprocessed %} <select name="type" id=type{{forloop.counter}}> {% for counter, value in values %} <option value="{{forloop.counter}}">{{ value }}</option> {% endfor %} </select> {% endfor %} </form> <script type="text/javascript"> $(document).ready(function () { $('#mainDD').on('change', function() { var thisType = "type" + $(this).val(); for(i=1; i<6; i++) { var thisId = "type" + i; if(thisType !== thisId) { $("#"+thisId).hide(); } else { $("#"+thisId).show(); } } }).trigger('change'); }); </script> <form id="postform" action="http://localhost:8000/app/test_view" method="POST"> {% csrf_token %} <input type="submit" value="SEND"> </form> <script type="text/javascript"> //this code let key = "prop"; let value = "value"; document.querySelector("input[type=button]").onclick = e => { const test = window.open(`test.html?${key}=${value}`, "_blank"); console.log(test); } </script> </body> I moved up codes within script tag in the place is under body tag to solve this error, but same error happens.How can I fix this? -
design pattern for masking group of objects as one
I'm working on a simple messaging app using Django. here is a problem I encountered. I want users to be able to send message to a group of other users. I also want to show the last sent and received messages for each user. the problem is when you send out a message to a lot of people. your messages Interface will be filled with the same message (one for each receiver). what I want to do is have the same UI as group messaging in smartphones meaning all the messages in a group message will be shown as one unless someone answers the message in which case a new conversation will be displayed for that user. I don't want to create a new model (class) for group messages and it would be inefficient to manage this in front end level. is there any design pattern that helps me do this? how can I do this without iterating over all the messages and finding the ones that belong to the same group? thanks in advance. what I have now: message for person 1: hi message for person 2: hi message for person 3: hi message for person 4: hi message … -
Deploying django app in google cloud
I am looking for a good tutorial for deploying django app to google cloud. Do you have any recommendations? I have tried this https://cloud.google.com/python/django/flexible-environment#setting_up_your_local_environment But I am stuck in this part. I used this command: ./cloud_sql_proxy -instances="[YOUR_INSTANCE_CONNECTION_NAME]"=tcp:5432 And the output is the screenshot below. It's taking to forever or is it normal? ; Since I was stuck in it. I proceeded to the next steps which is creating a new sql database and new user and password in google cloud. Then proceeded to the 'Configure the database settings', then 'Running app on local computer'. Now, I also have errors when I run: python manage.py migrate Error: So, I proceeded again to next steps. By modifying the settings.py and app.yaml. Then, errors occurred like invalid google cloud sql name I know it was not a good thing proceeding to the next steps without fixing first the first encountered errors, but it was taking me too long to wait like 2 hours. -
Can I use the python object directly in template?
In my views.py I get the bellow Object(openstack.compute.v2.server.ServerDetail): openstack.compute.v2.server.ServerDetail( OS-EXT-STS:task_state=None, addresses={u'private': [{u'OS-EXT-IPS-MAC:mac_addr': u'fa:16:3e:08:bf:54', u'version': 4, u'addr': u'192.168.1.8', u'OS-EXT-IPS:type': u'fixed'}, {u'OS-EXT-IPS-MAC:mac_addr': u'fa:16:3e:08:bf:54', u'version': 4, u'addr': u'103.35.202.3', u'OS-EXT-IPS:type': u'floating'}]}, links=[{u'href': u'http://controller:8774/v2.1/99a50773b170406b8902227118bb72bf/servers/d0ba93a8-952f-4c7f-a439-d4722c4100f8', u'rel': u'self'}, {u'href': u'http://controller:8774/99a50773b170406b8902227118bb72bf/servers/d0ba93a8-952f-4c7f-a439-d4722c4100f8', u'rel': u'bookmark'}], image={u'id': u'ecbd1ef0-7dcf-41ff-8618-4501aa4e3945', u'links': [{u'href': u'http://controller:8774/99a50773b170406b8902227118bb72bf/images/ecbd1ef0-7dcf-41ff-8618-4501aa4e3945', u'rel': u'bookmark'}]}, OS-EXT-STS:vm_state=active, OS-EXT-SRV-ATTR:instance_name=instance-0000003a, OS-SRV-USG:launched_at=2017-09-28T07:20:57.000000, flavor={u'id': u'1', u'links': [{u'href': u'http://controller:8774/99a50773b170406b8902227118bb72bf/flavors/1', u'rel': u'bookmark'}]}, id=d0ba93a8-952f-4c7f-a439-d4722c4100f8, security_groups=[{u'name': u'default'}], user_id=fb52853bde3d4d3e8e831749781f8671, OS-DCF:diskConfig=MANUAL, accessIPv4=, accessIPv6=, progress=0, OS-EXT-STS:power_state=1, OS-EXT-AZ:availability_zone=nova, metadata={}, status=ACTIVE, updated=2017-09-28T07:20:58Z, hostId=76f61a58cf6d411a30e3e34da4dd252a03aa0093d9dd19c653b234b3, OS-SRV-USG:terminated_at=None, key_name=None, OS-EXT-SRV-ATTR:hypervisor_hostname=controller, name=liao01, created=2017-09-28T07:20:44Z, tenant_id=99a50773b170406b8902227118bb72bf, os-extended-volumes:volumes_attached=[], config_drive=) I make it as a list(server_list) to pass to the template, can I use the object directly in the template? I tried bellow method, but can not get the values. {% for server in server_list %} {{server.name}} .... {% endfor %} But can not get the server.name. -
Django oscar uk and uk_UA translations
I have faced with such weird problem: I use django-oscar in my project. And need to translate the site to Ukrainian. There are two translation files in django-oscar core: uk and uk_UA. But the difference is that there are not all translated strings in uk_UA: https://github.com/django-oscar/django-oscar/blob/master/src/oscar/locale/uk/LC_MESSAGES/django.po#L4759 - uk strings and https://github.com/django-oscar/django-oscar/blob/master/src/oscar/locale/uk_UA/LC_MESSAGES/django.po#L4763 - uk_UA My django project determines to use a uk_UA file and there are not needed for my translations. I need a uk... My django settings: LANGUAGE_CODE = 'ru' LANGUAGES = [ ('ru', _('Russian')), ('uk', _('Ukrainian')), ] USE_I18N = True USE_L10N = True LOCALE_PATHS = (os.path.join(BASE_DIR, 'locale'),) PARLER_LANGUAGES = { None: ( {'code': 'ru',}, {'code': 'uk',}, ), 'default': { 'fallback': 'uk', 'hide_untranslated': False, } } Why django select uk_UA but not uk files? How to fix it? I mean to choose uk files. Why there are not translations in django-oscar files? Thanks a lot!