Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django/SQL double entry table for template
I have the following models in my django app: from django.contrib.auth.models import User class Poll(models.Model): title = models.CharField(max_length=200) author = models.ForeignKey(User) class Choice(models.Model): poll = models.ForeignKey(Poll, on_delete=models.CASCADE) text = models.CharField(max_length=200) class Vote(models.Model): poll = models.ForeignKey(Poll) choice = models.ForeignKey(Choice) user = models.ForeignKey(User) For a given Poll, I need to display in the template a double-entry table like the following, listing all Users who have voted in this Poll and placing an 'x' for each Choice that the user has voted: [choice1] [choice2] [choice3] [user1] x [user2] x x [user3] x [user4] x x What would be the optimal way to implement this using the django ORM in order to minimize the database hits when populating the table? Which object should be passed to the template in the context variable, in order conduct the logic in the view instead of the template? -
Best approach to extensibility/modularity of your OOP Python web app
I'm considering undertaking a really ambitious project. The main part of its concept will be "open-sourceness" and easy extensibility, sort of "hot-plug" kind. As project will be complex and huge, I'll have to employ OOP to make it readable/manageable, thus easy for anybody to jump in and extend it on demand. As title says, it will be a web app, and I'm planning to use Django as a framework. But I'm a bit uncertain what will be the best, the only effective way to approach it. Here is my [possibly wrong] understanding of the situation. Let's suppose I have my basic, core functionality implemented. It's a bunch of classes, they are instantiated into objects, some functions of those objects are called, objects are being passed into other functions - things are humming and sun shines above :) Now, I need to implement sort of addon, or plugin, or whatever, which can be easily attached to existing code, preferably without changing anything at all in it, except for adding some includes - and will basically change how certain functions work and objects behave. Still doesn't seem like a too complex task, right? I know that functions can be re-loaded etc. But … -
How to avoid overwriting a SQL UPDATE statement when looping through list in Python?
I would like to iterate through my 2D list in python and make the elements similar. I want to update my database (mySQL) with IDs of index 0 to be like index 1. list_one = [ [1,3], [2,5], [3,1], [4,5], [5,2] ] loop 1: UPDATE 1 with 3 >> list_one[0] == 3 loop 2: UPDATE 2 with 5 >> list_one[1] == 5 loop 3: UPDATE 3 with 1 >> list_one[2] == 1 ## if you look closely, the first loop will be re-updated by the third loop because list_one[0] is currently == 3. ## So loop 1 will also output as 1 along with loop 3. list_one[0] is overwritten. >> list_one[0] == 1 How can I avoid this from happening? Is there a query in mySQL I can write to update everything at once? If there is, I don't know how many arrays I will have. I am using python, django and mysql. Please help, thank you! -
NameError: name 'order_vals' is not defined. - Python, Django
Alright I know this question title looks EXTREMELY familiar to many on this site but I swear I reviewed quite a few and almost all were issues with indentation and variable scope. That does not appear to be the case here so I'm hoping someone can help out. So I'm writing a function in my models.py to parse out a dataframe into a list of objects to send to my views.py function and I get the NameError referenced in the title, despite declaring the offending variable immediately before it is used. The code is shown below # Setting some default values for our order records. order_vals = { 'site': 'WH30-123', 'sale_type': 'CUST', 'sales_rep': 'JOHN DOE', 'customer_number': "123456789", 'cust_po_number': '{}-{}'.format(self.start_date.strftime(d_form),self.end_date.strftime(d_form)), 'fob': 'ORIGIN' } # Using a helper function to generate a list of orders. orders=helpers.order_parse(ords,order_vals) Okay, not only can I see nothing wrong with typing up a little dictionary and passing it to a function, when I step through this code using import pdb; pdb.set_trace() I can execute order_vals and it returns all the values exactly as I've written them out. I'm at a total loss here. If it helps, here is the function I am passing the dictionary to. def … -
django auth ldap fails to copy ldap group to db
I have implemented ldap on my Django site using django_auth_ldap library. As you can see below, I am doing a LDAP group search which returns 2 results for user 'cory' (see below). The problem is Django is not able to mirror the LDAP groups membership to the Django db. It does not see that cory is a member of 2 groups('jde-testrole1','jde-master'). Have any of you come across this issue where LDAP group search returns results but fails to copy group membershipt to Django? Any insight would be helpful. AUTH_LDAP_USER_DN_TEMPLATE = "cn=%(user)s,ou=Users,o=LDAP" AUTH_LDAP_BIND_AS_AUTHENTICATING_USER = True AUTH_LDAP_GROUP_SEARCH = LDAPSearch("ou=JDE,ou=Apps,ou=Groups,o=LDAP",ldap.SCOPE_SUBTREE) AUTH_LDAP_GROUP_TYPE = GroupOfNamesType(name_attr='cn') AUTH_LDAP_MIRROR_GROUPS = True AUTH_LDAP_ALWAYS_UPDATE_USER = True output: search_s('ou=JDE,ou=Apps,ou=Groups,o=LDAP', 2, '(&(objectClass=*)(member=cn=cory,ou=Users,o=LDAP))') returned 2 objects: cn=jde-testrole1,ou=jde,ou=apps,ou=groups,o=ldap; cn=jde-master,ou=jde,ou=apps,ou=groups,o=ldap Caught Exception while authenticating cory NOT NULL constraint failed: auth_group.name -
How to use django session just using django-orm-standalone?
I'm just creating an API using just django-orm-standalone, no web stuff so there's no request object etc..., so, how can I use django sessions to handle user login/logout/access... Is there a "good way" to do this? Regards. -
How to delete from binarytree data and upgrade descendents ? django-mptt
im trying a same days to solve, but i cant image the algorithm for this. for example have a binary tree. # [1] # [2] [3] # [4] [5] [6] [7] # [8][9][10][11] [12][13][14][15] im need to delete for [3], and the logical upgrade of descendents is, [6] in espace of [3], and [7] on space of [6]... [14] on space of [7]... always on logical up and left movement. im try to apply this conditions if can convert this tree to a list python data based on element deleted. # if list[0].children == 0 : # element.delete # if list[0].children == 1 : # list[0] go to element.position # if list[0].children == 2 : # list[0] go to element.position # list[1] go to list[0].position im try to using django-mptt but i cant solve o im hang on this. -
response = request.urlopen(image_url) AttributeError: 'module' object has no attribute 'urlopen'
Python 2.7.10 and urllib3 are on my computer. Following is my forms.py file: from urllib3 import request ...... class ImageCreateForm(forms.ModelForm): def save(self, force_insert=False, force_update=False, commit=True): ...... response = request.urlopen(image_url) After running server in terminal I got error like this: AttributeError: 'module' object has no attribute 'urlopen' How can I fix it? -
Django Cookies not working
I have an HttpResponse object res res.set_cookie('x-abc-ba-abcabcab-abcd-/','trolling',max_age=3) res.set_cookie('yeha','trolling',max_age=3) This is what i see in res.cookies <SimpleCookie: csrftoken='9TviXgSynURxWZDAAu8j7bCzVJGTM0gjgFX4LgKelPSUop8zohx8X8o253Oq1pob' x-abc-ba-abcabcab-abcd-/=None yeha='trolling'> The first set_cookie's value is not registering, whereas the second one does. Whats happening? -
Trouble locating module
Trying to get a hand of Django. Made en virtual environment started a project started an app (posts) added that app to settings.py trying to import the view.py containing home(request) tried both from posts import views and from OrphBlog.posts import view getting the same error. Can anyone guide me in the right direction ? -
django 404 error - urlPattern definition not working
I have the the following setup: Python 3.6.2 (pip 9.0.1), Django 1.10, Pycharm CE 2017.2.3 running with JRE 1.8.0 Here is a small change of code that I made after running: django-admin.exe startproject main from django.conf.urls import url from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^hello/', admin.site.urls), <<<< code that was added ] When running with the address: http://127.0.0.1:8000/hello, I get the following: What is the problem here? TIA -
Dynamic logic query builder in Django
I'm have 2 table in DB: class Param(models.Model): s_name = models.CharField(max_length=200) n_name = models.CharField(max_length=200) class ParamValue(models.Model): param = models.ForeignKey(Param) value = models.IntegerField() created = models.DateTimeField(default=datetime.now, blank=True) I wanted to create dynamic constructor. Is there any library or method for create dynamic logic filter like as Apache Lucene or Solr? I mean something like this: dyn_filter = parse("(value < 200 AND value__s_name == 'pressure') OR (value > 10 AND value__s_name == 'depth')") result = ParamValue.objects.filter(dyn_filer) -
provide credentials on TDD oauth toolkit django
I'm using Django-Oauth-toolkit, I'm trying to make a test and provide the credentials for the user. but I don't find the way to provide the headers adequately. My test is from rest_framework.test import APIClient from rest_framework.test import APITestCase from django.urls import reverse import json from .models import Client as Cliente from rest_framework import status from .serializers import ClientSerializer # Create your tests here. client = APIClient() client.credentials(HTTP_AUTHORIZATION='Bearer zfMCmzJkLJGkVOwtQipByVSTkXOVEb') class CreateNaturalClient(APITestCase): # Prueba para verificar la insercion de cliente natural def setUp(self): self.valid_payload = { 'username': 'darwin', 'nick': 'dar', 'type_client': 'n', 'first_name': 'darwin' } def test_create_natural_client(self): response = self.client.post( reverse('clients'), data=json.dumps(self.valid_payload), content_type='application/json' ) self.assertEqual(response.status_code, status.HTTP_201_CREATED) and the response always is HTTP 401 Unauthorized I check my token and hasn't expired I test the view with Postman and Curl, and is perfectly fine. In my settings.py 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated',] ¿What I need to do to provide the headers adequately? -
How to create a django model from an existing specific database table?
Can I use inspectdb, if so how can I use it in pycharm? I am new to django. Thanks -
Redirected blog.example.com to example.com/blog but the Wordpress files aren't showing - Django main site, Wordpress on subdomain, Apache server
As the question says, I installed Wordpress on the blog.example.com subdomain. My example.com site is a Django site. They are both running on the same Apache server. I followed this guide to create the virtual host for the subdomain. My problem is: the Wordpress site works fine at blog.example.com, but I want it to run at example.com/blog. I am able to redirect the blog.example.com to example.com/blog However, the Wordpress files don't load, I just get the 404 page from the main Django site. I have tried redirecting in both a separate VH file and the .htaccess file on the subdomain, but neither work (Both redirect fine, but Wordpress doesn't load). My Virtual Hosts file for blog.example.com looks like this: <VirtualHost *:80> ServerName blog.example.com Redirect 301 / https://example.com/blog/ DocumentRoot /var/www/blog.example.com/public_html/ ServerAlias www.example.com/blog </VirtualHost> Any help would be greatly appreciated. Thanks. I feel like it's something so stupid and simple but I can't seem to find out after searching for at least 2 or 3 hours now. Also, let me know if you need more clarification or additional files. -
How to convert datetime in Django to string with genitive month name?
I'd like to convert DateTimeField value from Django model to human-readable string as D genitive_month YYYY. D - day without leading zero, genitive_month - month in genitive form (so called Polish-like locale meaning "of that month"). It's got to be done in backend, not using template tags, and should be saved in specifin non-English language (Russian, as this is my language in current Django project). Initial localization params from settings.py: from django.conf.locale.ru import formats as ru_formats LANGUAGES = [ ('ru', 'Русский'), ] LANGUAGE_CODE = 'ru-RU' TIME_ZONE = 'UTC' USE_TZ = True USE_I18N = True USE_L10N = True ru_formats.DATE_FORMAT = 'd.m.Y' ru_formats.TIME_FORMAT = 'H:i' ru_formats.DATETIME_FORMAT = 'd.m.Y H:i' DATE_FORMAT = 'j E Y' TIME_FORMAT = 'H:i' DATETIME_FORMAT = 'j E Y H:i' Backend code: from django.utils import dateformat some_date_humanized = '{date_humanized} г.'.format( date_humanized=dateformat.format(some_datetime, settings.DATE_FORMAT) ) On one hand, MAYBE Django get localization parameters from system settings having USE_L10N = True. Please reply whether I'm right or wrong with that. As documentation says: Note that if USE_L10N is set to True, then the locale-dictated format has higher precedence and will be applied instead". So I've tried to set USE_L10N = False and it seemed to help. On the other hand, genitive month … -
Prevent Django i18n_patterns from using dash as prefix separator
Django's documentation states that i18n_patterns uses the forward slash as prefix separator for language codes. So, the URL /en/id-123 activates English as language, while /id/id-123 activates Indonesian. However, it seems that the dash is also used as a separator, because the URL /id-123 also activates Indonesian as language. But that's undesired in my use case, because this URL should only fetch an object with ID = 123 instead of switching the language. Is there some setting for determining this behavior? -
Access the choice via my django model
settings.py PERIODS = ( ('day', _('Per day')), ('week', _('Per week')), ('month', _('Per month')), ('year', _('Per year')), ) models.py class Statistics(TimeStampedModel): @property def per_period(self): return settings.PERIODS[self.] def nb_of_customers_per_period(self): pass views.py class StatisticsIndexView(StaffRestrictedMixin, TemplateView): model = Statistics() template_name = 'loanwolf/statistics/index.html' def get_context_data(self, **kwargs): context = super(StatisticsIndexView, self).get_context_data(**kwargs) context.update({ 'applications_by_state': ApplicationsByState(), 'applications_calendar': ApplicationsCalendar(), 'new_customers_calendar': NewCustomersCalendar(), 'statistics': Statistics(), 'form': StatisticsBaseForm(), }) return context forms.py class StatisticsBaseForm(forms.Form): type_choice = forms.ChoiceField(label=_("Type"), choices=settings.STATISTICS_TYPE_CHOICES, initial=0, required=False) period = forms.ChoiceField(label="Period", choices=settings.PERIODS, initial='week', required=False) from_regular_product = forms.ModelChoiceField( queryset=ProductConfig.objects.filter(pk=-1), required=False, label=_('Product')) from_special_product = forms.ModelChoiceField( queryset=ProductConfig.objects.filter(pk=-1), required=False, label=_('Product')) product_type = forms.ChoiceField( choices=settings.LOANWOLF_PRODUCT_TYPE_CHOICES, required=False, initial='regular', label=_('Product type')) debit_frequency = forms.ChoiceField( choices=settings.LOANWOLF_PRODUCT_DEBIT_FREQUENCIES_CHOICES, required=False) def __init__(self, *args, **kwargs): super(StatisticsBaseForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.form_class = 'row' self.helper.layout = StatisticalToolsLayout company = get_current_company() regular_products = company.available_products.filter( is_active=True, product_type='regular') special_products = company.available_products.filter( is_active=True, product_type='special') self.fields['from_regular_product'].queryset = regular_products self.fields['from_special_product'].queryset = special_products if regular_products: self.fields['from_regular_product'].initial = \ settings.LOANWOLF_EXTERNAL_REQUEST_DEFAULT_PRODUCT_INDEX if special_products: self.fields['from_special_product'].initial = \ settings.LOANWOLF_EXTERNAL_REQUEST_DEFAULT_PRODUCT_INDEX class Meta: model = Statistics fields = '__all__' Ok, here is my problem. I have a form with a period drop-down menu which allows me to select different types of period (Per day, Per week, Per month or Per year). For instance, if I select Per week, I would like to have access to … -
Tango with Django (v1.9/1.10) - Chapter 5, populate_rango issues
I will try to be concise. The background for this issue is that I'm familiar with Python, however I am BRAND NEW to django. This book is my first exposure to it and I've come to find the more I work through the book that online Q/A's for django are not very general, thus making it harder to "just google it" and find an answer. MY ENVIRONMENT Resource: Tango with Django (for version 1.9/1.10) Distro: Elementary OS, Patched to the latest Python Version: 3.5 Django Version: 1.11.x MY PROBLEM What Is my Error: django.core.exceptions.FieldError What are the Details: Invalid field name(s) for model Page: 'category'. What does the Error mean?: Per The Docs, This error is raised when there is a problem with a field inside a model..Of the reasons listed The following look relevant to my issue: An infinite loop is caused by ordering. I have verified the the order in which the fields are declared in the model is consistent with how the add_page. as well, I have debugged my code and see that all the fields appear to be correct as they pass through the various functions. however I'm thinking perhaps [this] is might be the issue. … -
How embed (cross compile) python library (twisted, pscopg) in a not common linux & architecture
Im trying to have some python libraries running in a embedded system running Linux but with a not common architecture. Installing python libraries that dont use C dependencies went fine (e.g django library): #1. Download wheel pip install django.whl But with twisted and psycopg libraries that have some C dependencies I need to cross compile it. Any advice how to make it? My goal is to embed the python web server (django framework using twisted and other libraries) Thank you in advance. -
I need to filter a large database 2 billion entries using python and sql
The data is in bytea format, how do I query the postgresql database, its is indexed in the bytea column i need to query by the first 4 bytes. I have tried SELECT * FROM table WHERE addr LIKE '%8ac5c320____' but it takes too long to find. Any suggestions? if I query the whole string then it works fast, but there are about 2 billion entries and i cant use wild cards... -
Is there possible to restart gunicorn by writing a script inside a python-django application? If yes, how should this script look like?
Sometimes the server of my website crashes and/or gets really slow, usually from multiple api processes, thread calls that last really long, and multiple workers/users preforming different activities. After getting a 502 bad gateway, I usually restart the gunicorn. In my understanding the reason for the 502 Error means that the Nginx is having trouble connecting to the Gunicorn process. The solution I have so far is by manually login into the server, and performing sudo systemctl restart gunicorn, and I manually kill those processes based on their pids. However I would like to know if there is anyway of restarting gunicorn automatically by using some sort of script; and repeat process once or twice a week? -
Run python TensorFlow code on a Django made website?
I want to make a website using entirely python and I want to add code made using the TensorFlow module. The idea is to create a website me and my friends can upload training data too no matter where we are. I am trying to make a website using python (it must remain entirely in python) so i'm looking at Django for the website. Using Django (or any other framework) can I add code onto the site even if its from TensorFlow such as this. import tensorflow as tf node1 = tf.constant(3.0, dtype=tf.float32) node2 = tf.constant(4.0) # also tf.float32 implicitly print(node1, node2) Tensor("Const:0", shape=(), dtype=float32) Tensor("Const_1:0", shape=(), dtype=float32) sess = tf.Session() print(sess.run([node1, node2])) Is what I want possible to do in python? -
In Django 1.11 getting Circular Import Errors When including app URLconf files in project URLconf File
I'm new to Django, have been doing several tutorials to get really comfortable with the structuring, and am now running through the official tutorial. I've created an App, which has views.py file as follows: from django.shortcuts import render from django.http import HttpResponse # Create your views here. def index(request): return HttpResponse("Hello, World. You're at the polls index.") I've also created an App URLconf file (urls.py) with the following code: from django.conf.urls import url from . import views url_patterns = [ url(r'^$', views.index, name='index'), ] This is pretty much exactly as done in the Django tutorial. My issue is when I'm specifying url routes in the main url.py file on a project level as such: from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^polls/', include('polls.urls')), url(r'^admin/', admin.site.urls), ] When doing this, I get the following error: django.core.exceptions.ImproperlyConfigured: The included URLconf '<module 'polls.urls' from 'ProjectFolder\\polls\\urls.py'>' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. This is how the official Django tutorial dictates it to be done. However, if I explicity import the views.py file from the app, I can accomplish … -
Swapping Inlines (and dynamic Model creation)
A game, and lets say there are different (restrictive) settings for recreation and I want to adjust via django admin. models.py: class Board(models.Model): name = CharField() class Player(models.Model): bord = Foreignkey('Board') max_cards = IntegerField() class Card_Slot(models.Model): owner = Foreignkey('Player') card = CharField() A Board should have a random number of Players associated with it. An inline TabularInline should be used to add or delete Players, with an IntegerField for the max number of Cards (max_cards). I use signals on save to create dynamically Card_Slots appropriate to the number of max_cards. --- thats what I have, now what I want --- 'Swapping' the Inline after setting the max_cards, for an Inline that represents the Players and their Cards (thus Playername and card in Card_Slot should be editable). Several headaches come up for me on that. If possible I don't want to overwrite admin templates. If I should, I would appreciate a hint that goes further then pointing to the docs, meaning pointing in a direction on good practice. I'm also not sure, if I should use one Model for Player and Card_Slot. (This would make the edit name thing easier, but the dynamic size of Card_Slots worse).. I think. I have …