Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why is my variable not defined inside a list comprehension?
I'm retrieving a 5 random filtered queryset on django, as mentioned in the title, my variables are not defined inside my comprehension list. NameError : 'address' is not define (same for 'website') To do as the description and avoid performance issues, I'm using this method: website = True address = True object_data = SomeModal.objects.filter(address=address, website=website) number_of_records = object_data.count() - 1 #count filtered records random_sample = random.sample(range(number_of_records), 5) #get 5 random samples (ex: ['2', '0', '3', '6', '7']) The error occurs at this stage: #get those 5 random samples. layouts = [SomeModal.objects.filter(address=address, website=website)[random_int] for random_int in random_sample] What could be the reason of this problem? -
Limit user to access a APIView
I want to get the user's detail information: class UserDetailAPIView(RetrieveAPIView): """ User detail information """ queryset = User.objects.filter(is_valid=True).exclude(status=4) serializer_class = UserDetailSerializer lookup_field = "username" I want to limit other users to access this APIView, I want only admin user and the user it self to access that. How to limit this? -
Django: best way to define a form to insert long texts?
I am working with Django1.8 and Python 2.7.+ I want to define a form that has text field where the user can insert a text as long as he needs to. The first thing that I tried was defining a forms.TextField, but it turns out TextField only exists under models, not under forms. This is how I have defined it: selected_services = forms.CharField(label="Selected_services *", max_length=999999999, widget=forms.Textarea()) But the max_length=999999999, looks terrible. What would be a more elegant way of defining a form field to store very long texts? -
Get current server ip or domain in Django.
I have a util method in Python Django project: def getUserInfo(request): user = request.user user_dict = model_to_dict(user) user_dict.pop("password") user_dict.pop("is_superuser") user_dict["head_img"] = user.head_img.url # there is `/media/images/users/head_img/blob_NOawLs1` I want to add my server domain or ip in the front of it, like: http://www.example.com:8000/media/images/users/head_img/blob_NOawLs1 How to get current ip( or domain )? -
Django AD authentication
I have a django project and have hosted on azure IIS and i want to validate the user-id and password (not search) with my organization AD. Please can anyone suggest a way? I have already tried django_auth_ldap but it is not suggesting any way to authenticate. I have tried ldap to install but its showing error about VC++ but i have already VC++ install the error is C:\Users\username\AppData\Local\Programs\Common\Microsoft\Visual C++ for Python\9.0\VC\Bin\amd64\cl.exe /c /nologo /Ox /MD /W3 /GS- /DNDEBUG -DHAVE_TLS -DHAVE_LIBLDAP_R -DHAVE_SASL -DLDAPMODULE_VERSION=2.5.2 "-DLDAPMODULE_AUTHOR=python-ldap project" "-DLDAPMODULE_LICENSE=Python style" -IModules -I/usr/include -I/usr/include/sasl -I/usr/local/include -I/usr/local/include/sasl -Ic:\python27\include -Ic:\python27\PC /TcModules/LDAPObject.c /Fobuild\temp.win-amd64-2.7\Release\Modules/LDAPObject.obj LDAPObject.c c:\users\username\appdata\local\temp\pip-build-dqfo_q\python-ldap\modules\errors.h(7) : fatal error C1083: Cannot open include file: 'lber.h': No such file or directory error: command 'C:\Users\username\AppData\Local\Programs\Common\Microsoft\Visual C++ for Python\9.0\VC\Bin\amd64\cl.exe' failed with exit status 2. -
Dynamic field in Django forms
I have a django form where a particular field (called parameter) is repeated multiple times as per the users choice. For eg, when a user is creating an object, he/she may choose to include 1, 2 or n parameters. So I want the form to be initialized with only 1 parameter field. Then if the user clicks on say a + symbol, another parameter field would pop up. Is there a way to do this with Django forms? -
Django file_move_safe error with SELinux
PermissionError on upload of large files (large enough to not use the in-memory file class) when SELinux is in enforce mode, in CentOS 7. The error happens after the file is copied to the destination folder. As seen in the trace below, when copystat is called from file_move_safe, shutil tries to set attributes to the destination file with setxattr. But this is failing when SELinux is enabled. I noticed on temporarily disabling SELinux that the files, which are successfully uploaded now, have a context of 'httpd_tmp_t' as opposed to the context of 'httpd_sys_rw_content_t' which the directory is configured with. So, when SELinux is enabled, setxattr is failing when the context of the file is 'httpd_sys_rw_content_t'. I don't remember having this issue before as the site has been running for a few years. I recently upgraded to Python 3.6 from 3.4 (manually compiled) and has applied all the OS updates. Traceback (most recent call last): File "/home/portal/venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/home/portal/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 249, in _legacy_get_response response = self._get_response(request) File "/home/portal/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/portal/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/portal/venv/lib/python3.6/site-packages/django/contrib/auth/decorators.py", line 23, in _wrapped_view return … -
Infinite scroll not triggered automatically | How to fix?
I want to use infinite scroll option of waypoints plugin in my Django project. I use next code but plugin don't work correctly. When I go at the end of the document, I want automatically trigger the plugin. But right now plugin works only when I change the size of browser. Where is my mistake, I am little bit confused. links: <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/waypoints/4.0.1/jquery.waypoints.min.js"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/waypoints/4.0.1/shortcuts/infinite.min.js"> Django render me next html: <ol class="infinite-container"> <li class="infinite-item"></li> <li class="infinite-item"></li> <li class="infinite-item"></li> <li class="infinite-item"></li> <li class="infinite-item"></li> <li class="infinite-item"></li> </ol> <div class="loading"> <i class="fa fa-cog fa-spin fa-3x fa-fw" aria-hidden="true"></i> </div> <a class="infinite-more-link" href="?page=2"></a> <script> var infinite = new Waypoint.Infinite({ element: $('.infinite-container')[0], onBeforePageLoad: function () { $('.loading').show(); }, onAfterPageLoad: function ($items) { $('.loading').hide(); } }); </script> -
How to use django + react + nodejs + rest api + redis for scale chat application?
I want to make a scale chat application with web socket. be able to that i have to use Django for login and this kind of things but besides that i want to use web socket for chat side with node.js. The reason that i want node.js is very powerful for socket. and i want to use redis for cache. How can i do that with these skills? How can i ensure the web security? How can i ensure to communicate with rest api(django) for android later? How to use influentially this architecture? or do you have any idea? Thank you. -
Django - CSS File Not Loading In Production (Debug: False)
Current error (Debug=False) "[16/Jan/2018 15:18:42] "GET /static/style.css HTTP/1.1" 404 90" Web site loads but broken formatting because CSS file not loaded Logging: On the CMD prompt it says "[16/Jan/2018 15:49:05] "GET /beginners/ HTTP/1.1" 200 3760 [16/Jan/2018 15:49:05] "GET /static/style.css HTTP/1.1" 404 90 " I'm not sure why this isn't working: my style.css is located in my static folder, and the static folder is the same folder as manage.py When I set Debug = True, I reload the page and it works fine - my static folder is active and I get no static error: [16/Jan/2018 15:58:11] "GET /beginners/? HTTP/1.1" 200 3759 [16/Jan/2018 15:58:11] "GET /static/style.css HTTP/1.1" 200 5014 Please help!! STATIC_URL = '/static/' PROJECT_DIR = os.path.dirname(os.path.abspath(__file__)) STATIC_ROOT = os.path.join(PROJECT_DIR, 'static') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] DEBUG = True ALLOWED_HOSTS = ['127.0.0.1'] BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -
Django: Chatterbot comparision function return internal error 500
I am facing the problem while using the comparison function in chatter-bot. My chatter-bot is working fine but sometimes it returns in-sensible answers so i am using comparison function for better response but unfortunately it return 500 internal error POST http://127.0.0.1:8000/en/api/chatterbot/ 500 (INTERNAL SERVER ERROR) Here is my settings.py CHATTERBOT = { 'name': 'Django ChatterBot Example', 'trainer': 'chatterbot.trainers.ListTrainer', 'logic_adapters':[ { "import_path": "chatterbot.logic.BestMatch", "statement_comparison_function": "chatterbot.comparisons.jaccard_similarity", "response_selection_method": "chatterbot.response_selection.get_first_response" }, { 'import_path': 'chatterbot.logic.LowConfidenceAdapter', 'threshold': 0.65, 'default_response': "I didn't understand that question; do you need help with Math, Excel, Music or Graphic?" } ], 'django_app_name': 'django_chatterbot', 'read_only': True, 'training_data': [ "Music", "Hey I see you need help with Music please click on the following link Etc", "Excel", "Hey I see you need help with Microsoft Excel please click on the following link Etc", ], } -
How to upload image from Django admin to only AWS S3 not mysql?
I created AWS S3 bucket to hold all static and media file for my website. In my website Django admin. I have a field to upload image. What I expected is upload the image to my S3 bucket's media folder only. However, the image will upload to both my database(I use AWS RDS) and S3 bucket. I think I can remove the image field of models.py but my admin will not show the field of uploading image. Which files should I modify and how to modify it? (If need to see any codes I can upload more snapshot of the codes) -
Running 2 django project in different port number at the same time
As what the title said, is it possible to run 2 django project at the same time ? Since by default, all django run by http://127.0.0.1:8000/. Is there anyway i can change the port number for both the django project ? My task is this: Integration of django 1 api and django 2 api, to setup two django app, on same server / PC, with different port As far from what i know, i can change the port number in the settings.py database section. I also cant seems to find much information about this. The only solution i found which is running this command: manage.py runserver 8005 will allow the django project to run in 8005 port. But is it possible to do it without writing the command and just do it in the settings.py or other file ? As i know this is just for development phrase. If its on production, it cannot use in this way. -
How to iterate 'dict' with 'enumerate'
I have the following code. This just show me one user instead of all the users I have inside my JSON, and also I have another problem, when I'm concatenating my strings it show me a "\" after I put a '"': def get(self, request, format=None): users = Caseworker.objects.all() response = self.serializer(users, many=True) for j in range(0,len(response.data)): dictionary = response.data[j] myresponse = "" for i, (val, v) in enumerate(dictionary.items()): myresponse = myresponse + '{"text":' + '"' + v + '"' + '}' + ',' print(myresponse) # for i,(k,v) in enumerate(dictionary.items()): # myresponse = myresponse + '{"text":' + '"' + v + '"' + '}' + ',' # print(myresponse) return HttpResponse(json.dumps({'messages': myresponse}), content_type='application/json') -
Django under supervisord?
django project is running under supervisord, when i try to edit the html templates, nothing changes in the web site, should I restart the supervisord or is there other easier way to make changes to the project? -
Update django view context from another part of application
I have two django applications A and B, i have overidden a template of A in B by dding an extra button. Now on click of this button i want to update the context of application A view. How can i do it in application B. -
Integrating redis with django
I am newbie in Django,My task is design a backend where there will be login system(using the dfault user table provide by django).There are two other tables one is the image table which has the imgvalue column which contains the key from redis database.The other table(imgacl) is to provide the access control to users for viewing the particual images which a required user has access.The redis databse is actually storing the images with key-value pair,and that key is stored in the imgvalue column.Here are my codes: models.py: from django.db import models from django.contrib.auth.models import User # Create your models here. class Image(models.Model): imgvalue = models.Charfield(max_length =250) class Imageacl(models.Model): id = models.ForeignKey(Image,on_delete =models.CASCADE) A separate python program for storing 50 images in Redis db.Suppose there are 5 users, the user1 can view 10 images,users2 can view 15 images............ import redis from PIL import Image rd = redis.StrictRedis() for x in range(1,51): img = open("{}.jpg".format(x),"rb").read() rd.set("key{}".format(x),img) I have two question:1)How I wll integrate redis with django & 2)How I will provide the access control to users?? -
Java based ORM vs Django ORM?
I have worked on Java web applications (using Spring framework with Hibernate as ORM) and python web applications (using Django with its inbuilt ORM). Please help me in comparing Hibernate (or any java based ORM like datanucleus or mybatis) and django ORM. Comparison will be specific to: Ease of use Handling of complex queries like doing multiple joins, partitioning, group by, having clause etc. Query execution performance Prior experience with java based ORM - not at all easy to use, have to do a lot of configuration, unable to write complex queries like joining multiple tables and all(it might be design issue). I have seen a lot of projects in which raw query has been written for the particular database which beats the MAIN purpose of ORM. Experience with Django ORM - easy to configure, easy to use, can easily write complex queries. -
How to create a virtual environment for Django in Pycharm?
Currently, I am developing a Django web app in a virtual environment but when I try to edit the web app it just seems that the libraries that I installed in the virtual environment are not found. This is the scenario I have: I installed a virtual environment in C:\Users\myUser\PycharmProjects. mkdir virtualenvs ; cd virtualenvs python -m venv virtualenvs I got access to the new folder, activated the virtual environment, upgrading pip and started installing the libraries I need for my project. cd C:\Users\myUser\PycharmProjects\virtualenvs\virtualenvs\Scripts ; .\activate (virtualenvs) python -m pip install --upgrade pip (virtualenvs) pip install django djangorestframework pandas numpy requests I go back to C:\Users\myUser\PycharmProjects to create my new Django project (I am still inside of my virtualenvs). (virtualenvs) mkdir C:\Users\myUser\PycharmProjects\apps ; cd C:\Users\myUser\PycharmProjects\apps (virtualenvs) django-admin.exe startproject app1 (virtualenvs) python manage.py startapp web_app_navigator (virtualenvs) python manage.py runserver I am able to see the Django successful message The install worked successfully! Congratulations!, but when I open this new application in PyCharm to do some changes such as trying to import any library that I installed I get an error message that the library is not found. My guess is that the virtualenvs and app folder is in some way disconnected … -
Django: how do i create a model dynamically
How do I create a model dynamically upon uploading a csv file? I have done the part where it can read the csv file. -
How can i resolve HTTPSConnectionPool(host='www.googleapis.com', port=443) Max retries exceeded with url (Google cloud storage)
I have created API using Django Rest Framework. API communicates with GCP cloud storage to store profile Image(around 1MB/pic). While performing load testing (around 1000 request/s) to that server. I have encountered the following error. I seem to be a GCP cloud storage max request issue, but unable to figure out the solution of it. Exception Type: SSLError at /api/v1/users Exception Value: HTTPSConnectionPool(host='www.googleapis.com', port=443): Max retries exceeded with url: /storage/v1/b/<gcp-bucket-name>?projection=noAcl (Caused by SSLError(SSLError("bad handshake: SysCallError(-1, 'Unexpected EOF')",),)) -
How to iterate the values in the list in django template?
I am going to print four array values simultaneously in django template . like this the four arrays are of equal length ,they are header_list , domain_list , domain_data , dom for i in range(10): print headerlist[i] print domain_list[i] print domain_data[i] print dom[i] how to acheive these in django template . also tried from django import template register = template.Library() @register.filter(name='myrange') def myrange(number): return range(number) -
Django Rest Framework - Multiple "lookup_fields" URL router.register
I can't seem to figure out how to register a route with multiple lookup_fields in the case where there is a composite primary key. My look up fields are isin and valuedate The ideal url would look either like: /price/?isin=AT0000383864&valuedate=2018-01-16 or /price/AT0000383864/2018-01-16 when i update my views.py to the multi look up I get the following error lookup_field = ('isin','valuedate') ImproperlyConfigured: "^price/(?P[^/.]+)/(?P[^/.]+)//(?P<(u'isin', u'valuedate')>[0-9a-f]{32})/$" is not a valid regular expression: bad character in group name u"(u'isin', u'valuedate')" urls.py # router.register('price', priceViewSet, 'price') If i revert back to just isin in my lookup_field I can narrow my record set by making the URL /price/AT0000383864 But never the next level Thanks -
how to pass the email of the current user login in python function django
this is my python function i want to pass the user's email to my variable to_email how can i do that? def email_two(request): subject = "Skin Diagnosiss" message = 'Image that has been diagnosed \n https://aqueous-citadel-60536.herokuapp.com' + fname from_email = settings.EMAIL_HOST_USER member = Member.objects.get(email=request.POST['email']) to_email = [member] send_mail(subject, message, from_email, to_email, fail_silently=False) return HttpResponse('Diagonis successfully sent to your emai') -
I did not get the data in APIView
In my APIView: data = { "user":user_dict, # the user_dict have data. "account":account_dict # the account_dict have data too. } serializer = UserInfoSerializer(data=data) is_valid = serializer.is_valid() # the `is_valid` is True return Response(data=serializer.validated_data, status=HTTP_200_OK) But when I access this APIView, I get nothing. The UserInfoSerializer code is bellow: class UserInfoSerializer(Serializer): user = serializers.DictField(read_only=True) account = serializers.DictField(read_only=True)