Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django lightweight "update" of huge dataset
I have a very large dataset that I need to update as rapidly as possible. I do my calculations and at the end of it have a list of things that need to be updated: updates = [(instance_pk, value_to_update), (instance_pk, value_to_update), ..] The Model is the same throughout, as is the column being updated. In the past I have used Django Bulk Update —and I'm fairly sure I could here— but even this is ridiculously overpowered (and therefore doing far too much processing, because it handles full instances) for such a simple write that I need to happen fast. Did I mention speed was important here? Does Django provide anything that might make this easier, without needing to write raw SQL? -
Django : translation not found only during tests
I'm doing functional tests (Selenium) on my django app, and i want to include some fixtures. So first, i tried to load fixtures using manage.py : ./manage.py dumpdata > db.json ./manage.py loaddata db.json No errors, i decided to use this data for my tests : class FrontTest(LiveServerTestCase): fixtures = ['db.json'] But when i run my test : django.core.serializers.base.DeserializationError: Problem installing fixture '/srv/app/event.json': EventBlock has no field named 'content_fr' Have you ever get this error ? Thank you in advance. -
Django query engine - Migrating from 1.11 to 2.0
I'm trying to migrate from Django 1.11 to 2.0. After running my test suite, I'm getting in many db transactions the error: django.db.utils.ProgrammingError: subquery has too many columns , which didn't happen while running the test suite with 1.11. The database I'm using is postgres (with psycopg2-binary v2.7.4 module). Did anything change in the query engine between Django 1.11 to 2.0? I can't see anything like that in the release notes, nor anywhere else. -
Django AttributeError: Form object has no attribute '_errors'
I'm overriding the init method in my form andthis is now returning an error 'TransactionForm' object has no attribute '_errors'. I would expect this to work because I've included super in my init, however perhaps I don't understand how to use this correctly. An explanation would be appreciated. What do I need to do to get form.errors working? Full traceback Traceback: File "C:\Program Files\Python36\lib\site-packages\django\core\handlers\exception.py" in inner 35. response = get_response(request) File "C:\Program Files\Python36\lib\site-packages\django\core\handlers\base.py" in _get_response 128. response = self.process_exception_by_middleware(e, request) File "C:\Program Files\Python36\lib\site-packages\django\core\handlers\base.py" in _get_response 126. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\py\portfolio-project\myportfolio\views.py" in add_transaction 136. return render(request, 'myportfolio/add_transaction.html', {'form': form}) File "C:\Program Files\Python36\lib\site-packages\django\shortcuts.py" in render 36. content = loader.render_to_string(template_name, context, request, using=using) File "C:\Program Files\Python36\lib\site-packages\django\template\loader.py" in render_to_string 62. return template.render(context, request) File "C:\Program Files\Python36\lib\site-packages\django\template\backends\django.py" in render 61. return self.template.render(context) File "C:\Program Files\Python36\lib\site-packages\django\template\base.py" in render 175. return self._render(context) File "C:\Program Files\Python36\lib\site-packages\django\template\base.py" in _render 167. return self.nodelist.render(context) File "C:\Program Files\Python36\lib\site-packages\django\template\base.py" in render 943. bit = node.render_annotated(context) File "C:\Program Files\Python36\lib\site-packages\django\template\base.py" in render_annotated 910. return self.render(context) File "C:\Program Files\Python36\lib\site-packages\django\template\loader_tags.py" in render 155. return compiled_parent._render(context) File "C:\Program Files\Python36\lib\site-packages\django\template\base.py" in _render 167. return self.nodelist.render(context) File "C:\Program Files\Python36\lib\site-packages\django\template\base.py" in render 943. bit = node.render_annotated(context) File "C:\Program Files\Python36\lib\site-packages\django\template\base.py" in render_annotated 910. return self.render(context) File "C:\Program Files\Python36\lib\site-packages\django\template\loader_tags.py" in … -
Django smart products filters
I have a product model with color, size, brand, discount and some other params. It attributes - filters on catalog. What's right way to dynamic filter products? For example, the user checked some colors - show only available sizes, brands and etc. This is a facets search? Or I may use a standard Django ORM + js (with Django filter)? -
Django QuerySet Two-Valued Subquery
Given a model class Entity(models.Model): identifier = models.IntegerField() created = models.IntegerField() content = models.IntegerField() class Meta: unique_together = (('identifier', 'created')) I would like to query for all objects with created being maximal among objects with common identifier. In SQL a window function in a subquery solves the problem: SELECT identifier, content FROM entity WHERE (identifier, created) IN (SELECT identifier, max(created) OVER (PARTITION BY identifier) FROM entity); See also: http://sqlfiddle.com/#!17/c541f/1/0 Both window functions and subqueries are available in Django 2.0. However, I have not found a way to express subquery expressions with multiple columns. Is there a way to translate that SQL query into the Django QuerySet world? Is this maybe a an XY problem and my problem can be solved differently? -
How to improve the performance of database queries of an django sites running with SQL Server database?
I'm working on a project that is using django 1.11.0, SQL server and azure as deployment site. It takes longer than the actual execution time shown on console. We tried to follow django best practices for better performance. But still now it is rarely acceptable for performance issue. Can anyone suggest me how could I improve the performance to reduce the view response time? Currently it takes 6 seconds in view for response while in console it takes only 1.2 second for 1444 records. How can I reduce the difference between console time and view response time? -
Django admin display the instances of a model filtered by a field
I would like to provide a view in the django admin based on a model but filtered on a criteria. Here for example the updated date , like that the user can rack the changes made on the model. I have admin.py where I register the ModelAdmin but how I need to proceed: create a new ModelAdmin with a list filter? extend the template change_list.html or create a new one I would like that the user would be able to select a date to track the instance of the model have been changed. Thank in advance for any link, lesson, example speaking about that. I found the only basic example how to play with the admin. -
django model.objects.filter(mydate__date=date.today().month) not working
I've been staring at this for a bit and can't see the issue. Basically I have a number of views and filter by different date combinations, for example by this year, or this month or even today etc. I'm struggling with one view, the filter by this month. For the current year filter, this works: queryset = mymodel.objects.filter(mydate__year=date.today().year).order_by('field') However, trying this approach for the current month doesn't: queryset = mymodel.objects.filter(mydate__month=date.today().month).order_by('field') An exception is thrown, which basically is summarised as: TypeError at /core/tcCoreVendor/ not all arguments converted during string formatting I can work around it by doing: month = date.today().month where = "%(month)s = MONTH(mtime)" % {'month': month} queryset = mymodel.objects.extra(where=[where]) but that seems crazy! Any help or advice much appreciated! -
Django JWT Get User Info
If I'm using Django JWT authentication with the Django Rest Framework, how can I later get user info of the logged in user after I already retrieved the token? -
django running few taks in parallel
I am having a web application build out of Django version 2.0.1 User uploads a file and based on the content there are tasks which are executed in a serial fashion . After execution the results are shown to the user Some of the tasks are independent of each other I want to execute the independent tasks in parallel i tried using multiprocessing within views.py but there are some errors thrown up when the processes are spawn .These tasks analyse few information and write to a file .The files are then combined to show the results to the user. These tasks cannot be done asynchronous as the results produced needs to be shown to the user waiting .So i have dropped the idea of using Celery as recommended in other discussions Anyone suggestions would be helpful thanks -
Fetch the Django Serializer Indirectly
I am having a circular dependency problem. In order to avoid that I am using apps.get_model('ModelName') Is there a way to fetch the serializer class in the same way? -
ajax in django formView
Hi i am creating a Django app for the first time i have read some tutorial and have understood views, urls and models. app : given a number in a an input box . multiply it by 5 and display the result. This is just a dummy app i am making. Problem: ideally i could create a static page with a template and when submit is clicked i could use ajax .and for handling the ajax call i could create a view handler inheriting from generic class view. but i found out that django already has FormView which could be used to render my input form, but the problem that i am having is how do i use the ajax in this? class ResultView(LoginRequiredMixin, FormView): template_name = 'res.html' form_class = MyForm success_url = '/result/' ## ---> i want the result to be displayed on same page.but this will redirect it some other page def form_valid(self, form): ## should ajax be handled here??????????? 1)is my first approach valid? 2)is this not what FormView is used for? 3)what could be the better approach? keeping in mind that i will have to create some sort of cache later on. -
How to filter Django queryset by non field values.
I need to query a model by their local time. send_reminder_query = PersonModel.objects.filter('It's after 7pm thier localtime') -
How can I use Google cloud Storage with django-storages
I'm not using App Engine. I read this page. Configure Django and Google Cloud Storage? I installed django-storages and boto. I set my setting file like this. DEFAULT_FILE_STORAGE = 'storages.backends.gs.GSBotoStorage' GS_ACCESS_KEY_ID = '***@***.iam.gserviceaccount.com' GS_SECRET_ACCESS_KEY = '***' GS_BUCKET_NAME = '***' STATICFILES_STORAGE = 'storages.backends.gs.GSBotoStorage' Then I run this code from django.core.files.storage import default_storage default_storage.exists('storage_test') Then I got this error. --------------------------------------------------------------------------- GSResponseError Traceback (most recent call last) <ipython-input-2-8a49776d7c1d> in <module>() 1 from django.core.files.storage import default_storage ----> 2 default_storage.exists('storage_test') /Users/trmt_8/.pyenv/versions/3.5.0/lib/python3.5/site-packages/storages/backends/s3boto.py in exists(self, name) 433 return False 434 --> 435 return self._get_key(name) is not None 436 437 def listdir(self, name): /Users/trmt_8/.pyenv/versions/3.5.0/lib/python3.5/site-packages/storages/backends/s3boto.py in _get_key(self, name) 419 if self.entries: 420 return self.entries.get(name) --> 421 return self.bucket.get_key(self._encode_name(name)) 422 423 def delete(self, name): /Users/trmt_8/.pyenv/versions/3.5.0/lib/python3.5/site-packages/boto/gs/bucket.py in get_key(self, key_name, headers, version_id, response_headers, generation) 109 try: 110 key, resp = self._get_key_internal(key_name, headers, --> 111 query_args_l=query_args_l) 112 except GSResponseError as e: 113 if e.status == 403 and 'Forbidden' in e.reason: /Users/trmt_8/.pyenv/versions/3.5.0/lib/python3.5/site-packages/boto/s3/bucket.py in _get_key_internal(self, key_name, headers, query_args_l) 230 else: 231 raise self.connection.provider.storage_response_error( --> 232 response.status, response.reason, '') 233 234 def list(self, prefix='', delimiter='', marker='', headers=None, GSResponseError: GSResponseError: 403 Access denied to 'gs://***/storage_test'. How can I solve this problem.please help me! This is document of django-storages -
Different serializers for different instances in a queryset in Django Rest Framework
In generics.GenericAPIView, overriding the get_serializer_class() method only dynamically chooses a serializer for the entire query set. Is there a way to apply different serializers to different objects in the same queryset based on some attribute value of the object? Thanks in advance! -
How to upload Django project using FileZilla
everyone. I have a webpage hosted by one.com. I upload my files by using FileZilla simply by dragging them into the root folder... I recently discovered Django, and I find it very interesting, so I want to transfer my webpage to the DJango way, but I don't know how to upload the whole project into FileZilla. Hope someone can help me out here, Thank you. -
redirect godaddy home Page to django server
Is there a way to redirect the GoDaddy home page to Django server? I have now an economy account with GoDaddy. When I run my django project on the server, it still takes me to the Godaddy welcome Page. Please help. -
Using Django-Admin's Create/Update/Delete templates OUTSIDE of admin?
I am currently prototyping a web application with django and I would like to know whether it's possible to use Django-admin's Create/Update/List html templates outside of Django-admin. Currently I have the following views: class TaskCreate(CreateView): model = Task fields = ['priority', 'title', 'content', 'visible_to', 'awake_at', 'is_completed'] class TaskUpdate(UpdateView): model = Task fields = ['priority', 'title', 'content', 'visible_to', 'awake_at', 'is_completed'] class TaskDelete(DeleteView): model = Task success_url = reverse_lazy('tasks-list') When I visit TaskCreate's view, I would like to have a form that renders all the correct widgets for different types of fields defined in my model. -
how to use html input form in django
How can I input values from an HTML form in django. I am new to django and trying to make a clone of social network. I am not sure what code to write for forms.py,views.py, urls.py and models.py in order to input data. Also, I have various fields in html form like textbox, check box , radio buttons. How to input data from these fields to the backend ? html <form method = 'POST' id = "new_post" action = "/posts/new/"> {% csrf_token %} <div class="form-group col-md-6"> <label>Title</label><br> <input type="text" class="form-control" id="inputTitle" placeholder="Enter title"> </div> <div class="form-group col-md-12"> <label>Situation Description</label><br> <textarea rows="4" cols="70" class="form-control" placeholder="Enter the situation description"></textarea> </div> <div class="form-group col-md-12"> <label>Outcome Description</label><br> <textarea rows="4" cols="70" class="form-control" placeholder="Enter the outcome description"></textarea> </div> <div class="form-group col-md-4"> <label>Outcome Type</label><br> <select id="inputO_type" class="form-control"> <option>Positive</option> <option>Neutral</option> <option>Negative</option> </select> </div> <br> <div class="form-group col-md-4"> <div class="multiselect"> <div class="selectBox" onclick="showCheckboxes()"> <option>reviewed?</option><select></select> <div class="overSelect"></div> </div> <div id="checkboxes"> <label for="one"> <input type="checkbox" id="one" />Commissioning</label> <label for="two"> <input type="checkbox" id="two" />Construction</label> </div> </div></div> <div class="form-row"> <br> <div class="form-group col-md-4"> <label>Tags</label><br> <select id="inputTag" class="form-control"> <option selected>Algorithms</option> <option selected>Architecture</option> <option selected>Automobile</option> <option>...</option> </select> </div> <div class="form-row"> <div class="form-group col-md-4"> <form method="post" action="#"> <div> <input type="checkbox" name="FormStuff" id="FormStuff" required> <label for="FormStuff">Can't find … -
Accessing mobile camera through django webapp
How can I implement a function to open a django web app user's camera when clicking a link in the template. After he has accessed the camera, when he takes a photo I'd like that image to be saved in the django admin or anywhere really. Id appreciate some help here. -
Set serializer field from data having diffenent data
I have a Request model and follows class TruRouteRequest(models.Model): msisdn = models.CharField('Subscriber international MSISDN ', max_length=25) sessionid = models.CharField(max_length=100, unique=True) msg_type = models.CharField(max_length=255) msg = models.CharField(max_length=255) I failed to write the name of the model field as 'type' so i wrote 'msg_type'. I have a ModelSerializer for the above model. Data I am receiving have field 'type' which is required. How do I map type from serializer data to msg_type to avoid this error when calling is valid >> serializer = TruRouteRequestSerializer(data=request.data) >> serializer.data >> {'msisdn': 'M', 'sessionid': 'S', 'msg': 'MSG'} >> request.data >> {'msisdn': 'M', 'type': 'T', 'sessionid': 'S', 'msg': 'MSG'} # there is type >> serializer.is_valid() >> False >> serializer.errors >> {'msg_type': [ErrorDetail(string='This field is required.', code='required')]} -
Running XAMPP on external hard drive?
I have an issue where my current hard drive space is not big enough to fit all my programming needs. Currently I am on 2 projects where I need to run a react webapp and also build a DJANGO app. Now I am using XAMPP(If anyone knows something better I can use please let me know) and am going to run it on an external hard drive. Now I put the XAMPP folder and the manager-os.app file in the external hard drive but when I go to open it up I get "Cant run because app needs admin privileges" etc. SO ok I go into terminal and I run the app with sudo and it works. Well 1 how do I remove the need to use sudo? and well what other problems is this going to cause? I need to be able to run the webservices from here and also update a database. Is there anything I am missing here that I need to take care of? -
selenium - the string is not a valid xpath expression
I am running a selenium tutorial in PyCharm and am getting an invalid XPATH expression. I have reviewed the Selenium Documentation and it appears that I am writing the XPATH correctly. It opens Chrome just fine and must be seeing the image avatar after loading. It then gets the XPATH error. I am trying to perform the following tutorial: https://medium.com/the-andela-way/introduction-to-web-scraping-using-selenium-7ec377a8cf72 selenium.common.exceptions.InvalidSelectorException: Message: invalid selector: Unable to locate an element with the xpath expression //a[@class =’text-bold’] because of the following error: SyntaxError: Failed to execute 'evaluate' on 'Document': The string '//a[@class=’text-bold’]' is not a valid XPath expression. (Session info: chrome=66.0.3359.181) (Driver info: chromedriver=2.38.552522 (437e6fbedfa8762dec75e2c5b3ddb86763dc9dcb),platform=Windows NT 10.0.16299 x86_64) This is my code: from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.common.exceptions import TimeoutException # https://medium.com/the-andela-way/introduction-to-web-scraping-using-selenium-7ec377a8cf72 option = webdriver.ChromeOptions() option.add_argument(' — incognito') # Now create an 'instance' of your driver # This path should be to wherever you downloaded the driver browser = webdriver.Chrome(executable_path=r"C:\Users\Kyle Linden\Downloads\chromedriver") # A new Chrome (or other browser) window should open up browser.get('https://github.com/TheDancerCodes') # Wait 20 seconds for page to load timeout = 20 try: WebDriverWait(browser, timeout).until(EC.visibility_of_element_located((By.XPATH, "//img[@class='avatar width-full rounded-2']"))) except TimeoutException: print('Timed out waiting for page to … -
LiveServerTestCase - Internal server error contact administrator
I have spent all day, trying to figure out why LiveServerTestCase keeps failing to run to no avail.... google searched, dived intro django docs yet found nothing... Looking at this stack trace what can one make from it and how to fix it. It throws and ImportError at the end with no information whatsoever where the error occured. Am I missing something? With a whole chunk of importlib bootstrap confusions.... These are my first suites with LiveServerTestCase, for the record I am trying to configure LiveServerTestCase with selenium and I have managed to get selenium to work with remote urs this far. Traceback (most recent call last): File "/home/fenn/projects/portal/venv/lib/python3.5/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/home/fenn/projects/portal/venv/lib/python3.5/site-packages/django/core/handlers/base.py", line 244, in _legacy_get_response response = middleware_method(request) File "/home/fenn/projects/portal/venv/lib/python3.5/site-packages/django/middleware/locale.py", line 24, in process_request i18n_patterns_used, prefixed_default_language = is_language_prefix_patterns_used(urlconf) File "/home/fenn/projects/portal/venv/lib/python3.5/site-packages/django/conf/urls/i18n.py", line 29, in is_language_prefix_patterns_used for url_pattern in get_resolver(urlconf).url_patterns: File "/home/fenn/projects/portal/venv/lib/python3.5/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/fenn/projects/portal/venv/lib/python3.5/site-packages/django/urls/resolvers.py", line 405, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/home/fenn/projects/portal/venv/lib/python3.5/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/fenn/projects/portal/venv/lib/python3.5/site-packages/django/urls/resolvers.py", line 398, in urlconf_module return import_module(self.urlconf_name) File "/home/fenn/projects/portal/venv/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line …