Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Elasticsearch:Unknown command: 'search_index'
Hi I am trying to implement elasticsearch using django. I am following this tutorial https://www.codementor.io/samueljames/using-django-with-elasticsearch-logstash-and-kibana-elk-stack-9l4fwx138 I am getting , Unknown command: 'search_index' Type 'manage.py help' for usage. when trying to create index using cmd python manage.py search_index --rebuild please help -
Static file "debug_toolbar/css/print.css" does not exist when starting Kiwi Tcms
I'm trying to run Kiwi TCMS on my pc, windows 10, and getting error : Exception at /accounts/login/ Static file "debug_toolbar/css/print.css" does not exist and will cause 404 errors! I don't know what's wrong, already searched and tried the solutions from stackoverflow (that I found relevant) but nothing worked for me. Screenshots are attached. Screenshot1 Screenshot2 -
NLTK. Punkt not found
As the title suggests, punkt isn't found. Of course, I've already 'import nltk' and 'nltk.download('all')'. This still doesn't solve anything and I'm still getting this error: Exception Type: LookupError Exception Value: NLTK tokenizers are missing. Download them by following command: python -c "import nltk; nltk.download('punkt')" I ran nltk.data.path and it output ['/root/nltk_data', '/usr/nltk_data', '/usr/share/nltk_data', '/usr/lib/nltk_data', '/usr/share/nltk_data', '/usr/local/share/nltk_data', '/usr/lib/nltk_data', '/usr/local/lib/nltk_data'] punkit is under /root/nltk_data and I've already checked file permissions. Anything I'm missing? -
Using Jinja2 {{ variable }} into {% instructions %} with Django
I try to setup a webp image converter into my Django templates this way : <img alt="background" src={% webp "/static/img/{{ article.image }}" %} alt="{{ article.name }}" /> It returns me an escape string like this (for exemple in a Jinja loop) : <img alt="background" src="/static/static/img/%7B%7B%20article.image%20%7D%7D"> Is there a way to combinate both in a clean way ? NB : it works in debug False but in production it returns me a 400 Bad Request with no details. Thanks ! -
How to make user to Like/Dislike post only for once in Django?
Started learning Django a few days ago but now I'm stuck with this issue. It's a blog website and i'm working with like/dislike function at the moment. For now authenticated user can like the same post as many times as he wants. I guess there's problem with my model. (Or maybe its conditions in my view) I would be very grateful for the help and clarifications! :) Here's my model (Post.py): class Post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="Пользователь", related_name='author') title = models.CharField(max_length=80, verbose_name="Название") body = models.TextField(verbose_name="Текст публикации") created = models.DateTimeField(auto_now_add=True, verbose_name="Дата создания") modified = models.DateTimeField(auto_now=True, verbose_name="Дата обновления") description = models.CharField(max_length=400,verbose_name = "Описание") reading_time = models.PositiveSmallIntegerField(verbose_name="Время для чтения в минутах") likes = models.PositiveIntegerField(default=0) dislikes = models.PositiveIntegerField(default=0) users_reaction = models.ManyToManyField(User, blank=True, verbose_name='Реакция юзеров', related_name='react') My view (Post.py): class UserReactionView(View): template_name='post.html' def get(self, request, *args, **kwargs): post_id = self.request.GET.get('post_id') post = Post.objects.get(id = post_id) like = self.request.GET.get('like') dislike = self.request.GET.get('dislike') post_user_reactions = Post.objects.filter(user=request.user) if like and (request.user not in post_user_reactions.all()): post.likes += 1 post.users_reaction.add(request.user) post.save() if dislike and (request.user not in post_user_reactions.all()): post.dislikes += 1 post.users_reaction.add(request.user) post.save() data = { 'likes': post.likes, 'dislikes': post.dislikes } return JsonResponse(data) And jquery block in the template {% block jquery %} <script> $(document).ready(function(){ $('#like').on('click', function(e){ e.preventDefault() var … -
ValueError: Cannot assign "5687": "Table2.kid" must be a "Table1" instance
Table1 where i get the data from a management script that calls a certain API. Table2 also gets data from an Api. The scenario is xid & kid are same, so i have implemented a OneToOne relationship so that i can easily get the related item from table1 in context of table2. Table1 has to be populated in order to populate table1, as only then assignment of table2 instance can be done. 5687 Already exists in table1 but still i get the error: ValueError: Cannot assign "5687": "Table2.kid" must be a "Campaign" instance. Models.py class Table1(models.Model): xid = models.IntegerField(primary_key=True) amount = models.IntegerField() class Table2(models.Model): kid = models.OneToOneField(Table1,primary_key=True, on_delete=models.CASCADE) vid = models.IntegerField(null=True, blank=True) g_amount = models.IntegerField() This is my script code that is same for both management commands that get me data. Management/commands/script.py """ API CODE """ data = { 'kid': kid, 'vid': vid, 'g_amount': g_amount } if Table2.objects.filter(vid=xid).exists() or Table1.objects.filter(xid=kid).exists() is False: continue else: # print(data) instance = Table2(**dataff) instance.save() Or should is there a way i don't need to have OneToOne relationship. Using Django's ORM a query can be constructed that will get combine the instance from these two table in one and place it in a Virtual Table … -
django summernote img does not contain full path to uploaded img with host name
I am using https://github.com/summernote/django-summernote for rich test eidtor functionality in my backend. The backend sends the created content to SPA app written in Angular 7. Unforutnelty uploaded files does not contains full path to location with server address. For example { "id": 1, "title": "xxx", "section": "xxx", "urlKey": "xxx", "content": "<p>Title...</p><p><img src=\"/media/django-summernote/2019-03-20/70447090-363a-484c-8f4c-b691a821e3cb.jpg\" style=\"width: 50%; float: right;\" class=\"note-float-right\">/p>" } As we can see the img src=/media/django-summernote/2019-03-20/70447090-363a-484c-8f4c-b691a821e3cb.jpg but I want it to point it to my backend API so it shoudl be img src=http://127.0.0.1:8000/media/django-summernote/2019-03-20/70447090-363a-484c-8f4c-b691a821e3cb.jpg I dont know how to solve the problem either in backed or frontend app. Any help? -
`basename` argument not specified, and could ' \
I am getting the below error again and again.I am trying to solve it from morning but nothing is happening. assert queryset is not None, 'basename argument not specified, and could ' \ AssertionError: basename argument not specified, and could not automatically determine the name from the viewset, as it does not have a .queryset attribute. models.py class Language(models.Model): A = models.CharField(max_length=50) B = models.ForeignKey(User,on_delete=models.CASCADE,null=True) C = models.CharField(max_length=60) D = models.TextField(max_length=256) E = models.BooleanField(default=False) serializers.py class LanguageSerializer(serializers.ModelSerializer): class Meta: model = Language fields = ("__all__") views.py class LanguageView(viewsets.ModelViewSet): queryset = Language.objects.all() serializer_class = LanguageSerializer urls.py router = routers.DefaultRouter() router.register('ln/languages', views.LanguageView) There are many more models(tables) in models.py, Every other model(table) is working fine for getting results but Language model(table) is givin the error assert queryset is not None, 'basename argument not specified, and could ' \ AssertionError: basename argument not specified, and could not automatically determine the name from the viewset, as it does not have a .queryset attribute. -
open edx-ora2 customization
I am recently assigned with a task to add some custom fields in openedx ORA2 xblock . I have installed openedx hawthorn release , the docker version of it . So now openedx is running well but now for customization I am searching for the ORA2 code but I did not find the code . I am preciously looking for this code https://github.com/edx/edx-ora2 in my system so that I can customize it . So can anyone help me out I am totally lost in edx, can anyone tell me where is the code location of ORA2 and how can I customize it . I know python and django but I am totally confused in edx :/ -
Likes/Dislikes in django rest framework [on hold]
How to create likes/dislikes system in Django Rest Framework? I mean how to handle this system in API? And allow users to vote? -
IP and port of current server in django
I want to user the current IP and port as a variable at multiple servers in Django. I have tried calling api.ipify.org to get IP but is there any better way without making an api call? -
Non-model field from data in Serializer DRF
I am trying to serialize an object where I would pass data which are non-model field into the serializer data = { 'field1': 'abc', 'field2': 123, } serializer = UserSerializer( user, context={"request": request}, data=request.data, partial=True, ) serializer.is_valid(raise_exception=True) result = serializer.validated_data where I have a UserSerializer as such class UserSerializer(serializers.ModelSerializer): field1 = serializers.SerializerMethodField() field2 = serializers.SerializerMethodField() class Meta: model = User fields = ( 'username', 'field1', 'field2', ) But I am getting empty DefaultDict() from the serializer.validated_data -
Plotly Gantt Chart: How to change the legend bar and colors to show each row in Dataframe individually? (Accdg to index_col)
My current chart looks like this. This is a production schedule. Each row in Dataframe is a job. The code is below: def chart(task_list, filename): fig = ff.create_gantt(task_list, colors='Rainbow', index_col='Resource', show_colorbar=True, group_tasks=True) # plot(fig, filename=filename) return plot(fig, filename=filename, include_plotlyjs=False, output_type='div') #print(fig) 'Rainbow' is a default plotly colorscale. However, it is limited to just two colors if I'm not mistaken. I just want the chart to have a legend that is similar to this (be it dots or lines, just not a gradient bar like the current Gantt): This is from the Plotly Gantt Chart documentation. Code for this is as follows: df = [dict(Task="Job A", Start='2016-01-01', Finish='2016-01-02', Resource='Apple'), dict(Task="Job B", Start='2016-01-02', Finish='2016-01-04', Resource='Grape'), dict(Task="Job C", Start='2016-01-02', Finish='2016-01-03', Resource='Banana')] colors = dict(Apple = 'rgb(220, 0, 0)', Grape = 'rgb(170, 14, 200)', Banana = (1, 0.9, 0.16)) fig = ff.create_gantt(df, colors=colors, index_col='Resource', show_colorbar=True) py.iplot(fig, filename='gantt-dictioanry-colors', world_readable=True) However, when I use the code from the documentation, it only has a limited number of colors, set by the dict colors. I want the colors to be able to generate on its own whenever a new row comes in from the Dataframe. TLDR; need a COLORSCALE that will be able to accommodate increasing numbers of … -
Pyinstaller binaries giving key Error on Pandas dataframe columns
I have build a binary using pyinstaller for my python module. Below is the spec file: # -*- mode: python -*- block_cipher = None a = Analysis(['manage.py'], pathex=['.envLibsite-packagesscipyextra-dll', '/Users/Python_binaries/t_c','/Users/Python_binaries/t_c/t_c/views.py'], binaries=[('/System/Library/Frameworks/Tk.framework/Tk', 'tk'), ('/System/Library/Frameworks/Tcl.framework/Tcl', 'tcl')], datas=[], hiddenimports=['scipy._lib.messagestream', 'sklearn.neighbors.typedefs'], hookspath=[], runtime_hooks=[], excludes=[], win_no_prefer_redirects=False, win_private_assemblies=False, cipher=block_cipher) def get_pandas_path(): import pandas pandas_path = pandas.__path__[0] return pandas_path dict_tree = Tree(get_pandas_path(), prefix='pandas', excludes=["*.pyc"]) a.datas += dict_tree a.binaries = filter(lambda x: 'pandas' not in x[0], a.binaries) pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher) exe = EXE(pyz, a.scripts, a.binaries, a.zipfiles, a.datas, name='t_c', debug=False, strip=False, upx=True, runtime_tmpdir=None, console=True ) scoll = COLLECT(exe, a.binaries, a.zipfiles, a.datas, strip=None, upx=True, name='Hello') Module is built successfully. But when i hit the api it gives error on line of code which has pandas module in it. I get error as Exception Type: KeyError Exception Value:'originalSentence' Exception Location: t_c/views.py in trainModel, line 26 Below is my code: def trainModel(request): user = request.GET.get('username') client = MongoClient('localhost:27017') # creating connectioons for communicating with Mongo DB client = MongoClient('localhost:27017') db = client.Zeva cursor = db["ProcessedData"].find({}, {"_id": -1, "originalSentence": 1, "topic": 1, "username": user}) # Expand the cursor and construct the DataFrame df = pandas.DataFrame(list(cursor)) df = df[pandas.notnull(df['originalSentence'])] unique_cat = len(df["topic"].unique()) print("len of categories = ", unique_cat) if unique_cat > 1: model … -
security finding: HTTP Parameter Override
There was an identified finding on my django application. HTTP Parameter Override. Basically, this came up because the forms don't have an action value as one of the attributes. But upon checking though, the links provided to me where this was found on the django.contribu.auth pages, specifically the login and password reset pages. Should I perform modifications on the libraries provided by django? Or is there to satisfy the requirement without touching the existing libraries? -
Chart.js and Django for more than one user
I am in the process of creating a web application but when i generate a chart with chart.js, I save the save the chart's data on (site url)/data. This means that anyone who enters the site will see that chart. Is there a way I can store data that is dependent on the user. Meaning that everyone can see different graphs. -
In which place or APP of django should I store data?
Which is the secure and suitable place to store data in django? In already created APP like Users or in custom APP like Posts or something else? -
TypeError : HTTP status code must be an integer, Django
I'm using wkhtmltopdf library & django wrapper to render html template as PDF document. After specifying the content-type='text-html' I've got TypeError : HTTP status code must be an integer During handling of the above exception (invalid literal for int() with base 10: 'text/html'), another exception occurred: on response. NOTE: projects_data is a list of dictionaries. response = PDFTemplateResponse(request=None, template='pdf_export/portfolio_pdf.html', filename="{}.pdf".format(slug), context={'pages': projects_data}, show_content_in_browser=False, content_type='text/html', cmd_options={'disable-smart-shrinking': True, 'T': 0, 'R': 0, 'B': 0, 'L': 0, 'margin-top': 0, 'margin-bottom': 0, 'margin-left': 0, 'margin-right': 0} ) -
How to load iframe in Python Django?
I have a HTML file that store in different folder with django. Below is my HTML code that I run under Python Django: <body> {% load staticfiles %} {{graph|safe}} {% for i in graph %} <div class="box"> <iframe width="47%" height="700" src="{{i|safe}}" frameborder="1" allow="autoplay; encrypted-media" allowfullscreen align="left" ></iframe> </div> {% endfor %} </body> The output for graph is ["a.html","e.html","I.html"] So the iframe create is 3 for this case, I able saw there is 3 box of the iframe generated but fail to see the content. Anyone can share ideas? -
Working with Django Websockets using UWSGI and NGINX
I am trying to use websockets in my Django App. I am using Django channels for websocket communication. I had it working at one point and now I am not sure what went wrong.I was following this article. Here is an outline of my configuration This is the nginx configuration in sites-enabled upstream django { server unix:///home/ec2-user/MyDomainVenv/MyDomainWeb/site1.socket; # for a file socket } server { # the port your site will be served on listen 80; server_name .MyDomain.com; charset utf-8; # max upload size client_max_body_size 75M; location /ws/ { proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_pass http://unix:///home/ec2-user/MyDomainVenv/MyDomainWeb/web.socket; } # Finally, send all non-media requests to the Django server. location / { uwsgi_pass django; # the uwsgi_params file you installed include /home/ec2-user/MyDomainVenv/MyDomainWeb/uwsgi_params; } } This is what I added in my main filename: wsgi_websocket.py import os import gevent.socket import redis.connection redis.connection.socket = gevent.socket os.environ.update(DJANGO_SETTINGS_MODULE='main.settings') from ws4redis.uwsgi_runserver import uWSGIWebsocketServer application = uWSGIWebsocketServer() and this is how I am launching the websocket /home/ec2-user/MyDomainVenv/bin/uwsgi --virtualenv /home/ec2-user/MyDomainVenv --http-socket /home/ec2-user/MyDomainVenv/MyDomainWeb/web.socket --gevent 1000 --http-websockets --workers=2 --master --module main.wsgi_websocket Now when I attempt connecting to it using ws://34.212.WebsiteIP/ws/ The socket connects but when i try to send something I get no response. I am suppose to … -
how to save a an entity which has a foreign key to User in django rest framework?
In my django rest framework project, i have a model names Profile and which has a forignkey for the User(to store the third party variables like address etc.). class Profile(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) # other user data title = models.TextField(max_length=50, blank=False) contact_number = models.TextField(max_length=12, blank=True) description = models.TextField(max_length=500, blank=True) location = models.TextField(max_length=200, blank=True) What i need to know in how to to write the serializer class and View to create the profile. When the a new user removes from the app, the associated profile should be deleted too. Problem: how to write the serializer class and view to create profile. -
How to secure files upload using django
The code below works very well by uploading files to server. please how do I validate and secure the files upload by checking the files Size (Eg. 2mb), file extension name, Files Mimetype and other checking to ensure that only image like .jpg,.gif,.png are uploaded and not virus. model.py from django.db import models # Create your models here. class File(models.Model): file = models.FileField() def __str__(self): return self.file.name View.py from django.shortcuts import render from django.core.files.storage import FileSystemStorage from .models import File import os, datetime from .forms import uploadForm # Create your views here. def index(request): if request.method == 'POST' and request.FILES: form = uploadForm(request.POST,request.FILES) if form.is_valid(): file = request.FILES['file'] # process the data in form.cleaned_data as required file_object = form.cleaned_data['file'] extension = os.path.splitext(file_object.name)[1] rename = datetime.datetime.now().strftime("%Y_%m_%d %H_%M_%S") + extension fss = FileSystemStorage() filename = fss.save(rename, file_object) file = File(file=rename) file.save() upload_file_path = fss.path(filename) return render(request, 'file/index.html', { 'upload_file_path': upload_file_path}) print('uploaded') else: print("Not Valid") else: return render(request, 'file/index.html') forms.py from django import forms class uploadForm(forms.Form): #file = forms.CharField() file = forms.FileField() -
Django deployed with Apache and mod_wsgi gives internal server error 500
I have created a Django application and want to deploy it using apache, mod_wsgi, but the configuration gives error: Internal Server error 500 apache default-ssl.conf <VirtualHost *:80> ServerName my.subdomain.in ServerAlias my.subdomain.in ServerAdmin webmaster@localhost DocumentRoot /home/ubuntu/myproject Alias /static/ /home/ubuntu/myproject/static/ LoadModule wsgi_module /usr/lib/apache2/modules/mod_wsgi.so <Directory /home/ubuntu/myproject/static/> Options Indexes FollowSymLinks AllowOverride all Require all granted </Directory> ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined <Directory /home/ubuntu/myproject/myproject/wsgi.py> Require all granted </Directory> <Directory /home/ubuntu/myproject/> Options Indexes FollowSymLinks AllowOverride all Require all granted </Directory> WSGIDaemonProcess my.subdomain.in processes=2 threads=25 python-home=/home/ubuntu/myproject/venv/lib/python3.6 python-path=/home/ubuntu/myproject #Pointing wsgi script to config file WSGIProcessGroup my.subdomain.in WSGIApplicationGroup %{GLOBAL} WSGIScriptAlias / /home/ubuntu/myproject/myproject/wsgi.py </VirtualHost> wsgi.py import os import time import traceback import signal import sys import site site.addsitedir('/home/ubuntu/myproject/venv/lib/python3.6/site-packages') sys.path.append('/home/ubuntu/myproject') os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings.prod') try: application = get_wsgi_application() except Exception: # Error loading applications if 'mod_wsgi' in sys.modules: traceback.print_exc() os.kill(os.getpid(), signal.SIGINT) time.sleep(2.5) I have install mod-wsgi module as: sudo apt-get install libapache2-mod-wsgi-py3 What am I missing here? Thanks in advance. -
Django CACHE router with multiple databases: route per app
I have two databases and would like for each to have a cache table: DATABASE1: web CACHE TABLE: web_cache DATABASE2: services CACHE TABLE: services_cache Within my project, I switch between the two databases frequently. I'm using the django cache api, and I need to be able to switch to the services_cache table when necessary e.g., if an app is registered on the services DB. The issue is that the app_name always appears as django_cache during the routing, which gives me no meaningful information as to where the cache .set() was called from. Here is my CacheRouter: class CacheRouter: """A router to control all database cache operations""" service_apps_r = ('services_cache', 'schema_manager') def db_for_read(self, model, **hints): """Send all read operations on the services apps to the services DB, else go to the default db""" if model._meta.app_label in self.service_apps_r: return 'services' return 'default' def db_for_write(self, model, **hints): "All cache write operations go to primary" if model._meta.app_label == 'django_cache': # if calling app is schema_manager <----- How can I achieve this? return 'services' return None def allow_migrate(self, db, app_label, model_name=None, **hints): "Only install the cache model on primary" if app_label == 'django_cache': return db == 'services' return None I can't find any helpful info … -
How can i get data from multiple nested serializer
CarrGetOrderDetails class CarrGetOrderDetails(serializers.Serializer): order = CarrGetOrderDetail(required = False) template = CarrGetOrderDetailTemplate(required = False, many = True) extra_fields = CarrGetOrderDetailExtraFields(required = False, many =True) View File class CarrierOrderDetails(APIView): permission_classes = (IsAuthenticated,) def get(self, request): order_id = request.GET['order_id'] #order_obj = Order.objects.filter(id = order_id) obj = self.get_objects(order_id) #print('#####',obj) serializ = CarrGetOrderDetails(obj, many = True) return Response(serializ.data) def get_objects(self, order_obj): model1 = Order.objects.filter(id = order_obj) model2 = OrderTemplate.objects.filter(id = 1) model3 = OrderExtraField.objects.filter(id = 1) obj = {'order': model1,'template':model2,'extra_fields':model3} return obj here i'm try to hit multiple serializer objects but got null data in serializer.data Out put [ {}, {}, {} ]