Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Use getattr inside of another getattr
How can I use getattr method inside of another getattr? I want to write something like that: my_attr = 'group.getattr(name)' my_list = list() for q in queryset_for_table: y = getattr(q, my_attr, None) my_list.append(y) How can i write my_attr string correct? -
pipenv graph showing files not in Pipfile
I'm somewhat new to pipenv and I'm having trouble getting it to behave as it should. Here's a short aggravating conversation I had with my windows PowerShell: PS C:\Users\Win7\OneDrive\Programming\Git\lang> pipenv --where Pipfile found at C:\Users\Win7\OneDrive\Programming\Git\lang\Pipfile. Considering this PS C:\Users\Win7\OneDrive\Programming\Git\lang> pipenv graph coverage==4.4.1 dj-database-url==0.4.2 Django==1.11.6 - pytz [required: Any, installed: 2017.3] django-bootstrap3==9.1.0 django-widget-tweaks==1.4.1 googletrans==2.2.0 - requests [required: Any, installed: 2.18.4] - certifi [required: >=2017.4.17, installed: 2017.7.27.1] - chardet [required: >=3.0.2,<3.1.0, installed: 3.0.4] - idna [required: >=2.5,<2.7, installed: 2.6] - urllib3 [required: >=1.21.1,<1.23, installed: 1.22] gunicorn==19.7.1 pip==9.0.1 psycopg2==2.7.3.2 setuptools==36.4.0 wheel==0.29.0 whitenoise==3.3.1 PS C:\Users\Win7\OneDrive\Programming\Git\lang> pipenv uninstall django.widget-tweaks Un-installing django.widget-tweaks... No package django.widget-tweaks to remove from Pipfile. Locking [dev-packages] dependencies... Locking [packages] dependencies... Updated Pipfile.lock! PS C:\Users\Win7\OneDrive\Programming\Git\lang> pipenv graph coverage==4.4.1 dj-database-url==0.4.2 Django==1.11.6 - pytz [required: Any, installed: 2017.3] django-bootstrap3==9.1.0 django-widget-tweaks==1.4.1 googletrans==2.2.0 - requests [required: Any, installed: 2.18.4] - certifi [required: >=2017.4.17, installed: 2017.7.27.1] - chardet [required: <3.1.0,>=3.0.2, installed: 3.0.4] - idna [required: >=2.5,<2.7, installed: 2.6] - urllib3 [required: >=1.21.1,<1.23, installed: 1.22] gunicorn==19.7.1 pip==9.0.1 psycopg2==2.7.3.2 setuptools==36.4.0 wheel==0.29.0 whitenoise==3.3.1 What lead to this heated debate? Well, I'm trying to deploy my project which depends on the django-widget-tweaks package, but when I push it, the server doesn't install django-widget-tweaks. And sure enough, it does not appear in … -
Is it possible to overwrite a CSV file on a javascript event fired on the front end?
I would like to know the feasibility of doing the following: Fire a JavaScript event on the front end that changes a variable within a CSV (possibly by simply overwriting that file), then Run a python script on the Django backend which reads that CSV and outputs to another CSV (my understanding is that AJAX works for this), then Read the output with JavaScript and used on the front end. Is this a possible event loop, particularly given the asynchronous issues presented? So far I've been able to accomplish step 3 using jquery-csv, and I believe it's possible to run a python script with an AJAX call, making step 2 seem pretty doable. But is it possible to look into an input csv, grab a particular variable I want to change, and then change it? -
JSONField vs. many Charfields
I have an object that has around 25 semantically similar attributes which I could store in individual model.CharField or make use of JSONField (or similar). I'm looking for ideas which approach might be better. The attributes are going to be static, so not change after being setup when the particular instance is initialized. What do you guys think? -
Building a login form
I'm building a login form in Django and as far as my research about it goes is seems like I can't create login form that is "independent" from admin interface. What I mean by that is visitor doesn't have to be registered user in admin. Much like in PHP and MySQL. I can do what I need with PHP but I've been learning Python for some time now and would like to build it in Python. Is Django really gives me this only option ? Makes me wonder how Pinterest did this. I know vast majority of the app is built in Django and people are presented with a login form on front page. -
Custom render RichTextBlock to remove <div class="rich-text">
I'm sure the answer is right there and I'm not seeing it... How can I render a RichTextBlock to remove the wrapping ? {% include_block block %} and {{ block.value }} both give the wrapping div. Thanks in advance! -
Django: Connecting to Active Directory
I am trying to connect my login with active directory. Here is my code: # Baseline configuration. AUTH_LDAP_SERVER_URI = "ldap://domain.ch:389" AUTH_LDAP_BIND_DN = "CN=ipa,OU=Users,DC=domain,DC=ch" AUTH_LDAP_BIND_PASSWORD = "mypassword" AUTH_LDAP_CONNECTION_OPTIONS = { ldap.OPT_DEBUG_LEVEL: 1, ldap.OPT_REFERRALS: 0, } AUTH_LDAP_USER_SEARCH = LDAPSearch("DC=domain,DC=ch", ldap.SCOPE_SUBTREE, "(sAMAccountName=%(user)s)") # Set up the basic group parameters. AUTH_LDAP_GROUP_SEARCH = LDAPSearch("DC=domain,DC=ch", ldap.SCOPE_SUBTREE, "(objectClass=group)") AUTH_LDAP_GROUP_TYPE = GroupOfNamesType() # Populate the Django user from the LDAP directory. AUTH_LDAP_USER_ATTR_MAP = { "first_name": "givenName", "last_name": "sn", "email": "mail" } AUTH_LDAP_USER_FLAGS_BY_GROUP = { "is_active": "CN=ipa-users,OU=Users,DC=domain,DC=ch", "is_staff": "CN=ipa-users,OU=Users,DC=domain,DC=ch", "is_superuser": "CN=ipa-users,OU=Users,DC=domain,DC=ch" } # This is the default, but I like to be explicit. AUTH_LDAP_ALWAYS_UPDATE_USER = True # Use LDAP group membership to calculate group permissions. AUTH_LDAP_FIND_GROUP_PERMS = True # Cache group memberships for an hOUr to minimize LDAP traffic AUTH_LDAP_CACHE_GROUPS = True AUTH_LDAP_GROUP_CACHE_TIMEOUT = 3600 # Keep ModelBackend around for per-user permissions and maybe a local superuser. AUTHENTICATION_BACKENDS = ( 'django_auth_ldap.backend.LDAPBackend', 'django.contrib.auth.backends.ModelBackend', ) This should be enough for a baseline configuration or am I missing something? If i try to log in with my "ipa" account, this is what the console gives me: Caught LDAPError while authenticating ipa: INVALID_CREDENTIALS({'info': u'80090308: LdapErr: DSID-0C09042F, comment: AcceptSecurityContext error, data 52e, v2580', 'desc': u'Invalid credentials'},)[21/Nov/2017 15:46:17] "POST /account/login/ HTTP/1.1" 200 2916 -
install django on Hostgator status 500
I want create site in hostgator. For this, I use this tutorial. I did everything as it is written. Change '/home/username' to '/home3/mikl/'. And this link for download django not work, for this line svn co http://code.djangoproject.com/svn/django/trunk/django. And I change this export PATH=".:/home/username/django/django/bin:$PATH" row in .bash_profile to path to server current django export PATH=".:/usr/lib/python2.6/site-packages/django/bin:$PATH" Everything else is done as it is written. Right now, I have 500 status, and empty log errors list. How I can debug code to find bug? Or if I can download django from another place? Any idea? -
django css works on chrome but not firefox
I'm developing django website and am using bootstrap, I can see the styles on chrome browser but not firefox. firefox inspection shows 404 error for the bootstrap and chrome doesn't. Thankful for any idea. Code :- settings.py Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(file))) PROJECT_DIR = os.path.dirname(os.path.abspath(file)) STATIC_URL = '/static/' STATIC_ROOT = '%s/coffestatic/' % (BASE_DIR) STATICFILES_DIRS = ['%s/website-static-default/'% (BASE_DIR), ("bootstrap", '%s/bootstrap' % (BASE_DIR)),] HTTP file.html {% load static %} <link href="{% static'bootstrap/css/bootstrap.css'%}"rel="stylesheet"> </head> Files structure BASEDIR ________ PROJECTDIR _____ APPs ________ BOOTSTRAPDIR _____ CSS Work flow Define static files python manage.py collectstatic Define styles in html run project Thanks -
Django add comment model for comment
I have a model News and model Comment for it. And it works norm. class News(models.Model): title = models.CharField(max_length=100) text = models.TextField() date = models.DateTimeField(auto_now_add=True) class Comment(models.Model): text = models.TextField() for_news = models.ForeignKey(News) In admin.py from .models import News, Comment class NewsAdd(admin.StackedInline): model = Comment extra = 0 class newseAdmin(admin.ModelAdmin): inlines = [NewsAdd] admin.site.register(News, newseAdmin) In view def showNews(request, news_id=1): news = Article.objects.get(id=article_id) comments = Comment.objects.filter(comments_news_id=article_id) return render(request, 'page.html', {'news': news, 'comments': comments}) How I can and bind a comment for comment? If I make new model class CommentComment(models.Model): text = models.TextField() for_comment = models.ForeignKey(Comment) But, how I can it to admin and bind with parent comment? -
Override keyCode events
I have a Django application and I am using django-autocomplete-light for my select lists. However, I need to change the default behaviour of the key press events that are coming from select2 the underlying JavaScript module that the autocomplete uses. The relevant code from select2 can be found here, and this is what I want to change. Essentially I want to change the keypress event to this: this.on('keypress', function (evt) { var key = evt.which; if (self.isOpen()) { if (key === KEYS.ESC) { self.close(); evt.preventDefault(); } else if (key === KEYS.ENTER) { self.trigger('results:select', {}); evt.preventDefault(); } else if ((key === KEYS.SPACE && evt.ctrlKey)) { self.trigger('results:toggle', {}); evt.preventDefault(); } else if (key === KEYS.UP) { self.trigger('results:previous', {}); evt.preventDefault(); } else if (key === KEYS.DOWN || KEYS.TAB) { self.trigger('results:next', {}); evt.preventDefault(); } } else { if (key === KEYS.ENTER || key === KEYS.TAB) { self.open(); evt.preventDefault(); } } }); where KEYS.pressedbutton equates to the corresponding js keycode. My template (with some omissions) looks like this: {% block content %} <div> <h1 class="text-center">Create New Activity</h1> <div class="row"> <div class="col"></div> <div class="col-md-8 col-lg-8"> <form role="form" method="post"> {% csrf_token %} {{ form|crispy }} <hr> <h4>Add Key Characteristics</h4> <div id="formset"> {{ activitykeycharacteristics_formset.management_form }} {% for form … -
Import errors in django app during runserver and test related to __init__.py
I'm using django 1.11.7 and this is my project structure: > project1 > app1 >__init__.py >views.py >models.py >tests >__init__.py >test_*.py > project2 > app1 >__init__.py >views.py >models.py >tests >__init__.py >test_*.py I was trying to import models from project1.app1 into project2.app1 and even after providing the proper path using sys and os packages it wouldn't work when I would runserver. I found a solution which said to create init file at project level in both places. So now the project structure looks like this: > project1 > __init__.py > app1 >__init__.py >views.py >models.py >tests >__init__.py >test_*.py > project2 > __init__.py > app1 >__init__.py >views.py >models.py >tests >__init__.py >test_*.py And I could run my application from the browser. Then I ran my unit tests and again it couldn't find the models from the other project. On removing the recently added init files (reverting to the original project structure), the import error wasn't being raised. Is there some other solution by which I can runserver and test without the application throwing import errors due to the presense/absence of project level init file? -
If I don't know, what is in array or object, how I can show it in Django in console or page like php var_dump?
I want to know what the array contains, like JS concole.log() or php var_dump def showArticle(request): articles = Article.objects.all() return render(request, 'article.html', {'articles': articles}) templates <pre> {{ articles }} </pre> its show: <QuerySet [<Article: Article object>]> if I use {% for article in articles %} {{ article }} {% endfor %} I will show same Article object Article object Article object and if I want show request. def printRequest(request): req = str(request) print(request) Print only: <WSGIRequest: GET '/'> -
Jquery ajax setInterval not working
i want to make an ajax request every x seconds. This is the function. function test() { alert("wow"); $.ajax({ url: url, type: 'get', dataType: "json", success: function (data) { alert("success"); } }); } If i call it like this test(); it works but if i call it like setInterval(function(){ test(); }, 15000); it will call the first alert and then wont make the ajax call. -
New added static file not found
added a new static file to my project by copy/paste into the static directory for my project. But I get 'File not found' when checking debug mode in the browser. This is my folder structure: - static - projectname -OldScript.js -NewAwesomeScript.js And this is my base.html <script src="{% static 'projectname/OldScript.js' %}" type="text/javascript"></script> <script src="{% static 'projectname/NewAwesomeScript.js' %}" type="text/javascript"></script> The oldscript.js have been in the project for a long time. Just wanted to add a new static file I need to load in base.html. So after copying the file to my folder I copy the include script code and changed the name to NewAwesomeScript.js. It's not working and when checking debug in the browser, it says 'File not found 404'. OldScript.j is loading, NewAwesomeScript.js is not loading. I have restarted the server instance. It's in development. So not a production. Therefore I do not need to run 'collectstatic'. But desperate as I am, I also did this. I have also checked read/write privileges. Trying to find anything in the documentation about adding new static files. Without luck to finding my mistake. What have I forgotten to do? -
Django web app that detects a smart-phone user's position
I want to build a web app using Django-Python that will be mainly used from smart-phones. I want the app to be able to detect the user's position and showcase it into a google maps front end. Basically, I want the app to be something like google maps GPS and then I will make some calculations with the coordinates and print out to the user some alternatives. Do you have any suggestions about what modules, libraries or packages can I use to get this done? -
Can't import users.form when using django-users2
Here are my import from users.forms import RegistrationForm If i just import like this, an exception will be raised: django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet. and I have tried using django.setup() after secure_key being set in settings bur another exception will be raised: RuntimeError: Model class Article.models.Article_model doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. But I have put Article in INSTALLED_APPS . I don't know why Here are where the exception was raised enter image description here enter image description here -
Translating django python 3 to python 2
I have been writing this site but my server host only maintains python 2. The website I wrote is on python 3 and I am not sure if I have to rewrite the whole thing or there is some way to port it. -
Django - ReactJS, How to resize image to optimal size?
I am using Django - GraphQL (Graphene/Relay) - ReactJS for my website. Before I request an image from my Django application I already know the exact size the image needs to be. I would like to resize my image on the server before sending it to the Client, this would just make more sense to me than to upload every image 10 with different sizes and then use logic to determine which one I need (doesn't it?). I found django-imagekit but I didn't manage to find anything that would work for an application not using Django for the views, preferably something that works with GraphQL. What is the best way to do this? -
enum34 issue in Elastic Beanstalk
I'm trying to set up a django environment in Elastic Beanstalk. I am running into a python3.6 issue when I try to install through a requirements.txt file. File "/opt/python/run/venv/bin/pip", line 4, in <module> import re File "/opt/python/run/venv/lib64/python3.6/re.py", line 142, in <module> class RegexFlag(enum.IntFlag): AttributeError: module 'enum' has no attribute 'IntFlag' I cannot set up my environment properly while this is an issue. Some searching around pinpointed the enum34 module as the cause of the issue, but when I try to ssh into my EB environment and remove it using: /opt/python/run/venv/bin/pip3 uninstall enum34 I get the same error, indicating the venv is broken in some way. How do I get around this issue? here are the extension files I pass into the environment for reference: django.config: option_settings: aws:elasticbeanstalk:container:python: WSGIPath: yahoo_serp/wsgi.py aws:autoscaling:launchconfiguration: InstanceType: t2.large packages: yum: libjpeg-turbo-devel: [] db-migrate.config container_commands: 01_migrate: command: "./manage.py migrate" leader_only: true option_settings: aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: yahoo_serp.settings -
Set ModelChoiceField default value
I want to set a default value for a form field, as the field is not defined in the model, and thus not saved in the db. class DeviceForm(forms.ModelForm): uses = forms.MultipleChoiceField(choices = Device.objects.none(), required = False) ...... def __init__(self, *args, **kwargs): if kwargs["instance"]: CHOICES = [(x.name, x.name) for x in Device.objects.filter( trashed = None).exclude(pk = kwargs["instance"].id)] self.fields['uses'].choices = CHOICES self.fields['uses'].initial = [x.name for x in Device.objects.filter(used_in = kwargs["instance"].id)] But this does not work, if I change the value, save and then try to edit, the default value, which should be the previously selected choice, does not show up in the field (for example, I create a Device, select 'a', save, click edit and want the field to already contain the checked 'a', so that I can remove it again), but the field is simply empty. I already tried doing this with .default(...), but that doesn't work either. Is there any way do define a default value in __init__? -
How to extract model fields from Serializer in DRF?
I need to get model fields list in Django Rest Framework. i got field list from models by below method, filter_fields = model._meta.get_all_field_names() but i want to get it from serializer itself instead extracting from model. is there a way to do so? -
Add a glyphicon even if i use Django
Hi I'd like to know how can i add a glyphicon to the left of "input" in my code because I'm using django and I have to use forms.py you know. My HTML code : <form methode="post" action="/connexion" class="form-horizontal" role="form"> {% csrf_token %} {{ form.as_p }} <div> <button type="submit" class="btn btn-info"><span class="glyphicon glyphicon-off">Connexion</button> </div> </form> forms.py : class ConnexionForm(forms.Form): user = forms.CharField(label='', max_length=30, widget=forms.TextInput(attrs={'placeholder': "Nom d'utilisateur"})) password = forms.CharField(label='', widget=forms.PasswordInput) -
Python Logging: Change "WARN" to "INFO"
If our Django web application returns a 404, we see this in the logs: 2017-11-21 12:48:26 django.request.get_response: WARNING Not Found: /foooooo I would like to change this particular line created by get_response() from WARN to INFO. How to configure this with Django and Python? -
Can we write one app inside some another django-app
Is there any way to create one app inside another django-app. like Vendor ---> Parent app alpha ---> Child of vendor beta ---> Child of vendor