Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Count field choices in a model?
Im new to django and Im helping in creating a website, now what they've requested is to show a specific number and Im trying to use a for loop it goes something like this: class Students(models.Model): ... section = (('1', '1'), ('2', '2'), ('3', '3'), ('4', '4'), ('5', '5'), ('6', '6')) BlockNumber = models.CharField(max_length=10, choices=section) now what I want to do is to count each section choice in the Students model class. I've tried using the code below to count each choice: def yearCount(request): year = Students.objects.all(Count('year')) blocks = Students.onjects.all(Count('section')) context = {'year': year,'blocks': blocks} return render(request, './chairperson/students/student_bsit1.html', context) Any help would be appreciated, thank you. -
AJAX is calling multiple times even when i click once
My HTML CODE: <div class="filter-section"> {% for key, values in positions.items %} <h3>{{key}}</h3> {% for position in values %} <a id="view-job-{{position.id}}" style="cursor:pointer" onclick="getPositionInfo({{position.id}})" class="list-row"> <span class="list-item">{{position.position_name}}</span> </a> {% endfor %} {% endfor %} </div> JS Code: <script type="text/javascript"> function getPositionInfo(id){ var j_id = "#view-job-" + id; $(j_id).on('click', function(e) { e.preventDefault(); $.ajax({ url : '/apply_now/', type: 'POST', data:{ job_id : id, csrfmiddlewaretoken: '{{ csrf_token }}' }, success:function(data){ alert(JSON.stringify(data)); } }); }); } </script> Problem: When on the first click nothing happens, but from the second click, it calls multiple times. Example: 1st click -> no call 2nd click -> calls 2 times 3rd click -> calls 3 times nth click -> calls n times For 3rd click ajax called 5 times -
cannot install environ in virtualenv , No module named 'pip'
I have environ installed in my system but I cannot install it in my virtual environment. when I run python manage.py runserver I get error File "E:\Django Projects\Django_projects\taskmate\taskmate\settings.py", line 15, in <module> import environ ModuleNotFoundError: No module named 'environ' and when I try to install environ in my virtual environment I get error (tmenv) E:\Django Projects>pip install django-environ Traceback (most recent call last): File "E:\Python\lib\runpy.py", line 197, in _run_module_as_main return _run_code(code, main_globals, None, File "E:\Python\lib\runpy.py", line 87, in _run_code exec(code, run_globals) File "E:\Django Projects\tmenv\Scripts\pip.exe\__main__.py", line 4, in <module> ModuleNotFoundError: No module named 'pip' -
Im unable to start server using django python manage.py runserver. Im getting the below error
raise ServerSelectionTimeoutError( pymongo.errors.ServerSelectionTimeoutError: cluster0-shard-00-02.gtkp9.mongodb.net:27017: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1125),cluster0-shard-00-01.gtkp9.mongodb.net:27017: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1125),cluster0-shard-00-00.gtkp9.mongodb.net:27017: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1125), Timeout: 30s, Topology Description: <TopologyDescription id: 60c1c8dc887aed978363ee86, topology_type: ReplicaSetNoPrimary, servers: [<ServerDescription ('cluster0-shard-00-00.gtkp9.mongodb.net', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('cluster0-shard-00-00.gtkp9.mongodb.net:27017: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1125)')>, <ServerDescription ('cluster0-shard-00-01.gtkp9.mongodb.net', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('cluster0-shard-00-01.gtkp9.mongodb.net:27017: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1125)')>, <ServerDescription ('cluster0-shard-00-02.gtkp9.mongodb.net', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('cluster0-shard-00-02.gtkp9.mongodb.net:27017: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1125)')>]> -
Django channels don't activate asgi functions through testing?
when I run WebSocket in the front end and it connects I got the code line print(scope) #<==🔴 runs correctly. But, when I run testing this function and the whole asgi file don't run at all. However, I need the asgi file to handle the token in order to get the user and add it to the scope data. #asgi.py from urllib.parse import parse_qs from channels.db import database_sync_to_async from channels.routing import ProtocolTypeRouter, URLRouter from django.contrib.auth.models import AnonymousUser from django.core.asgi import get_asgi_application # from jwt import decode from rest_framework_simplejwt.tokens import UntypedToken from Alerts.routing import websocket_urlpatterns from Functions.debuging import Debugging from users.models import User # TODO encode and decode the jwt_token @database_sync_to_async def get_user(querys): token = parse_qs(querys.decode("utf8"))['token'][0] token_data = UntypedToken(token) user_id = token_data["user_id"] try: return User.objects.get(id=user_id) except User.DoesNotExist: return AnonymousUser() class QueryAuthMiddleware: def __init__(self, app): # Store the ASGI application we were passed self.app = app async def __call__(self, scope, receive, send): # Look up user from query string (you should also do things like # checking if it is a valid user ID, or if scope["user"] is already # populated). print(scope) #<==🔴 scope['user'] = await get_user(scope["query_string"]) return await self.app(scope, receive, send) application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": QueryAuthMiddleware( URLRouter( websocket_urlpatterns ) … -
I have 1form with two buttons. one button will execute external python script. On clicking on other button it should save my data in database (django)
This is my Views.py. My nested if statement is not working. My data is getting stored before this condtion is statisfed [if request.POST.get('confirm',None)] def external(request, *args, **kwargs): if request.method == 'POST': request_getdata = request.POST.get('img64',None) selected_radio = request.POST.get('radio_seleect',None) headed, encoded = request_getdata.split(",",1) data = base64.b64decode(encoded) with open("D:/Django/env/src/OCR/media/image.png", "wb") as f: f.write(data) path = 'D:/Django/env/src/OCR/media/img.png' if selected_radio=='option1': raw_out = run([sys.executable,'D://Django//env//src//OCR//text_detect_raw.py',path],shell=False,stdout=PIPE) out = run([sys.executable,'D://Django//env//src/OCR//detect_text.py',path],shell=False,stdout=PIPE) raw_output = raw_out.stdout.decode('utf-8') final_output = out.stdout.decode('utf-8') print(raw_output) print(final_output) if request.POST.get('confirm',None): record2 = TemperatureRecordsF(raw_value=raw_output,actual_value=final_output) record2.save() return JsonResponse({'output':final_output},status=200) elif selected_radio=='option2': raw_out = run([sys.executable,'D://Django//env//src//OCR//text_detect_raw.py',path],shell=False,stdout=PIPE) out = run([sys.executable,'D://Django//env//src/OCR//detect_text.py',path],shell=False,stdout=PIPE) raw_output = raw_out.stdout.decode('utf-8') final_output = out.stdout.decode('utf-8') print(raw_output) print(final_output) if request.POST.get('confirm',None): record2 = TemperatureRecordC(raw_value=raw_output,actual_value=final_output) record2.save() return JsonResponse({'output':final_output},status=200) Here is my html form. I have 4 radio buttons. 1 button to execute python script. Another button to save my contents in database. <form class="contentarea" action="/external" method="POST" id="capture" name="capture"> {% csrf_token %} <input class="form-check-input" type="radio" name="inlineRadioOptions" id="inlineRadio1" value="option1"> <label class="form-check-label" for="inlineRadio1">Temperature °F</label> <input class="form-check-input" type="radio" name="inlineRadioOptions" id="inlineRadio2" value="option2"> <label class="form-check-label" for="inlineRadio2">Temperature °C</label> <input class="form-check-input" type="radio" name="inlineRadioOptions" id="inlineRadio3" value="option3"> <label class="form-check-label" for="inlineRadio3">Blood Pressure</label> <input class="form-check-input" type="radio" name="inlineRadioOptions" id="inlineRadio4" value="option4"> <label class="form-check-label" for="inlineRadio4">Oxygen Saturation Levels</label><br> <video id="video">Video stream not available.</video><br> <button id="startbutton">Take photo</button><br> <textarea id="message">{{output}}</textarea><br> <input type="button" name="confirm" id="confirm" value="Please Confirm" /> <canvas id="canvas" style="display: none;"><br> </canvas> <div class="output"> <img … -
why are SQL inserts (mariadb getting slower as a table grows
I'm trying to process some data and write it to a mariadb (10.5.10) table using django : Here is my model class AbstractCandle(models.Model): exchanged_security = models.ForeignKey('market.exchangedsecurity', on_delete=models.CASCADE) date = models.DateTimeField(db_index=True) duration = models.DurationField(db_index=True) ask_open = models.FloatField(default=-1, db_index=True) ask_high = models.FloatField(default=-1, db_index=True) ask_low = models.FloatField(default=-1, db_index=True) ask_close = models.FloatField(default=-1, db_index=True) class Meta: unique_together = [('exchanged_security', 'date', 'duration')] abstract = True I've made some tweaking to mariadb to make it faster : innodb_compression_algorithm=none innodb_autoinc_lock_mode=2 innodb_buffer_pool_size=1024M max_allowed_packet=1024M innodb-log-buffer-size=512M wait_timeout=28800 unique_checks=0 innodb_flush_log_at_trx_commit=0 foreign_key_checks=0 sync_binlog=0 My problem is that insert throughput is getting slower as the table grows (the table for that object is around 28gb for a 80 million rows ) ? Monitoring shows this (server is only used for mariadb): Network Read 15.2GB Write 2.78GB BLOCK I/O Read 238GB Write 14.9TB Questions Is storage write speed the bottleneck ? Why does mariadb write so much stuff to hard drive even though i disabled indexes and constraints ? How can i keep insert speed from going down as the table grows ? (I'm only at 25% of all the rows i need to insert and i fear the last 10% will be way longer expected) -
On click of table row i want to view the data of that row as a modal popup in Django
I'm working on a Django project where my requirement is whenever I click on a table row a modal popup will open to show the data of that row. If I click a different row then the popup data should be from that rows. Now my problem is how to show data of that particular row that I clicked??Here everything is coming from database Here's my html <div class="col-sm-12" id="tablediv" style="margin-top: 40px; margin-bottom: 40px;"> <table class="table table-hover" id="header-fixed" style="color: black; margin-top: -20px;"> <thead> <tr> <th>Jira Story</th> <th>Short Description</th> <th style="width: 103px;">DX4C Object</th> <th>Sprint</th> <th>Points</th> <th> <nobr>SB Assigned</nobr> </th> <th> <nobr>Developer Assigned</nobr> </th> <th>Action</th> </tr> </thead> {% for rt in JIRA %} <tbody> <!-- <tbody id="myTable"> --> <tr data-toggle="modal" data-id="1" data-target="#orderModal"> <td>{{rt.Jira_ID}}</td> <td> {{rt.Jira_Story}}</td> <td>{{rt.DX4C_Object}}</td> <td>{{rt.Sprint}}</td> <td>{{rt.Story_Points}}</td> <td>{{rt.Sandbox}}</td> <td>{{rt.Developer_Assigned}} </td> <td> <nobr> <a href="{% url 'UpdateJira' rt.id %}" class="btn btn-warning btn-sm"><i class="fas fa-edit"></i> </a> <form action="{% url 'deletedata' rt.id %}" id="delform" method="post" class="d-inline" style="display: inline-block;"> {% csrf_token %} <button type="submit" id="delbtn" class="btn btn-danger btn-sm" onclick="return confirm('Please click on OK button to delete Robot !')"><i class="fas fa-trash-alt"></i> </button> </form> </nobr> </td> </tr> </tbody> {% endfor %} </table> </div> <!-- The Modal --> <!-- Modal content --> <div class="modal-content"> <span class="close">&times;</span> <p>Some text … -
Is there any way to stop the logs being stored in database using drf-api-tracking in django?
I have created a small project using Django, And to check the logs in Database, I have installed the drf-api-tracking library from Django. I have passed the LoggingMixin parameter into all classes in views.py file in Django. I am able to view the logs in db. If I prefer not to write those logs for sometime in db, Is there a way to stop it, rather than uninstalling and removing the parameters. -
Django rest framework with multiple platforms
Hi all I have an arduino and android app I need to write data from arduino to database without authentication but if user wants to see data from android app he needs to be authenticated how can I do it thanks. -
Django - filtering prefetch_related to today's date
Filtering prefetch_related. I have two tables: Student attendance data class studentAttendance(models.model): id = models.AutoField(primary_key=True) date = models.DateField() status = models.CharField(max_length=255) student = models.ForeignKey(Student, related_name='student', on_delete=models.PROTECT) objects = models.Manager() Student personnel record class Student(models.model): id = models.AutoField(primary_key=True) fname = models.CharField(max_length=255) active = models.BooleanField(default=True) objects = models.Manager() Objective: I want to have a "daily register" html form. When loading the daily register I want it to show the following columns: First Name | Last Name | Status | Next to it I will have checkboxes for the teacher to select "Present" or "Absent". My issue: I need to show a list of all "active" students and then also either display empty statuses for those that haven't signed in yet, or show the value that already exists for those students that have signed in. I figure since one student can have many "days" in the attendance table, this counts as a 'prefetch_related' scenario, not 'select_related'. If I were going the other way, from the attendance table to the Student, then that would be a 'select_related', since only one row in the Student table would match. That was the way I was initially doing it, but then I quickly realised that for those students … -
Django : cannot find the static files
In my Django project, the settings are the following ones: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') When I launch collectstatic the static folder is mounted at the root of the project, as planned. However, the static files are not found neither by the html pages, although configured as seach: {% load static %} <!DOCTYPE html> <html lang="eng"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1, initial-scale=1"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous"> <link rel="stylesheet" href="{% static 'style_sheet.css' %}"> <title>{% block title %}Advocacy Project{% endblock %}</title> </head> and when I check with findstatic, it looks like it does not look into the right folders: python manage.py findstatic style_sheet.css --settings my_project.settings.production --verbosity 2 No matching file found for 'style_sheet.css'. Looking in the following locations: /Users/my_name/Documents/my_project/venv/lib/python3.7/site-packages/django/contrib/admin/static My question is: How could I make Django check in the right folders ? -
Not able to access wildcard subdomain in Django app on online server
I am hosting a Django app on managed server with passenger_wsgi file. Let assume app main url is 'www.mysite.com'. When i visit this it shows me the homepage. What i want is to use wildcard subdomains in the app. Like www.user1.mysite.com , www.user2.mysite.com , www.user3.mysite.com and so on, it can be any wildcard. I have created a wildcard subdomain from cpanel like "*.mysite.com" , also added wildcard in my django settings.py file too. But when i visit the "www.user1.mysite.com" browser says Not Found The requested URL was not found on this server. Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request. Any kind of help would be great. Thanks..!! -
getting this error when run makemigrations
ERROR: You are trying to add a non-nullable field 'course' to learning without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: Provide a one-off default now (will be set on all existing rows with a null value for this column) Quit, and let me add a default in models.py Select an option: MODELS.PY from django.db import models # Create your models here. class Course(models.Model): name = models.CharField(max_length=30,null=False) description = models.CharField(max_length=200,null=True) price = models.IntegerField(null=False) discount = models.IntegerField(null=False,default=0) active = models.BooleanField(default=False) thumbnail = models.ImageField(upload_to='files/thumbnail') date = models.DateTimeField(auto_now_add=True) resource = models.FileField(upload_to='files/resource') length = models.IntegerField(null=False) class CouseProperty(models.Model): description = models.CharField(max_length=20,null=False) course = models.ForeignKey(Course, null=False, on_delete=models.CASCADE) class Meta : abstract = True class Tag(CouseProperty): pass class Prerequisite(CouseProperty): pass class Learning(CouseProperty): pass class Video(models.Model): title = models.CharField(max_length=100,null=False) course = models.ForeignKey(Course,null=False,on_delete=models.CASCADE) serial_number = models.IntegerField(null=False) video_id = models.CharField(max_length=100, null=False) is_preview = models.BooleanField(default=False) admin.py from django.contrib import admin from courses.models import Course, Tag, Prerequisite, Learning, Video # Register your models here. class TagAdmin(admin.TabularInline): model = Tag class LearningAdmin(admin.TabularInline): model = Learning class PrerequisiteAdmin(admin.TabularInline): model = Prerequisite class CourseAdmin(admin.ModelAdmin): inlines = [TagAdmin,LearningAdmin,PrerequisiteAdmin] admin.site.register(Course, CourseAdmin) admin.site.register(Video) -
In Django CMS, how can I prevent duplicate items in a queryset when I order them by .order_by('title_set__title')
Let's say I am viewing a changelist for a set of pages in a Django CMS project and I want to sort that by title. But for each title/language that is created and published, a duplicate tree item will be displayed. For any other kind of sorting that I have created, this does not happen and it works as it should. This will return one tree item for each language that has been published and I am pretty sure created as well. Even with the .distinct() it will return one tree item for each title/language that exists. Examples below. This example produces duplicate or even 3, 4, 5 copies of the same tree item if there are that many language titles that exist. def get_queryset(self, request): queryset = super(PageAdmin, self).get_queryset(request) queryset = queryset.order_by('title_set__title').distinct() Now in this example, if I order tree items by anything else, or (-publication_date, publication_end_date, -publication_end_date). I will only get one result for pages that have multiple titles/languages that exist, just like it should. def get_queryset(self, request): queryset = super(PageAdmin, self).get_queryset(request) queryset = queryset.order_by('publication_date').distinct() My educated guess is that it has something to do with the "title_set", which is being prefetched elsewhere, being a collection of many … -
django - ASGI 'lifespan' protocol appears unsupported
im using django 3.1.2 with uvicorn[standard]==0.13.4 but im keep getting this error ASGI 'lifespan' protocol appears unsupported that prevents application from starting and from what I've seen it seems this is common with django 3+ is there anyway around this? -
How to Edit Data in Django dropdown HTML form?
I have a form where I am editing single leads data, I submitted data using the Django default admin panel. But now I am editing data on my default form. So my concern is, if I edit any leads then the default value should be selected in the dropdown which is available in the database, and if I want to change the dropdown value then I can select it from the dropdown list. Here are my Models.py file class Leads(models.Model): SOURCE = ( ('Facebook', 'Facebook'), ('Website', 'Website'), ('PPC', 'PPC'), ('Reference', 'Reference'), ('Other Source', 'Other Source') ) name = models.CharField(max_length=50, default=None) email = models.EmailField(max_length=50, null=True, blank=True) phone = models.CharField(max_length=10, default=None) source = models.CharField(choices=SOURCE, default=2, max_length=100) here are my urls.py file path(r'^leads/<int:id>/change',views.leads_edit, name="leads_edit"), here is my views.py file... def leads_edit(request, id): leads = Leads.objects.get(id=id) context = {'leads':leads} template_name = 'file/edit.html' return render(request, template_name, context) here is my edit.html file, where is am trying to edit using the dropdown field... {% for obj in leads.SOURCE %} <option value="{{ leads.source }}">{{ obj}}</option> {% endfor %} Please check my code and let me know how I can display the selected field from the database, and how I can display the rest other fields in the … -
How to merge code of two person working on same branch with different commits?
I and my colleague is working on a django (python) project and pushing our code on same branch(lets say branch1), as a beginner i know how to push the code on a particular branch but have no idea how pull and merge can be done. what should i do if i want full project including his codes and my codes together without overriding the whole file(lets say he made views1.py and i made views2.py, then after merge and all, the result must be views3.py) now views3.py contains my code and his code. Any kind of help would be appreciated. -
Django DateField: enter a date without a year to mean this year
I want to allow the entry of a date without a year into a DateField to mean the actual year. Like "10.6." should mean 10 June 2021, since it's 2021 at the time of writing. The following DATE_INPUT_FORMATS didn't cut it: DATE_INPUT_FORMATS = ('%d.%m.%y', '%d.%m.%Y', '%Y-%m-%d', '%d.%m.') This does allow such input, but the year will be 10 June 0000; not what I aimed for. Any advice? -
Keycloak: unable to fetch token when OTP is enabled
I am using Google Authenticator to generate OTP and using Python Keycloak Openid for my rest api @api_view(['POST', 'GET']) def login(request): # marketplace login try: if 'clientId' in request.headers and request.headers["clientId"] != 'null' and request.headers["clientId"] != None: keycloak_openid = keycloak_openid_method( request.headers["clientId"]) else: keycloak_openid = keycloak_openid_method() keycloak_admin = keycloak_admin_method() token2 = keycloak_admin.token["access_token"] token = keycloak_openid.token( request.data["username"], request.data["password"] , totp=request.data["totp"]) headers = {"Authorization": "Bearer " + keycloak_admin._token["access_token"], "Content-type": 'application/json' } return HttpResponse(json.dumps({"body": token, "statusCode": 200})) except Exception as e: log_error = "Log: {url: " + str(request.get_full_path()) + \ ", error: " + str(e) + ", time: " + str(datetime.now()) + "}" logSaver(str(log_error)) Postman Screen -
Unable to migrate Django to Oracle 12c ( specified length too long for its datatype)
I want to connect my Oracle 12c instance to Django. It works, migrates some 6-7 odd auth tables before breaking down: django.db.utils.DatabaseError: ORA-00910: specified length too long for its datatype Please help out. I tried to refer other answers but unable to figure out the exact steps. -
KeyError at / 'assets'
When I am at http://127.0.0.1:8000/ I'm gettings this error KeyError at / 'assets' In settings.py Installed apps INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', #own 'rest_framework', 'rest_framework.authtoken', 'allauth', 'allauth.account', 'allauth.socialaccount', 'rest_auth', 'rest_auth.registration', 'crispy_forms', 'webpack_loader', 'users', 'questions', Webpack Loader WEBPACK_LOADER = { 'DEFAULT': { 'CACHE': not DEBUG, 'BUNDLE_DIR_NAME': 'dist/', 'STATS_FILE': str(BASE_DIR.joinpath('frontend', 'webpack-stats.json')), 'POLL_INTERVAL': 0.1, 'TIMEOUT': None, 'IGNORE': [r'.+\.hot-update.js', r'.+\.map'], } } In templates folder (index.html) {% load render_bundle from webpack_loader %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>QuestionTime</title> </head> <body> <h1>Vue JS</h1> <div id="app"></div> {% render_bundle 'app' %} </body> </html> I also have the vue.config.js file In the terminal it says this asset = assets['assets'][chunk] KeyError: 'assets' -
How to pass/send Value{Hex) to serial COM port from Django?
I have connected my PID to my local PC with Serial Port via RS485 to USB converter. I can read and write the resister value from Python Code. now i want to read and write the register values from Django web. Please suggest any example of Modbus-Django or just let me know how to pass value from Django Vies.py to my local serial connection? -
init mysql database in Django got error: django.db.utils.OperationalError: (1071, 'Specified key was too long; max key length is 3072 bytes')
I have used Django to develop a web app. When I tried to init the mysql database using python manage.py migrate, I got the error: _mysql.connection.query(self, query) django.db.utils.OperationalError: (1071, 'Specified key was too long; max key length is 3072 bytes') I have tried : ALTER DATABASE databasename CHARACTER SET utf8; CREATE DATABASE mydatabase CHARACTER SET utf8 DEFAULT COLLATE utf8_general_ci; All failed in my case. model.py: class Publisher(models.Model): name = models.TextField(blank=True, help_text="Publisher name") contact = models.CharField(max_length=50, blank=True, null=True) def __str__(self): return self.name class Meta: ordering = ['name', ] class Title(TimeStampedModel): title = models.CharField(max_length=190, db_index=True) author = models.CharField(max_length=100, blank=True, null=True) description = models.TextField(max_length=2000, help_text="Enter a brief description of the book", blank=True, null=True) ... How could I quickly fix this problem? -
How to move existing Django project template to React JS with Django Rest API
I am having a Django project with approximately 200 methods in view and 40+ HTML templates; in this case, I don't want to move to Django Rest Framework to connect with React JS. Is there any way to migrate from the Django template to react UI without using the Rest framework? I also want to know to pass data from view to components.