Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
d3.js pan zoom issue
I am working on a django project in which I use intensively d3.js. I have a javascript function that works well: function three_lines_pan_zoom_chart(id, data, options) { var plotChart = d3.select(id).classed('chart', true).append('svg') .attr('width', options.w + options.margin.left + options.margin.right) .attr('height', options.h + options.margin.top + options.margin.bottom) .append('g') .attr('transform', 'translate(' + options.margin.left + ',' + options.margin.top + ')'); var plotArea = plotChart.append('g') .attr('clip-path', 'url(#plot_Area_Clip)'); plotArea.append('clipPath') .attr('id', 'plot_Area_Clip') .append('rect') .attr({ width: options.w, height: options.h }); var navChart = d3.select(id).classed('complex_chart', true).append('svg') .classed('navigator', true) .attr('width', options.nav_w + options.margin.left + options.margin.right) .attr('height', options.nav_h + options.margin.top + options.margin.bottom) .append('g') .attr('transform', 'translate(' + options.margin.left + ',' + options.margin.top + ')'); var minN = d3.min(data, function (d) { return d.date; }).getTime(), maxN = d3.max(data, function (d) { return d.date; }).getTime(); var minDate = new Date(minN - 8.64e7), maxDate = new Date(maxN + 8.64e7); var yMin = d3.min(data, function (d) { return Math.min(d.value, d.valueBchk, d.valueIdx); }), yMax = d3.max(data, function (d) { return Math.max(d.value, d.valueBchk, d.valueIdx); }); var xScale = d3.time.scale() .domain([minDate, maxDate]) .range([0, options.w]), yScale = d3.scale.linear() .domain([yMin, yMax]).nice() .range([options.h, 0]); var navXScale = d3.time.scale() .domain([minDate, maxDate]) .range([0, options.nav_w]), navYScale = d3.scale.linear() .domain([yMin, yMax]) .range([options.nav_h, 0]); var xAxis = d3.svg.axis() .scale(xScale) .orient("bottom") .ticks(5); var yAxis = d3.svg.axis() .scale(yScale) .orient("left"); plotChart.append('g') .attr('class', … -
How to get the IP address of a client using aiohttp
I am currently working on a django project where I use aiohttp to communicate between the backend and frontend. I wanted to get the IP address of a client when a request is made from the frontend. Looked in different docs but none seems to point to exactly how to get the IP address using aiohttp. Someone Help! from aiohttp import web async def handler(request): ws = web.WebSocketResponse() await ws.prepare(request) try: async for msg in ws: # handle incoming messages # use ws.send_str() to send data back ... finally: task.cancel() -
Display previously uploaded files or images
I have two data tables and am using Django at the back end and Vuejs at the front end. (1) Products, stores the product details and a single image. (2) Products_Images, stores the multiple images with relation to the product. The below code is called from < Product List > when Editing the product details including adding images or removing images. My problem is that in Edit mode I need the previously selected displayed instead of ( No Files Chosen ) <!-- Edit a Product (Start) --> <template id="product-edit"> <div> <h2>Product (Edit)</h2> <form method="post" enctype="multipart/form-data" ref="itemMaster"> <!-- Display Product Name --> <div class="form-group"> <input class="form-control" id="edit-name" v-model="product.itemfullhd" required/> </div> <!-- Upload Single Image --> <div class="form-group"> <!-- ### MY PROBLEM HERE ### --> <label for="edit-imagemain">Main Image </label> <input type="file" id="edit-imagemain" v-model="product.Image_file" @change="onFileChanged" required/> <img class="cart-thumbnail" v-bind:src="'/media/' + product.image_file" alt="image"/> </div> <!-- Upload Multiple Images --> <div class="form-group"> <!-- ### MY PROBLEM ALSO HERE ### --> <label for="files">Xtra Images</label> <input type="file" id="files" ref="files" multiple v-on:change="handleFilesUpload()"/> <div> <!-- Display the Multiple Images --> <table class="table table-striped "> <thead> <tr> <th>Xtra Image File/s</th> <th>Image</th> <th>Delete</th> </tr> </thead> <tbody> <tr v-for="imagerec in products_images" and v-if="( imagerec.itemfullhd == product.itemfullhd )" style="clear: both;"> <td>/media/{{imagerec.images_multiple}}</td> <td> <img … -
django heroku in deploy debug mode
STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'staticproject') ] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(STATIC_ROOT, 'media') server 500 Error when i add to setting.py django_heroku.settings(locals()) urlr.py urlpatterns = [ url(r'^media/(?P.)$', serve,{'document_root': settings.MEDIA_ROOT}), url(r'^static/(?P.)$', serve,{'document_root': settings.STATIC_ROOT}), path('admin/', admin.site.urls), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
changing javascript function name or ID of element in HTML template makes it stop working
I am developing an app in Django. I have this weird issue. on my template I have: <div class="form-group"> <input name="Data_inserimento_entry" type="date" class="form-control" id="date_to_turn_into_toda" > </div> <script type="text/javascript" src={% static "js/get_today_date.js" %}></script> <script> get_today_date(date_to_turn_into_toda) </script> on the js file get_today_date.js stored at static > js > get_today_date.js I have function get_today_date(id_data) { var now = new Date(); var day = ("0" + now.getDate()).slice(-2); var month = ("0" + (now.getMonth() + 1)).slice(-2); var today = now.getFullYear()+"-"+(month)+"-"+(day); document.getElementById(id_data).value = today; } when I load the template, in the input slot, today's date appears. I am glad of that. But if I change the id , like this: <div class="form-group"> <input name="Data_inserimento_entry" type="date" class="form-control" id="date_to_turn_into_today" > </div> <script type="text/javascript" src={% static "js/get_today_date.js" %}></script> <script> get_today_date(date_to_turn_into_today) </script> It does not work anymore. Why? And even if I change the function name in both scripts, like: <script type="text/javascript" src={% static "js/get_today_date.js" %}></script> <script> get_today_date_ID(date_to_turn_into_today) </script> and function get_today_date_ID(id_data) { var now = new Date(); var day = ("0" + now.getDate()).slice(-2); var month = ("0" + (now.getMonth() + 1)).slice(-2); var today = now.getFullYear()+"-"+(month)+"-"+(day); document.getElementById(id_data).value = today; } It does not work anymore. Why? Is the syntax to call javascript correct? Am I forgetting to change the … -
Convert Raw SQL to Django ORM code , possibility
Is it possible to perform something like this with only Django ORM? with connection.cursor() as cursor: cursor.execute( """SELECT word FROM ts_stat( 'SELECT to_tsvector(''simple'', description) FROM api_product');""", #[source, ] ) words_in_product_model = frozenset( more_itertools.one(word) for word in cursor.fetchall() db-Postgres 11 Thanks -
How to retrieve metrics such as CPU loading, database connections, memory with django-prometheus
Is it possible to retrieve CPU info, total database connections and memory info with django-prometheus? After installing django-prometheus to my Django project prometheus/metrics I cannot understand is there any metrics to achieve my goals. Or it there another ways to do it? -
How to integrate mockaroo with django
I would like to integrate django with mockaroo since mockaroo provides rest api to download data ,I would like to use it with django project. Any help would be appreciated -
POST method not allowed in custom viewsets
if I am going to add products to cart I get error. POST method not allowed views.py class CartViewSet(viewsets.ModelViewSet): queryset = Cart.objects.all() serializer_class = CartSerializer @action(methods=['post', 'put'], detail=False) def add_to_cart(self, request, pk=None): cart = self.get_object() try: cart.user = self.request.user product = Product.objects.get(pk=request.data['product']) quantity = int(request.data['quantity']) except Exception as e: print(e) return Response({'status': 'fail'}) if product.inventory <= 0 or product.inventory - quantity < 0: print('There is no inventory in store') return Response({'status': 'fail'}) existing_cart_item = CartItem.objects.filter(cart=cart, product=product).first() if existing_cart_item: existing_cart_item.quantity += quantity existing_cart_item.save() else: new_cart_item = CartItem(cart=cart, product=product, quantity=quantity) new_cart_item.save() serializer = CartSerializer(cart) return Response(serializer.data, status=status.HTTP_201_CREATED) It works when i give the url like that carts/1/add_to_cart here I am giving my cart id but in my case it is wrong because when user is created cart is also created that's why user and cart ids are same. I do not nedd to give cart id in the url because I am putting token in Authorization section in Postman, from that it should detect which user is sending post request. It is shown above that I added cart.user=self.request.user with it still it is not working. How can I solve this issue? Any help would be appreciated) -
Django - force user password reset/expiration
I'm stuck at this issue now for a good few hours. I've implemented all the standard password change, reset, etc functionalities which are built in with django.contrib.auth.forms. The task I want to accomplish is to force users to regularly change their passwords. Which leads to the following issues: If I redirect them to the reset workflow it will change the password and I have not found a way to update my password_changed timestamp in my custom user model since the functionality is built into django. I could redirect them to the password change view (which also uses a builtin form), unfortunately if the user is not logged in (which would be counter productive in this case) the user attribute in the request is "None" Maybe I'm thinking too complicated, can someone give me a hint whats the easiest way to implement this?? -
django get data from api with ajax
I was trying to get some information from API using ajax. I was able to post data but I was unable to get all the data from the server. I am new in the Django environment, though i have tried some references. I was wanted to get the data from the server using the API that I provide and show those data by using ajax get call. References that I have followed: 1.Django Ajax Jquery Call 2.https://simpleisbetterthancomplex.com/tutorial/2016/11/15/how-to-implement-a-crud-using-ajax-and-json.html 3.https://www.sourcecodester.com/tutorials/python/11762/python-django-simple-crud-ajax.html My code for get call: $.ajax({ type: "GET", url: "/save_composition", dataType: "json", success: function(data) { alert(data) }, error: function(xhr, textStatus) { alert("error.."); }}); Url section : path('restore_composition/', views.restore_composition, name='restore_composition') Views.py: def restore_composition(request): data = SaveComposition.objects.all() return render(request, 'index.html', context={'data': data}) -
Meaning of some errors while hosting django application on Cloud Foundry
While trying to host my Django application on Cloud foundry using Gunicorn, my application will be hosted correctly on the URL, but when I see the logs by doing cf logs --recent I see some errors: 2019-10-18T17:06:36.85+0530 [APP/PROC/WEB/0] ERR [2019-10-18 11:36:36 +0000] [9] [INFO] Starting gunicorn 19.9.0 2019-10-18T17:06:36.86+0530 [APP/PROC/WEB/0] ERR [2019-10-18 11:36:36 +0000] [9] [INFO] Listening at: http://0.0.0.0:8080 (9) 2019-10-18T17:06:36.86+0530 [APP/PROC/WEB/0] ERR [2019-10-18 11:36:36 +0000] [9] [INFO] Using worker: sync 2019-10-18T17:06:36.86+0530 [APP/PROC/WEB/0] ERR [2019-10-18 11:36:36 +0000] [68] [INFO] Booting worker with pid: 68 I want to know what are these errors. And, after these errors also the application is hosted and is up. -
How to implement protected file download with requests and authentication in django
I have a django app where I can upload files. I show my files in an API. Like so: class FileCollection(models.Model): name = models.CharField(max_length=120, null=True, blank=True) store_file = models.FileField(upload_to=upload_file, null=True, blank=True) creation_date = models.DateTimeField(null=True, blank=True) class FileDownloadAPIListView(ListAPIView): """Lists all files. """ queryset = FileCollection.objects.all() serializer_class = FileCollectionSerializer Later I will implement different queries to get specific files. I'd like to download these files from a script using python without the need to open up a browser or anything like that. I want to make an authenticated API call with requests that gets my file and then saves it to the local computer. The problem is that my files need to be private and only authenticated users should be able to download it. For my other APIs I am using JWT token authentication. My question now is: How do I implement this? Do I a) Save my files in S3 and make an API call to that URL somehow authenticating me with my AWS credentials? b) Save my files somewhere in my PostgrSQL database and get everything from there with an authenticated API call using JWT. c) third option I didn't consider Also if I use a, b or c how … -
"ModuleNotFoundError: No module named 'django'" when trying to deploy Django server on Azure
After I tried to deploy my Django website on Azure, I got an error saying: ModuleNotFoundError: No module named 'django' I added a requirements.txt in the root directory of my Django project, am I missing anything else? I've tried to install Django from Kudu BASH but it gets stuck on "Cleaning Up". Here is the full error: https://pastebin.com/z5xxqM08 I built the site using Django-2.2 and Python 3.6.8. -
What are the skills and steps required to do an interactive info chart like this?
As a beginner in python and with an interest in data visualisation, I am intrigued by this https://opportunityatlas.org It inspires me to use it as a guide to break down what to learn and skills to acquire to learn to do something similar. I wonder is the map done using matplotlib? or is it HTML/CSS? Is it Django or Flask for the interactive web interface? My knowledge at the moment is too limited to know what's out there or any terms to search on. If anyone knows what are the steps and skills to acquire for developing an application like this, can you share a general guideline? Or is there any tutorial out there? Thanks. -
How to set on_delete=models.CASCADE default in python 3?
Currently I am working to convert my python2 Django web-project into python 3. My project contains lots of models.py files so I have to add manually on_delete=models.CASCADE in all files where I have set default it in python 2. Now there are around more than 2000 instances where I need to do same practice. Is there are any hacks or possible solution available so that I can set on_delete=models.CASCADE in my all models instantly. -
Debugging Javascript in a Python Django project
I have a Python/Django project and am currently trying to find a way to debug the Javascript components on the site using VSCode. I've done some research and the only method I can find is to use the paid version of PyCharm. Does anybody know how to configure VSCode to do this? -
alternative to wkhtmltopdf to render pdf with javascript charts and bootstrap classes
I have a web application and I use the tool wkhtmltopdf to perform pdf exports. I am using wkhtmltopdf version 0.12.4 with unpatched QT (minimal version). I want to add a footer to the pdf pages and I saw that the wkhtmltopdf version with patched QT support this operation with the flag --footer-html. Unfortunately I noticed that the css and js engine under this version create some problem in rendering my html pages: First of all there are problem with the grid system in Bootstrap v > 4.1 Then also the javascript chart in my page are no more rendered in the pdf with this version of wkhtmltopdf So, is there an alternative to wkhtmltopdf that allow me to export to pdf my web pages ? My project is written in django / javascript so I would prefer a python of javascript tool. I also tried pdfkit but I discart it because I saw it is based on wkhtmltopdf , and django-weasyprint but I discarted because it does not support javascript (so my charts are not rendered). Finally the tool should allow me to connect to the web page passing cookies or similar, because login is required to access the … -
How to integrate SaaS result which needs to create multiple URLs at the website end?
Assume there is a SaaS product where user can create multiple pages and content at the dashboard. Now we wish to make a plugin system where we can let the website owner just plug it and display all the content. Now we are facing problem where we don't have an effective way to automatically create the different URL as required by the backend content. What is the best way to do it? Is there any workable example of this? -
Django: int() argument must be a string, a bytes-like object or a number, not 'Post'
I am getting this error for a long time and I tried to solve with some forums but I don't find the gap. Here is my Models.py: class Post(models.Model): def show_article(request, id_post): article= Post.objects.get(id=id_post) if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): nick = form.cleaned_data['nick'] message= form.cleaned_data['message'] email = form.cleaned_data['email'] rating = form.cleaned_data['rating'] to = article #comentario = Comment(nick=nick, email=email, message=message, rating=rating, to=to) comentario = Comment() comentario.nick=nick comentario.email=email comentario.message=message comentario.rating=rating comentario.to_id=to comentario.save() send_mail( "Thanks for your comment %s" % nick, "Here is a copy of your message: \n %s" % message, 'noreply.ibai@gmail.com', [email], fail_silently=False) return redirect('/news/%i' %id_post) else: form = CommentForm() context = {'articulo': article, 'form':form} return render(request, "cnn/articulo.html", context) And: class Comment(models.Model): nick= forms.CharField(max_length=10) email= forms.EmailField(max_length=30) message= forms.CharField(max_length=600) rating= forms.ChoiceField(choices=LIKE_CHOICES) to_id= models.ForeignKey(Post, on_delete=models.CASCADE) class CommentForm(forms.Form): nick= forms.CharField(max_length=10) email= forms.EmailField(max_length=30) message= forms.CharField(max_length=600) rating= forms.ChoiceField(choices=LIKE_CHOICES) The problem came when I do 'migrate', because with de makemigrations the error dont occured. This is the log from console: (env2) C:\Users\ibaig_vi6j6bo\AppData\Local\Programs\Python\Python37-32\.projects\pruebasDjango>python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, polls, sessions Running migrations: Applying polls.0013_comment_to...Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\ibaig_vi6j6bo\AppData\Local\Programs\Python\Python37-32\.virtualenvs\env2\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() … -
Djnago channels security
I'm studying django channels and there's this problem: let's say I have a routing channel: websocket_urlpatterns = [ re_path(r'^ws/chat/(?P<id>[^/]+)/$', ChatConsumer), ] It turns out that anyone who knows the channel number can listen to messages that go to this address. Maybe you can send data (for example, a token) sometime during the socket connection? Thank you. -
Best way to save data to a Django project from serverless functions
I'm currently trying to migrate some of the regular periodic tasks we have running from our main app server (Django) to serverless functions. More or less all these tasks work the same way: Query some data from the Postgres DB (Using the Django ORM) Manipulate the data Save the data (Also using the Django ORM) What would be the best way to replicate saving the data, I've got a few options I've thought about: Bundle the Django project with the serverless function and just use the Django ORM Direct connection to the Postgres DB Perhaps create a POST API endpoint on the main server that can be used to send the data from the function to the main app server? Would love to know what everyone thinks or other ideas you think are better? -
If condition for having checkbox checked only working the first time in Flask?
I have a table with products and a checkbox which tells if the user likes the products or not which is the products.like = {1,0} variable. I have a hidden button and a checkbox button such that both 1 and 0 state of the checkbox will be posted to the application. {% for product in products %} ... <td>{{product.like}}<input id = "h" type="hidden" name="checkbox:{{product.index}}" value={{product.like}}><input type="checkbox" onclick="this.previousSibling.value=1-this.previousSibling.value" {% if product.like == 1 %} checked {% else %} {% endif %}></td> From the application I then update the product.like if the user has clicked the checkbox. ¨ app.py @app.route('/', methods = ['GET', 'POST']) def index(): name = None checkbox_count = 0 if request.method == 'POST': for key in request.form: if key == 'search': name = request.form['search'] if name is not None or name != "": query_product = Products.query.filter(Products.productname==name).first() if (query_product is not None) and (query_product not in product): product.append(product) if str(key).find('checkbox') != -1: #Check if key is a checkbox value. company[checkbox_count].like = request.form[key] #Update the like variable checkbox_count = checkbox_count+1 return render_template('index.html', products = product) The firs time I load the table, the correct checkboxes (the ones where product.like == 1) are checked in, but when I press the "update" button, … -
Django media file not found
Media file is not getting. urls.py added the below codes. from django.conf.urls.static import static from django.conf import settings urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) settings.py configured like below. STATIC_URL = '/static/' STATICFILES_ROOT = os.path.join(BASE_DIR,'static') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR,'media') profile.html these are html code. {% extends 'base.html' %} {% block main %} {{object.email}} {{request.user}} <img src="{{object.profileimage.image.url}}"> {% endblock %} Error code at console Not Found: /media/profile/1/function_uuid4_at_0x7fbf37ce42f0.jpeg [18/Oct/2019 10:01:45] "GET /media/profile/1/function_uuid4_at_0x7fbf37ce42f0.jpeg HTTP/1.1" 404 3421 -
Installing webpack_loader (webpack-template-loader) gives attribute error on assignment_tag
I'm trying to add webpack-template-loader to my project (djang=2.2.1, django-webpack-loader===0.2.4, webpack-bundle-tracker=^0.4.3,webpack=^4.41.2). To the best of my ability, I've followed the instructions here. My settings.py looks like this: INSTALLED_APPS = [ ... 'webpack_loader', ] # webpack loader BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'assets'), ) WEBPACK_LOADER = { 'DEFAULT': { 'CACHE': False, 'BUNDLE_DIR_NAME': 'assets/', 'POLL_INTERVAL': 0.1, 'TIMEOUT': None, 'IGNORE': [r'.+\.hot-update.js', r'.+\.map'] } } in my package.json I have the following: { ... "scripts": { "build": "webpack --config ./webpack/prod.config.js", "build-dev": "webpack --config ./webpack/dev.config.js --display-error-details" }, "dependencies": { "webpack": "^4.41.2", "webpack-bundle-tracker": "^0.4.3", "webpack-cli": "^3.3.9" } } and running npm run build-dev correctly builds my bundle without error. On adding 'webpack_loader' to INSTALLED_APPS my server stops turning and i get the error: Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/django/template/utils.py", line 66, in __getitem__ return self._engines[alias] KeyError: 'django' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/lib/python3.6/threading.py", line 916, in _bootstrap_inner self.run() File "/usr/local/lib/python3.6/threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "/usr/local/lib/python3.6/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 390, in check include_deployment_checks=include_deployment_checks, File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 377, in _run_checks return checks.run_checks(**kwargs) File "/usr/local/lib/python3.6/site-packages/django/core/checks/registry.py", line …