Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to determine wagtail Page content type within django template?
The core problem is that handling of wagtail RichTextField and StreamField is radically different in the templates. I'm trying to accomplish something similar to the following: {% with post=post.specific %} {% if post.content_type == 'streamfield' %} {% include_block post.body %} {% else %} {{ post.body|richtext }} {% endif %} {% endwith %} -
Python Django Subcategory
I want to print the subcategory names of each Main Category. The below code is now showing all subcategories for every Main category. How can I do? index.html {% for mainCatList in main_cat_list %} <li class="subMenu"><a>{{ mainCatList.main_category_name }}</a> <ul> {% for subCat in cat_list %} <li><a href="products.html"><i class="icon-chevron-right"></i>{{ subCat.category_name }}</a></li> {% endfor %} </ul> </li> {% endfor %} views.html from django.shortcuts import render from .models import Product, Category, Main_Category def homePageView(request): main_cat_list = Main_Category.objects.all() cat_list = Category.objects.all() context = {'main_cat_list': main_cat_list, 'cat_list': cat_list} return render(request, 'index.html', context) -
Table loop printing backwords & in reverse [Django Template]
<table> <tr> {% for i in "5555" %} <th> {{ forloop.revcounter }} </th> {% endfor %} </tr> <tr> {% for i in "11" %} <th> {{ forloop.revcounter }} </th> {% endfor %} </tr> <tr> {% for i in "1444" %} <th> {{ forloop.revcounter }} </th> {% endfor %} </tr> </table> {% endblock % output: I had to use forloop.revcounter so the numbers appeared in order Anyway what I'm trying to do is dynamically generate a stem-and-leaf-plot sort of graph, but encountered this weird issue I am not sure how to solve. -
In django , how to produce an another form from the obtained result?
I had scraped the data from the web , it produces a list of links . Now i wanted to seggregate the list into wanted or unwanted , by making status choices . But i am in a chaos , how to do it . I got results from web now wanted to create a form with links and the status choices and need to update them in db . -
Django and SQL. Join and group by
Sorry if you dislike my question's title. I just did not know how to name it. In short i have model. class Country(models.Model): title = models.CharField(max_length=255) class Visitor(models.Model): name = models.CharField(max_length=255) country = models.ForeignKey(Country) For example there 300 Visitors From USA 120 from France 25 From Spain. I need to get name of country and max amount how many visitors from this country? I am not good on sql and asking this question Is there way how to realize it? Thanks :) -
Additional field gets lost after validation in model serializer. Django Rest Framework
I want to be able to get list of filenames in ReporterViewset's perform_create method. However I can't do this because I can't reach files from ReportSerializer's validated_data. I want to get file names as additional and validated data from Report serializer. Here is my report serializer class ReportSerializer(serializers.ModelSerializer): files = serializers.ListField(read_only=True, child=serializers.CharField()) class Meta: model = api_models.Report fields = ("id", "reporter", "timestamp", "files", "description") And this is ReportViewset class ReportViewset(viewsets.ModelViewSet): queryset = api_models.Report.objects.all() serializer_class = api_serializers.ReportSerializer def perform_create(self, serializer): file_names = serializer.validated_data.get('files', []) instance = serializer.save() -
django+uwsgi+nginx Excessive use of memory
when I use the component of django+uwsgi+nginx, I found memory has been excessive using , have anyone have some experience or give some tips first I use reload-on-as,reload-on-rss,reload-on-rss,to handle the error So there is the logs of my running uwsgi logs of my uwsgi It's the profiles of nginx,uwsgi user nobody; worker_processes 4; worker_rlimit_nofile 65535; error_log /data/nginx/logs/error.log notice; events { use epoll; worker_connections 4096; } http { include mime.types; default_type application/octet-stream; full_log_format full '$remote_addr $request_length $body_bytes_sent $request_time[s] - - [$time_local] ' '"$request" $status $http_referer "-" "$http_user_agent" $server_name $server_addr ' '$http_x_forwarded_for $http_x_real_ip'; full_access_log /data/nginx/logs/allweb.log full; log_format combinedio '$remote_addr - $remote_user [$time_local] ' '"$request" $status $body_bytes_sent ' '"$http_referer" "$http_user_agent" $request_length $request_time $upstream_response_time'; access_log off; sendfile on; gzip on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 0; client_body_timeout 10; client_header_timeout 10; client_header_buffer_size 1k; large_client_header_buffers 4 4k; output_buffers 1 32k; client_max_body_size 64m; client_body_buffer_size 256k; server { listen 80; server_name 0.0.0.0; location / { include uwsgi_params; uwsgi_pass 127.0.0.1:8080; } location /static/{ alias xxx/server/www/static/; } } include include/*.conf; } uwsgi.ini [uwsgi] socket = 0.0.0.0:8080 master = true vhost = true no-stie = true worker-reload-mercy = 10 harakiri = 60 harakiri-verbose = true vacuum = true max-requests = 5000 reload-on-as = 512 reload-on-rss = 256 limit-as = 2048 buffer-size … -
DJANGO + REACT + WEBPACK-DEV-SERVER
I've big problem with a project I inherit without documentation. The project is build with Django and React. This is the project structure (without not important stuffs): myapp/ ├── assets │ ├── bundles │ │ ├── bar.js │ │ ├── bar.js.map │ │ ├── login.js │ │ ├── login.js.map │ │ ├── main.js │ │ ├── main.js.map │ │ ├── messages │ │ │ └── assets │ │ │ └── js │ │ │ ├── appbar.json │ │ │ [...] │ ├── css │ │ ├── bootstrap.min.css │ │ ├── [...] │ ├── js │ │ ├── appbar.js <<<--- REACT COMPONENT!!! │ │ ├── [...] <<<--- OTHER REACTS COMPONENTS!! ├── conf │ ├── default_settings.py │ ├── default_settings.pyc │ ├── __init__.py │ ├── __init__.pyc │ ├── settings.py │ ├── settings.pyc │ ├── urls.py │ ├── urls.pyc │ └── wsgi.py ├── core │ ├── admin.py │ ├── admin.pyc │ ├── apps.py │ ├── color_palette.py │ ├── color_palette.pyc │ ├── constants.py │ ├── constants.pyc │ ├── decorators.py │ ├── decorators.pyc │ ├── __init__.py │ ├── __init__.pyc │ ├── models.py │ ├── models.pyc │ ├── tests.py │ ├── urls.py │ ├── urls.pyc │ ├── utils.py │ ├── utils.pyc │ ├── views.py │ └── views.pyc … -
Hide button after 1 week
I have a button that I want to hide after a week. But I can't figure out how. from datetime import datetime,timedelta now = datetime.now() weekago = now - timedelta(weeks=1) if (now - weekago > 7) { button.hide } I hope someone can help me with this, maybe with another methode. timesince ? -
I want to crate a Django field in my model to display a word after each new entry
So I want to create a field in my Django models.py, so that the user can select a number of years as integer (e.g. 3) and then after each new entry the words 'years' to be automatically displayed. I do not want to do this with CharField. class StudyProgramme(models.Model): period = models.IntegerField(2) -
join two tables in django ORM using foreign key
I am a beginner in Django. I am facing a problem the details are given below. Kindly take a look and provide me a way out. I have two models "Internalorder2" an "Position3" info mentioned below. I want to join the tables with using Django ORM mentioned below app/models.py class Internalorder2(models.Model): order_id = models.AutoField(primary_key=True) ticker = models.CharField(max_length=64) class Meta: managed = True db_table = 'internalorder2' app/models.py class Position3(models.Model): pos_id = models.AutoField(primary_key=True) parent_order = models.OneToOneField(Internalorder2, models.DO_NOTHING) action = models.CharField(max_length=4) class Meta: managed = True db_table = 'position3' python manage.py shell command from app.models.py import * new = Internalorder2.objects.all().select_related() new = Position3.objects.all().select_related("parent_order") python shell result In [102]: new[0].__dict__ Out[102]: {'_parent_order_cache': <Internalorder2: Internalorder2 object>, '_state': <django.db.models.base.ModelState at 0x13209f0>, 'action': 'B', 'parent_order_id': 1, 'pos_id': 1} But we don't get "Ticker" field please help me where am I doing wrong -
build python list from ansible list of values
I'm trying to 12-factor my django settings by passing environment variables from ansible. I'm trying to get: MYSETTING = ['host1', 'host2] I have tried various options in ansible: # settings.py MYSETTING = os.environ.get(ANSIBLE_VALUE, []) # ansible vars file ANSIBLE_VALUE: "['host1', 'host2']" or # settings.py MYSETTING = [os.environ.get(ANSIBLE_VALUE, None)] # ansible vars file ANSIBLE_VALUE: "'host1', 'host2'" but neither option seems to work. I'm sure there is something simple, but I can't figure it out. -
Adding Multiple Data in Embedded Document as a list with python?
I'm Using Mongoengine with Django, Basically, i want to add lots of additional fields, the number of fields is not predefined. models.py class ProductAdditionalDetails(EmbeddedDocument): detail_name = StringField(required=True) detail_value = StringField(required=True) class Product(Document): __tablename__ = 'product' product_code = StringField(required=True) product_title = StringField(required=True) additional_details = ListField(EmbeddedDocumentField(ProductAdditionalDetails)) views.py class ProductCreateView(APIView): def post(self, request): serializer = AddProductSerializer(data=request.data) if serializer.is_valid(): additional_details = [] for details in additional_details: j = ProductAdditionalDetails( detail_name = serializer.data["detailName"], detail_value = serializer.data["detailValue"] ) additional_details.append(j) new_product = Product( product_code = serializer.data["productCode"], product_title = serializer.data["productTitle"], additional_details = additional_details, ) new_product.save() The Code Below Works! I can pass it as an object in the API but why not in the serializers? fields1 = ProductFields(key_name="size", value="M") fields2 = ProductFields(key_name="size", value="L") fields3 = ProductFields(key_name="size", value="XL") new_product = Product( name=serializer.data["name"], description=serializer.data["description"], fields=[fields1,fields2,fields3] ) new_product.save() -
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)