Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python django-admin startproject mysite
First timer here with Django and I am running into some issues trying to start the site with the Windows command prompt django-admin startproject mysite My pip install worked as I can import the module and check the Django version. I am also running Python version 3.6... >>> import django >>> print(django.get_version()) 2.0.4 I also created a directory on my windows machine so my windows command prompt looks like this: C:\Users\b\Documents\Python\Django>django-admin startproject mysite But I am getting an error 'django-admin' is not a recognized as an internal or external command, operable program or batch file.' Any tips to try??? Thanks -
How to get current user id Django
I am stuck with the JWT, can any one tell me how can I get user ID along with token. My url.py : from rest_framework_jwt.views import obtain_jwt_token from scrumboard.views import UserDetail from scrumboard import views urlpatterns = [ url(r'^api-token-auth/', obtain_jwt_token), url(r'^users/$', views.UserList.as_view()), ] views.py: class UserList(generics.ListAPIView): queryset = User.objects.all() serializer_class = UserSerializer class UserDetail(generics.RetrieveAPIView): queryset = User.objects.all() serializer_class = UserSerializer serializers.py: class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'email', 'password') The problem is that when i go to api-token-auth/, its only giving me the username and password and not the id. -
django_auth_ldap - AUTH_LDAP_REQUIRE_GROUP
I am using django_auth_ldap. Login without checking for a group works fine. But trying to login with the user example_user which was added to the group example_group on LDAP and setting AUTH_LDAP_REQUIRE_GROUP fails. settings.py AUTH_LDAP_SERVER_URI = "ldap://ldap.example.com" AUTH_LDAP_START_TLS = True AUTH_LDAP_BIND_DN = "" AUTH_LDAP_BIND_PASSWORD = "" AUTH_LDAP_USER_SEARCH = LDAPSearch("cn=users,dc=example,dc=com", ldap.SCOPE_SUBTREE, "(uid=%(user)s)") # Set up the basic group parameters. AUTH_LDAP_GROUP_SEARCH = LDAPSearch("cn=example_group,cn=groups,dc=example,dc=com", ldap.SCOPE_SUBTREE, "(objectClass=groupOfNames)" ) AUTH_LDAP_GROUP_TYPE = GroupOfNamesType(name_attr="cn") AUTH_LDAP_REQUIRE_GROUP = "cn=example_group,cn=groups,dc=example,dc=com" From the logs: search_s('cn=users,dc=example,dc=com', 2, '(uid=%(user)s)') returned 1 objects: cn=example_user,cn=users,dc=example,dc=com cn=example_user,cn=users,dc=example,dc=com is not a member of cn=example_group,cn=groups,dc=example,dc=com Authentication failed for example_user: user does not satisfy AUTH_LDAP_REQUIRE_GROUP $ ldapsearch -x -h ldap.example.com b"cn=example_group,cn=groups,dc=example,dc=com" ldap_bind: Success (0) [...] # extended LDIF # # LDAPv3 # base <cn=example_group,cn=groups,dc=example,dc=com> with scope subtree # filter: (objectclass=*) # requesting: ALL # # example_group, Groups, example.com dn: cn=example_group,cn=Groups,dc=example,dc=com cn: example_group objectclass: top objectclass: groupOfUniqueNames objectclass: orclGroup description: [...] displayname: example_group orclisvisible: true uniquemember: cn=example_user,cn=users,dc=example,dc=com # search result search: 2 result: 0 Success # numResponses: 2 # numEntries: 1 -
Python get URL parameters of parent URL
Getting URL's is working fine if I go to the view url directly but if the view is put into an iframe the code no longer works. Simply the parameters I am trying to get are not being saved. I have tried both these versions: views.py if request.method == 'POST': form = LeadCaptureForm1(request.POST) if form.is_valid(): # Save lead lead = form.save(commit=False) lead.created = created lead.birth_date = form.cleaned_data.get('birth_date') lead.ipaddress = get_real_ip(request) lead.joinmethod = "Iframe2" try: lead.referral_id = request.GET["affiliate_id"] except: pass try: lead.click_id = request.GET["click_id"] except: pass lead.save() and views1.py if request.method == 'POST': form = LeadCaptureForm1(request.POST) if form.is_valid(): # Save lead lead = form.save(commit=False) lead.created = created lead.birth_date = form.cleaned_data.get('birth_date') lead.ipaddress = get_real_ip(request) lead.joinmethod = "Iframe2" lead.referral_id = request.GET.get("affiliate_id") lead.click_id = request.GET.get("click_id") lead.save() -
Django 2.0.4 not serving style.css
I am trying to load some static files in Django 2.0.4: <script type="text/javascript" src="{% static 'js/jquery.js' %}"></script> <link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}" /> the jquery file loads fine, but the css results in a 404. Why? I have tried running python manage.py collectstatic, but I don't think it is picking up the css file for some reason.. -
Django: How to update a IntegerField based on previous ChoiceField, but keep it editable?
I hava the following form: class form1(forms.ModelForm): CHOICES = (('EASY', 'EASY'), ('MEDIUM', 'MEDIUM'), ('HARD', 'HARD')) dificulty = forms.ChoiceField(choices=CHOICES) xp = forms.IntegerField() I want to change the xp field based on the dificulty field choice. Like, if the user put EASY on dificulty, change xp to 30. But keeping it editable, so the user can specify if it will be 31 or 29, or something like that. -
How to get logging working with django?
I am testing my own auth backend, as descried here. I have a added some logging. Please obviate these two issues, which are known to me: I am using the root logger (bad) I am using the error log level (bad) (I just want to find out why my log messages are not being shown, and want to make sure I am hitting a working logger / level) import logging from django.conf import settings from django.contrib.auth.hashers import check_password, make_password from django.contrib.auth.models import User class SettingsBackend: """ Authenticate against the settings ADMIN_LOGIN and ADMIN_PASSWORD. Use the login name and a hash of the password. For example: ADMIN_LOGIN = 'admin' ADMIN_PASSWORD = 'pbkdf2_sha256$30000$Vo0VlMnkR4Bk$qEvtdyZRWTcOsCnI/oQ7fVOu1XAURIZYoOZ3iq8Dr4M=' """ def authenticate(self, request, username=None, password=None): logging.error('authenticate') login_valid = (settings.ADMIN_LOGIN == username) pwd_valid = check_password(password, settings.ADMIN_PASSWORD) logger.error('username={} login_valid={} pwd_valid={}'.format(username, login_valid, pwd_valid)) if login_valid and pwd_valid: try: user = User.objects.get(username=username) except User.DoesNotExist: # Create a new user. There's no need to set a password # because only the password from settings.py is checked. user = User(username=username) user.is_staff = True user.is_superuser = True user.save() return user return None def get_user(self, user_id): logging.error('get_user') try: return User.objects.get(pk=user_id) except User.DoesNotExist: return None def has_perm(self, user_obj, perm, obj=None): logging.error('has_perm') return user_obj.username == settings.ADMIN_LOGIN I have … -
Django - Unable to import XXX module
I am just starting with Django, and I ran into some issues on my first project. For some reason I am getting the following error: Unable to import 'package name'. Here is the picture : As you can see, there were no issues identified when i try to run my Django Project. I've managed to create a simple Http call and everything still works perfectly fine. But it bothers me that half of my project is red and it is showing error messages but no actual error when i run it. When building my Django Projects I am using: Linux OS Python 3.65 Django 2.02 Visual Studio Code If anyone has any idea whats going on I would really appreciate the help. Thank you in advance! -
Could not satisfy Django application requirements
I have been trying run Django application since afternoon. It application probably uses Python 2.7. I have created virtual environment and I have installed Django from Python PIP package manager. However, this application requires JQuery package to proper working. Unfortunately, an error was occurred when I tried install JQuery package from PIP: (my_env) user➜~/carcaresilesia» pip install jquery [16:39:44] ⚡[..........] Collecting jquery Using cached https://files.pythonhosted.org/packages/05/45/9a6d7ff770b1279c901c8dfca1f9a9d6c9822d75a2bad834d0e2ddd4f8cd/jquery-1.2.3.zip Complete output from command python setup.py egg_info: Traceback (most recent call last): File "<string>", line 1, in <module> File "/tmp/pip-install-wKwd78/jquery/setup.py", line 2, in <module> from turbogears.finddata import find_package_data ImportError: No module named turbogears.finddata ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-install-wKwd78/jquery/ I tried install turbogears package, unsuccessfully with below error: (my_env) user➜~/carcaresilesia» pip install turbogears Collecting turbogears Using cached https://files.pythonhosted.org/packages/1d/35/80872474a6663b6994b6879041a38b2fa81a34098e331f2ffddd43e2c8d3/TurboGears-1.5.1.tar.gz Collecting CherryPy>=3.1.2 (from turbogears) Using cached https://files.pythonhosted.org/packages/b8/6d/d0d951dee5ba50900eccb71ef501a847d0392f50056d36234740f97a2ef8/CherryPy-14.2.0-py2.py3-none-any.whl Collecting ConfigObj>=4.3.2 (from turbogears) Using cached https://files.pythonhosted.org/packages/64/61/079eb60459c44929e684fa7d9e2fdca403f67d64dd9dbac27296be2e0fab/configobj-5.0.6.tar.gz Collecting FormEncode>=1.2.1 (from turbogears) Using cached https://files.pythonhosted.org/packages/2f/53/707c2b9b65ea6bedde67c21cbf7c71394f4a198620d4e9c1771214b91dcc/FormEncode-1.3.1.tar.gz Collecting Genshi>=0.4.4 (from turbogears) Using cached https://files.pythonhosted.org/packages/c5/2f/34493b2286561d0ea003c568a6c80343eee3c9975a69964d22ce8501dd3f/Genshi-0.7.tar.gz Collecting PasteScript[cheetah]>=1.7 (from turbogears) Using cached https://files.pythonhosted.org/packages/06/7d/ddc3efab0967e7056bcd6adea0b860717b4b6e4d3ea8ec49985ed0f43cb0/PasteScript-2.0.2-py2.py3-none-any.whl Ignoring Cheetah: markers 'extra == "Cheetah"' don't match your environment Collecting PEAK-Rules>=0.5a1.dev-r2555 (from turbogears) Could not find a version that satisfies the requirement PEAK-Rules>=0.5a1.dev-r2555 (from turbogears) (from versions: ) No matching distribution found for PEAK-Rules>=0.5a1.dev-r2555 (from turbogears) … -
Django and Collectstatic Issue
I'm trying to deploy my Django web Application (2.0.1) thanks to Nginx and I'm getting an issue. I configured the new Ubuntu server, add my Django Project and I downloaded nginx. My Django project looks like : Mysite ├── App1 ├── App2 ├── App3 ├── lib ├── Global_variables.py ├── Mysite ├── settings.py I have to make collectstatic with nginx, so I execute this command : python manage.py collectstatic But into my settings.py file, I have : #from django.conf import global_settings import os, datetime import lib.Global_variables And this issue : File "/var/www/Mysite/Mysite/settings.py", line 16, in <module> import lib.Global_variables ImportError: No module named lib.Global_variables However my import seems to be right. Any idea ? -
Run celery periodic task for 1 hour, it it takes more then 1 hour, expire that task?
I have a periodic task for data purging which run once a day. i want that task to run only for 1 hour, if the duration of processing that task is more than 1 hour expire that task, which will run next day again for 1 hour. This is because if traffic is high then that particular cerely task keeps on running for 10-15 hours.Thanks in advance. -
Change models.AutoField(primary_key=True) to Hexadecimal
I am using django with mongodb using the djongo orm. I am facing a problem. I want to set id to be the autofield and according to django autofield is of integerfield type. But when it is inserted in mongodb, mongodb uses its conventional 12byte hexadecimal value. This is the problem why I cannot edit in django admin. because autofield is integer but in mongo it becomes hexadecimal. I want help. I want to create a custom autofield which will be hexadecimal so as to solve my problem. Please help me. -
Messenger bots - latency on some messages
I'm currently working on a Messenger bot with Django. Sometimes, the bot takes time to answer. When I look at my server logs, I can see that the webhook does not send the request to my server. What can cause this issue ? Is this problem intern to Facebook ? On the developper platform, it is written that the API performance are lower at the moment, but I am not sure if my issue is related to that. Please notice that my server can perfectly send requests to Facebook through the SEND API. There is a latency only from the webhook to my server. I am using Ngrok to create a tunnel to my local machine. -
Live Django quiz app
I want to develop a django quiz app with following specifications: A room will be created at a specific time for all users. show questions to all online users(who join the room) at same time and allot a short time slot (1 min) for answering questions. They choose one option which will auto-submit as time ups. user will be disqualified as soon as he gives wrong answer to any question. Score of user is added to his previous points. -
Cleanest Way to Allow Empty Scheme in Django URLField
I'm using Django 2.0 and trying to allow users to input a link to their website in a django ModelForm. I would like for my URLField to validate urls even when they have no scheme prefix. I have read this solution: django urlfield http prefix. I'm wondering if there is a way to achieve this without writing my own custom regex in a RegexValidator. It doesn't seem like a very DRY solution to repeat all of the regex logic that is built into the URLValidator. I want to do something like the below: website = models.CharField(max_length=400, blank=True, null=True, validators=[URLValidator(schemes=['', 'http', 'https', 'ftp', 'ftps'])]) This obviously doesn't work because of the way the URLValidator's call method validates against the given schemes. def __call__(self, value): # Check first if the scheme is valid scheme = value.split('://')[0].lower() if scheme not in self.schemes: raise ValidationError(self.message, code=self.code) Adding an empty string to the schemes list doesn't work because splitting the url in this way returns the entire URL (as a user typically does not include :// if that user is not including a scheme prefix). Now, I could subclass URLField and overwrite the entire call method in order to change the way that it handles … -
Django Admin inlineformsets with custom forms and/or custom fields
I want to use in Django Admin a custom form, that have a formset included as a field. Main model: class C(models.Model): name = models.CharField(max_length=255) short_description = models.CharField(max_length=12) In admin: class CAdmin(admin.ModelAdmin): form = CModelForm fieldsets = ( ('C Data', { 'fields': ('name', 'short_description', 'add_field') }), ........ In form: class CModelForm(models.ModelForm): class Meta: model = CModel fields = ['name', 'short_description'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # instantiate the CAFormSet and added as an attribute to the form self.lg = CAFormSet( instance=self.instance, prefix='ca' data=self.data if self.is_bound else None, files=self.files if self.is_bound else None, auto_id=False) I use this technique to push a formset of a related model(FK) in the main form.This is working for my forms, but fails in Django Admin, I recieve an error: 'Unknown field(s) ('add_field') specified for C Using Django inline forms, doesn't look good as UI separation, but I accept also an answer were I can modify the inlineform form (I need to automate some fields value on form save - I tried but failed) -
Django: Aggregate (sum) of a field on two different set of data in a single query
My Model looks something like: Class Transaction(models.Model): type = models.CharField(max_length=255, db_index=True) amount = models.DecimalField(decimal_places=2, max_digits=10, default=0.00) I have few transactions, few of which are credit and other are debit (determined by type column). I need to check the balance of all transaction i.e., (debit - credit) Currently, I could do that using 2 queries as below: debit_amount=Transaction.objects.fitler(type='D').aggregate(debit_amount=Sum('amount'))['debit_amount'] credit_amount=Transaction.objects.fitler(type='C').aggregate(credit_amount=Sum('amount'))['credit_amount'] balance = debit_amount - credit_amount I am looking something like: Transaction.objects.aggregate(credit=Sum('amount', filter=Q(type='C')), debit=Sum('amount', filter=Q(type='D'))) -
Django: Form with multiple inputs is invalid
My template html has the following inputs (multiple): <form method="post" enctype="multipart/form-data"> {% csrf_token %} <input name="image_field" type="file"> <input name="image_field" type="file"> My view is: def add_listing(request): if request.method == 'POST': image_form = ImageForm(request.FILES) files = request.FILES.getlist('image_field') if object = Object.create() # since all images should relate to this object e.g. this object is the foreign key for f in files: # add images Image.objects.create(pk=None, object=object, image=f) object.save() return render(request, 'dashboard/add_listing.html', {'image_form': image_form}) My goal is to process the form which can take n inputs with the same name, and for each file in the input, validate it and create an object. -
Unable to find out the page.In python D-jango getting an error shows FileNotFoundError at /bcr/bcr/
In my d-Jango project I am unable to find out my page for bcrr.html which is stored in a static folder.I am getting an error shows FileNotFoundError at /bcr/bcr/ [Errno 2] No such file or directory:'D:\\dfg\\dfg\\nlp\\static\\bcard\\Chinees-naamkaartje.jpg' Given below is my code for views.py and url.py for my project: # MyApp/urls.py from django.conf.urls import url, include from nlp import views #from . import views from django.views.generic import TemplateView urlpatterns = [#'MyApp.views', url(r'^signin/$', views.signin, name = 'signin'), url(r'^LTT/$', views.LTTpageView.as_view()), url(r'^BCR/$', views.BCRpageView.as_view()), url(r'^RTNT/$', views.RTNTpageView.as_view()), url(r'^$', views.MainPageView.as_view()), url(r'^TSA/$', views.TSApageView.as_view()), url(r'^AFT/$', views.AFTpageView.as_view()), url(r'^ACT/$', views.ACTPageView.as_view()), # Add this /about/ route # url(r'^$', views.HomePageView.as_view()), url(r'^CID/$', views.CIDPageView.as_view()), # Add this /about/ route url(r'^login/$', views.NATPageView.as_view(template_name = 'login.html')), # Add this /about/ route url(r'^home/$', views.HomePageView.as_view(template_name = 'index.html')), # Add this /about/ route url(r'^aboutus/$', views.AboutUSPageView.as_view(template_name = 'AboutUs.html')), # Add this /about/ route url(r'^SAN/$', views.SANPageView.as_view()), # Add this /about/ route url(r'^FAT/$', views.FATPageView.as_view()), # Add this /about/ route url(r'^act/act/$', views.act, name = 'act'), url(r'^aft/aft/$', views.aft, name = 'aft'), url(r'^bcr/bcr/$', views.bcr, name = 'bcr'), url(r'^ltt/ltt/$', views.ltt, name = 'ltt'), url(r'^rtnt/rtnt/$', views.rtnt, name = 'rtnt'), url(r'^login/login/$', views.login, name = 'login'), url(r'^cid/cid/$', views.cid, name = 'cid'), url(r'^fat/fat/$', views.fat, name = 'fat'), url(r'^tsa/tsa/$', views.tsa, name = 'tsa'), url(r'^test/$', views.TestpageView.as_view()), url(r'^test/test/$', views.test, name = 'test'), ] and my … -
Django: Joining a group Works, But I cant leave A group
I have added the join group functionality, and it works fine. Now, However, Im trying to add the leave group functionality, which seems like it would be similar, but it isn't working, and not throwing me an error either. here is the code for both join and leave group. it should be noted that there is a M2M relationship between User and Group. (urls.py): from . import views from django.urls import path app_name = 'groups' urlpatterns = [ path('create/', views.create, name='create'), path('index/', views.index, name='index'), path('<int:group_id>/', views.detail, name='detail'), path('<int:group_id>/join/', views.join, name='join'), path('<int:group_id>/leave/', views.join, name='leave'), ] (views.py): def join(request, group_id): group = get_object_or_404(Group, pk= group_id) if request.method == 'POST': group.members.add(request.user) group.save() return redirect('/groups/' + str(group_id) ) else: return render(request, '/groups/detail.html', {'group': group}) def leave(request, group_id): group = get_object_or_404(Group, pk= group_id) if request.method == 'POST': if request.user in group.members.all: group.members.remove(request.user) group.save() return redirect('home') else: return render(request, '/groups/index.html') groups/detail.html {% extends "base.html" %} {% block content %} <div class="row"> <div class="col-4"> <h1>{{group.name}}</h1> </div> <div class="col-6"> <p>{{group.description}}</p> </div> {% if user in group.members.all %} <div class="col-2"> <a href="javascript:{document.getElementById('leave').submit()}"><button class="btn btn-primary btn-lg btn-block"> Leave {{product.members.count}}</button></a> </div> {% else %} <div class="col-2"> <a href="javascript:{document.getElementById('join').submit()}"><button class="btn btn-primary btn-lg btn-block"> Join {{product.members.count}}</button></a> </div> {% endif %} </div> <div class="row"> … -
Login with Django Rest Framework and Angular 2
I'm new using Angular 2 with django restframework, How can I do a login and register page with those. I've been searching for tutorials but I did not find a good one Any tutorial to suggest? -
Social login from webview in Android
I have a website and since we are a startup, it changes frequently. We have developed our website in a manner that it is mobile friendly (looks good in mobile browser). Now, we want to launch our android app. To launch it quickly we just created a simple android app with webview that launched our website. Everything looks good but social logins (google, fb and twitter) they need sign in again by opening a custom webview client. I followed this question and it's answers and it works fine also. But, I want to know is there still a way in which I can leverage social login which android through it's account manager provides if someone calls code from native app and able to get user information from it. My backend is in django and frontend is in react. Also I am using session based authentication system. Also, I would like to know another good way to launch our android app. -
Using mysql AES encrypt and decrypt from Django
In my Django app, I want to use AES_ENCRYPT and AES_DECRYPT from the mysql database to encrypt and decrypt stuff. I know that python's Crypto package has AES support but the Crypto AES doesn't produce the same result as mysql AES although I made sure that both are using the ECB mode. So, now I'm doing this: sql = "select 1 as id, AES_ENCRYPT(my_field, '16-bytes encryption key') as field_enc from appname_table" encrypted_fields = MyModel.objects.raw(sql) This gets me the field values after encryption and it works fine. The issue is that the AES algorithm encryption final result has many unprintable characters, it looks like this: encrypted_fields[3].field_enc '\x88\xc5\xe4\xa0c?\xf8\x16|^1JB\x83{\xdf' print(encrypted_fields[3].field_enc) ���c?�|^1JB�{� So, now when I try to take this same value to decrypt it, the mysql replies with an error that says "OperationalError: (1300, "Invalid utf8 character string: '\x88\xC5\xE4\xA0c'")" I guess this is because I tried to send unprintable characters to the mysql query. So, how do I approach this? Please note that I have to use the MySQL functions because I encrypted some database fields using these functions so I need to decrypt them with the same function because Crypto's AES doesn't get the same results. Crypto keeps asking that the text … -
Django - the best option to develop real-time messaging
I want to implement to my Django project existing app/framework which logged users can communicate in real time. I was reading about django-channels and django-chatrooms, but I'm not convinced. Somebody has experience with real-time chatting using Django and Django-users? I'm looking for the most secure solution for the latest(Django 2.0 & Python3) versions. Thanks in advance! -
Pyinstaller with Django: ModuleNotFoundError: No module named 'django.contrib.admin.apps'
I'm getting an error when trying to run my packaged python application in cmd line: ModuleNotFoundError: No module named 'django.contrib.admin.apps' I tried the answer from pyinstaller 3.2 with django 1.10.1, but I still get the same error. The only difference is a ModuleNotFoundError rather than an ImportError. Does anyone know what I could be doing wrong?