Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django prefetch_related performance - to_attr not working on nested lookups
I have a relatively complex model structure in a django project (v2.1.4). Let's say: class Pizza(models.Model): pass class ToppingPlacedOnPizza(models.Model): # Breaks a many-to-many relationship between Pizza and Topping and stores specific data # like the position of the topping in the pizza pizza = models.ForeignKey(Pizza, related_name='placed_toppings') topping = models.ForeignKey(Topping) # position ... class Topping(models.Model): brand = models.ForeignKey(Brand) class Brand(models.Model): name = models.CharField(max_length=32) I need to retrieve all the names of the brands that make toppings for each pizza of a set of pizzas. Say: pizza1: brand1, brand2, brand3 pizza2: brand2, brand4 ... To do so, prefetch_related has been of great help in order to improve performance: pizzas.prefetch_related('placed_toppings__topping__brand') But when making a query for ~1000 pizzas it starts being really slow. According to this stackoverflow answer, using Prefetch class and to_attr could improve performance, but I couldn't make it work on my case. It's not clear in which object to_attr will write the new attribute because of the nested lookup. I made to_attr work on first level. When setting pizzas.prefetch_related(Prefetch('placed_toppings', to_attr('mytoppings'))), then pizzas[0].mytoppings exists. But when setting pizzas.prefetch_related(Prefetch('placed_toppings__topping__brand', to_attr('mybrands'))), none of the following exist: pizzas.mybrands pizzas[0].mybrands pizzas[0].placed_toppings.mybrands pizzas[0].placed_toppings.first().mybrands pizzas[0].placed_toppings.first().topping.mybrands Any ideas on how to improve performance or make to_attr work on … -
Django app crashes on deploying to Heroku - Error H10
I am trying to deploy my django app on heroku and it crashes with exit status 1 error code h10. I am deploying to heroku for the first time and cannot find a fix. It is a simple project so i was trying to deploy it on sqlite database only. My project name is portfolio, appname is mywebsite heroku logs 2020-06-05T12:58:10.098179+00:00 heroku[web.1]: State changed from starting to crashed 2020-06-05T12:58:15.673642+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=harnaman.herokuapp.com request_id=a553ec3b-75b5-46c6-bf04-a3a2cfd6829c fwd="106.204.196.204" dyno= connect= service= status=503 bytes= protocol=https 2020-06-05T12:58:16.236791+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=harnaman.herokuapp.com request_id=e0f1cc63-1163-45c1-855d-784e1a1536be fwd="106.204.196.204" dyno= connect= service= status=503 bytes= protocol=https 2020-06-05T13:13:36.052752+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=harnaman.herokuapp.com request_id=5c0b2b72-48aa-412d-b6b7-1560fb6c72cc fwd="106.204.196.204" dyno= connect= service= status=503 bytes= protocol=https 2020-06-05T13:13:37.136635+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=harnaman.herokuapp.com request_id=88373377-a732-490d-a420-8b2295739eb3 fwd="106.204.196.204" dyno= connect= service= status=503 bytes= protocol=https 2020-06-05T13:13:44.436995+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=harnaman.herokuapp.com request_id=8fed326e-1da8-44a3-a79d-52df93f307e6 fwd="106.204.196.204" dyno= connect= service= status=503 bytes= protocol=https 2020-06-05T13:13:45.262259+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=harnaman.herokuapp.com request_id=85a7b359-74ef-40ee-8c08-f89cab6a2349 fwd="106.204.196.204" dyno= connect= service= status=503 bytes= protocol=https 2020-06-05T13:18:29.000000+00:00 app[api]: Build started by user *******@gmail.com 2020-06-05T13:19:02.798192+00:00 app[api]: Deploy 0823f045 by user *******@gmail.com 2020-06-05T13:19:02.798192+00:00 app[api]: Release v17 created by user *******.com 2020-06-05T13:19:02.976994+00:00 heroku[web.1]: State changed from crashed to starting … -
Django View Causes Psycopg2 Cursor Does/Does Not Exist Error
I run a Django site which has a simple ModelForm type view that is generating cursor errors. In the past two days, this view was POSTed to a couple hundred times and about 8% of the time generated an error. I ONLY have this problem with this view, even though I have another which is very similar. That's the frustrating thing is I haven't figured out what's special about it. I just started seeing these errors after upgrading to Django 2.1/2, but I think they may have pre-existed, yet were not seen. Full stack trace here: https://gist.github.com/jplehmann/ad8849572e569991bc26da87c81bb8f4 Some examples from logging from query [error] (internal users edit) OR (psycopg2 errors cursor) with usernames redacted, to show timing: Jun 04 12:42:12 ballprice app/web.1: [ERROR] Internal Server Error: /users/a/edit [log:228] Jun 04 12:42:12 ballprice app/web.1: psycopg2.errors.InvalidCursorName: cursor "_django_curs_140401754175232_2" does not exist Jun 04 12:42:12 ballprice app/web.1: psycopg2.errors.InvalidCursorName: cursor "_django_curs_140401754175232_2" does not exist Jun 04 12:42:27 ballprice app/web.1: [ERROR] Internal Server Error: /users/a/edit [log:228] Jun 04 12:42:27 ballprice app/web.1: psycopg2.errors.InvalidCursorName: cursor "_django_curs_140401754175232_3" does not exist Jun 04 12:57:51 ballprice app/web.3: [ERROR] Internal Server Error: /users/a/edit [log:228] Jun 04 12:57:51 ballprice app/web.3: psycopg2.errors.DuplicateCursor: cursor "_django_curs_140092205262592_2" already exists Jun 04 12:57:51 ballprice app/web.3: psycopg2.errors.InvalidCursorName: cursor … -
compress image before direct uploading to s3
I can direct upload the image to s3 with the help of django-s3direct. my question is How to compress image before upload to s3 ? because its direct upload I can't use PIL for compress from backend. is there any way to compress the image before direct upload to s3 ? I also want to preview the uploaded image to user after upload. when user cancel upload when its uploading then image is not stored. But after uploaded when we remove image and choose new, the previous uploaded image still in bucket. I want to delete that previous uploaded image. How to do it. What I try: I tried to compress image in model to over write save method. But I get error Errno 22] Invalid argument: 'https://s3-ap-south-1.amazonaws.com/collegestudentworld-assets/img/mainpost/amar.jpg I known because it's url can't open in PIL. is it good idea to get image and compress and then stored to s3? I think its best to compress before uploading. I also tired before uploading with javascripts but when I select image its directly start uploading . I am new to javascripts. models.py from django.core.files.uploadedfile import InMemoryUploadedFile from s3direct.fields import S3DirectField # Create your models here. class MainPost(models.Model): author = models.ForeignKey(main_user,on_delete=models.CASCADE,default=1) … -
How do I add custom file input button to Django TinyMCE editor for uploading like STL/ZIP files?
I just want to add file button to TinyMCE editor for uploading STL/ZIP/etc. files on Django. When I add "file" plugin to my TINYMCE_DEFAULT_CONFIG, It says "Failed to load plugin: file from url http://localhost:12000/static/tinymce/js/tinymce/plugins/file/plugin.min.js" I am using django-tinymce4-lite 1.7.5 My config file that is at settings.py is below: TINYMCE_DEFAULT_CONFIG = { "height": 360, "width": 1120, "cleanup_on_startup": True, "custom_undo_redo_levels": 20, "selector": "textarea", "theme": "modern", "plugins": """ textcolor save link image media file preview codesample contextmenu table code lists fullscreen insertdatetime nonbreaking contextmenu directionality searchreplace wordcount visualblocks visualchars code fullscreen autolink lists charmap print hr anchor pagebreak """, "toolbar1": """ fullscreen preview bold italic underline | fontselect, fontsizeselect | forecolor backcolor | alignleft alignright | aligncenter alignjustify | indent outdent | bullist numlist table | | link image media file | codesample | """, "toolbar2": """ visualblocks visualchars | charmap hr pagebreak nonbreaking anchor | code | """, "contextmenu": "formats | link image", "menubar": True, "statusbar": True, "default_link_target": "_blank", } -
Django and Stripe logging
With Django logging settings setup like below how can I get stripe info to log to only the stripe logger? With this setup it's logging to both loggers. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse', }, }, 'formatters': { 'verbose': { 'datefmt': '%Y-%m-%d %H:%M:%S', 'format': '[{asctime}] {levelname} {name}: {message}', 'style': '{', } }, 'handlers': { 'file': { 'level': 'INFO', 'filters': ['require_debug_false'], 'class': 'logging.handlers.RotatingFileHandler', 'filename': os.path.join(BASE_DIR, 'logs/django.log'), 'formatter': 'verbose', 'maxBytes': 5 * 1024 * 1024, # 5MB 'backupCount': 2, }, 'stripe': { 'level': 'INFO', 'filters': ['require_debug_false'], 'class': 'logging.handlers.RotatingFileHandler', 'filename': os.path.join(BASE_DIR, 'logs/stripe.log'), 'formatter': 'verbose', 'maxBytes': 5 * 1024 * 1024, # 5MB 'backupCount': 2, }, }, 'loggers': { '': { 'handlers': ['file'], 'level': 'INFO', 'propagate': True, }, 'stripe': { 'handlers': ['stripe'], 'level': 'INFO', 'propagate': True, }, } } Example function that logs to both files: def create_payment_intent(self): stripe.api_key = settings.STRIPE_SECRET amount = int(self.total * 100) intent = stripe.PaymentIntent.create( amount=amount, description=f'Order #{self.id}', receipt_email=self.customer_email, setup_future_usage='off_session', ) return intent -
Django - Is there a way to configure certain url to be inaccessible from browser request?
I've searched for this question but could not found an answer. Basically, let's say i have my_app/successfully_page that i want to be displayed within the application flow. I don't want that to be displayed if some one is typing into browser the direct url. How can i make that url page INACCESSIBLE from browser search? -
i want to display the list of pruducts based on the choice of the category chosing -django
so i want to khow what i have to add in the urls.py and in the views.py to add this functionnality: if i click in one of this categories here my categories display some products based on the category chosen. and this the models.py class Product(models.Model): name=models.CharField(max_length=200,null=True) price=models.DecimalField(max_digits=7,decimal_places=2) digital=models.BooleanField(default=False,null=True,blank=True) image=models.ImageField(blank=True,null=True,upload_to ='images/',default="images/default.jpg") categories = models.ForeignKey(Category,on_delete=models.CASCADE,blank=True, null=True) def __str__(self): return self.name @property def imageURL(self): if self.image and hasattr(self.image, 'url'): return self.image.url else: return '/static/images/default.png' class Category(models.Model): name = models.CharField(max_length=50) slug = models.SlugField(max_length=50, unique=True, help_text='Unique value for product page URL, created from name.') is_active = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: db_table = 'categories' ordering = ['-created_at'] verbose_name_plural = 'Categories' def __unicode__(self): return self.name and this is the template : <div class="dropdown-menu" aria-labelledby="navbarDropdown"> <form method="get" action=""> {% for c in active_categories %} <a class="dropdown-item" href='#'>{{ c.name }}</a> {% endfor %} <a class="dropdown-item" href="#">something else</a> </form> </div> -
UNIQUE constraint failed even after deleting the OneTone relation in Django
I've a OneToOneField in my Django models , and it gives me the error UNIQUE constraint failed even after remove it before trying to save ,, here is an example: models.py class Employee(models.Model): name = models.CharField(max_length=120) phone = models.CharField(null=True, blank=True, max_length=20) salary = models.IntegerField(default=0) shift = models.OneToOneField(Shift, on_delete=SET_NULL, null=True, blank=True, related_name='employee') def __str__(self): return self.name def get_absolute_url(self): return reverse('employee_details', args=[str(self.id)]) class Shift(models.Model): branch = models.ForeignKey(Branch, on_delete=CASCADE) start_time = models.TimeField() end_time = models.TimeField() def __str__(self): return str(self.branch) + ' ( ' + str(self.start_time) + ' / ' + str(self.end_time) + ' )' forms.py class AssignEmployeeToShift(forms.Form): employee = forms.ModelChoiceField(queryset=Employee.objects.filter(shift__isnull=True), widget=forms.Select()) views.py class EmployeeAssignToShift(SuccessMessageMixin, FormView): form_class = AssignEmployeeToShift template_name = 'back_office/employee_assign_to_shift.html' def get_success_url(self): return reverse_lazy('branch_details', args=[str(Shift.objects.get(id=self.kwargs['pk']).branch.id)]) def get_context_data(self, **kwargs): context = super(EmployeeAssignToShift, self).get_context_data(**kwargs) context['current_shift'] = Shift.objects.get(id=self.kwargs['pk']) return context def form_valid(self, form): shift_object = get_object_or_404(Shift, pk=self.kwargs['pk']) employee_instance = form.cleaned_data['employee'] employee_object = Employee.objects.filter(shift=shift_object) if employee_object.count() != 0: employee_object[0].shift = None employee_object[0].save() employee_instance.shift = shift_object employee_instance.save() else: employee_instance.shift = shift_object employee_instance.save() return super(EmployeeAssignToShift, self).form_valid(form) -
Docker & Django : Google Maps JavaScript API error
I am trying to include Google Map into my project using "Maps JavaScript API". I am able to successfully run in my local system when using the command ./manage.py runserver and the "Google Map Platform API Checker" return's success like this but when I run in docker with the commands docker-compose down docker-compose build docker-compose up and then check the the Google Map wont load and the "Google Map Platform API Checker" return's failure like this any solution to this ? -
Google App Engine: Deplying frontend and backend configuration (Nuxt + Django)
I am deploying Nuxt (frontend, universal configuration), Django (backend API, DRF), and Postgres on Google App Engine and Cloud SQL. If this is relevant: (I need to be able to store images, dynamically create and store new images and dynamically create and store pdfs.) In Google App Engine, what is the ideal setup for Django and Nuxt in terms of speed and performance? Should they be on separate apps? Any information you can provide/suggest regarding this setup would be helpful as this is my first time deploying this configuration on GAE. -
How to get video player to read local video files in djangocms?
I setup djangocms following instructions from https://www.django-cms.org/en/. When trying to embed a video using the default Video Player plugin. I see the following message under the embed video textfield: Use this field to embed videos from external services such as YouTube, Vimeo or others. Leave it blank to upload video files by adding nested "Source" plugins. Now I left it blank, but could not figure how to add a "nested Source plugin". Any thoughts? -
Push file create by Django than need to be ignore by git
I have make a first push to Gitlab with git, but the.gitignore wasn't completely configure. I configure the .gitignore like this now : # Environments env/ # Byte-compiled / optimized / DLL files poc_project/poc_project/__pycache__ poc_project/pollution/__pycache__ __pycache__/ *.py[cod] *$py.class # Django stuff: *.log local_settings.py db.sqlite3 db.sqlite3-journal The env/ and poc_project/poc_project/__pycache__ aren't push but the db.sqlite3 and poc_project/pollution/__pycache__ are already on the distant repository (Gitlab). I use this https://github.com/github/gitignore/blob/master/Python.gitignore for configure my .gitignore because I use django. My teammate will soon start working on the project. It's a problem to have pycache file and db.sqlite3 for team work on distant repository with Django? If yes how can I delete these files correctly from gitlab repository ? -
can you help me to how to fix this error in django?
I was working on project to import contacts from yahoo.I created app in yahoo developer(for client id and secret key). I was using contacts importer module for Django but I am getting this error.I unable to debug. Can you help me how to fix this error? This is the file producing error. I have provided error below. # -*- coding: utf-8 -*- """ Yahoo Contact Importer module """ from .base import BaseProvider from ..lib import oauth1 as oauth from urllib.parse import urlencode from urllib.parse import parse_qs from uuid import uuid4 as uuid from collections import OrderedDict from time import time from hashlib import md5 import requests import json REQUEST_TOKEN_URL = "https://api.login.yahoo.com/oauth/v2/get_request_token" REQUEST_AUTH_URL = "https://api.login.yahoo.com/oauth/v2/request_auth" TOKEN_URL = "https://api.login.yahoo.com/oauth/v2/get_token" CONTACTS_URL = "http://social.yahooapis.com/v1/user/%s/contacts" class YahooContactImporter(BaseProvider): def __init__(self, *args, **kwargs): super(YahooContactImporter, self).__init__(*args, **kwargs) self.request_token_url = REQUEST_TOKEN_URL self.request_auth_url = REQUEST_AUTH_URL self.token_url = TOKEN_URL self.oauth_timestamp = int(time()) self.oauth_nonce = md5("%s%s" % (uuid(), self.oauth_timestamp)).hexdigest() def get_request_token(self): request_params = dict( oauth_consumer_key=self.client_id, oauth_nonce=self.oauth_nonce, oauth_signature_method="plaintext", oauth_signature=self.client_secret + "&", oauth_timestamp=self.oauth_timestamp, oauth_version="1.0", oauth_callback=self.redirect_url ) request_url = "%s?%s" % (self.request_token_url, urlencode(request_params)) response = requests.post(request_url) query_string = parse_qs(response.text) self.oauth_token = query_string["oauth_token"][0] self.oauth_token_secret = query_string["oauth_token_secret"][0] def request_authorization(self): request_params = dict(oauth_token=self.oauth_token) return "%s?%s" % (self.request_auth_url, urlencode(request_params)) def get_token(self): request_params = dict( oauth_consumer_key=self.client_id, oauth_signature_method="plaintext", oauth_nonce=self.oauth_nonce, oauth_signature=self.client_secret + … -
Can you mock out a Python enums class?
I am trying to test a function that makes use of enums. permanent = [] temp = [] for category in enums.Category: category_name = str(category.name) if category_name in labels: if not category.is_temporary_code: permanent.append(category) else: temp.append(category) for category in permanent: category_name = str(category.name) internal_code = models.RecordType.objects.get( code=category.value ).internal_code field_label = labels[category_name] self.fields[internal_code] = forms.BooleanField(label=field_label, required=False) In my test, I make use of a factory that adds a Record Type to the test database. However, when the test calls this page and runs the function, it iterates over all the existing enums and therefore relies on the RecordType table containing all the rows from the real database. I feel a way to overcome this would be to mock out the enums, and replace it to contain only the value that corresponds with the factory Record Type. Is there a way of doing this? -
How to prefill a form with data from the same form in Django
I have a form, that calls itself and displays a result at the bottom. I want the form to be filled with the data from the previous POST request from the same form, so that I do not have to type in the same data again, after submitting it. This took me some time to figure out, so I'll self answer this yet again. -
Heroku Redis - What counts as a connection? Why does my connection limit not drop to zero, after Python Celery completes task?
I am using the Heroku Redis add-on for my Django application, as the broker for my Python Celery background tasks. The Celery background task is successfully completed using Heroku Redis as the broker. However within the Heroku Redis add-on dashboard (data.heroku.com/datastores/) it still says there are 8 clients (connections). 1) Why is that, I thought it would be 0 clients (connections) since the celery background task is completed. 2)In the Heroku Redis dashboard the number of clients so far has varied between 13 and 8 clients. Why so many clients? I am only running a single python celery background task at a time, so thought it would always say 1 client. -
How to save an instance and update a reverse M2M field in a modelForm
I have two models with an M2M relationship: class Author(models.Model): name = models.CharField() class Publisher(models.Model): authors = models.ManyToManyField(Author) When creating a new Author, I want to be able to set Publishers for that Author. Currently I handle this in the form: class AuthorForm(forms.ModelForm): publishers = forms.ModelMultipleChoiceField(queryset=Publisher.objects.all()) def __init__(self, *args, **kwargs): super(AuthorForm, self).__init__(*args, **kwargs) # If the form is used in a UpdateView, set the initial values if self.instance.id: self.fields['publishers'].initial = self.instance.publisher_set.all( ).values_list('id', flat=True) def save(self, *args, **kwargs): instance = super(AuthorForm, self).save(*args, **kwargs) # Update the M2M relationship instance.issuer_set.set(self.cleaned_data['issuers']) return instance class Meta: model = Author fields = ['name', 'publishers'] This works fine when updating an existing Author. However, when I use it to create a new one I get: <Author: Sample Author> needs to have a value for field "id" before this many-to-many relationship can be used. I understand this is because the instance needs to be saved first, however in def save() I am doing this (instance = super(AuthorForm, self).save(*args, **kwargs)). Where am I going wrong? -
How to set cache control headers in a Django view class (no-cache)
Now this took me some time to figure out, so I will self-answer it. I wanted to disable browser caching for one specific page in Django on a View. There is some information how to do this if the view is a function, but not if it's a class. I did not want to use a middleware, because there was only one specific view that I didn't want to be cached. -
passing token as headers from an html file using js
i have added an input field which takes token as input and fetches a page with authenctication required and sends that token as header but this doesnt seem to work..all i want to do is take token as input from frontend page and give access to pages instead 0f using POSTMAN <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form> <input type="text" id="token" placeholder="token"> <button type="button" onclick="myFun()"> submit</button> </form> </body> <script> function myFun() { var token = document.getElementById("token").value; object = { method: 'GET', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + token } } fetch('http://127.0.0.1:8000/app/task-list/', object) </script> </html> -
run an os.system command via Django on Raspberry pi
Hello i have set up a django website on my raspberry pi running with apache2 i want to controll some wireless sockets via 433mhz and the 433Utils/RPi_utils Library. I've installed the Library inside my virtualenv. my views.py looks like this: from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect import os def light(response): return render(response,"light/light.html", {}) def one_on(request): os.system("/home/pi/Dev/cfehome/src/light/433Utils/RPi_utils/codesend 1381717") return render(request, "light/one_on.html") If i open http://.../light/one_on.html in my browser the page loads and everything is there but the pi sends nothing to the wireless socket Could you please helb me? -
Django not creating user after extending AbstractUser
I tried extending my AbstractUser to allow more user types and to also allow users to create an account using their email address. However, I have been facing issues with user creation form on the frontend despite the fact that my Django admin works perfectly as I can create or sign in using email address instead of a username. In addition, I noticed that anytime I submit the account creation form, the values auto-populate my browser's address bar, and of course, the user won't be created. I don't know if I can get some help to this issue, maybe I am simply missing a very vital step. Below is a sample of auto-populated values shown in my browser's address bar when I (users) submit the form http://127.0.0.1:8000/signup/company/?csrfmiddlewaretoken=7AC4rKoyFsYTkcOKLpaiREAYZQwu1i3hGlF51I3Svs65Kf4Fkc64j25YZAN2pKE4&email=jyak%40yahoo.com&password1=oluwasegun01&password2=oluwasegun01&name=Hedge&number_of_employees=20&country=1&phone=012345678901 Below are my codes: Models.py from django.contrib.auth.base_user import AbstractBaseUser from django.contrib.auth.models import PermissionsMixin, AbstractUser from django.db import models from django.utils import timezone from django.utils.translation import ugettext_lazy as _ from accounts.managers import CustomUserManager from accounts.validators import validate_digit_length from data.models import Country class User(AbstractUser): email = models.EmailField(_('email address'), unique=True) #some other user types username = None USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() def __str__(self): return self.email class Company(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, … -
Django migration strategy for changing ForeignKey to IntegerField without losing data
I have model class SomeModel(models.Model): target_field = models.ForeignKey( 'OtherModel', on_delete=models.PROTECT, verbose_name=_('Target Field'), ) And i want to change it to class SomeModel(models.Model): target_field_id = models.PositiveIntegerField(_('Target field id')) I want to do it without losing data stored in target_field_id by ForeignKey field. I tried just to run makemigrations. But it deletes column and then creates new. Much appreciate any help. -
When migrating: Encoding "UTF8" has no equivalent in encoding "LATIN1"
Django 3.0.6 PostgreSQL 12.3 At my localhost everything is Ok. But when I try to deploy to my production server: (venv) root@tmpgmv:~/pcask/pcask# python manage.py migrate Operations to perform: Apply all migrations: admin, applications, auth, author, category, code_sample, contenttypes, general, hyper_link, image, languages, marketing, people, polls, post, quotations, sessions, sidebar, taggit, videos Running migrations: No migrations to apply. Traceback (most recent call last): File "/root/pcask/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 86, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UntranslatableCharacter: character with byte sequence 0xd0 0xa0 in encoding "UTF8" has no equivalent in encoding "LATIN1" The above exception was the direct cause of the following exception: 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 "/root/pcask/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/root/pcask/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/root/pcask/venv/lib/python3.6/site-packages/django/core/management/base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "/root/pcask/venv/lib/python3.6/site-packages/django/core/management/base.py", line 369, in execute output = self.handle(*args, **options) File "/root/pcask/venv/lib/python3.6/site-packages/django/core/management/base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "/root/pcask/venv/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 256, in handle self.verbosity, self.interactive, connection.alias, apps=post_migrate_apps, plan=plan, File "/root/pcask/venv/lib/python3.6/site-packages/django/core/management/sql.py", line 50, in emit_post_migrate_signal **kwargs File "/root/pcask/venv/lib/python3.6/site-packages/django/dispatch/dispatcher.py", line 175, in send for receiver in self._live_receivers(sender) File "/root/pcask/venv/lib/python3.6/site-packages/django/dispatch/dispatcher.py", line 175, in <listcomp> for receiver in self._live_receivers(sender) File "/root/pcask/venv/lib/python3.6/site-packages/django/contrib/auth/management/__init__.py", line … -
How to transfer a html table from a template to a database table
I have an HTML template (index.html) which gets populated dynamically with an HTML table. The table data can be changed by the user. After the user has made his changes, he then can save the whole table data to a Django database table by clicking a submit button.