Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using one modal for multiple forms in django?
I can't figure out how to use one modal for multiple forms. Now, I can not find a way to have only one modal for severals form that I want to create. I don't really want to have 30 modals in the html for the 30 forms that I am going to submit. Is there another way to fill it automatically? My model is class Project(models.Model): project_name = models.CharField(max_length=30) project_status = models.IntegerField(choices=PROJECT_STATUS,default=1) project_sponsor = models.CharField('Project Sponsor', max_length=255,default=1) scope = models.TextField(max_length=10240, blank=True) description = models.TextField(max_length=10240, blank=True) Then, I wanted to have one form for each model attribute. For example, I would like to have a form for description, then another one for scope... class ScopeForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(ScopeForm, self).__init__(*args, **kwargs) for field in self.fields: self.fields[field].required = False class Meta: model = Project fields = ['project_scope',] class DescriptionForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(DescriptionForm, self).__init__(*args, **kwargs) for field in self.fields: self.fields[field].required = False class Meta: model = Project fields = ['description',] In my html file, I am using a modal to submit the form <a href="#" data-toggle="modal" data-target="#purpose">Purpose</br></a> <div class="modal fade" id="purpose" tabindex="-1" role="dialog" aria-labelledby="modalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button> <h3 class="modal-title" id="lineModalLabel">Purpose</h3> … -
Python 3 VirtualEnv ImportError: No module named djangocms_admin_style
I am migrating a Django project to production and was going through python manage.py collectstatic phase. After running this command, I get an error: ImportError: No module named djangocms_admin_style However, I clearly have this module installed as both pip list and a manual inspection of the directories shows. What's more, preceeding this error, there is the following traceback: File "manage.py", line 10, in execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 354, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/site-packages/django/core/management/init.py", line 328, in execute django.setup() File "/usr/local/lib/python2.7/site-packages/django/init.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python2.7/site-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/usr/local/lib/python2.7/site-packages/django/apps/config.py", line 86, in create module = import_module(entry) File "/usr/lib64/python2.7/importlib/__init__.py", line 37, in import_module import(name) What confuses me about the traceback is that there are multiple references to the system-wide Python instead of the one I created within the virtualenv. Why is that? I suspect that this has something to do with the error above. If it helps, I do not have anything custom (including django_admin_styles) installed in the system Python environment, only within my virtualenv, which is also activated when the commands are run. Any help is appreciated. -
django - is it possible to abstract the group model?
I know it's possible to do something like the following: class EnterpassUser(AbstractUser): uuid = models.UUIDField(default=uuid4, editable=False, unique=True) is_application = models.BooleanField(default=False, editable=False) class Meta: db_table = 'enterpassuser' managed = True def __str__(self): return self.username Which allows me to use the auth_user model and create a unique enterpassuser model to replace it. I'd like to do something similar with the group model however every option I come across forces me to keep the table name as auth_group and auth_group_permissions where I'd like it to maintain the same process flow as creating a custom user model. -
Django ORM: Group By/Min and return full rows
I have a model table like this Table A Fields A, B, C, D, E (5 Fields) I want to group by field B and min by field C so in the end, i need to have a full queryset like A, B, C, D, E, Min(C)GroupBY(B) (6 Fields). I know about A.objects.values(B).annotate(min(C)) but it returns only 2 fields and not a full row. My requirements are to use only pure Django ORM or extra. I can't use raw SQL (limitations for filter, rawqueryset etc) cause i need a queryset to import to Django-Tables2. Any advice how i can achieve this? -
Python Selenium Local Storage returns None
i am writing some unit tests with Django and Selenium with PhantomJS. Things seem to be working, apart from the fact i need to access the browser local storage to validate that my tokens are correct. My code so far is: from selenium.webdriver.phantomjs.webdriver import WebDriver class UserSeleniumTestCase(StaticLiveServerTestCase): @classmethod def setUpClass(cls): super(UserSeleniumTestCase, cls).setUpClass() cls.selenium = WebDriver() cls.selenium.implicitly_wait(10) @classmethod def tearDownClass(cls): cls.selenium.quit() super(UserSeleniumTestCase, cls).tearDownClass() def setUp(self): # create the users. def test_login(self): self.selenium.get( '%s%s' % (self.live_server_url, reverse_lazy('account_login'))) self.assertIn(_('Sign In'), self.selenium.title) login_input = self.selenium.find_element_by_name("login") login_input.send_keys('test@example.com') password_input = self.selenium.find_element_by_name("password") password_input.send_keys('safe!') self.selenium.find_element_by_id("btn_login").click() self.selenium.get( '%s%s' % (self.live_server_url, reverse_lazy('polls:poll-add'))) self.assertIn(_('Create Polls'), self.selenium.title) print(self.selenium.execute_script('localStorage.getItem("token");')) My problem is that i am getting None with print(self.selenium.execute_script('localStorage.getItem("token");')) were at this point in the login it should be populated (in the browser works just fine). Am i missing something? i also tried print(self.selenium.execute_script('window.localStorage.getItem("token");')) -
how to deal with virtual index in a database table in Django + PostgreSQL
Here is my current scenario: Need to add a new field to an existing table that will be used for ordering QuerySet. This field will be an integer between 1 and not a very high number, I expect less than 1000. The whole reasoning behind this field is to use it for visual ordering on the front-end, thus, index 1 would be the first element to be returned, index 2 second, etc... This is how the field is defined in model: priority = models.PositiveSmallIntegerField(verbose_name=_(u'Priority'), default=0, null=True) I will need to re-arrange (reorder) the whole set of elements in this table if a new or existing element gets this field updated. So for instance, imagine I have 3 objects it this table: Element A priority 1 Element B priority 2 Element C priority 3 If I change Element C priority to 1 I should have: Element C priority 1 Element A priority 2 Element B priority 3 Since this is not a real db index ( and have empty values), I'm gonna have to query for all elements on database each time a new element is created / updated and change priority value for each record in table. Not really worried … -
Django admin fails with bootstraps "danger" class?
In my django admin, error messages (using the messages framework) are created with danger class. However the message looks green with an approval sign over it: When looking into admin/css/base.css, it looks like the error class is error and not danger. Why does it show as danger? How can I change it? -
Django: Temporarily redirect all URLs to one view
I am building site and thought it would be nice to have some sort of maintenance page where I could redirect users if need be. How can I start redirecting all requests to one specific view? I am using Constance to have maintenance switch in my admin view (just a bool value). Its value is then available thorough the project. I've already prepared another list of urlpatterns but cannot figure out how to dynamically change them so the redirect works. maintenance_urlpatterns = [ url(r'^$', views.maintenance, name='maintenance'), ] This is urls.py file from app, not the project one which I would leave alone. I also thought about modifying base.html template and rendering "maintenance page" this way, but I think that is pretty bad solution. -
How to configure a consumer(client) with Django Oauth Toolkit
I have 2 sites and I want to share the accounts between them, I found django oauth toolkit and I setup Site 1 as a server and I want Site 2 to be the client, Im following this tutorial https://django-oauth-toolkit.readthedocs.io/en/latest/tutorial/tutorial.html but I dont understand what I need to configure on Site 2 to login with the accounts of Site 1. Im new to Django, and maybe Im omitting something obvious. -
Query db to receive array of objects
Scenario Lets say i have a model book with fields: id name author rating (Keeping it simple :) ) Now lets say we have multiple rows of books in our db. Question How can I query the db to receive a array of Book objects who have the same author for instance? array = Book.objects.filter(author='JK Rowling') --> returns a QuerySet But i want an array of Book objects. [{id:1, name:'HP 1', author: 'JK Rowling'},{id:2, name:'HP 2', author: 'JK Rowling'},{id:3, name:'HP 3', author: 'JK Rowling'}] -
Diagnosing AttributeError in Django view
In a Django project of mine, I've written simple webhook logic that pings a url for certain payload if some condition is met. Here's the code: @csrf_exempt def webhook_event(request,*args,**kwargs): if request.method == 'POST': data = json.loads(request.body) event_type = data['event'] # use CDN URL from webhook payload if event_type == 'project.datafile_updated': url = data['data']['cdn_url'] config_manager.set_obj(url) return json.dumps({'success':True}), 200, {'ContentType':'application/json'} return json.dumps({'success':False}), 400, {'ContentType':'application/json'} else: return render(request,"404.html",{}) I'm using the following to test it: import requests import json # Update project_id project_id = "<some_id>" data = {"timestamp": 1463602412, "project_id": project_id, "data": {"cdn_url": "https://cdn.example.com/json/{0}.json".format(project_id), "origin_url": "https://example.s3.amazonaws.com/json/{0}.json".format(project_id), "revision": 15}, "event": "project.datafile_updated"} r = requests.post("http://127.0.0.1:8000/ohook/", data=json.dumps(data), headers={'Content-Type': 'application/json'}) print r It all works perfectly, but the tuple returned by webhook_event is giving me the following error: Internal Server Error: /ohook/ Traceback (most recent call last): File "/home/hassan/.virtualenvs/myenv/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 187, in get_response response = middleware_method(request, response) File "/home/hassan/.virtualenvs/myenv/local/lib/python2.7/site-packages/newrelic-2.56.0.42/newrelic/hooks/framework_django.py", line 328, in wrapper return wrapped(*args, **kwargs) File "/home/hassan/.virtualenvs/myenv/local/lib/python2.7/site-packages/django/middleware/clickjacking.py", line 30, in process_response if response.get('X-Frame-Options', None) is not None: AttributeError: 'tuple' object has no attribute 'get' Can anyone help me diagnose this? -
Requested setting DEFAULT_INDEX_TABLESPACE, but settings are not configured
Slighty new to django.. I got this error when attempting to do "django-admin makemigrations" django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. Also get this error when attempting to load my home page: OperationalError at /home/ no such table: home_post -
create a chatbot app for each user in django
i have a django website that runs a chatbot app to simulate a customer service by getting the question and retrieving the best match reply in the DB using queries. view.py: @csrf_exempt def home(request): context= locals() template= 'home.html' return render(request,template,context) @csrf_exempt def male_chatbot(request): if not request.session.session_key: request.session.create() context= locals() template= 'male_chatbot.html' return render(request,template,context) @csrf_exempt def run_python_male(request): if request.method == "POST": session_key = request.session.session_key param11 = request.POST.get('param1') msg = chatbot.run_conversation_male(param11) return JsonResponse({ 'msg': msg}) chatbot.py: raw_chatting_log =[] chatting_log =[] def chatting_log_data(raw_Input,Input,check): if check== "check": if raw_Input in raw_chatting_log: return True else: return False else: if check== "app": raw_chatting_log.append(raw_Input) chatting_log.append(Input) def check_lastB(): new='جديد' if len(raw_chatting_log) == 0: return new else: return raw_chatting_log[-1] def delandsave_chat_log(): name= str(uuid.uuid4()) thefile = open('/home/mansard/webapps/gadgetron/src/chatting_logs/'+name+'.txt', 'w') for item in chatting_log: thefile.write("%s\n" % item) thefile.close() raw_chatting_log.clear() chatting_log.clear() def run_conversation_male(user_in): last_B = check_lastB() H = user_in NN1= "H:"+str(user_in) New_H= ' '.join(PreProcess_text(H)) if last_B== 'تقييمك للمحادثة و الخدمة؟': #do_somthing else: if chatting_log_data(H,NN1,"check") == True: #do_somthing else: #find_replay So, the idea is saving the input/output conversation in two list : raw_chatting_log ==> hold the data with out the addition 'H:' or 'B:' just a the input and output.to help the chatbot remembering the asked questions and using it in chatting_log_data(H,NN1,"check"). chatting_log=> will … -
Required field in Django model not mandatory?
I have the following Django model: class Customer: email = models.EmailField(unique=True) In my testcase, I instantiate it without an e-mail. class CustomerTestCase(TestCase): def test_that_customer_can_be_created_with_minimum_data(self): customer = Customer.objects.create() print(customer.__dict__) I expect it to raise an error, but it creates a record with an empty field email. The same thing happens if I explicitly say null=False and blank=False. Instead, it just prints the empty email. {'email': ''} What am I missing? -
not getting expected django session id
Something very strange is causing me much grief and it has to do with Django sessions. Sometimes my code works as expected, and other times it does not. The workflow I have is this: User visits URL '/connect/', which resolves to the following function 'get_session_id'. Inside this function, I obtain an "ebay session id", which is a session ID that the ebay API sends me. After I obtain this "ebay session id", I redirect users to an ebay URL that allows users to validate themselves. import json import pytz import requests from django.contrib.auth import authenticate, login, logout from django.http import HttpResponseRedirect from django.shortcuts import redirect, render from ebaysdk.trading import Connection as Trading from ebaysdk.exception import ConnectionError def get_session_id(request): api = Trading( appid="XXXXXXXXXXXXXX", devid="XXXXXXXXXXXXXX", certid="XXXXXXXXXXXXXX", config_file=None, ) res = None max_retries = 5 number_retries = 0 while number_retries <= max_retries: try: res = api.execute( 'GetSessionID', {"RuName": "XXXXXXXX"} ) except requests.exceptions.ReadTimeout as exception: if number_retries > max_retries: raise exception number_retries += 1 except ConnectionError as exception: raise Exception('ConnectionError:\n%s' % json.dumps(exception.response.dict(), sort_keys=True, indent=5)) else: break redirect_url = "https://signin.ebay.com/ws/eBayISAPI.dll?SignIn&runame=%s&SessID=%s" % \ ("XXXXXXXXXXXXXX", res.reply.SessionID) response = HttpResponseRedirect(redirect_to=redirect_url) print 'Fetched eBay SessionID: %s' % res.reply.SessionID print 'Django Session Key: %s' % request.session._get_session_key() request.session['ebay_session_id'] = res.reply.SessionID request.session.modified … -
Django: Unable to import models globally
I am running some python scripts which pertains with a django application. So I manually made a folder (named scripts) that contains some python scripts but is not made using ./manage.py startapp scripts. Along with this folder there is a modelsapp django app (which contains my models) and then project folder containing settings.py and urls.py. I run ./manage.py shell < scripts/script.py to run my script. Now here is a sample code of my scripts.py from modelsapp.models import * print(Room.objects.all()) This works pretty well. Now consider a second case. I now just run ./manage.py shell and then put the following commands- from modelsapp.models import * def init(): print(Room.objects.all()) init() This also works pretty well. But now when I run the above code through the file in the first case, it says NameError: name 'Room' is not defined It looks like the model classes which I just imported aren't accessibly inside a function. This behavior is a bit weird. Please help. In case I missed anything to mention, do comment below. -
Django base translation file is not used?
I have a Django project and would like to use i18n to have support of diferent languages. In my template I write: {% load i18n l10n %} <span>{% trans 'Sun' %}</span> then I create required directories inside my BASE_DIR: ./locale/LC_MESSAGES/ar ./locale/LC_MESSAGES/ru My settings: LANGUAGE_CODE = 'en-us' LANGUAGES = ( ('en', _('English')), ('ar', _('Arabic')), ('ru', _('Russian')), ) LOCALE_PATHS = ( join(BASE_DIR, 'locale'), ) Then I run python manage.py makemessages -a, the .po files are getting created. So far, so good.. Examining the .po files I see the folowing (among tons of other lines): #: myproject/web/templates/reports/mycalendar.html:24 #: venv/lib/python3.5/site-packages/django/utils/dates.py:11 msgid "Sun" msgstr "" Hey, do they want me to translate all messages from Django myself?? Lets open a file venv/lib/python3.5/site-packages/django/conf/locale/ar/LC_MESSAGES/django.po: msgid "Sun" msgstr "أحد" So, the translation already exists for this word! Running python manage.py compilemessages - this has no effect for this word, it became English. I've tried to include native django's locale path LOCALE_PATHS: from django.conf import locale as django_locale DJANGO_LOCALE_PATH = abspath(dirname(django_locale.__file__)) LOCALE_PATHS = ( DJANGO_LOCALE_PATH, join(BASE_DIR, 'locale'), ) No way. Still the line presents in my .po file and still msgstr is empty. I tried to delete these lines from my .po file, but after makemessages they appear again. … -
Pycharm: Navigating to JS source specified in require('path/to/file')
Is there a way in pycharm to directly navigate to a file specified as a part of the require? For instance, I have the import of the model randomFile.js var RandomFile = require('./path/to/file/randomFile'); When I create a instance like this: var rf = new RandomFile({'val': 'xyz'}); I would like to navigate to the randomFile.js when I hover & click on RandomFile. For Django application mark directory as -> Sources root helped but this does not work for js files. Thoughts? Thanks in advance -
Third Party Apps Installed In Django Location
So I've installed django-messages and django-notifications into my django projects, when i was in src with pip install django-messages etc. However i can find where the files are, ive done a search of the whole folder but nothing, I've looked in lib/site-packages but nothing. Are they even in my folder or being hosted elsewhere, its so confusing. please help -
How do i render detail template on the same page as category template Django 1.10
I am interested in displaying the detail template on the same page as the category template so that when a category is clicked its content(models) is displayed beside it. something like this Illustration Currently the detail template is rendered independently after clicking a category link. The models class Category(models.Model): cat_name = models.CharField(max_length = 200) def __str__(self): return self.cat_name def get_models(self): return Role_model.objects.filter(category=self) class Role_model(models.Model): category = models.ForeignKey(Category, related_name ='categories') #photos = models.ImageField(upload_to ='users/%Y/%m/%d', blank = True) name = models.CharField(max_length = 200, blank = False) importers = models.IntegerField(blank = True, null = True) def __str__(self): return self.name Views.py def categories(request): cats = Category.objects.all() models = Role_model.objects.all() return render(request, "category.html", {'cats':cats,'models':models}) def DetailView(request, cat_id): #cat = get_object_or_404(Category, id = id) return render(request,"detail.html", {'category':Category.objects.get(id = cat_id)}) urls url(r'^$', views.categories, name='categories'), url(r'^celebs/(?P\d+)/$', views.DetailView, name='detail'), Category.html <div class="categories"> {% for category in cats %} <ul class = "breadcrumb"> <li><a href = "celebs/{{category.id}}/">{{category.cat_name}}</a></li> </ul> </div> {% endfor %} Detail.html <div class="content"> {% for model in category.get_models %} <h5><a href = "#">{{model.name}}</a></h5> {% endfor %} </div> -
Return Excel file from django view to html for downloading at client
I have a django app in which excel file is generated at server side and I want that to be downloaded at client. I am sending request through Ajax call in JavaScript that goes to server generates excel which needs to be downloaded. The view should generate http response that sends excel file to html that could be downloaded to a file at client -
Join results of subqueries in Django
I'm implementing a distributed event store using Vector Clocks to establish a deterministic ordering of events. I'm attempting to perform the following raw query using Django ORM: SELECT dev_snapshots.global_snapshot_id as snapshot_id, dev_snapshots.environment_id, dev_snapshots.clock, test_snapshots.environment_id, test_snapshots.clock FROM ( SELECT global_snapshot_id, clock, environment_id FROM environment_snapshot WHERE environment_id = 'dev') dev_snapshots JOIN ( SELECT global_snapshot_id, clock, environment_id FROM environment_snapshot WHERE environment_id = 'test') test_snapshots ON dev.global_snapshot_id = test.global_snapshot_id ORDER BY dev_snapshots.clock, test_snapshots.clock My models are as follows: class Environment(models.Model): env_name = models.TextField(primary_key=True) current_clock = models.BigIntegerField() class EnvironmentSnapshot(models.Model): global_snapshot = models.ForeignKey('GlobalSnapshot') environment = models.ForeignKey('Environment') clock = models.BigIntegerField() class GlobalSnapshot(models.Model): id = models.AutoField(primary_key=True) Environment has a name and a counter value called clock. EnvironmentSnapshot is a snapshot of a single Environment's clock value during a single GlobalSnapshot. GlobalSnapshot collects EnvironmentSnapshots for all environments that exist at the time the GlobalSnapshot is created. The idea is to sort all the GlobalSnapshots first by the clock value of the "dev" Environment, then by the clock value of the "test" Environment to get a deterministic order of events regardless of when the event was received. GlobalSnapshot is eventually joined to an event that is recorded in the event store. I've looked into Query.join() in Django but it doesn't … -
Django ModelForm: skip a field's validation during edit
I have a form that has several unique fields that become readonly during edit. There are no problems during creation. Unfortunately the ModelForm.is_valid() method catches these and still validates during edit. My model is a simple Django object with its form: from django import forms from .models import Sample class SampleForm(forms.ModelForm): class Meta: model = Sample fields = "__all__" The view method is just a simple save() if is_valid() is true otherwise show the error messages. I manually setup the form in the view file/I do not use the auto-generated form structure by ModelForm. In node.js, I just have this simple validation to catch these (the field slug for example): isSlugUnique(slug, operation) { return new Promise((resolve, reject) => { Sample.findOne({ slug: slug }, (err, sample) => { if(err) throw err; if(sample === null) { resolve(); } else if(slug === sample.slug && operation === 'edit') { resolve(); } else { reject(); } }) }) }, It has a catch to skip the validation if the slug attribute is not unique and the form operation is editing. I tried catching it alongside my is_valid() method (the error message for existing fields is of the pattern "[Model] with this [Field] already exists." so … -
Django - Display Jsonresponse after Fetch POST
I am currently posting audio through javascript fetch to a Django server, post-processing it and returning a JsonResponse. I now would like to display the JsonResponse on my website as they come in. I understand I need some type of listener in my JS that gets triggered with every POST request that is being made, probably after my fetch function or maybe a separate function? My Js function makeLink(){ let blob = new Blob(chunks, {type: media.type }) let fd = new FormData; fd.append("audioRecording", blob); fetch("https://localhost/news/audio/", {method:"POST", body:fd}) .then(response => response.ok) .then(res => console.log(res)) .catch(err => console.error(err)); } This POSTS the audio and triggers the following views.py: def audio(request): if request.method == 'POST': #Store audio #Make some API calls return JsonResponse({"abc":123}) Now let's suppose I have a TextField in plain html and I would like the JsonResponse to be displayed in the TextField without the need of reloading the website. <!DOCTYPE html> <html> <body> <textarea id="text"> Response should be here </textarea> </body> </html> How can I achieve this? -
Can't load a template in Django - 'TemplateDoesNotExist at /home/' error
I'm learning Django from 'Mastering Django: Core' book and now I'm stucked in this third chapter of the book which describes about the Django template. The problem I'm facing is I can't load a template from a specific directory because it gives me this "TemplateDoesNotExist at /home/" error. Here is my project directory : mywebsite/ mywebapp/ ... ... views.py ... temp/ template.html Here is TEMPLATES list from settings.py : TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['/home/temp'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] And finally here's my view : from django.template.loader import get_template def home(request): t = get_template("template.html") c = Context({'heading':'Welcome to MyWebsite.', 'name':'Arya Stark','age':19}) return HttpResponse(t.render(c)) Note: The template I'm using in this view is in the temp directory. So, can you please explain me why would that error happen?