Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django-Haystack: How to pass extra context with FacetedSearchView
This is my current view. class FacetedSearchView(BaseFacetedSearchView): form_class = FacetedProductSearchForm facet_fields = ['TopCategory'] template_name = 'shop-grid-ls.html' paginate_by = 20 context_object_name = 'object_list' extra = TopCategory.objects.all() def extra_context(self): return { 'extra': self.extra, } I can't access the 'extra' objects within my templates. How can I pass context through a FacetedSearchView. Thanks. -
django popup a window to show your mysql table
I want to create a button in the template that if i press submit i want a popup to show off and in that popup i want to display my Table from models.py. Basically i want that popup to have all the columns names and the all the date of that tabled display. with pagination if its possible Can someone please help me ? Thank you -
Long Mysql query results in website high loading time (not loading at all)
I've got a Django site and there is a long mysql query that runs every hour (query that I made) While that query runs, none of the pages on my Django websites can be loaded, it just hangs until the query finish... In general, I also got a PHP site on the same server and I've got the same issue there, so I'm guessing this is a configuration issue in Nginx or php-fpm? -
Saving a zipfile into directory using django
I am trying to save the zip file into one directory on my server. First, I am uploading a zip file using form and in python, I want to save it in one directory for further use. I got some piece of code after googling import os from zipfile import ZipFile zipf = ZipFile(frmUploadZipFile, 'w') zipdir('/data/apps/nms/maps/', zipf) def zipdir(path, ziph): for root, dirs, files in os.walk(path): for file in files: ziph.write(os.path.join(root, file)) Finally, after running this, I am getting some _ApRssiStore.txt file inserted in that folder. But not the zip file. I don't know whats happening in between. -
Django: prefetch_related grants performance only for non paginated requests?
For example, I have 1000 Users with lots of related objects that I use in template. Is it right that this: User.objects.all()[:10] Will always perform better than this: User.objects.all().prefetch_related('educations', 'places')[:10] -
RetrieveAPIView without lookup field?
By default RetrieveAPIView or RetrieveUpdateAPIView requires lookup_field to retrieve Model. However in my case, I want to retrieve my model by self.request.user. Here is views.py example class ProfileRetrieveAndUpdateProfile(generics.RetrieveUpdateAPIView): queryset = Profile.objects.all() serializer_class = ProfileRetrieveAndUpdateSerializer lookup_field = 'user_id' def get_queryset(self): qs = Profile.objects.all() logged_in_user_profile = qs.filter(user=self.request.user) return logged_in_user_profile Can I use RetrieveAPIView without lookup_field? -
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 …