Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python Sort by DateTime using list.sort()
I am trying to sort a list of comments by date. They have a date field that contains a datetime object(?) auto-created by Django. Because of how multiple comment-models have been combined in the list, I cannot use Django's built-in .order_by() sorter. Right now I am testing with just 3 comments, but they are already out of order when I sort them. The three datetimes as strings: 2020-08-21 16:17:40.690851+00:00 2020-08-21 15:04:32.315342+00:00 2020-08-21 12:10:21.720688+00:00 The comment models: class MealComment(models.Model): date = models.DateTimeField(auto_now_add=True) class Meta: ordering = ('-date',) class SubComment(models.Model): date = models.DateTimeField(auto_now_add=True) class Meta: ordering = ('-date',) How the list is created and sorted: mealcomments = user.mealcomment.all() subcomments = user.subcomment.all() if mealcomments and subcomments: comments = list() for comment in list(mealcomments): comments.append(comment) for comment in list(subcomments): comments.append(comment) comments.sort(key=lambda a: a.date) The comments are currently sorting into this order (which looks unsorted but is definitely going through the sort function): Aug. 21, 2020, 4:17 p.m. Aug. 21, 2020, 3:04 p.m. Aug. 21, 2020, 12:10 p.m. Why are they not sorting into any particular order, and how can I sort them correctly? -
Django manage.py shell save() doesn't save to postgresql database
I am new to Django. Testing out a simple application (test_cedar_app) with a PostgreSQL database called test_cedar. I have the following model for the application: class answer_key(models.Model): answer_text = models.CharField(max_length=20) def __str__(self): return self.answer_text I made a migration and applied it, and verified in my psql command-line client with \dt that the schema was created properly. I opened the Django command-line client using python manage.py shell and entered the following: ak_1 = answer_key(answer_text='Yes') ak_2 = answer_key(answer_text='No') ak_1.save() ak_2.save() These appeared to save, as the following revealed that the full query set for answer_key contains ak_1 and ak_2: from test_cedar_app.models import answer_key answer_key.objects.all() returned <QuerySet [<answer_key: Yes>, <answer_key: No>]> However, if I then enter the psql command-line (psql test_cedar), and enter the following: SELECT * FROM test_cedar_app_answer_key Nothing appears. Why do my changes not propagate to the database as it appears within the psql command-line tool? -
Issues with Secret Key when deploying Django App to Heroku
I keep getting django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. when trying to deploy my django app to heroku. I'm using python-dotenv and my settings.py file looks like this: import os from dotenv import load_dotenv load_dotenv() SECRET_KEY = os.getenv("DJANGO_SECRET_KEY") And the .env file (which is in my .gitignore file has the DJANGO SECRET KEY stored: export DJANGO_SECRET_KEY=mykeyhere I'm using pipenv if it helps - everything is working fine locally, but heroku doesn't seem to pick up on the variable. Any thoughts? (I also tried adding the secret key as a config variable on the heroku dashboard without success) -
SQLite 3.8.3 or later is required
I am really confused on why it keep saying that I need to be 3.8.3 or higher when I just updated it? https://i.stack.imgur.com/Ojs4n.png -
Why is django allauth redirecting to /accounts/login/?=next/MY_PAGE instead of logging in?
I am attempting to handle user authentication on a site using Django allauth. However, upon entering a username and password and clicking "log in" on my site, I am redirected to /accounts/login/?=next/MY_PAGE and the login page is simply reloaded. I have seen a number of similar questions, and I know that sometimes people run into issues with this when authenticating with socials, but I am not using any form of social authentication. I already have the LOGIN_REDIRECT_URL set to the desired page's URL, and I attempted to create an adapter as follows: class AccountAdapter(DefaultAccountAdapter): def is_open_for_signup(self, request): return getattr(settings, "ACCOUNT_ALLOW_REGISTRATION", True) def get_login_redirect_url(self, request): path = "/news/" return path where get_login_redirect_url should direct the application to the desired page. I have read in other posts that the fact that the next page (in this case "News") isn't being loaded means that allauth is not actually logging me in, and that's why I end up just getting the login page reloaded. Would anyone be able to point me in the right direction? Thanks! -
django_filter: remove 'ordering=' in url when ordering is empty string
How do i remove 'ordering=' from the URL when the ordering dropdown menu is set to None or '----' in this cause, which is the default option. '&ordering=' showing up in url Demo Link filters.py class BrandFilter(django_filters.FilterSet): brand = django_filters.ModelMultipleChoiceFilter(widget=forms.CheckboxSelectMultiple) category = django_filters.ModelMultipleChoiceFilter(widget=forms.CheckboxSelectMultiple) ordering = django_filters.OrderingFilter( choices = ( ('-is_featured', 'Featured'), ('-created_at', 'Date, New to Old'), ('created_at', 'Date, Old to New' ), ), fields = ( ('is_featured', 'featured'), #{model field name, parameter in the URL} ('created_at', 'created'), ('price', 'price'), ), field_labels = { 'is_featured': 'Featured', #{model field name, human readable label} 'created_at': 'Date', 'price': 'Price', } ) class Meta: model = Product fields = ('brand','category') def __init__(self, products= "", category=Category.objects.none(),*args, **kwargs): super(BrandFilter, self).__init__(*args, **kwargs) self.filters['brand'].queryset = Brand.objects.filter(product__in=products).distinct() self.filters['category'].queryset = category -
Django test db schema missing columns present in live db
I'm trying to set up more robust testing for my Django project but upon running python manage.py test I get an error: Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.InFailedSqlTransaction: current transaction is aborted, commands ignored until end of transaction block Presumably caused by: postgres_1 | 2020-08-21 16:15:11.365 UTC [441] STATEMENT: CREATE DATABASE "test_postgres" postgres_1 | 2020-08-21 16:15:16.594 UTC [443] ERROR: column memberships_membership.level does not exist at character 151 postgres_1 | 2020-08-21 16:15:16.594 UTC [443] STATEMENT: SELECT "memberships_membership"."id", "memberships_membership"."created_at", "memberships_membership"."modified_at", "memberships_membership"."name", "memberships_membership"."level", "memberships_membership"."stripe_id", "memberships_membership"."active", "memberships_membership"."info", "memberships_membership"."amount", "memberships_membership"."interval", "memberships_membership"."interval_count", "memberships_membership"."currency", "memberships_membership"."desktop_access", "memberships_membership"."past_projects" FROM "memberships_membership" WHERE ("memberships_membership"."active" = true AND "memberships_membership"."info" = 'Default free plan that allows TradePros to view Jobs/Leads but not interact with them or any TradeUser.' AND "memberships_membership"."level" = 1 AND "memberships_membership"."name" = 'Trades') postgres_1 | 2020-08-21 16:15:16.595 UTC [443] ERROR: current transaction is aborted, commands ignored until end of transaction block This is odd because the column is certainly present in the admin dashboard and even upon inspecting the database, we observe that the level column is there: postgres=# \d memberships_membership Table "public.memberships_membership" Column | Type | Collation | Nullable | Default ----------------+--------------------------+-----------+----------+-------------------------------------------------- -- id | integer | | not null … -
wagtail collectstatic is failing
I'm using python 3.7 , wagtail 2.10 After: python manage.py collectstatic I have the errors below. My insite about the issue is that there is a Django related problem about STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage' The files not founded must be used by Django admin. Can't figured out until now how to solve the problem. Post-processing 'bootstrap3/css/bootstrap.min.css' failed! ... File "/home/mihai/env_wagtail2/lib/python3.7/site-packages/django/contrib/staticfiles/storage.py", line 93, in hashed_name raise ValueError("The file '%s' could not be found with %r." % (filename, self)) ValueError: The file 'bootstrap3/fonts/glyphicons-halflings-regular.eot' could not be found with <django.contrib.staticfiles.storage.ManifestStaticFilesStorage object at 0x7fa45bdc5160>. -
Creating multiple objects with bulk_create() or models.Manager in Django
Let's say I have 2 sports modalities in the Athlete class, each with 7 categories and in each category there are 20 athletes. My goal is to fill out a form with training information about Tactic or Technique or Conditioning, of a specific modality/category, that can populate the 20 athletes at once. I'm only using djando Admin, so I don't have views.py Many websites indicate using bulk_create(), which receives a list as input, to create several objects. Another option seems to be to overwrite the object manager with models.Manager. I would like to know if any of these options apply to buy problem and how I could use them. I hope the information has been clear. Thank you. models.py class Athlete(models.Model): # Modalities BASKETBALL = 'Basketball' VOLLEYBALL = 'Voleyball' MODALITIES = [ (BASKETBALL, 'Basketball'), (VOLLEYBALL, 'Voleyball'), ] # Categories U12 = 'Under 12' U13 = 'Under 13' U14 = 'Under 14' U15 = 'Under 15' U17 = 'Under 17' U19 = 'Under 19' U21 = 'Under 21' CATEGORIES = [ (U12, 'Under 12'), (U13, 'Under 13'), (U14, 'Under 14'), (U15, 'Under 15'), (U17, 'Under 17'), (U19, 'Under 19'), (U21, 'Under 21'), ] id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False) modalities = … -
Get data from Django REST Framework into Vue & calling data from different components
I managed to get the data from my Django database into my Vue file. However, as this data will be used in multiple components, I want to make 1 data.js sheet from where I can call the data. Code in data.js file where I want to call the InvoiceData from. export default { name: 'InvoiceData', data(){ return { InvoiceData: [], } }, async created(){ var response = await fetch('http://127.0.0.1:8000/api/invoices/'); this.InvoiceData = await response.json(); },} My Code in component.vue file <template> <div> {{InvoiceData}} </div> </template> <script> import InvoiceData from "../../data" export default { name: 'componentfile', </script> when the codes are together in one Vue file, it works. <template> <div> {{InvoiceData}} </div> </template> <script> export default { name: 'InvoiceData', data(){ return { InvoiceData: [], } }, async created(){ var response = await fetch('http://127.0.0.1:8000/api/invoices/'); this.InvoiceData = await response.json(); },} </script> What am I doing wrong? Thanks for the help! -
Regex in django templates to match bold
im trying to define a function that renders Markdown, from .md formatted files, into HTML safely. Note: In this example i only try to bold text. What i got so far: def query(request, title_name): content = util.get_entry(title_name) bold_pattern = re.compile('[(\*\*|__)]{2}(?P<bold_text>[\w\s]+)[(\*\*|__)]{2}') bold_matches = re.findall(bold_pattern, content) #Returns list for match in bold_matches: for word in content: word = word.replace(match, f'<strong>{word}</strong>') word = mark_safe(word) return render(request, ".../entry.html",{ "content": content, ... }) The issue: It doesn't mark_safe the substring or it doesn't appear. {% extends "encyclopedia/layout.html" %} {% block title %}{{ title }}{% endblock title %} {% block body %} {{content}} <p>Edit this page <a href="{% url 'edit' title %}">here</a></p> {% endblock body %} -
Sqlite unable to recognise token ":"
I'm using Django Admin to create a port, here's how the model of the port is class Port(models.Model): interface = models.CharField(max_length=100) description = models.CharField(max_length=100) duplex = models.CharField(max_length=100) link_status = models.CharField(max_length=100) protocol_status = models.CharField(max_length=100) speed = models.CharField(max_length=100) access_vlan = models.CharField(max_length=100) native_vlan = models.CharField(max_length=100) admin_mode = models.CharField(max_length=100) mode = models.CharField(max_length=100) switchport = models.CharField(max_length=100) switchport_negotiation = models.CharField(max_length=100) trunking_vlans = ArrayField(models.TextField(blank=False), blank=False) switch = models.ForeignKey(Switch, on_delete=models.CASCADE) class Meta: unique_together = (("interface", "switch"),) def __str__(self): return f"Interface {self.interface}, description: {self.description}, duplex: {self.duplex}, " \ f"link_status:{self.link_status}, protocol_status: {self.protocol_status}, speed: {self.speed}, " \ f"access_vlan:{self.access_vlan}, native_vlan: {self.native_vlan}, " \ f"trunking_vlans: {self.trunking_vlans}, switch: {self.switch} " in the Django admin, when I use this: https://imgur.com/a/Tw79VDF as an input, the following error appears: File "/home/dias/ssc-webapp/ssc_django/venv/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py", line 396, in execute return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: unrecognized token: ":" During handling of the above exception, another exception occurred: ... File "/home/dias/ssc-webapp/ssc_django/venv/lib/python3.8/site-packages/django/db/backends/sqlite3/operations.py", line 141, in _quote_params_for_last_executed_query return cursor.execute(sql, params).fetchone() sqlite3.InterfaceError: Error binding parameter 12 - probably unsupported type. -
Django Database Model Terminal issue
I've tried to run Django database with this command (python manage.py makemigrations) And I've got an issue I wish you can help me to handle this problem, Thank you very much Terminal -
AttributeError: module 'MySQLdb.constants.FIELD_TYPE' has no attribute 'JSON' while migrating in Django
I do not know in what way solve this error. Any hints? I have simple Django projects and receive this error when try to do python3 manage.py migrate. This is related to any programming error in app or this is possible there is any error related to installation of mysql and completeness of its packages? Maybe there is any error in manage.py file? Or maybe this is case in not compatible version of Django and mysql? Traceback (most recent call last): File "manage.py", line 23, in <module> execute_from_command_line(sys.argv) File "/home/anna/.local/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/anna/.local/lib/python3.7/site-packages/django/core/management/__init__.py", line 377, in execute django.setup() File "/home/anna/.local/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/anna/.local/lib/python3.7/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/home/anna/.local/lib/python3.7/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/anna/.local/lib/python3.7/site-packages/django/contrib/auth/models.py", line 2, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/home/anna/.local/lib/python3.7/site-packages/django/contrib/auth/base_user.py", line 48, in <module> class AbstractBaseUser(models.Model): File "/home/anna/.local/lib/python3.7/site-packages/django/db/models/base.py", line 122, … -
Django multiple requests made when passing variable
I am trying to create an update form from an inlineformset and include a button that checks the next record. Here is my view: def update_challenges(request, challenge_id): challenge_ids = list(ChallengeModel.objects.values_list('id', flat=True)) next_index = challenge_ids.index(int(challenge_id)) + 1 next_challenge_id = challenge_ids[next_index] challenge = ChallengeModel.objects.get(pk=challenge_id) RoundFormset = inlineformset_factory(ChallengeModel, Round, fields=('index','description'),extra=0, widgets = { 'description': TextInput(), 'index':NumberInput() }) VarFormset = inlineformset_factory(ChallengeModel, Var, fields=('name',),extra=0) if request.method == 'POST': round_formset = RoundFormset(request.POST, instance=challenge) var_formset = VarFormset(request.POST, instance=challenge) if round_formset.is_valid() and var_formset.is_valid(): round_formset.save() var_formset.save() return redirect('update_challenges', challenge_id=challenge.id) round_formset = RoundFormset(instance=challenge) var_formset = VarFormset(instance=challenge) return render(request, 'drinking_game/update_challenges.html', {'round_formset':round_formset, 'var_formset':var_formset, 'challenge_id':challenge_id, 'next_challenge_id':next_challenge_id}) And here is the button I use for going to the next challenge:<button class="home-play-btn" onclick="location.href='{% url 'update_challenges' next_challenge_id %}'">Next challenge</button> However, when I check the output of my console, a new get request to the old url gets made right after the new request. This looks the following: [21/Aug/2020 15:29:23] "GET /update_challenges/221/ HTTP/1.1" 200 6373 [21/Aug/2020 15:29:23] "GET /update_challenges/220/ HTTP/1.1" 200 6339 The url path for this view is path('update_challenges/<challenge_id>/', views.update_challenges, name='update_challenges') What goes wrong that the old request is also made? Thanks. -
How to fix Blocked a frame with origin "https://s3.amazonaws.com" from accessing a cross-origin frame
I have integrated the SCORM xblock with edx-plaform but I am trying to launch my SCORM course it is giving me an error in chrome console. scormfunctions.js:38 Uncaught DOMException: Blocked a frame with origin "https://s3.amazonaws.com" from accessing a cross-origin frame. at ScanForAPI (https://s3.amazonaws.com/dev-ironwood-edx-uploads/scorm/aea0be6310754d3aab1649c5282bbd29/c8d75aa6c54a807e870b6afd4dd9a817aacaccc3/shared/scormfunctions.js:38:16) The exception I am sharing above is raising when a javascript function is trying to access the window.variable of the parent window, and browser is blocking that access to prevent clickjacking attacks. I have tried to search on StackOverflow and other forums but I am unable to find a solution. I have the idea, I will have to play with Content-Security-Policy I will be grateful if anyone can help me in pointing out the header values. -
Python Django PCF SSO
I am trying to enable the SSO service on PCF for my Django application. All the information I found online seems don't give a direct pointer, they are either: you need to set both Provider (Resource URL) and application together, or or, correct examples using Java Spring which hides the details I want to know Anyone successfully done it, may you share the procedures or the library you used? Thanks for your help. -
How can I save data from form in base?
I am study python and Django now. I don't understand, why my form doesn't save and haven't any errors. Here is my code: Model: class TelegramSettings(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, related_name='TelegramSettings', default=0 ) bot_name = models.CharField(max_length=255) bot_address = models.CharField(max_length=255) bot_token = models.CharField(max_length=255) def __str__(self): return f'{self.bot_name}: {self.bot_token}' Form: class TelegramSettingsForm(forms.ModelForm): class Meta: model = TelegramSettings fields = ['bot_name', 'bot_address', 'bot_token'] labels = { 'bot_name': 'Имя бота', 'bot_address': 'Адрес бота', 'bot_token': 'Токен' } widgets = { 'bot_token': forms.TextInput( attrs={'size': 30, 'placeholder': '522081070:AAFuXy8ngp32_Cv-sa7a0exdDsfvtraCjVA'}), 'bot_address': forms.TextInput( attrs={'size': 30, 'placeholder': '@somename_bot'}), 'bot_name': forms.TextInput( attrs={'size': 30, 'placeholder': 'Для моего канала'}), } View: @login_required(login_url="/login/") def telegram_settings_view(request): template_name = 'settings.html' saved_data = TelegramSettings.objects.get(user=request.user.id) if request.method == 'POST': form = TelegramSettingsForm(request.POST, instance=request.user) if form.is_valid: form.save(commit=False) webhook = bot_setwebhook(form.cleaned_data['bot_token']) if webhook: bot_deletewebhook(saved_data.bot_token) form.save(commit=True) context = {'form': form, 'is_updated': 'ok'} return render(request, template_name, context) context = {'form': form, 'is_updated': 'error'} return render(request, template_name, context) return render(request, template_name, {'form': form, 'is_valid': form.is_valid()}) if request.method == 'GET': # form = TelegramSettingsForm(initial=model_to_dict(saved_data)) form = TelegramSettingsForm(instance=saved_data) context = { 'form': form, } return render(request, template_name, context) When I generate POST request from my template, everything is ok, but data not saved in base! I am looking for my request in connection(from django.db import … -
How to generate these filenames?
Today most of the website use following types of file names for their static assets. For example, <link rel="stylesheet" href="./assets/app.98443-as3e-adwe3-ddfef-3ddd-de3dsds.css"> The long string between the filename (Here 'app') and the file extension (Here '.css') changes every time when a page is reloaded. I want to know how to achieve this in Django. -
Django | Apply FilterSet within Multiple Models
I'm running a query in Django for a model. However, I would like to know if there is some way possible to extend the query to other models. I'll show my files to exemplify and point out what is exactly that I'm trying to do. models.py from django.db import models class SomeThings(models.Model): id_thing = models.PositiveIntegerField(blank=False, primary_key=True) thing_1= models.PositiveIntegerField(blank=False) thing_2= models.PositiveIntegerField(blank=False) class SomeStuff(models.Model): id_thing = models.OneToOneField(SomeThings, on_delete=models.PROTECT) stuff_1 = models.CharField(max_length=255, blank=False) stuff_2 = models.CharField(max_length=255, blank=False) filters.py import django_filters from .models import * class myFilter(django_filters.FilterSet): class Meta: model = SomeThings fields = '__all__' views.py from django.shortcuts import render from django.http import HttpResponse from .filters import myFilter def search(request): products = SomeThings.objects.all() filter= myFilter(request.GET,queryset=products) products= filter.qs context = {'products':products,'filter':filter,} return render(request, 'search.html', context) search.html {% load static %} ... some html stuff ... <form method="get"> {{ filter.form.thing_1 }} {{ filter.form.thing_2 }} <button class="btn btn-primary" type="submit"> Search </button> </form> Basically, my filter looks indise SomeThings model and renders the query in search.html, however, there is some information in SomeStuff that I would like to use as part of my filter. Here is my pseudo code of what I'm trying to do in search.html {% load static %} ... some html stuff ... <form method="get"> … -
POST Ant Design Upload file with axios to django ImageField
How can i send Ant Design Upload file into my Django backend model ImageField. I am using axios to use PUT method as updating users profiel. At the moment i set my image into state and access file object to send it to my backend. This however throws 404 error. Should i somehow change my file data before POSTing it or what could be issue here? File where i post: state = { file: null, }; handleImageChange(file) { this.setState({ file: file }) console.log(file) }; handleFormSubmit = (event) => { const name = event.target.elements.name.value; const email = event.target.elements.email.value; const location = event.target.elements.location.value; const image = this.state.file; const sport = this.state.sport; axios.defaults.headers = { "Content-Type": "application/json", Authorization: this.props.token } const profileID = this.props.token axios.patch(`http://127.0.0.1:8000/api/profile/${profileID}/update`, { name: name, email: email, location: location, sport: sport, image: image, }) .then(res => console.log(res)) .catch(error => console.err(error)); } when i console.log(file), i can correctly see my file that i have uploaded, but i think sending it causes error -
Unable to connect to Django app in Docker container with Nginx
I'm trying to deploy a Django app locally with django/cookiecutter on Docker using nginx and mkcert for local certifiactes. This sets up an nginx container using jwilder/nginx-proxy:alpine. I'm able to connect to the app at 127.0.0.1:8000 but now I'm trying to develop locally with HTTPS using mkcert. My steps for setting up are as follows: Generate certificates with mkcert, in which I set the url as my-dev-env.local and the key and cert as my-dev-env.local.key and my-dev-env.local.crt. Move the key and cert files into the projects ./cert directory Add the nginx-proxy service to my docker-compose file: nginx-proxy: image: jwilder/nginx-proxy:alpine container_name: nginx-proxy ports: - "80:80" - "443:443" volumes: - /var/run/docker.sock:/tmp/docker.sock:ro - ./certs:/etc/nginx/certs restart: always depends_on: - django Add environment variables in my Django app: # HTTPS # ------------------------------------------------------------------------------ VIRTUAL_HOST=my-dev-env.local VIRTUAL_PORT=8000 Add "my-dev-env.local" to ALLOWED_HOSTS in my Django settings. Everything appears to build and run successfully and as I said, I can connect to the app at http://localhost:8000/. When I attempt to reach https://my-dev-env.local/ I get nowhere: This site can’t be reached my-dev-env.local’s server IP address could not be found. DNS_PROBE_FINISHED_NXDOMAIN I'm confused how my browser is supposed to know to connect to the app when I type in https://my-dev-env.local/. Is there something … -
AttributeError: 'DeferredAttribute' object has no attribute '_meta'
I got this error I don't understand the cause of the error. -
django deployed project raised ascii error code
I deployed my Django project that uses Apache and MySQL. all apps features work fine, but in an application's views.py, when I try to access it, it raises this error. UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 9735: ordinal not in range(128) it works fine in localhost I searched a lot but none of them works for me. The views.py of the app has many queries (for calculating), annotate and aggregate also Case(When())? this is my error.log [Fri Aug 21 14:30:46.907352 2020] [wsgi:error] [pid 20969:tid 140683116439296] [remote 95.159.84.254:12151] File "/var/www/projectname/venv/lib/python3.6/site-packages/django/views/debug.py", line 94, in technical_500_response [Fri Aug 21 14:30:46.907356 2020] [wsgi:error] [pid 20969:tid 140683116439296] [remote 95.159.84.254:12151] html = reporter.get_traceback_html() [Fri Aug 21 14:30:46.907362 2020] [wsgi:error] [pid 20969:tid 140683116439296] [remote 95.159.84.254:12151] File "/var/www/projectname/venv/lib/python3.6/site-packages/django/views/debug.py", line 332, in get_traceback_html [Fri Aug 21 14:30:46.907379 2020] [wsgi:error] [pid 20969:tid 140683116439296] [remote 95.159.84.254:12151] t = DEBUG_ENGINE.from_string(fh.read()) [Fri Aug 21 14:30:46.907387 2020] [wsgi:error] [pid 20969:tid 140683116439296] [remote 95.159.84.254:12151] File "/usr/lib/python3.6/encodings/ascii.py", line 26, in decode [Fri Aug 21 14:30:46.907391 2020] [wsgi:error] [pid 20969:tid 140683116439296] [remote 95.159.84.254:12151] return codecs.ascii_decode(input, self.errors)[0] [Fri Aug 21 14:30:46.907402 2020] [wsgi:error] [pid 20969:tid 140683116439296] [remote 95.159.84.254:12151] UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 9735: ordinal not in range(128) [Fri Aug 21 … -
Is there any way to capture image from webcam and store it in database using Django
I'm trying to capture image from webcam and store it in database using Django, But I'm getting " 'method' object is not subscriptable" this error. I am using javascript to use webcam to capture image and assign that image to image tag using js. Is there any way to access webcam to capture image and then process it to store into database in Django or is it possible by using django-forms?? Here's my Views.py def register(request): if (request.method == 'POST'): rollNumber = request.POST['rollNumber'] firstname = request.POST['firstname'] lastname = request.POST['lastname'] email =request.POST['email'] phone = request.POST['phone'] year = request.POST['year'] shift = request.POST['shift'] img = request.POST.get['student_img'] student = Student.objects.get() student.rollNumber = rollNumber student.firstname = firstname student.lastname = lastname student.phoneNumber = phone student.email = email student.year = year student.shift = shift student.image = img student.save() print("data recieved") return HttpResponse("Image upload successful\n Welcome " + firstname + " " + lastname) else: print("Error") return HttpResponse("Error") Here's index.html {% load static %} <!doctype html> <html> <body> <div class="content-agileits"> <h1 class="title">Student registration Form</h1> <div class="left"> <form action="register" method="post" enctype="multipart/form-data" data-toggle="validator"> {% csrf_token %} <div class="form-group"> <input type="text" class="form-control" id="firstname" name="firstname" placeholder="First Name" data-error="Enter First Name" required> <div class="help-block with-errors"></div> </div> <div class="form-group"> <input type="text" class="form-control" id="lastname" name="lastname" …