Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
UNIQUE constraint failed in django test client
I have a code like this inside tests.py: thirduser = User( username = "thirduser", password = "12345678" ) thirduser.save() third_user = Profile( user = thirduser ) third_user.save() it returns the error of UNIQUE... If I remove third_user.save() it works. But when I want to assign it to my project as project01 = Project( user = third_user, title = "prg01", description = "dsc01", category = cleaning, deadline = deadline, date_posted = date_posted, status = OPEN ) project01.save() Then it returns another error of save() prohibited to prevent data loss due to unsaved related object 'user'. Note: The user for project should be from Profile model that I have in my code. and Profile model has a field named user which is from User (from django.contrib.auth.models import User) -
'Update' in model results in overwriting
I have a code here to update a field in database which is null initially. dumlist=['ss','bb'] for ntn in imggetvalues: for datas in dumlist: imgget.update(data=datas) where imgget gives objects of the Django ORM imgget=Model.objects.filter(page_num=3) imggetvalues=[smtng for smtng in imgget] But this code only overwrites the previous entry as the inner loop runs. How can I get 1st value from dumlist to update 1st field in model object and 2nd in 2nd field,considering there are 2 objects? -
Django - How to subclass a CBV so that it will render according to a condition?
I am at a point where I need to check whether a user is using facebook or google-auth to log in or their e-mail address and password. So, before using PasswordResetView, I would like to check this and do something different according to the answer. Can somebody tell me how to subclass this CBV so that I can do check for a condition before rendering? Thanks in advance! -
How to add custom headers in django test cases?
I have implented a custom authentication class in django rest framework which requires client id and client secret on user registration in headers. I am writing test cases for user registration like this:- User = get_user_model() client = Client() class TestUserRegister(TestCase): def setUp(self): # pass self.test_users = { 'test_user': { 'email': 'testuser@gmail.com', 'password': 'Test@1234', 'username': 'test', 'company': 'test', 'provider': 'email' } } response = client.post( reverse('user_register'), headers={ "CLIENTID": <client id>, "CLIENTSECRET": <client secret> }, data={ 'email': self.test_users['test_user']['email'], 'username': self.test_users['test_user']['username'], 'password': self.test_users['test_user']['password'], 'company': self.test_users['test_user']['company'], 'provider': self.test_users['test_user']['provider'], }, content_type='application/json', ) self.assertEqual(response.status_code, status.HTTP_201_CREATED) def test_register(self): response = client.post( reverse('user_register'), headers={ "CLIENTID": <client id>, "CLIENTSECRET": <client secret> }, data={ "first_name": "john", "last_name": "williams", "email": "john@gmail.com", "password": "John@1234", "username": "john", "company": "john and co.", "provider": "email", }, content_type="application/json" ) self.assertEqual(response.status_code, status.HTTP_201_CREATED) Here is my custom authentication class:- from oauth2_provider.models import Application from rest_framework import authentication from rest_framework.exceptions import APIException class ClientAuthentication(authentication.BaseAuthentication): @staticmethod def get_client_credentials(request): try: client_id = request.headers.get('CLIENTID') client_secret = request.headers.get('CLIENTSECRET') except: raise APIException(detail="Missing Client Credentials", code=400) return { 'client_id': client_id, 'client_secret': client_secret } def authenticate(self, request): credentials = self.get_client_credentials(request) client_instance = Application.objects.filter( client_id=credentials['client_id'], client_secret=credentials['client_secret'], ).first() if not client_instance: raise APIException("Invalid client credentials", code=401) return client_instance, None But it is still giving me 500 internal … -
local variable 'post_image' referenced before assignment [duplicate]
I am very new to python and django, am making an app using beautifulsoup to extract some infos from an eCommerce site, everything worked perfectly until i tried to extract images. i added the class of the img tag and tried to extract the src but it ended up giving this error: UnboundLocalError at /new_search local variable 'post_image' referenced before assignment Request Method: POST Request URL: http://127.0.0.1:8000/new_search Django Version: 2.2.5 Exception Type: UnboundLocalError Exception Value: local variable 'post_image' referenced before assignment Exception Location: C:\Users\Ahmed\codelist\myapp\views.py in new_search, line 51 Python Executable: C:\Users\Ahmed\Anaconda3\python.exe Python Version: 3.7.4 Python Path: ['C:\\Users\\Ahmed\\codelist', 'C:\\Users\\Ahmed\\Anaconda3\\python37.zip', 'C:\\Users\\Ahmed\\Anaconda3\\DLLs', 'C:\\Users\\Ahmed\\Anaconda3\\lib', 'C:\\Users\\Ahmed\\Anaconda3', 'C:\\Users\\Ahmed\\Anaconda3\\lib\\site-packages', 'C:\\Users\\Ahmed\\Anaconda3\\lib\\site-packages\\win32', 'C:\\Users\\Ahmed\\Anaconda3\\lib\\site-packages\\win32\\lib', 'C:\\Users\\Ahmed\\Anaconda3\\lib\\site-packages\\Pythonwin'] Server time: Mon, 23 Mar 2020 07:28:15 +0000 my view.py final_postings = [] for post in post_listings: if post.find(class_='_2LFGJH'): post_title = post.find(class_='_2LFGJH').text elif post.find(class_='_2cLu-l'): post_title = post.find(class_='_2cLu-l').text else: post_title = post.find(class_='_3wU53n').text post_url = post.find('a').get('href') post_price = post.find(class_='_1vC4OE').text if post.find(class_='_1Nyybr _30XEf0'): post_image = post.find(class_='_1Nyybr _30XEf0').get('src') print(post_image) final_postings.append((post_title, post_url, post_price, post_image)) my new_search.html file {% extends 'base.html' %} {% block content %} <div class="container"> <style> .column { float: left; width: 50%; } </style> <h2 style="text-align: center">{{ search | title }}</h2> <div class="row"> <div class="column"> <h4 style="text-align: center;"><strong>Delta</strong></h4> {% for post in final_postings %} <div class="col s12"> <div … -
Django: Cannot reference a fieldname in template which contains a dot
The object which I pass from view to template has a few fields which are dynamically incremented and allocated e.g the object looks like: row = { 'id':id, 'input.object1':obj1 'input.object2':obj2 } I am trying to access the value of "input.object1" as "{{ row.input.object1 }}" in template. but the page does not show anything for this field (same for "input.object2") {% for row in row_list %} <tr> <td>{{ row.id }}</td> <td>{{ row.input.object1 }}</td> <td>{{ row.input.object2 }}</td> </tr> {% endfor %} Is there anyway to access these values in html ? Thanks in advance :) -
Better way of sending bulk requests to a remote API with Django Celery?
I have users table with 24K users on my Django website and I need to retrieve information for each of my users by sending a request to a remote API endpoint. So my plan is to use the Celery periodic tasks with a new model called "Job". There are two ways in my perspective: 1. For each user I will create a new Job instance with the ForeignKey relation to this user. 2. There will be a single Job instance and this Job instance will have a "users" ManyToManyField field on it. Then I'll process the Job instance(s) with Celery, for example I can process one Job instance on each run of periodic task for the first way above. But..there will be a huge amount of db objects for each bulk request series... Both of them seem bad to me since they are operations with big loads. Am I wrong? I guess there should be more convenient way of doing so. Can you please suggest me a better way, or my ways are good enough to implement? -
Django Admin Profile Display to the Front -End
I want to show my admin profile info to the front-end. Not editable profile just admin profile. How can I do that? -
Django - Email is not sent but its object is created in DB
When I try to send email via django, I notice that object of email is created and all fields (email, title, body) are in it, but the actual email is not sent. When I check celery logs, I see the following message: SMTPAuthenticationError(code, resp) smtplib.SMTPAuthenticationError: (535, b'5.7.8 Username and Password not accepted. Learn more `at\n5.7.8 https://support.google.com/mail/?p=BadCredentials` but I'm 100% sure that I use correct credentials and my mailbox isn't secured with two factor authentication Code in settings.py EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend" EMAIL_HOST = 'smtp.gmail.com' EMAIL_USE_TLS = True EMAIL_USE_SSL = False EMAIL_PORT = 587 EMAIL_HOST_USER = '*******@gmail.com' # my email, I'm sure it's correct EMAIL_HOST_PASSWORD = '********' # my password, I'm sure it's correct Code in views.py (contact form where I gather needed info - email, title, body) class ContactUs(CreateView): template_name = 'my_profile.html' queryset = Contact.objects.all() fields = ('email', 'title', 'body') success_url = reverse_lazy('index') def form_valid(self, form): response = super().form_valid(form) message = form.cleaned_data.get('body') subject = form.cleaned_data.get('title') email_from = form.cleaned_data.get('email') recipient_list = [settings.EMAIL_HOST_USER, ] send_email_async.delay(subject, message, email_from, recipient_list) return response Code in tasks.py (for celery) @shared_task() def send_email_async(subject, message, email_from, recipient_list): send_mail(subject, message, email_from, recipient_list, fail_silently=False) but it doesn't really matter if it's celery or not - email is not sent itself but … -
when i add a field in model,,this is not support migrate,that time showing this error
WARNINGS: ?: (mysql.W002) MySQL Strict Mode is not set for database connection 'default' HINT: MySQL's Strict Mode fixes many data integrity problems in MySQL, such as data truncation upon inse rtion, by escalating warnings into errors. It is strongly recommended you activate it. See: https://docs.djangop roject.com/en/3.0/ref/databases/#mysql-sql-mode Operations to perform: Apply all migrations: Hospitalapp, admin, auth, contenttypes, sessions Running migrations: No migrations to apply. -
Deploy elasticsearch + mongodb and django on different machines
I just used elasticsearch integrated with mongodb and django. I am using django-elasticsearch-dsl. I have run successfully on the same machine. Currently, I want to deploy django on one machine and elasticsearch mongodb on another machine. I transferred mongodb but with elasticsearch, I do not know how. In the settings in django, I have set: ELASTICSEARCH_DSL = { 'default': { 'hosts': 'ip-mongodb: 9200' }, } but got an error elasticsearch.exceptions.ConnectionError: ConnectionError (<urllib3.connection.HTTPConnection object at 0x7ffac85d7a58>: Failed to establish a new connection: [Errno 111] Connection refused) caused by: NewConnectionError (<urllib3.connection.HTTPConnection object at 0x7ffac85d7a58>: Failed to establish a new connection: [Errno 111] Connection refused) Hope everyone helps me solve this problem -
Need Help setting up Database Router for multiple mysql databases
I created a project that has two identical models for work from home(wfh) employees, and work from office (wfo) employees. I want wfh employee data to be stored in 'wfh' database and wfo data in 'wfo' database. Database used is mysql. However I am facing following troubles: 1) Migration fails with error: In allow_migrate() method in Router_name.py, model_name received multiple values. So I had to replace allow_migrate() method with allow_syncdb() which got rid of error and migrations were applied. 2)tables are not generated even though migrations are successful for all databases. Python shell is unable to add new employee entries to database (table does not exist error) 3)Creating superuser, after entering just the username, throws exception for improperly configured database 4)superuser created earlier (just after making project) on trying to login from admin panel gives incorrect credentials message Project Structure Project Folder | +--env | +--multi_db | +--basic_app | | | +--AuthRouter.py | +--DbRouter.py | +--models.py | +--multi_db | | | +--settings.py | +--manage.py settings.py DATABASES = { 'default': {}, 'auth_db': { 'NAME': 'auth_db', 'ENGINE': 'django.db.backends.mysql', 'HOST': '127.0.0.1', 'PORT': '3306', 'USER': '***', 'PASSWORD': '***', # connect options 'OPTIONS': {'init_command': "SET sql_mode='STRICT_TRANS_TABLES'", }, }, 'work_from_home':{ 'ENGINE': 'django.db.backends.mysql', 'HOST': '127.0.0.1', 'PORT': '3306', … -
Adding field to serializer with 2 foreign keys
I have 2 models that look like this: class Topic(models.Model): name = models.CharField(max_length=25, unique=True) def save(self, *args, **kwargs): topic = Topic.objects.filter(name=self.name) if topic: return topic[0].id super(Topic, self).save(*args, **kwargs) return self.id class PostTopic(models.Model): topic = models.ForeignKey(Topic, on_delete=models.CASCADE) post= models.ForeignKey(Post, on_delete=models.CASCADE) If the topic is already in the Topic table, then we return the id of that topic. We do not create another. When a user submits a Post with tagged topics (think of it as hashtags), then if those topics don't exist in the Topic table they will be created along with the relationship in PostTopic That being said, here's how my serializer looks: class PostSerializer(serializers.ModelSerializer): topics = serializers.ListField( child=serializers.CharField(max_length=256), max_length=3 ) class Meta: model = Post fields = ('user', 'status', 'topics') def create(self, validated_data): topics= validated_data.pop('topics') post = Post.objects.create(**validated_data) for topic in topics: topic_id = Topic(name=topic).save() PostTopic(post_id=post.id, topic_id=topic_id).save() return post Currently, my serializer gives me an AttributeError, because topics is not a field in Post. How can I fix this so that I can make it work? If I use PostTopic then how would I get the user to give the actual topics? -
get all value of foreign key table drf django
i have this tables. i want to get all the fields of teacher table from school. current its getting the name and employee field pointing to key of teacher class Teacher(models.Model): name = models.CharField(max_length=100) key = models.CharField(max_length=50,unique=True) value = models.CharField(max_length=50) def __str__(self): return self.name class School(models.Model): name= models.CharField(max_length=100) employee = models.ForeignKey(Teacher, to_field="key",on_delete=models.CASCADE) def __str__(self): return self.name serializers.py: class TeacherSerializer(serializers.ModelSerializer): class Meta: model = Teacher fields = ('name','key','value') class SchoolSerializer(serializers.ModelSerializer): teacher = TeacherSerializer(many=True, read_only=True) class Meta: model = School fields = ('name','employee','teacher') views.py: @api_view(['GET']) def SchoolList(APIView): queryset = School.objects.all().values('name','employee','employee__value') asd=[] for sdf in queryset: asd.append(sdf) serialized_obj = SchoolSerializer(queryset,many=True) return HttpResponse(json.dumps(serialized_obj.data)) traceback: traceback (most recent call last): File "/home/tboss/Desktop/environment/tryme/venv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/tboss/Desktop/environment/tryme/venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/tboss/Desktop/environment/tryme/venv/lib/python3.7/site-packages/django /core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/tboss/Desktop/environment/tryme/venv/lib/python3.7/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/tboss/Desktop/environment/tryme/venv/lib/python3.7/site-packages/django/views/generic/base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "/home/tboss/Desktop/environment/tryme/venv/lib/python3.7/site-packages/rest_framework/views.py", line 505, in dispatch response = self.handle_exception(exc) File "/home/tboss/Desktop/environment/tryme/venv/lib/python3.7/site-packages/rest_framework/views.py", line 465, in handle_exception self.raise_uncaught_exception(exc) File "/home/tboss/Desktop/environment/tryme/venv/lib/python3.7/site-packages/rest_framework/views.py", line 476, in raise_uncaught_exception raise exc File "/home/tboss/Desktop/environment/tryme/venv/lib/python3.7/site-packages/rest_framework/views.py", line 502, in dispatch response = handler(request, *args, **kwargs) File "/home/tboss/Desktop/environment/tryme/venv/lib/python3.7/site-packages/rest_framework/decorators.py", line 50, in handler return func(*args, **kwargs) File … -
Facing ModuleNotFoundError: No module named 'blog_project.wsgi'
I am trying to deploy the django application on heroku. The build was successfull however when I launched the application, I faced the import error. " No module named 'blog_project.wsgi'" . The application is running fine on the local environment. (blog) ashish@tiwari:~/Documents/Django/blog$ heroku logs --tail › Warning: heroku update available from 7.39.0 to 7.39.1. 2020-03-23T02:37:56.149348+00:00 app[web.1]: [2020-03-23 02:37:56 +0000] [4] [INFO] Listening at: http://0.0.0.0:57707 (4) 2020-03-23T02:37:56.149552+00:00 app[web.1]: [2020-03-23 02:37:56 +0000] [4] [INFO] Using worker: sync 2020-03-23T02:37:56.160538+00:00 app[web.1]: [2020-03-23 02:37:56 +0000] [10] [INFO] Booting worker with pid: 10 2020-03-23T02:37:56.170494+00:00 app[web.1]: [2020-03-23 02:37:56 +0000] [10] [ERROR] Exception in worker process 2020-03-23T02:37:56.170497+00:00 app[web.1]: Traceback (most recent call last): 2020-03-23T02:37:56.170497+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker 2020-03-23T02:37:56.170498+00:00 app[web.1]: worker.init_process() 2020-03-23T02:37:56.170498+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/workers/base.py", line 129, in init_process 2020-03-23T02:37:56.170499+00:00 app[web.1]: self.load_wsgi() 2020-03-23T02:37:56.170499+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/workers/base.py", line 138, in load_wsgi 2020-03-23T02:37:56.170499+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2020-03-23T02:37:56.170500+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/base.py", line 67, in wsgi 2020-03-23T02:37:56.170500+00:00 app[web.1]: self.callable = self.load() 2020-03-23T02:37:56.170501+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 52, in load 2020-03-23T02:37:56.170501+00:00 app[web.1]: return self.load_wsgiapp() 2020-03-23T02:37:56.170501+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 41, in load_wsgiapp 2020-03-23T02:37:56.170502+00:00 app[web.1]: return util.import_app(self.app_uri) 2020-03-23T02:37:56.170502+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/util.py", line 350, in import_app 2020-03-23T02:37:56.170503+00:00 app[web.1]: __import__(module) 2020-03-23T02:37:56.171265+00:00 app[web.1]: ModuleNotFoundError: No module named 'blog_project.wsgi' 2020-03-23T02:37:56.173904+00:00 app[web.1]: [2020-03-23 02:37:56 +0000] … -
how to check and pass the instance of the user in my form in Django?
Hi I'm trying to create a form that accepts Log from the user however I don't know how to pass the instance of the user. I'm used to creating a CreateView for this, however since I'm planning to use customized widgets and settings, I'm using a modelform to create logs for the user. My question is is this the same way as create view to check the instance of the user? Is it still the same as what I did to my createview which is: def form_valid(self,form) : form.instance.testuser = self.request.user return super().form_valid(form) Or do I have to do something else entirely? Here is my Forms.py: from django import forms from profiles.models import User from .models import DPRLog class DateInput (forms.DateInput): input_type = 'date' class Datefield (forms.Form): date_field=forms.DateField(widget=DateInput) class dprform(forms.ModelForm): class Meta: model = DPRLog widgets = {'reportDate':DateInput()} fields = ['status','login','logout','reportDate','mainTasks','remarks'] Models.py: from django.db import models from profiles.models import User from django.urls import reverse # Create your models here. class Points(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) points = models.IntegerField(default=0, null=False) def __str__(self): return self.user.username class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.png', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' class Manager(models.Model): manager = models.OneToOneField(User, on_delete=models.CASCADE) def __str__(self): return self.manager.full_name class Member(models.Model): … -
show sub categories actual category
class Category(models.Model): parent_category = models.ForeignKey('self',related_name='child_category_list',on_delete=models.SET_NULL,blank=True,null=True) name = models.CharField(max_length=255) cat_id = models.CharField(max_length=255,null=True,blank=True) path = models.TextField(null=True,blank=True) def pre_save_parent_category(sender,instance,**kwargs): instance.path = instance.name parent_category_obj = instance.parent_category while parent_category_obj is not None: instance.path = parent_category_obj.name + " > " + instance.path parent_category_obj = parent_category_obj.parent_category pre_save.connect(pre_save_parent_category,sender=Category) I have numerous categories if user input category id how can i show the sub categories of that category -
Django Rest FrameWork // Conditional Model of OneToOneField
I'm developing restful API with Django Rest Framework for a statistics homepage for Admin. The service is already in progress, and I attached Django to the database that has already been created. models.py was created through managy.py inspectdb. There are no foreign keys(or OneToOneField) in the existing tables. So I am trying to create a foreign key myself in the generated models.py. But I found a table that inserts PKs of multiple tables in one column. # models.py Amodel(models.Model): consult_id = models.IntegerField(primary_key=True) # number start from 100,000 .... Bmodel(models.Model): note_id = models.IntegerField(primary_key=True) # number start from 1 .... Cmodel(models.Model): consult_note_id = models.IntegerField(primary_key=True) # saved 'consult_id from Amodel' and 'note_id from Bmodel' with unique property. ... what_is = models.CharField(max_length=7, ...) # saved 'consult' for consult table's data and 'note' for note table's data I'm trying to replace that consult_note_id in the Cmodel with OneToOneField for a smoother ORM use. Expected code below. Cmodel(models.Model): consult_note_id = models.OneToOneField(Amodel or Bmodel, on_delete=models.SET_NULL, null=True, blank=True, db_column='consult_note_id') ... what_is = models.CharField(max_length=7, ...) Expected serialized result {consult_note_id : 100001, ..., what_is : consult}, {consult_note_id : 1, ..., what_is : note}, {consult_note_id : 100002, ..., what_is : consult}, {consult_note_id : 100003, ..., what_is : consult}, {consult_note_id : 2, … -
Django Rest Framework, is it possible to organize uploaded files by associated user?
I'm planning out a backend which takes in an email associated with a file upload. Would it be possible to make the backend create a new sub-folder (with the name being the uploaded email address) in my main media folder every time a file was uploaded with a new email, or put files into the corresponding sub-folder? I've tried to look up any examples of this, but haven't come across any. Thanks! -
How to annotate a queryset with an indirectly related table?
I've got the following table: class Parent: pass class Child: fk_parent = models.OneToOneField(Parent, on_delete=models.CASCADE) class Cousin: fk_parent = models.OneToOneField(Parent, on_delete=models.CASCADE) I want to get a queryset of Child that is annotated with it's Cousin. In PSQL, I would simply write: SELECT a.*, b.* FROM child a INNER JOIN cousin b ON b.fk_parent_id = a.fk_parent_id Is this possible? -
How can I solve this error [ModuleNotFoundError: No module named 'django.utils.inspect']
When I launch my Django project in a local server, It doesn't work with the errors. It seems finally has an ImportError of the Django, but first I want to solve the error brow. ModuleNotFoundError: No module named 'django.utils.inspect' in this case, how should I do? Would you mind telling me how should I solve this problem? Thank you in advance. detailed error Traceback (most recent call last): File "/Users/apple/GoogleDrive/project_django/harvest_timer/manage.py", line 10, in main from django.core.management import execute_from_command_line File "/Users/apple/GoogleDrive/project_django/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 13, in <module> from django.core.management.base import ( File "/Users/apple/GoogleDrive/project_django/venv/lib/python3.7/site-packages/django/core/management/base.py", line 11, in <module> from django.core import checks File "/Users/apple/GoogleDrive/project_django/venv/lib/python3.7/site-packages/django/core/checks/__init__.py", line 8, in <module> import django.core.checks.caches # NOQA isort:skip File "/Users/apple/GoogleDrive/project_django/venv/lib/python3.7/site-packages/django/core/checks/caches.py", line 2, in <module> from django.core.cache import DEFAULT_CACHE_ALIAS File "/Users/apple/GoogleDrive/project_django/venv/lib/python3.7/site-packages/django/core/cache/__init__.py", line 18, in <module> from django.core import signals File "/Users/apple/GoogleDrive/project_django/venv/lib/python3.7/site-packages/django/core/signals.py", line 1, in <module> from django.dispatch import Signal File "/Users/apple/GoogleDrive/project_django/venv/lib/python3.7/site-packages/django/dispatch/__init__.py", line 9, in <module> from django.dispatch.dispatcher import Signal, receiver # NOQA File "/Users/apple/GoogleDrive/project_django/venv/lib/python3.7/site-packages/django/dispatch/dispatcher.py", line 4, in <module> from django.utils.inspect import func_accepts_kwargs ModuleNotFoundError: No module named 'django.utils.inspect' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Users/apple/GoogleDrive/project_django/project/manage.py", line 21, in <module> main() File "/Users/apple/GoogleDrive/project_django/project/manage.py", line 16, in main ) from exc ImportError: … -
Why am I getting django.template.base.VariableDoesNotExist: Failed lookup for key [url] on all my Django webpages
Everything works as expected in my Django app, but I don't understand why I'm getting DEBUG messages as follows for all my webpages, the problem that I have with these messages is that it's unnecessarily filling up my log file (with about 300 lines at once): django.template.base.VariableDoesNotExist: Failed lookup for key [url] in [{'True': True, 'False': False, 'None': None}, {'csrf_token': <SimpleLazyObject: 'VBjv3GthwGz8kVX4aArtnnNKEpRzwtQvG4uv62GAQtXmJUOwtbP2zMiOBzWfigWgXha'>, 'request': <WSGIRequest: GET '/'>, 'user': <SimpleLazyObject: <function AuthenticationMiddleware.process_request.<locals>.<lambda> at 0x0000023C30CEEEA0>>, 'perms': <django.contrib.auth.context_processors.PermWrapper object at 0x0000023C3044C518>, 'messages': <django.contrib.messages.storage.fallback.FallbackStorage object at 0x0000023C304C9F60>, 'DEFAULT_MESSAGE_LEVELS': {'DEBUG': 10, 'INFO': 20, 'SUCCESS': 25, 'WARNING': 30, 'ERROR': 40}}, {}] django.template.base.VariableDoesNotExist: Failed lookup for key [title] in [{'True': True, 'False': False, 'None': None}, {'csrf_token': <SimpleLazyObject: 'VBjv3GthwGz8kVX4aArtnnNKEpRzwtQvG4uv62GAQtXmJUOwtbP2zMiOBzWfigWgXha'>, 'request': <WSGIRequest: GET '/'>, 'user': <SimpleLazyObject: <function AuthenticationMiddleware.process_request.<locals>.<lambda> at 0x0000023C30CEEEA0>>, 'perms': <django.contrib.auth.context_processors.PermWrapper object at 0x0000023C3044C518>, 'messages': <django.contrib.messages.storage.fallback.FallbackStorage object at 0x0000023C304C9F60>, 'DEFAULT_MESSAGE_LEVELS': {'DEBUG': 10, 'INFO': 20, 'SUCCESS': 25, 'WARNING': 30, 'ERROR': 40}}, {}] django.template.base.VariableDoesNotExist: Failed lookup for key [media] in [{'True': True, 'False': False, 'None': None}, {'csrf_token': <SimpleLazyObject: 'VBjv3GthwGz8kVX4aArtnnNKEpRzwtQvG4uv62GAQtXmJUOwtbP2zMiOBzWfigWgXha'>, 'request': <WSGIRequest: GET '/'>, 'user': <SimpleLazyObject: <function AuthenticationMiddleware.process_request.<locals>.<lambda> at 0x0000023C30CEEEA0>>, 'perms': <django.contrib.auth.context_processors.PermWrapper object at 0x0000023C3044C518>, 'messages': <django.contrib.messages.storage.fallback.FallbackStorage object at 0x0000023C304C9F60>, 'DEFAULT_MESSAGE_LEVELS': {'DEBUG': 10, 'INFO': 20, 'SUCCESS': 25, 'WARNING': 30, 'ERROR': 40}}, {}] I do have url variable in all my templates, used … -
How can I use filter() with Djongo to lookup a TextField?
Admin.py Models.py Example of a post at my Mongodb collection: My entire code: https://github.com/mtrissi/news_site_project So, I'm trying to develop an app with Django and with a Mongodb database. I'm using Djongo as the connector. All seems to work fine, except the search at the attribute 'content' of my model 'Post'. It should work fine with a simple posts = Post.filter(content__icontains=r_search). But it does not. My views.py are like this: How can I perform a search at the 'content' attribute? -
how to store conditional statement variable in django model?
i am trying to store manage_quota and govt_quota to my model choice_filling but the error says that above named variables are not defined. how do i store those values in database? here is my views.py def seat_info(request): global manage_quota, govt_quota if request.method == "POST": institute_code = request.POST['institute_code'] seats = request.POST['seates'] # s75 = int(seats) * 75 / 100 s25 = int(seats) * (25 / 100) # s25 = int(float(seats) * (25.0 / 100.0)) print("25% is ", s25) mq = request.POST['manage_quota'] mq15 = int(float(s25) * (15.0 / 100.0)) print("15% is ", mq15) # mq = float(mq) / 15.0 if float(mq) <= mq15: manage_quota = int(s25 * float(mq)) gov = request.POST['govt_quota'] gov10 = int(float(s25) * (10.0 / 100.0)) # gov = float(gov) / 10.0 if float(gov) <= gov10: govt_quota = int(s25 * float(gov)) clg_id = request.POST['clg_id'] fees = request.POST['fees'] course = request.POST['course'] s = seat_metrix(clg_id_id=clg_id, code=institute_code, total_seats=seats, course_id=course, govt_quota=govt_quota, manage_quota=manage_quota, fees=fees) s.save() return redirect('college-dashboard') strm = streams.objects.all() title = "Seat Information" page = "Seat Registration" return render(request, 'seat_info.html', {'strm': strm, 'title': title, 'page': page}) And the error traceback Traceback (most recent call last): File "C:\Users\Dell\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\Dell\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) … -
I want to put html tag in password_reset_email.html but it doesn't render. How can I render it?
I want to put html tag in password_reset_email.html but it doesn't render. How can I render it? Django version is 1.4 There is no content in the document, is there any way? https://django-doc-test-kor.readthedocs.io/en/old_master/topics/auth.html