Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Not able to get groups that belong to current user
I'm building a Django app that needs two things. First, it needs the set of groups that the user has access to. With this set of groups, my template is supposed to create a button for each group. Next, it needs the set of "Property" objects that are ManyToMany related to a group in the previously found set of groups (this is to say that I need every property that is assigned to a group that the user has access to). For each of these properties, a button is created. I'm working with an admin user on localhost right now while building this, and I've created a test group with test properties and assigned the admin user to that group. Django however, doesn't seem to be detecting this. The relevant code is below: views.py from __future__ import unicode_literals from django.shortcuts import render from UsageData.models import Property, User, Group, MeterData from django.contrib import auth def reports_proerty_list(request): if request.user.is_authenticated(): current_user_groups = Group.objects.filter(id__in=request.user.groups.all()) current_user_properties = Property.objects.filter(groups__in=current_user_groups) return render(request, 'App/App-Template-Page.html') else: # The user is redirected to the sign-in page App-Template-Page.html <div class="row"> {% if current_user_groups %} {% for group in current_user_groups %} <div class="col-sm-2 col-md-2 col-lg-2 text-center"> <button class="tab-selector inactive" id="{{ group.id }}">{{ … -
Update content of static html file in Django
I saved an HTML as a static file in order to save it in cache and render it through a service worker when Offline. I would like to make a small change on my HTML in order to get the appropriate encoding. I am using pythonanywhere as my server. And I have defined in my settings.py the following paths: STATIC_URL = '/static/' STATIC_ROOT = u'/home/cocoa/cocoa/static' When I look at my file in the server in the following directory is: /home/cocoa/cocoa/static/login/Offline/HTML/mEstado.html My file looks like this: If I visit the following URL: https://cocoa.pythonanywhere.com/static/login/Offline/HTML/mEstado.html My file looks like this: I allready tried reloading on shift. Unabling the service-worker and python manage.py collectstatic But nothing seems to work. I do not know where the problem is, nor how to solve it. Any help would be appreciated. -
Missing argument inside a form of django app
I am trying to access a user product list inside the form of my django app. The user information should be the input options of a form from the app. What argument should I pass in my list_prod bellow? I am receiving the following error message: TypeError: list_prod() takes exactly 1 argument (0 given) Please Help! Form class ProductsForm(forms.Form): def __init__(self, *args, **kwargs): self.request = kwargs.pop('request', None) super(ProductsForm, self).__init__(*args, **kwargs) def list_prod(self): user_name = (self.request).user.username u = User.objects.get(username=user_name).accesslevel.prod.split(',') v=(('---------','---------'),) for l in u: v=v+((l.lstrip(),l.lstrip()),) model = Factory Lists = forms.ChoiceField(choices=list_prod()) -
how to use ManyToManyField of model in itself
scenario i have group of users instrest in each others activity when ever a user of this group see a feed (record) or show some activity (like , comment , star) and continue. then whenever next user opens the app randomly sees the feed or show some activity (like , comment , star) so app will lead the second user to first user foot steps until it ignore the at least 3 feeds (records) so the best i come up with is ManyToManyField of model in itself by this method i will be able to classify every record (feed) and add all it's related feed back to the same model even witout adding a new record . example : Sam saw a feed 1 then Sam saw feed 5 then Sam saw feed 10 now it will add feed 5 and 10 as inner_feed to feed 1 and feed 10 to 5 is something like this model possible in django ? class NewsFeed(models.Model): id = models.AutoField(primary_key=True) user = models.ForeignKey(User, models.DO_NOTHING, related_name="feeduser") date_created = models.DateTimeField(default=timezone.now) last_update = models.DateTimeField(default=timezone.now) inner_feed = models.ManyToManyField(NewsFeed) if there is anything hard to understand please ask -
Django converts value to tuple after model-field updating
I'm using Django 2.0. I have a model with a field declared as: px = models.DecimalField(max_digits=10, decimal_places=2, default=0) After getting an instance of this object from database, I try to update its property with: obj.px = "-2.6" The value "-2.6" comes from a variable, but I've tested with hard code: -2.6, 2.6, decimal.Decimal("-2.6"), etc. It always converts that value to a tuple I don't know why. What I get in django result is: argument must be a sequence of length 3 Django raises this error when calling the "save" method from the model, and it internally does the conversion: return decimal.Decimal(value) When I print the new value of "px" I get this: (2.6,) The only fix that I did was the following: if isinstance(obj.px, tuple): obj.px = obj.px[0] -
Django IntegerField ignores specified default value when blank=True and empty string posted
Consider the following model field: myfield = models.IntegerField(_('My field'), blank=True, default=0) If the myfield is completely omited from the post the default is properly used by default ModelForm implementation. However if empty string is posted for that field the field value stays None and postgres fails with the IntegrityError on non-null field: IntegrityError: null value in column "myfield" violates not-null constraint Question: How to enforce a default for both cases where either the myfield value is not present or present but empty string? -
Assigning JSON to a Python dictionary with POST and retrieving values with GET
I have a mobile app that is sending JSON to a Python 3.5.2 Django server in the form of POST requests. For testing I want to retrieve specific values from the posted JSON with GET requests to the same url. I've been trying to do this by initializing a global dictionary which is then updated by POST requests. This is my views.py: from django.http import HttpResponse from json import loads import json import string json_data = { "key_1": "placeholder_value_1", "key_2": "placeholder_value_2", "key_3": "placeholder_value_3" } def show_json(request): global json_data if request.method == "POST": body_unicode = request.body.decode('utf-8') json_data = json.loads(body_unicode) return HttpResponse("OK") if request.method == "GET": return HttpResponse(json_data['key_3']) My JSON in the POST request.body has the same keys as the json_data dictionary but different values. When I make GET requests after POST, this code returns placeholder_value_3 instead of the new value I want to assign it. I also tried initializing json_data as an empty dictionary with json_data = {} but GET requests just returned an empty string with that. I think this should be an easy problem for experienced Python programmers to solve but I'm a beginner and no other SO answers I've found have worked so far. What am I doing … -
DRF: Pass response from 3rd party API to serializer
Django Rest Framework serializers expect a QueryDictionary object that's created from a request. I query an API (it responds with a JSON object) in one of my views and use several attributes from the response in a model. The only field in the model that's part of the user's initial request is a foreign key so when I initialize my serializer I'm not sending it any data. Instead I send the data to the serializer when I call save on it. Now that works but it seems like how this should work is I use the API response attributes to initialize my serializer, however I'm having a difficult time getting them in the QueryDictionary object that the serializer likes. What am I missing? The API response format is: Customer object @ 0x7f5012351b38 JSON: {account_balance: 0, id=1235, name=foo bar, etc} -
How to get the date from foreign Key column in Django
I am new to Django.I have two tables StatusTable and SystemTable in where the SystemTable has a foreign column "Status" where is stores the id of the status from StatusTable.The data save is working fine as expected. I need to show the Statusname of the system in a Statuspage but instead I am getting only the id of the status stored in SystemTable. Models.py class StatusTable(models.Model): status = models.CharField(max_length=20,default='') def __str__(self): return self.status class SystemTable(models.Model): sid = models.CharField(max_length=3) status = models.ForeignKey(StatusTable,null=True) Viwes.py def systemstatuspage(request): form = CreateTaskMaster() task_title = TaskMaster.objects.all() my_list = [ model_to_dict(x) for x in task_title] return render(request, 'task/task.html', {'form': form, 'sid':my_list}) enter image description here -
Django scientific notation input validation
I have the following fields on my model: class Range(models.Model): optimal_low = models.DecimalField(max_digits=30, decimal_places=8) optimal_high = models.DecimalField(max_digits=30, decimal_places=8) And here's how I bring them into the form (because the form's primary object is not this model, I just need the fields, and don't want to duplicate the max_digits and decimal_places. class ReadingMappingForm(forms.ModelForm): optimal_low = Range._meta.get_field('optimal_low').formfield() optimal_high = Range._meta.get_field('optimal_high').formfield() It seems django allows entering of decimals in scientific notation out of the box, but there's a glitch above a certain threshold. In the form, if I input 1.5E9 it works fine, and the value gets saved as 1500000000.00000000 (Here's an online scientific notation calculator). However if I input 1.5E10 it says: Ensure that there are no more than 8 decimal places. Which is wrong, because I'm not adding any decimal places. In fact, if I enter 1.5E10 in normal notation, even with the 8 decimal places added, i.e. 15000000000.00000000 it works fine. So I think something is not working correctly under the hood... -
Django web services api deployed on IIS giving 500 server error when 500 concurrent requests are hit
I have django app as webapi running on Azure Application service. Production environment configurations are as- Web server : IIS 8 Application server : FastCGI So, This application will be having around 8k to 10k users. There is currently load testing is going on. Load testing observations are as- For 100 concurrent requests : Working Fine For 250 concurrent requests : All requests are passing but more response time For 500 concurrent requests : Most of the requests are failing. Which is giving 500 internal server error. When I checked application error logs there is None. I checked Azure app service logs, it is stating error in requests Can anyone suggest reason for requests failure. Do I have to do some specific configuration in FastCGI or other configurations ? Also I am open to hear alternative solution which helps to handle large load. Thanks in advance. -
django i18n doesn't work in mac
CommandError: errors happened while running msguniq msguniq: Cannot convert from "ASCII" to "UTF-8". msguniq relies on iconv(). This version was built without iconv(). I have mac high sierra. Already tried with brew install gettext & force options . Same error with anaconda. -
Django: How to handle the incremental id fields in a table
I'm swimming in my first Django project. Lately , a bunch of question came up to my mind. My big concern when I'm creating my app model is regarding how Django will take care of my tables when I will run the syncdb command.Firstly, let's introduce you on my scenario: app: different pages to show up according to the user profile Django 2.0 Python 3.6 DB: SQLite Relation diagram just for two likely tables in my model (one profile is linked with many users, whereas only one user is linked with one profile) Question I'm creating my model in the file project called model.py. I'm including a class per entity, I mean one class called user where I can define the kind of fields and the properties for each of this right. My question is more target on the model for profile. this entity or table that I'm not planning to use in my app. I know that once the model will be created the command syncdb will go thru the model.py file and create the required tables. Anways even if profile will not be part of the app I have to specify it as a class in my model? … -
Obtain the name of the logged user inside a form of a Django App and use the results as input of a form field
I would like to obtain the name of the logged user inside a form of a Django App and use the results as input of a form field. How can I do that? What should I do in my code? I tryied all the solutions. Here is my code Views.py form = ProductForm() Admin.py class AccessLevelInline(admin.StackedInline): model = AccessLevel can_delete = False verbose_name_plural = 'accesslevel' # Define a new User admin class UserAdmin(BaseUserAdmin): inlines = (AccessLevelInline, ) # Re-register UserAdmin admin.site.unregister(User) admin.site.register(User, UserAdmin) Form.py user_name = HOW DO I ACCESS THE USER NAME HERE? u = User.objects.get(username=user_name).accesslevel.prod.split(',') v=(('---------','---------'),) for l in u: v=v+((l.lstrip(),l.lstrip()),) class ProductForm(forms.Form): model = Manufact Prod = forms.ChoiceField(choices=v) -
ModuleNotFoundError: No module named 'bigchaindb_driver'
I'm using Django with Python 3.6.3 and Windows 7. I'm trying to install BigchainDB driver and want to use IPDB. I run this pip install bigchaindb and I guess it executed successfully. I import bigchaindb_driver like that from bigchaindb_driver import BigchainDB. But when i run the server using python manage.py runserver it gives me this error. ModuleNotFoundError: No module named 'bigchaindb_driver' My code look like this: import os from bigchaindb_driver import BigchainDB> tokens = {} tokens['app_id'] = 'my-app-id' tokens['app_key'] = 'my-apy-key' bdb = BigchainDB('https://test.ipdb.io', headers=tokens) My questions are: If i want to use IPDB, i still have to install bigchainDB on my local machine? What exactly i need to start a project on bigchainDB, as i have installed MongoDB and RethinkDB but i don't exactly know weather i need them or not. -
Users for multiple sites in Django
I am trying to get multiple sites to use the same database and code but in a way which forces each user to have their own login to each site. I have seen a few suggestions as to how to make this work but I'm not sure which way to go. I am using the Sites Framework, using the subdomain to identify the current site so I'm not using SITE_ID at all. Use the sites framework - This answer (https://stackoverflow.com/a/1405902/1180442) suggests using the sites framework to do it, but I'm having trouble with the get_user() method, as it doesn't have access to the request and that's where my site info is stored. Use separate databases for users - I'm really not sure about this one but I think it might cause bigger problems down the line. Change to using SITE_ID - I want to try and avoid this if possible as it will mean having to run many different instances of my app, one for each site, which uses it's own settings.py. This will quickly turn into a nightmare, I think. Permissions - I'm wondering if this should be something that I get the permissions framework to use? So one … -
Sorting queryset by prefetched data attribute
I have two models in my models.py Charge(models.Model): ... SPA(models.Model): charge = models.ForeignKey(Charge) processing_date = models.DateTimeField() ... When I'm doing my queries I do Charge.objects.filter(my_filter).prefetch_related(Prefetch('spa_set', Spa.objects.filter(charge_id__in=queryset), to_attribute="spas"))` How would I filter charges by SPA's processing_time. Unsorted Charge1 spa - processing_time 12:30 Charge2 spa - processing_time 14:30 Charge3 spa - processing time 13:30 Sorted Charge1 spa - processing_time 12:30 Charge3 spa - processing_time 13:30 Charge2 spa - processing_time 14:30 -
MySQL table locking issue in Amazon RDS
We are hosting MySQL database in Amazon RDS platform. We see a lot of deadlock issues due to locking. I am trying to understand the deadlock dump report which roughly describes the affected transactions & no of locks etc. Following is such a trace: 2017-12-14 09:00:21 2ba3a5758700 *** (1) TRANSACTION: TRANSACTION 1297355720, ACTIVE 0 sec inserting mysql tables in use 1, locked 1 LOCK WAIT 7 lock struct(s), heap size 1184, 3 row lock(s), undo log entries 1 MySQL thread id 9198894, OS thread handle 0x2ba0b33da700, query id 5198593130 In the above trace, the 4th line says - 'mysql tables in use 1, locked 1'. What does 'locked 1' mean? Does it mean the concerned table is fully locked during the transaction? We are not explicitly locking the table. We use Django @transaction.atomic at certain places, but no explicit Table locking is there in our code. Please help me understand how can I debug the Table locking issue. -
display dictionary file inside for loop in django template
I have the following dictionary: d = {'21': 'test1', '11': 'test2'} {% with '18 17 16 15 14 13 12 11 21 22 23 24 25 26 27 28' as list_upper %} {% for x in list_upper.split %} {% if x in dental_position %} <input type="text" placeholder = "{{ x }}" class="form-control" name="tooth[]" value="{{display dict.value here}}"> {% else %}<input type="text" placeholder = "{{ x }}" class="form-control" name="tooth[]"> {% endif%} {% endfor %} I want to display the d[value] inside input text value attribute when values from d[key] is found in list_upper How can I call {% if d.keys in x %} in django template? -
How to setup Django logging to log to console and Debug Toolbar same time?
I try to setup logging in Django to use console and Django Debug Toolbar. By default this line logger.debug('XXXXX') log to DDT and console stay empty. With this setup LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'level':'DEBUG', 'class':'logging.StreamHandler' }, }, 'loggers': { '': { 'handlers': ['console'], 'level': 'DEBUG', }, }, } logs appear in console, but disappear from DDT How to make it works in both destinations? -
What's the meaning of order in a django request processing?
OVERVIEW Consider the below urls.py: from django.contrib import admin from django.urls import re_path, include from django.conf.urls.static import static from django.conf import settings from django.contrib import admin from django.urls import path # a) urlpatterns = [ path('admin/', admin.site.urls), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # b) # urlpatterns = [ # path('admin/', admin.site.urls), # ] print(urlpatterns) As you can see we got 2 url lists, whose __str__ representation is: a) [<URLResolver <URLPattern list> (admin:admin) 'admin/'>] b) [<URLResolver <URLPattern list> (admin:admin) 'admin/'>, <URLPattern '^media\/(?P<path>.*)$'>] PROBLEM If I make the same request to localhost:8000 it's producing 2 different outcomes for the abovementioned url lists: Using a) , I'll get a 200 response: Using b) , I'll get a 404 response: QUESTION After reading the section "How django processes a request" I've observed it says in point 3): Django runs through each URL pattern, in order, and stops at the first one that matches the requested URL. What does the concept of "order" means in this context? For instance, let me put you an analogy of what I understand of "order processing", if i declare a couple of lists (b is extended from a), a=[0,1,2,3]; b=a+[4,5,6] and then i do a.index(2)=2, b.index(2)=2, that type of order … -
Upon running "python manage.py startapp blog" shows the following error
I'm learning from djangogirls tutorials and when inside myenv(virtual environment) I'm running the python manage.py startapp blog it shows me the following error and can not run anything at all error is Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "c:\Users\Divyesh\djangogirls\myenv\lib\site-packages\django \core\management\__init__.py", line 371, in execute_from_command_line utility.execute() File "c:\Users\Divyesh\djangogirls\myenv\lib\site-packages\django\core\management\__init__.py", line 347, in execute django.setup() File "c:\Users\Divyesh\djangogirls\myenv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "c:\Users\Divyesh\djangogirls\myenv\lib\site-packages\django\apps\registry.py", line 112, in populate app_config.import_models() File "c:\Users\Divyesh\djangogirls\myenv\lib\site-packages\django\apps\config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "C:\Program Files (x86)\Python36-32\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\Divyesh\djangogirls\dpblog\models.py", line 2, in <module> from utils import timezone ModuleNotFoundError: No module named 'utils' Also after that while running python manage.py makemigrations blog it shows almost identical error I don't know how to tackle this please help. Learning Django for the first time. -
django context processor form not showing errors when submitting
I`m using context processor to render form to the base template in my project and the form seems to work ok, except it doesnt show any errors for required fields being blank and etc. The page is simply reloaded even if fields are not filled in. I used this approach in other project before, and it worked just fine, but now I cant really figure out what happened and why it is like so. Here is my forms.py: from django import forms class VersionSelectorForm(forms.Form): mode = forms.ChoiceField(widget=forms.RadioSelect(), choices=(('live', 'Live'), ('history', 'History')), initial='live', required=True, help_text='Required') date = forms.DateField(widget=forms.TextInput(attrs={'class': 'datepicker'}), required=True, help_text='required') def clean(self): cleaned_data = super(VersionSelectorForm, self).clean() mode = cleaned_data.get('mode') date = cleaned_data.get('date') if mode == 'history' and not date: msg = 'Date should be picked if \'History\' mode selected' self.add_error('date', msg) view.py: from django.shortcuts import redirect from .forms import VersionSelectorForm def select_version(request): if request.method == "POST": form = VersionSelectorForm(request.POST) if form.is_valid(): print('I am valid') mode = form.cleaned_data["mode"] date = form.cleaned_data["date"] if mode == "History": request.session['selected_date'] = date else: request.session['selected_date'] = None else: form = VersionSelectorForm() return redirect(request.META['HTTP_REFERER']) context_processors.py: from .forms import VersionSelectorForm def VersionSelectorFormGlobal(request): return {'version_selector_form': VersionSelectorForm()} urls.py: from django.contrib import admin from diagspecgen import views urlpatterns = [ url(r'^admin/', … -
jQuery not found with Django RGBField
The project I'm working on uses an RGBField, which inserts this script into the template (which is deep in the bowels of django somewhere because I can't find where it lives): <script type="text/javascript"> (function($){ $(document).ready(function(){ $('#id_color').each(function(i, elm){ // Make sure html5 color element is not replaced if (elm.type != 'color') $(elm).colorPicker({"colors": ["f1c40f", "2ecc71", "9b59b6", "e74c3c", "34495e", "3498db", "1abc9c", "f39c12", "d35400"]}); }); }); })('django' in window && django.jQuery ? django.jQuery: jQuery); </script> In the console I'm getting an error: Uncaught ReferenceError: jQuery is not defined I'm unable to inspect where the error is happening, but removing the RGBField prevents the issue. Jquery is used in the project, and if I use jQuery in the template itself it works fine (so it's not a problem with the template per se). I've added django-jquery to the project, and included {% load staticfiles %} at the start of the template. Does not resolve the problem. I've been ignoring the whole thing happily but now I need to write a cypress test with this page and the error is blocking the test. Is there a way in cypress to ignore this error? Or is there a way to prevent the error from happening in the … -
Django formset - validate input based on user cookie?
I have a Django form (TestForm) that contains a single field, quantity. I also have a Django formset (TestFormset) that contains multiple instances of my TestForm. I want to write a custom clean() method for my TestFormset that validates that the sum of the quantities specified within my multiple TestForms is equal to a number, max_quantity, stored in a session variable. I know that I am able to perform this validation within views.py (for example, after my formset is validated and cleaned, I could manually sum up the 'quantity' variables in my TestForms and check to ensure that they are equal to request.session['max_quantity'], throwing an error if any problems are found). But ideally I'd love to move all my form validation logic into the clean() method of forms.py. However, I can't figure out how to pass an external value into my Formset that is not linked to one of its individual forms. Is this possible to do? forms.py from django.forms import BaseFormSet class TestForm(forms.Form): quantity = forms.IntegerField() class BaseTestFormset(BaseFormset): def clean(self): if any(self.errors): # Don't bother validating the formset unless each form is valid on its own return quantity = 0 for form in self.forms: quantity += form.cleaned_data['quantity'] # IF …