Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to correctly add AJAX to DataTable?
i'm using a bootstrap data table and i'm passing the registers through ajax. However, for some reason since i started filling the table with the ajax function, the search box, the pagination and the column ordering stopped working. At first it does print the registers, but if i search for one, it adds a row at the beggining of the table saying "No registers found", like it's empty. Same thing happens when i try to switch how many registers it shows per page. (And it doesn't paginate at all) Here is my code: <script type="text/javascript"> $(document).ready(function() { $('#dom').DataTable({ ajax:{ url: '/restapi/enviarjson/', type: 'get', success: function (json){ $("#dom > tbody").empty() var table = []; $.each(json, function(key, val){ table.push('<tr>'); table.push('<td style="vertical-align: middle; text-align: center;">'+ '<input type="checkbox" id="onff2" name="onff2" value="'+val.pk+'">' + '</td>'); table.push('<td style="color:#A9A9A9; vertical-align: middle; text-align: center;">'+val.pk+'</td>'); table.push('<td style="color:#A9A9A9; vertical-align: middle; text-align: center;">'+val.fields.nombre_activo+'</td>'); table.push('<td style="color:#A9A9A9; vertical-align: middle; text-align: center;">'+val.fields.desc_act+'</td>'); table.push('<td style="color:#A9A9A9; vertical-align: middle; text-align: center;">'+val.fields.dat_cont_arch+'</td>'); table.push('<td style="color:#A9A9A9; vertical-align: middle; text-align: center;">'+val.fields.resp_dom+'</td>'); table.push('<td style="color:#A9A9A9; vertical-align: middle; text-align: center;">'+val.fields.estado+'</td>'); table.push('</tr>'); }); $("<tbody/>", {html: table.join("")}).appendTo("table"); } }, language: {searchPlaceholder: "Buscar", search: "", "paginate": { "first": "Primero", "last": "Ultimo", "next": "Siguiente", "previous": "Anterior" }, "zeroRecords": "Sin resultados encontrados", "infoEmpty": "", "emptyTable": "No hay información", "lengthMenu": "Mostrar … -
how to return 200OK before the function is completed
I write a bot for Vkontakte on Django(2.2.4), with the vk_api library Some of the functions are quite long (performed in 5-7 seconds). But Vkontakte requires the server to respond no longer than 3 seconds. If the response is delayed, the request is sent again, and the bot starts sending the same message many times after a while. (I Use The Callback Api) I will describe my problem briefly my function runs for more than 6 seconds the 200OK response must be sent in less than 3 seconds Is it possible to solve this problem without major changes in the code? # views.py @csrf_exempt def MainBotView(request): # i need something like return HttpResponse('ok') here ... my slow code ... return HttpResponse('ok') # but I don't need it at the end (I use pythonanywhere and Celery perhaps does not work there) Should I use threading? How? -
Passing User Data to Admin Actions in Django
I am attempting to write an admin action that accesses data from selected users. i.e. email. However, when I access Account instances, I have only been able to access the instance/data of the user that is currently logged in. For example, to access the emails of selected users, I have tried: #models.py class Account(AbstractBaseUser): email = models.EmailField(max_length=60, unique=True) #admin.py from account.models import Account for Account in queryset: author = request.Account.email #OR author = Account.objects.get(email=request.email) and both of these will fill "author" with the email address of the admin that is trying to pull the data. Does anyone know how I could call to the instances of selected accounts with an admin action? -
How to calculate django model fields
I have the following fields in my models: class Materiale(models.Model): quantity=models.DecimalField(max_digits=5, decimal_places=2, default=0) price=models.DecimalField( max_digits=5, decimal_places=2, default=0) VAT=models.DecimalField(max_digits=5, decimal_places=2, default=0) VAT_amount=models.DecimalField(max_digits=5, decimal_places=2, default=0) But the VAT_amount is the result of quantity*price*VAT. How can store in my database that value automatically??? It's important that the field (VAT_amount) is present in database. Thanks. -
Django Rest Framework Permissions List Issues in ModelViewSet
I am trying to check multiple permissions classes in the get_permissions method of a ModelViewSet but even though the has_object_permission returns false on all of the classes in the list I'm still able to perform the action. Here's my get_permissions method: def get_permissions(self): if self.action in ("retrieve", "list",): permission_classes = [AllowAny] elif self.action in ("update", "partial_update", "destroy",): permission_classes = [IsOwner | IsAdminUser] else: permission_classes = [IsAdminUser] return [permission() for permission in permission_classes] On an update IsOwner returns True for has_permission and False for has_object_permission but even a non-admin can make updates. Anyone know what I'm doing wrong here? -
WebSocket handshake failed.. Error in the browser console, with response code: 500
My django channels app is not working. Can this be a reason that my site is 'not secure'. Does sockets work only on HTTPS? If someone could help... -
How to add more features to user permission in django?
I am new to django. I want to edit default user auth_permissions. More precisely I want to add an integer field in addition to "label", "code" features to distinct permission types (like strong, moderate and etc.). So far I could not find anything like this. I tried to make custom permissions, but could not add them to the permission database. Anyone could help me? -
Drag drop save database django
I have a django project that teacher assign students courses by drag drop.I made html part but I couldnt figure out how to save db. Is there any framework or method ? screenshot from my project -
Hosting a django app on a personal wondows machine
I've developed a django web application which I now want to deploy so that everyone in my organization can start accessing the website. However, I do not have a dedicated server location to actually host it. I have been given a dedicated Windows machine to host the app on. Previously I've always used things like Heroku or AWS to deploy websites which make it really easy, so I really have no idea how to turn a desktop into a server hosting a web application. Does anyone have any suggestions on how to do this using free software? Thanks in advance. -
Django admin filtering based on user profile
I have the following models in django: class Manager(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) company = models.ForeignKey(Company, on_delete=models.CASCADE) class Admin(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) company = models.ForeignKey(Company, on_delete=models.CASCADE) In Djanog admin I would like to filter based on the company field of Manager OR Admin based on which is currently logged in. I have the followin code for this: def get_queryset(self, request): qs = super(EmployeeAdmin, self).get_queryset(request) if request.user.is_superuser: return qs if hasattr(request.user, 'manager'): return qs.filter(company=request.user.manager.company) elif hasattr(request.user, 'admin'): return qs.filter(company=request.user.admin.company) It works nice, but I don't really like the way I have to allways check with hasattr() function which one is logged in. Also this is an error prone way, if I add another role for eg: Employer besides Manager and Ddmin and I forget to handle Employer... Could you recommend a more neat solution for this? Thank you! -
Not returning html page for viewing - django
error message --> The view orders.views.charge didn't return an HttpResponse object. It returned None instead. any reason why my charge.html isn't working? views,py import time import stripe from django.conf import settings from django.shortcuts import render from django.urls import reverse def charge(request): if request.method == 'POST': charge = stripe.Charge.create( amount=500, currency='eur', description='A Django charge', source=request.POST['stripeToken'] ) template = "orders/charge.html" return render(request, template) charge.html {% extends "fuisce/base.html" %} {% block content %} <div class="container mt-5 text-center"> <h2 class="text-center">Thanks, you for your Orders</h2> <a href="/my-orders" class="btn btn-success">My Orders</a> </div> {% endblock %} urls.py from django.urls import path from . import views from orders import views as order_views from users import views as user_views urlpatterns = [ path('checkout/', order_views.checkout, name='checkout'), path('charge/', order_views.charge, name='charge'), path('orders/', order_views.orders, name='user_orders'), path('add_user_address/', user_views.add_user_address, name='add_user_address'), ] -
Can I have Interprocess Communication with Django Channels?
I am building an architecture where I have several Services that runs in parallel, one of them serves the client application, which communicates through Websockets, call it Frontend. I choose Django with Channels for its implementation. I have another service (implemented in Python too) that needs to communicate with the Frontend, I need to do it through network sockets using a simple custom protocol. How can I integrate those services that way? I took a look at the Cross-Process Communication docs but I did not figured out how to do it. Can I push messages to a channel from any Python process? -
Use @propert based attr as Model slug, django's views?
I am trying to use an attribute created using the @property decorator im my model as a slug field for django DetailsView, as follow: class Province(models.Model): name = models.CharField(max_length=30) code = models.CharField(max_length=10) @property def slug(self): return slugify(self.name) My url: path("map/<slug:slug>", MyView.as_view()) My view: class MapTemplateView(DetailView): template_name="myapp/map.html" context_object_name = "province" model = Province But when accessing page I get the following exception: Cannot resolve keyword 'slug' into field. Choices are: code, id, name -
Post request to external Rest Service using Django - use returned json to update model
I require some advice on the best way to implement the following details using Camunda Rest API and Django: 1) User is presented with a form - Selects the details and then does a POST request to camunda using 'http://localhost:8080/engine-rest/process-definition/key/Process_B_PerProject/start' the details sent in this POST request consist of 3 variables in a JSON RAW : in the form of : {"variables": {"UserID" : {"value" : "user.", "type": "String"}, "OrganisationID" : {"value" : "some value", "type": "String"} }, "businessKey" : "SomeBusinessKey" } from views.py from django.shortcuts import render from django.views.generic import TemplateView from .forms import StartProject import requests class StartProcessView(TemplateView): template_name = 'startdeliveryphase.html' def get(self, request): form = StartProject() return render(request, self.template_name, {'form':form}) def post(self,request): form = StartProject() url = "http://localhost:8080/engine-rest/process-definition/key/Process_B_PerProject/start" payload = "{\"variables\":\r\n {\"Username\" : {\"value\" : \"[form.Username]\", \"type\": \"String\"},\r\n \"OrganisationInitiating\" : {\"value\" : \"[form.OrganisationInitiator]\", \"type\": \"String\"}},\r\n \"businessKey\" : {form.businessKey}\r\n }" headers = { 'Content-Type': 'application/json' } response = requests.request("POST", url, headers=headers, data = payload) return render(response, self.template_name, {'form':form}) The response is returned as a 200 along with a JSON payload in the form: { "links": [ { "method": "GET", "href": "http://localhost:8080/engine-rest/process-instance/fbff8359-84cd-11ea-a2e1-00155d891509", "rel": "self" } ], "id": "fbff8359-84cd-11ea-a2e1-00155d891509", "definitionId": "Process_B_PerProject:1:71921815-737c-11ea-91a6-00155d891509", "businessKey": "SomeBusinessKey", "caseInstanceId": null, "ended": false, "suspended": false, "tenantId": … -
django model and templates
I'm new to django, I'm trying to make a display for an e-commerce site enter image description here I would like to display only the sub-categories corresponding to the category -
Error accessing AWS elasticache redis in cluster mode) + TLS Enabled from django service
I'm trying to connect AWS elasticache(redis in cluster mode) with TLS enabled, the library versions and django cache settings as below ====Dependencies====== redis==3.0.0 redis-py-cluster==2.0.0 django-redis==4.11.0 ======settings======= CACHES = { 'default': { 'BACKEND': 'django_redis.cache.RedisCache', 'LOCATION': "redis://xxxxxxx.mc-redis-cache-v2.zzzzz.usw2.cache.amazonaws.com:6379/0", 'OPTIONS': { 'PASSWORD': '<password>', 'REDIS_CLIENT_CLASS': 'rediscluster.RedisCluster', 'CONNECTION_POOL_CLASS': 'rediscluster.connection.ClusterConnectionPool', 'CONNECTION_POOL_KWARGS': { 'skip_full_coverage_check': True, "ssl_cert_reqs": False, "ssl": True } } } } It doesn't seem to be a problem with client-class(provided by redis-py-cluster) since I'm able to access from rediscluster import RedisCluster startup_nodes = [{"host": "redis://xxxxxxx.mc-redis-cache-v2.zzzzz.usw2.cache.amazonaws.com", "port": "6379"}] rc = RedisCluster(startup_nodes=startup_nodes, ssl=True, ssl_cert_reqs=False, decode_responses=True, skip_full_coverage_check=True, password='<password>') rc.set("foo", "bar") rc.get('foo') 'bar' but I'm seeing this error when django service is trying to access the cache, is there any configuration detail that I might be missing? File "/usr/lib/python3.6/site-packages/django_redis/cache.py", line 32, in _decorator return method(self, *args, **kwargs) File "/usr/lib/python3.6/site-packages/django_redis/cache.py", line 81, in get client=client) File "/usr/lib/python3.6/site-packages/django_redis/client/default.py", line 194, in get client = self.get_client(write=False) File "/usr/lib/python3.6/site-packages/django_redis/client/default.py", line 90, in get_client self._clients[index] = self.connect(index) File "/usr/lib/python3.6/site-packages/django_redis/client/default.py", line 103, in connect return self.connection_factory.connect(self._server[index]) File "/usr/lib/python3.6/site-packages/django_redis/pool.py", line 64, in connect connection = self.get_connection(params) File "/usr/lib/python3.6/site-packages/django_redis/pool.py", line 75, in get_connection pool = self.get_or_create_connection_pool(params) File "/usr/lib/python3.6/site-packages/django_redis/pool.py", line 94, in get_or_create_connection_pool self._pools[key] = self.get_connection_pool(params) File "/usr/lib/python3.6/site-packages/django_redis/pool.py", line 107, in get_connection_pool pool = self.pool_cls.from_url(**cp_params) File "/usr/lib/python3.6/site-packages/redis/connection.py", line 916, … -
How can I make chained multiple choice fields in Django with JQuery?
I want to make a chained multiple choice field. I have working code for chained dropdown boxes below. I want to be able to choose more than one option at each level and have the next level return all records for each of the selected values. How can I make this happen? (my code is not very DRY, so appreciate any notes on that as well, but that is secondary) models.py class Nace_Level_1(models.Model): code = models.CharField(max_length=1) name = models.CharField(max_length=200) short_name = models.CharField(max_length=100) notes = models.TextField() def __str__(self): return self.short_name class Nace_Level_2(models.Model): parent = models.ForeignKey(Nace_Level_1, on_delete=models.CASCADE) code = models.CharField(max_length=2) name = models.CharField(max_length=200) short_name = models.CharField(max_length=100) notes = models.TextField() def __str__(self): return self.short_name class Nace_Level_3(models.Model): parent = models.ForeignKey(Nace_Level_2, on_delete=models.CASCADE) code = models.CharField(max_length=4) name = models.CharField(max_length=200) short_name = models.CharField(max_length=100) notes = models.TextField() def __str__(self): return self.short_name class Nace_Level_4(models.Model): parent = models.ForeignKey(Nace_Level_3, on_delete=models.CASCADE) code = models.CharField(max_length=5) name = models.CharField(max_length=200) short_name = models.CharField(max_length=100) notes = models.TextField() def __str__(self): return self.short_name class Nace_Level_5(models.Model): parent = models.ForeignKey(Nace_Level_4, on_delete=models.CASCADE, blank=True, null=True) level_3 = models.ForeignKey(Nace_Level_3, on_delete=models.CASCADE, blank=True, null=True) level_2 = models.ForeignKey(Nace_Level_2, on_delete=models.CASCADE, blank=True, null=True) level_1 = models.ForeignKey(Nace_Level_1, on_delete=models.CASCADE, blank=True, null=True) code = models.CharField(max_length=6) name = models.CharField(max_length=200) short_name = models.CharField(max_length=100) notes = models.TextField() def __str__(self): return self.short_name forms.py class NaceForm(forms.ModelForm): … -
multivaluedictkeyerror post django
I have a views.py where i get a list of value from user checked checkbox now i want it to store in database views.py def ResultTest(request): var = request.POST.get('selectedTests') request.session['var'] = var def PostTest(request): if request.method == 'POST': test = UserTest() var = request.session['var'] test.TestSelected = request.POST['var'] i have 2 function in ResultTest function i am getting the user checked result and i want that result to get store in database from PostTest function as i have a form which get submitted along with the result of checked checkbox . Being more specific after user checked the checkbox page redirect to next form where user get to fill a form and there is the value present which is selected by the user in previous checkbox page so now with other form details i want to save the checked result. -
psycopg2 installing within docker
I am learning django,currently while installing psycopg2 with the following command docker-compose exec web pipenv install psycopg2 binary==2.8.3 I got this error and my python version within docker is Python 3.7.7 the error message I got is Warning: Python 3.6 was not found on your system… You can specify specific versions of Python with: $ pipenv --python path/to/python can someone help me to find out the solution or the command to specify the python version -
How to prevent Throttling issue with celery workers?
I want to build script to pull data from amazon api, interesting thing in amazon api that they have strict Throttling rules by different endpoints, e.g.: Maximum request: quota 30 requests Restore rate: One request every two seconds Hourly request quota: 1800 requests per hour So for one account we can do 30 requests at one time without throttling, but not more than 1800 per hour. Restore rate means - that after we did 30 requests at once we have to wait 60 seconds(2 seconds * 30 request) to make again 30 requests at once. First I wanted to implement that with celery, but in this case need to use global lockers, which seems isn't best solution, and hard to maintain. In nodejs worlds we can use something like https://www.npmjs.com/package/bottleneck. const limiter = new Bottleneck({ maxConcurrent: 1, minTime: 333 }); limiter.schedule(() => myFunction(arg1, arg2)) .then((result) => { /* handle result */ }); Any similar libs in python, or maybe just good suggestion how to implement that, with ability to monitor, and reschedule if fail. -
Why i am see server error 500 in my website when Debug = False in django
I am see Server Error 500 in my website [www.softdlr.com] after i make Debug = Flase in settings.py this problem appear when i do search in other language ( except English ) when i use contact form how to fix this error (My priorities is to fix the contact form that i using gmail ) forms.py # contact form class ContactForm(forms.Form): contact_name = forms.CharField(required=True,label='Your name ') contact_email = forms.EmailField(required=True,label='Your email ') title = forms.CharField(required=True,label='The Subject') content = forms.CharField(required=True,label='Full Deatils ',max_length=500,widget=forms.Textarea(attrs={"rows":5, "cols":30}) ) views.py from django.core.mail import send_mail from first_app import forms from django.shortcuts import render from .forms import ContactForm from django.core.mail import EmailMessage # Contact form view def contact(request): Contact_Form = ContactForm if request.method == 'POST': form = Contact_Form(data=request.POST) if form.is_valid(): contact_name = request.POST.get('contact_name') contact_email = request.POST.get('contact_email') contact_content = request.POST.get('content') title = request.POST.get('title') template = loader.get_template('html_file/contact_form.txt') context = { 'contact_name' : contact_name, 'contact_email' : contact_email, 'title' : title, 'contact_content' : contact_content, } content = template.render(context) email = EmailMessage( "New contact form email", content, "Creative web" + '', ['myemail@gmail.com'], headers = { 'Reply To': contact_email } ) email.send() return redirect('Success') return render(request, 'html_file/contact_us.html', {'form':Contact_Form }) settings.py # email message contact EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST= 'smtp.gmail.com' EMAIL_HOST_USER= 'myemail@gmail.com' EMAIL_HOST_PASSWORD= 'mypass' EMAIL_USE_TLS= True … -
I want to beat goggle search which framework should i use django or flask
I wanted to create a search engine better than google. I did some research and found that search engine uses machine learning and deep learning, python is best at it. So i have chosen python but now which framework to use django or flask -
I want to get data based on header menu from the same table
Here is my code: models.py class HeaderMenu(models.Model): header_menu = models.CharField(max_length=50, primary_key=True) def __str__(self): return self.header_menu class SubMenu(models.Model): header_menu = models.ForeignKey(HeaderMenu, on_delete=models.CASCADE) sub_menu = models.CharField(max_length=50, primary_key=True) def __str__(self): return self.sub_menu class Category(models.Model): sub_menu = models.ForeignKey(SubMenu, on_delete=models.CASCADE) category = models.CharField(max_length=150, primary_key=True) def __str__(self): return self.category class Links(models.Model): header_menu = models.ForeignKey(HeaderMenu, on_delete=models.SET_NULL, null=True) sub_menu = models.ForeignKey(SubMenu, on_delete=models.SET_NULL, null=True) category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True) link_name = models.CharField(max_length=255) link_url = models.URLField() hits = models.IntegerField() def __str__(self): return self.link_name The table in my database: table whole data My requirement: let say there are 5 links in link_url under sports category under Home tab I want to render all the link name under the home(header_menu) > sports(category) > links like > home> home Submenu > Sports > and all the links name not whole table Help me out to write the view for this problem Thanks :) -
KeyError at /recommend/ in combined_features
why I am getting this error in combined features why this appears and show why df or local variables assigned def recommendation(Movie): Movie = Movie.lower() try: df.head() cosine_sim.shape except: cosine_sim = recommender_sim() if Movie not in df['title'].unique(): return('Search for another Movies') else: indices = pd.Series(df.index, index=df['title']) # Get the index of the movie that matches the title idx = indices[title] # Get the pairwsie similarity scores of all movies with that movie sim_scores = list(enumerate(cosine_sim[idx])) # Sort the movies based on the similarity scores sim_scores = sorted(sim_scores, key=lambda x: x[1], reverse=True) # Get the scores of the 10 most similar movies sim_scores = sim_scores[1:11] sim_scores = [] for i in range(len(sim_scores)): movie_indices = sim_scores[i][0] sim_scores.append(df['title'][movie_indices]) return sim_scores def recommend(request): if request.method == 'GET': movie = request.GET['movie'] movies = recommendation(movie) movie = movie.upper() if type(movies) == type('string'): return HttpResponse('recommend.html', movie=movie, movies=movies, t='s') else: return HttpResponse('recommend.html', movie=movie, movies=movies, t='sim_scores') return render(request, 'recommend.html') -
How to convert geojson file into class model in django
I have geojson data in the URL. Here is the URL: https://publoccityhealthdata.s3.us-east-2.amazonaws.com/chi_boundries.geojson I need to generate model class for Django using ogrinspect from django.contrib.gis.db import models