Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to avoid race updating postgres.JSONField in Django?
Using Django I learned to use F object to mitigate race conditions when updating values on a model. Now I have a bit more complex problem - I have a model using PostgreSQL's JSONField and I want to update a value contained within the field. I tried doing something like this: year = arrow.utcnow().date().year my_model.stats['views'][year] = F('stats__%s' & year) + 1 Unfortunately an error pops up: TypeError: Object of type 'CombinedExpression' is not JSON serializable I understand it can be done by using some intermediate models to simulate JSON structure but it is out of question here. So the problem is as in title - how to do this in Django? If not possible, what SQL syntax would do that? -
create a separate app for my REST api or inside my working app "Django"?
I'm building simple gis system on geodjango. the app displays set of maps and I'm also attending to provide RESTFULL api for these maps, but I'm facing a decision weather to create separate app for the api or working inside my existing app, the two apps are logically separate but they share the same models. So what is better??? -
Get unicode string rather than id when getting Foreign Key field values
I have a function that returns the field names and values of an object for a custom template tag in Django. def get_obj_fields(obj): try: return [(field.verbose_name, field.value_to_string(obj)) for field in obj._meta.fields] except: return But field.value_to_string(obj) is returning the Foreign Key IDs, and I want to print the __unicode__(self) result. Is there a simple way to do this? So if I run the function on an item, I want it to return the Category name rather than the ID. class Item(models.Model): category = models.ForeignKey(Category, verbose_name="Category") class Category(models.Model): name = models.CharField(max_length = 30, verbose_name="Name") def __unicode__(self): return str(self.name) Thanks -
How do I automatically backup db.sqlite3 file in Django App hosted on Azure Web Apps?
I have a Django web application hosted on _________.azurewebsites.net The folder structure is as follows: - Github Repository - settingsFolder - app1folder - app2folder - manage.py - web.config - db.sqlite3 I have Azure set up to where a push to my remote github branch causes Azure to sync the files with my Github branch to my /site/wwwroot/ folder. Explicitly, git push origin branch This causes a problem. Everytime I try to add changes to my website, using git push, the db.sqlite3 DOES NOT reflect the changes within the website environment. Thus, if someone were to save data to /site/wwwroot/db.sqlite3, then my github repository would be UNAWARE of the changes. Updating my github repository would take the OLD db.sqlite3 and reupload THIS OLD during a file sync between Azure and github. Consequently, the db.sqlite3 on /site/wwwroot/ gets overwritten and data would be lost. One solution is to manually make backups by connecting to my /site/wwwroot folder, saving db.sqlite3, and replacing it regularly in my Github repository. Is it possible to automate this? If so, what resources does Azure provide me to do so? -
Django add field to query set
Hi i have 3 models in my django projects: Material(has id,default price, and other informations for material) Dealer(has id, and informations about dealer) MaterialDealerDiscount(has material_id,dealer_id,and discount_ percent) when user send request i have his dealer_id i need return query set with info about material from Material table and for each row add discount_percent from last model where dealer_id = current dealer_id and row id. Please help me if you have answer. -
Django one user login per IP
How can I allow only one user login per IP in django? limiting number of concurrent users. I am new to django and quick and easy solutions will be appreciated. -
Creating multiple django objects with multiple django form entries
I'm trying to essentially create a quiz for a web app (user creates the quiz given a certain input of 1-25 questions). From here they can view a page with their set number of entry fields (1-25) and submit them to associate the questions and answers entered with the quiz they made (e.g. NewQuiz might have 5 questions and answers). My problem is, I don't know how to create 5 questions and answers in the one form with 1 submit button, and currently submitting all fields just saves the most recent field in the list (question and answer 5 will be saved out of 1-5 questions and answers). Would anyone be able to direct me on how to submit multiple objects of the same type over the one form? This is what I'm currently doing: views.py form = EditQuizForm(request.POST or None) if form.is_valid(): question_text = form.cleaned_data['question_text'] answer_text = form.cleaned_data['answer_text'] try: get_latestq = Question.objects.latest('id') latest_idq = get_latestq.id get_latesta = Answer.objects.latest('id') latest_ida = get_latesta.id except ObjectDoesNotExist: latest_idq = 0 latest_ida = 0 newQuestion = Question(question_text = question_text, exam = examInstance, related_quiz = examInstance.exam_id, id = latest_idq + 1) newQuestion.save() newAnswer = Answer(text = answer_text, question = newQuestion, related_quiz = examInstance.exam_id, id = … -
How to add not null unique value to existing Django Model with default attribute
I need to add slug field to django model, and i thing it's better when it not null. So i'm trying to add slug to model slug = models.SlugField( 'URL', unique=True, default=id_generator, ) my id_generator: import string import random def id_generator(): size=16 chars=string.ascii_lowercase + string.digits return ''.join(random.choice(chars) for x in range(size)) The problem is when i migrate changes. Method id_generator is calling one time and uses the same value for all model objects. So i have dupliicate entrie in unique field. How can i generate unique values? Django 1.11.5 P.S. I understand, that i can set null=True and customize model's save method to add slug when saving. -
Use django ORM with multiprocessing?
I have a Django ORM database (mysql or sqlite), and would like to process each row with a fairly computationally intensive operation. What I have right now is something like: entries = Entry.objects.filter(language='') for e in entry: e.language = detect_language(e.text) e.save() If the database was the bottleneck, I would use a transaction to speed it up. However, the detect_language function is what takes the most time. I could try to run the script multiple times in parallel, but that would introduce a race condition. I think this could be done with multiprocessing using Pool.map() - the main process fetches the DB entries, the child processes run detect_language. I am not sure how to do it in detail, e.g. whether to save the entries in the child process or in the main process. Is there anything to take care of when passing ORM objects between processes? Can you give a short example how to use the ORM with multiprocessing? -
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?