Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django csv output with react
I am working on a task that needs to write to csv and download in the frontend. In views I have done: ...omitted details data = data.values(*values_fields) response = HttpResponse(content_type='text/csv') writer = csv.DictWriter(response, fieldnames=values_fields) writer.writeheader() writer.writerows(data) return response And, in the frontend: let a = document.createElement("a"); document.body.appendChild(a); a.style = "display: none"; const blob = new Blob(res, {type: "text/csv"}); const url = window.URL.createObjectURL(blob); a.href = url; a.download = 'data.csv'; a.click(); window.URL.revokeObjectURL(url); a.remove() First of all, when I inspect res, I have only seen arrays of integers instead of dictionaries. How can I download my data? -
Where to put extra logic in django web API, in the view, or in the serializer?
I have a DRF view which extends CreateModelMixin and GenericViewSet. In the body of the post request, I want to accept an extra field, which does not belong to the related model. Then, I want to pop that extra field, use it for other purposes. I do not want to put that extra field back to the http response because it is a big and complex object. To explain it better here is a sample json input and the response that I want to return to the user: Request: # request { "name": "Why Nations Fail", "extra_field": { "my_keys": ["I'm", "a", "very", "big", "JSON-array", "object.", "..."] } } Response: # response { "id": 120 "name": "Why Nations Fail" } My problem is, I can't decide where to do this pop this extra_field; in the view or in the serializer (which extends ModelSerializer). Currently, I managed to do that by extending the create method handler of my view. But according the books and tutorials I've read: We should keep our views thin and our serializers thick. Keeping this in mind, I have tried to pop the field in the serializer but I couldn't manage to do that, I think because I'm … -
Cant use JsonResponse in Django
I have a bunch of values which I would like to send from views.py function to my template in Django. I saw some topics that the best way is by json format. So I did so. But because my values are not ascii I'm using a upgraded version which worked in normal Http response but don't work in JSON response. HERE is my code base = {weather_main_key : weather_main_values, wind_speed_key : wind_speed_value + "m", wind_deg_key : wind_deg_value, base_temp_key : base_temp_value + " ℃", base_press_key : base_press_value + " mbar", base_hum_key : base_hum_value + " % " } base = json.dumps(base, ensure_ascii=False).encode('utf8') return JsonResponse(json.dumps(base)) So I had an error msg In order to allow non-dict objects to be serialized set the safe parameter to False. So I did as it told me JsonResponse(json.dumps(base, safe=False, ensure_ascii=False).encode('utf8')) And now the error is __init__() got an unexpected keyword argument 'safe' And I can't move... -
Django - objects.all() shows nothing
I'm trying to get a list of objects in Django from a model. I just want to get the list of 'dht node' from the request user, but it shows nothing in the html file (as if the list was empty). The user that I'm using has 2 'dht nodes' and they're shown in the django admin. I don't know what is wrong, because if I use the instruction "member.dht.create(...)" in the views function and a create a new 'dht node' like this, this is shown. Only 'dht nodes' that I enter by form do not show. Can be the form? Thanks a lot, Here's my code: Models.py class Node(models.Model): name = models.CharField(primary_key=True, null=False, max_length= 50) description= models.CharField(default=None, null=False, max_length= 250) topic=models.CharField(default=None, null=False, max_length= 50, unique=True) def __unicode__(self): return self.name class dht(Node): temp = models.IntegerField(default=None, null=True) hum = models.IntegerField(default=None, null=True) class UserProfile(User): uid = models.CharField(default=None, null=False, max_length= 250) dht = models.ManyToManyField(dht, blank=True) def __unicode__(self): return self.user.username Views.py -dht list- @login_required(login_url = '/web/login') def listDhtSensor(request): member = request.user.userprofile list = member.dht.all() return render(request, 'web/listDhtSensor.html', {'list':list}) Html -listDhtSensor.html- {% block content %} {% for dht in list %} {{ dht.name }} {{ dht.topic }} {% endfor %} {% endblock %} Forms.py class … -
Python library can be found in PyPi but can't be installed by 'pip install'
I got django project code and tried to install all the requirements by 'pip install -r requiremets.txt' but somehow it doesn't work. occurred error is below Could not find a version that satisfies the requirement mkl-fft==1.0.9 (from -r requirements.txt (line 14)) (from versions: 1.0.0.17, 1.0.2, 1.0.6) No matching distribution found for mkl-fft==1.0.9 (from -r requirements.txt (line 14)) I tried to upgrade pip but it didnt work. -
How to show login form error in login page?
I'm trying to create a login page. I have used the default auth_view templates. I want to print the username and password field error in my login page. But cannot show them. I have tried using {{ form.username.errors }} but it is not working. But when is say {{ form.error }} it shows like below: __all__ Please enter a correct username and password. Note that both fields may be case-sensitive. urls.py path('login/', auth_views.LoginView.as_view(template_name='profiles/login.html'), name="login"), form template <div class="login-clean"> <form method="post"> <h2 class="sr-only">Login Form</h2> <div class="illustration"><i class="icon ion-code" style="color: rgb(71,151,244);"></i></div> {% csrf_token %} {{form.errors}} <div class="form-group"><input class="form-control" id="{{ form.username.id_for_label }}" type="text" name="{{ form.username.html_name }}" placeholder="username"></div> <div class="form-group"><input class="form-control" id="{{ form.password.id_for_label }}" type="password" name="{{ form.password.html_name }}" placeholder="username"></div> <div class="form-group"><button class="btn btn-primary btn-block" type="submit" style="background-color: rgb(71,151,244);">Log In</button></div><a class="forgot" href="#">Forgot your email or password?</a> </form> I want to see error results also If I want to style it, How to do it? -
Django with Apache and mod_wsgi: Timeout error
I'm trying to deploy Django application on a CentOS 7 server with Apache and mod_wsgi. The application is using plotly library to create graphs and plotly is using orca application to export created graph to image. I tested the application using the integrated django web server - everything works perfectly. So I set up Apache and mod_wsgi according official documentation. When I connect to Apache the application works, but it is not possible to export graphs. Browser ends up with Gateway Timeout Error. I inserted logger messages to the code which creates and exports graphs. The code runs until this line: static_image_bytes = plotly.io.to_image(figure, format='png', width=800, height=450) This line should run local Orca application and translate figure object to PNG image bytes. Orca requires X11 display server and CentOS is installed without GUI. I'm using Xvfb to emulate X11 (according to Orca's github page). Orca application is an AppImage downloaded from github. /bin/orca #!/bin/bash echo "`date` - ORCA STARTING with $@" >> /tmp/orca.log xvfb-run /usr/u/s/orca-1.2.1-x86_64.AppImage "$@" echo "`date` - ORCA FINISHED" >> /tmp/orca.log Also, I have tried to link /bin/orca directly to AppImage using: ln -s /usr/u/s/orca-1.2.1-x86_64.AppImage /bin/orca and adding this line to my code: plotly.io.orca.config.use_xvfb = True Apache error_log: … -
How do i get solve value error while using migrate command in django
I am working on exam-app using django frmaework and my make migration command is working properly but migrate command is giving error I have used Django frmawork but migration command givig error (ValueError: invalid literal for int() with base 10: 'Super Admin') this is my models.py file: `import uuid from django.contrib.auth.models import AbstractBaseUser, BaseUserManager from django.db import models class CustomUserManager(BaseUserManager): def create_user(self, email, password, **kwargs): if not email or not password: raise ValueError('User must have a username and password') user = self.model( email=CustomUserManager.normalize_email(email), **kwargs ) user.set_password(password) user.save() return user def create_superuser(self, email, password, **kwargs): user = self.create_user(email, password, **kwargs) user.is_admin = True user.is_staff = True user.save() return user class User(AbstractBaseUser): SUPER_ADMIN = 1 STUDENT = 2 TEACHER = 3 ROLE_CHOICES = ( (STUDENT, 'Student'), (SUPER_ADMIN, 'Super Admin'), (TEACHER , 'Teacher'), ) first_name = models.CharField(max_length=255, null=False) last_name = models.CharField(max_length=255, null=False) email = models.EmailField(null=False, unique=True) is_active = models.BooleanField(default=True) created_on = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now=True) is_staff = models.BooleanField(default=False) # Add custom fields here api_token = models.UUIDField(default=uuid.uuid4, editable=False) token_created_date = models.DateTimeField(auto_now_add=True) role = models.SmallIntegerField(choices = ROLE_CHOICES, null = True) objects = CustomUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name'] def get_full_name(self): return self.first_name + " " + self.last_name def get_short_name(self): return self.first_name def has_perm(self, … -
Trigger Django Signal from Different Database other than default db
I have different database other than default. @receiver(post_save, sender=Customer) def customer_post_save_task(sender, instance, created, **kwargs): print("hmm", created) But This only triggers when Customer is created from default db If Customer is created from another db it does not get invoked. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }, 'mydb': { 'ENGINE': 'django.contrib.gis.db.backends.mysql', 'NAME': 'Halanx', 'USER': 'root', 'PASSWORD': 'test', 'HOST': 'localhost', 'PORT': '3306', } When customer is created in mydb signal doesnot trigger. What can I do? -
How to capture middleware exception from other middleware in Django
I coding backend system with Django now, and I want control all exception from Django, so I create one middleware which name is CustomExceptoinMiddleware to control exception. But sometimes other middleware also raise exception, I hope CustomExceptoinMiddleware can capture it too, but I don't know how to do it. Can somebody help me? Thanks in advance! Python version: 3.7 Django version: 2.2.3 Setting.py MIDDLEWARE = [ ... "api.core.middleware.CustomExceptoinMiddleware ", "api.core.middleware.RaiseExcceptionMiddleware", ... ] # middleware.py class CustomExceptoinMiddleware(MiddlewareMixin): def process_exception(self, request, exception): print(f"Capture exception: {type(exception)}") class RaiseExcceptionMiddleware(MiddlewareMixin): def process_request(self, request): raise KeyError() -
Which is good for static and media when building a web server that can download files?
I want to build a web server that can only be downloaded to users by uploading large files. Where should I store my data files, static or media? Is it going to be good? (Size is 1 to 10GB compressed file.) Let me know if you have a better solution. -
Execute code in background after render page in Django
I have a script with twilio: from twilio.rest import Client def wa(testo): client = Client() # this is the Twilio sandbox testing number from_whatsapp_number='whatsapp:+14155238886' to_whatsapp_number='whatsapp:+39xxxxxxxxxx' ts = 'Anomalia Rapportino ' + str(testo) client.messages.create(body=ts, from_=from_whatsapp_number, to=to_whatsapp_number) I imported this script in view and I have this def: def grazieeprint(request, pk): intermedio = get_object_or_404(IntermProd, pk=pk) datilavoro = WhoWork.objects.get(pk=intermedio.work_id) try: return render(request, 'FBIsystem/thanksandprint.html', {'pkpreso': pk}) finally: try: appo = datilavoro.pezziorastima * 2 if datilavoro.pezziora >= appo: testo = datilavoro.pk subprocess.Popen([wa(testo)], shell=True) except: pass I need to run 'wa(testo)' after django load the page because all the process of sending message take approx 15/20 sec. I try whit 'try and finally' and whit 'subbrocess.Popen' but it send always the message before render the page. Please help TY -
ValueError: operands could not be broadcast together with shapes (256,) (128,)
I am making a Django Application using OpenCV and Dlib Library. I just wanted to implement face recognition feature using FILE UPLOAD. To store Image Hash at the backend I am using MongoDB. And hence I am using Djongo library to implement the same. Now here's the model which adds faces and it's hash to the database. Models.py class FaceDetails(models.Model): """ Model To Submit Face Details onto DB """ id_of_the_person = models.CharField(max_length=255, primary_key=True, default=uuid.uuid4, editable=False) name_of_the_person = models.CharField(max_length=255, blank=True) img_hash = models.CharField(max_length=4000, blank=True, null=True, editable=True) remarks = models.TextField(help_text='Remarks', blank=True, null=True) image_of_the_person = models.ImageField(upload_to='uploads/') created_at = models.DateTimeField(auto_now=True) def __str__(self): return "{}".format(self.name_of_the_person) @property def get_absolute_image_url(self): return '%s' % (self.image_of_the_person) @receiver(signals.post_save, sender=FaceAddition, dispatch_uid="update_img_hash") def face_addition_completed(sender, instance, **kwargs): img = cv2.imread(instance.get_absolute_image_url) bbs = dlib_detector(img) for k, bb in enumerate(bbs): shape = sp(img, bb) curr_rep = list(facerec.compute_face_descriptor(img, shape)) if kwargs.get('created', True): fa_object = FaceAddition.objects.get(id_of_the_person=instance.id_of_the_person) fa_object.img_hash = curr_rep fa_object.save() Here's my views.py file which handles image upload against which we search the database. I have done it very crudely though. Views.py def comparison_with_db(curr_rep): id_list = [] img_h_array = [] distance = 0.0 qs_fa = FaceDetails.objects.all() for obj in qs_fa: to_str_rp = obj.img_hash.replace( '[', '').replace(']', '').replace(",", "").replace("'", "").split() # So that it can be converted to list … -
How to pass a list instead of dictionary in python-django to html page
I want to display the list "response_body" to my html page "home.html" For that I retrieved id attribute from response_body and the last id which was stored in "id" variable is printed to my html file. I want to retrieve all the id's and print it to the html page I know this will be done through loop but how? I am new to django and python any help will be greatly appreciated. I have tried printing the last id before the loop ended and I was successful with it but now I want to print all the id'd in the loop. i tried passing response_body to html instead of context but it gives me an error as response_body is a list type and it asked me to pass a dictionary variable like context which works fine. how can I print all the id's in the reponse_body list home.html <p>results</p> <p>{{id}}</p> views.py as this is a fairly long code i am posting just the code which maybe useful. response_body = json.loads(response.read().decode('utf-8')) for j in response_body: print(j['id']) id = j['id'] context = { 'id': id, } return render(request, 'home.html', context) -
How to add a reset password button in django-administration
How to add a reset password button in django-administration. And also Reset password button act like Email verificationI want like this image -
Adding XSS to OPTIONS Call in Django
I wanted to add x-xss-protection to all my requests in my Django application. So I added secure_browser_xss_filter = True. All my requests are now safe. But when I look at the options, I am still not able to see "x-xss-protection: 1; mode=block" How can I add X-Xss to my OPTIONS call also? -
Django 2.3: Struggling to have form send email with an attachment. Not sure how files should be treated/ handled using FormView
OK so I am attempting to create a form on my website that will take input from a user. The fields include first_name, last_name, email, and then a file upload form that should take their resume. Unfortunately I cannot get this program to send an email that includes any document I attach. I am using FormView with django in order to handle the incoming information which seemed straightforward until it came time to handle a file. What i've seen from various other answers is that you'd use something like request.FILES['resume'] but that seems to be if you aren't using formview. I've been struggling with this for over 10 hours and would really love to have someone point me in the right direction. forms.py: from django.core.mail import EmailMessage from templated_email import get_templated_mail from django.conf import settings class UploadResumeForm(forms.Form): first_name = forms.CharField( widget=forms.TextInput( attrs={ 'type':'text', 'class': 'form-control', 'placeholder': 'First Name', }), required=True) last_name = forms.CharField( widget=forms.TextInput( attrs={ 'type':'text', 'class': 'form-control', 'placeholder': 'Last Name', }), required=True) email = forms.EmailField(widget=forms.TextInput( attrs={ 'type':'text', 'class': 'form-control', 'placeholder': 'Email', }), required=True) resume = forms.FileField(widget=forms.FileInput( attrs={ 'name': 'resume', 'placeholder': 'Resume', 'class':'file-path validate', }), required=False) class Meta: title = 'Resume Upload' def send_message(self, email, first_name, last_name, file): email_obj = … -
How do I import a PostgreSQL table into d3 for use?
I am currently using d3.csv to import a table for use in a graph, however, I instead want to use a table from my Postgres database. I have the database connected to Django however I am unsure what d3 function I can use to fetch a table from the database and use it instead of a csv file. d3.csv("[link]", function(data) { console.log(data); Console.log(data) returns a table that looks like this: IMG -
Avoid dyanmic content's translation in msgstr
I am using Django translations for ja and de using makemessage. There is a translation in that I don't want to translate dynamic content in de. I am using the following translations. msgid " and %(level3)s subgroups" msgstr "und aller Untergruppen von %(level3)s " But now I don't want to use dynamic content 'level3' in msgstr. I simply need need und aller Untergruppen von. so I changed it to msgid " and %(level3)s subgroups" msgstr "und aller Untergruppen von " but while doing compilemessages it's getting error CommandError: Execution of msgfmt failed: /Users/treeni/treeni_produts/sustain-online/so-web/locale/de/LC_MESSAGES/django.po:4409: a format specification for argument 'level3' doesn't exist in 'msgstr' msgfmt: found 1 fatal error -
Django API: Connect to different databases dynamically
I have a django app which asks user for the ip address, port, username, password and database of the server it wants to connect to. I want to create an API that connects to these databases dynamically, and execute a query like SHOW TABLES on it. I am unable to figure out how to do this. What I think is I will have to dynamically set settings. py and use it. Also the databases can be of any type amongst SQL, Mongo. The user also specifies the type of database. -
Get daily number of call API
I have django rest framwork support android, ios, web with some version different api and different version mobile app. Now i hope know how many time each api call in 1 day, 1 month....for optimize and remove unused api. My question is: how to know each api call how many time in 1 day? Have any library support it or any way do it. Thank you! -
Django query implementation of Wilson Score algorithm
I'm trying to determine the best way to implement the Wilson Score algorithm in a Django project. The project is a mashup of typical forum features and reddit's upvotes/downvotes/trending page. Each forum has threads, and users can upvote/downvote a thread. Should I score and sort my threads in a database query, and if so, how would I do that using Django's DB models? My current solution is to fetch the forum's threads, and then sort in python. wilson_score.py from datetime import datetime from math import log epoch = datetime(1970, 1, 1) def epoch_seconds(date): td = date.replace(tzinfo=None) - epoch return td.days * 86400 + td.seconds + (float(td.microseconds) / 1000000) def score(ups, downs): return ups - downs def hot(ups, downs, date): s = score(ups, downs) order = log(max(abs(s), 1), 10) sign = 1 if s > 0 else -1 if s < 0 else 0 seconds = epoch_seconds(date) - 1134028003 return round(sign * order + seconds / 45000, 7) models.py from . import wilson_score class ForumThread(models.Model): category = models.ForeignKey(ForumCategory, on_delete=models.CASCADE) up_votes = models.IntegerField(default=0) down_votes = models.IntegerField(default=0) @staticmethod def get_trending_threads(category): return sorted(ForumThread.objects.filter(category=category), key=lambda x: wilson_score.hot(x.up_votes, x.down_votes, x.date_created), reverse=True) views.py threads = ForumThread.get_trending_threads(category)[offset:offset + 20] -
Convert this html template into Django
I am currently learning django, and at the moment I want to convert this page https://colorlib.com/etc/lf/Login_v6/index.html into django. I have tried heaps of times, still can't make everything right. Let me show you my work structure below. My problem is about using css and js under static/vendor fold. Seems the way I used got a bit problem, I have also attached my code for invoking the css and js under vendor. Thanks for any help. MyFirstDjangoWeb --project --setting.py --urls.py --wsgi.py --init.py --project_app --template --myHtml.html --migration --0001_initial.py --init.py --__init_.py --admin.py --apps.py --models.py --test.py --urls.py --views.py --static --css --images --js --vendor manage.py '''html ''' -
Adding functionality to a button in HTML
I am creating a web-page for an online supermarket using Python and Django framework and for each of those products is an "Add to Cart" option.I want to make the code such that when the button is clicked it increases the quantity of that product by 1. This is the code for the the whole product Card :- <h5 class="card-title">{{ product.name }}</h5> <p class="card-text">{{ product.price }}</p> <a href="#" class="btn btn-primary">Add to Cart</a> -
NoReverseMatch pattern not found in django2
NoReverseMatch found for a url i have tried and {% url '/feedback/form/' %} i am using a feedback app. #feedback\urls.py from django.urls import path, include from .views import request_feedback urlpatterns = [ path('form/', request_feedback, name = 'get_feedback' ), ] #feedback\views.py def request_feedback(request): if request.method == 'POST': feedback_form = FeedBackForm(request.POST) if feedback_form.is_valid(): feedback_form.save() return redirect('') else: feedback_form = FeedBackForm() return render(request, 'feedback/feedbackform.html', {'feedback_form':feedback_form}) #webapp\urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('feedback/', include("feedback.urls")), path('user/',include("user.urls")), ] i am getting this error NoReverseMatch at /feedback/form/ Reverse for '' not found. '' is not a valid view function or pattern name i am using python 3.7 and django 2 i do mitigate this problem