Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
Django related association form field in create form
I'm using Django 1.11 I have a model.py class Business(models.Model): name = models.CharField(max_length=200) business_type = models.ForeignKey(BusinessType, on_delete=models.CASCADE)] def __str__(self): return self.name class BusinessAddress(models.Model): business = models.OneToOneField(Business, on_delete=models.CASCADE) line_1 = models.CharField(max_length=200) line_2 = models.CharField(max_length=200) city = models.CharField(max_length=200) state = models.ForeignKey(State, on_delete=models.PROTECT) postal_code = models.CharField(max_length=15) class BusinessEmail(models.Model): business = models.ForeignKey(Business, on_delete=models.CASCADE) email = models.EmailField(unique=True) class BusinessPhone(models.Model): business = models.ForeignKey(Business, on_delete=models.CASCADE) phone_number = models.CharField(max_length=15) and views.py using class-based view class BusinessCreate(CreateView): model = Business fields = ['name', 'business_type'] I want user to be able to create record for address, email and website along with adding a new business. How to add related fields in the form? One example here shows inline formsets with example in terminal shell. How to add fields in .html template form? -
I failed to get the desired by ORM
Django==1.11.5 I failed to get by ORM what I get by raw SQL select. Could you help me understand the situation: Is it possible to use ORM to get the desired result? If it is impossible, should I use python to refine the results of ORM selection? Or should I use my raw SQL? frametags.models class FrameTag(models.Model): frame = models.ForeignKey(Frame, on_delete=models.CASCADE, verbose_name=_("frame")) tag = models.ForeignKey(Tag, on_delete=models.CASCADE, verbose_name=_("tag")) ORM >>> f = Frame.objects.get(pk=1) >>> f.frametag_set.all() <QuerySet [<FrameTag: Frame 1, tag sport>, <FrameTag: Frame 1, tag dancing>]> PostgreSQL select select tag from frametags_frametag join tags_tag on (tags_tag.id = tag_id); Result: tag ---------- sport dancing (2 rows) -
How do I send message to web socket with Tornado
Hello I am using Tornado, Django frammwork on backend to handle sockets messages on frontend. I am not too much familar with my project but there is a file in my project where are classes that implement websocket.WebSocketHandler and web.Application. This is part of this file class Application(web.Application): """ Main Class for this application holding everything together. """ def __init__(self): PROJECT_NAME = os.path.basename(os.getcwd()) os.environ['DJANGO_SETTINGS_MODULE'] = PROJECT_NAME + 'tutorial/settings' # Handlers defining the url routing. handlers = [ ('/room', SocketHandler), ('/room/([a-zA-Z0-9|=%]*)$', SocketHandler), ('/video_call', VideoCallSocketHandler), ('/video_call/([a-zA-Z0-9|=%]*)$', VideoCallSocketHandler), ] In the frontend part is a function: var ws = new WebSocket('wss://domain.com:9003/video_call/' + conferenceId); ws.onmessage = function (ev) { window.location.replace(redirectUrl); }; I belive that this function get's message from our mobile aplication. So the problem is that I would like to send message to this url or whatever it is 'wss://domain.com:9003/video_call/' + conferenceId from my python view. for example: def some_view_function(request, **kwargs): conference_id = request.GET.data['conferenceId'] ... if something: send message to wss://domain.com:9003/video_call/' + conference_id How do I do that? -
why is the topic of templates so boring in django and is it a must to learn it?
I am new to django(and stack overflow) Why is the topic of templates so boring? Am I the only one who finds it boring? Any good explanations on the topic will help Thamks