Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django migration fails 'QuerySet' object has no attribute 'objects'
I have a set of models: class DebugConf(models.Model): is_setup = models.BooleanField(default=False) debug_setup_date = models.DateTimeField() def __str__(self): return self.is_setup class Currency(models.Model): currency_name = models.CharField(max_length=100) currency_value_in_dollars = models.FloatField() currency_value_in_dollars_date = models.DateTimeField() def __str__(self): return self.currency_name class User(models.Model): user_name = models.CharField(max_length=200) user_pass = models.CharField(max_length=200) join_date = models.DateTimeField() def __str__(self): return self.user_name class Transaction(models.Model): transaction_type = models.CharField(max_length=200) transaction_amount = models.FloatField() transaction_date = models.DateTimeField() transaction_currency = models.ForeignKey(Currency, on_delete=models.CASCADE) transaction_users = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.headline a project 'crypto' and an app 'manage_crypto_currency' nested into it: The app's views contains some initialization code: views.py: if IS_DEBUG_MODE: print('[!!!INFO!!!] DEBUG MODE SET! USING GENERATED TABLES') init_debug_tables() def init_debug_tables(): # Check if debug table has already been initialized debug_conf = DebugConf.objects.all() if debug_conf.objects.exists(): return At the moment, the db is not initialized; when running: python manage.py makemigrations manage_crypto_currency in the root (project dir): I get: [!!!INFO!!!] DEBUG MODE SET! USING GENERATED TABLES Traceback (most recent call last): File "manage.py", line 24, in <module> main() File "manage.py", line 20, in main execute_from_command_line(sys.argv) File "C:\projects\django\crypto-currency-board\venv\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\projects\django\crypto-currency-board\venv\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\projects\django\crypto-currency-board\venv\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "C:\projects\django\crypto-currency-board\venv\lib\site-packages\django\core\management\base.py", line 368, in execute self.check() File "C:\projects\django\crypto-currency-board\venv\lib\site-packages\django\core\management\base.py", line 392, in check all_issues = … -
Access django built in user
I'm currently trying to build a django application. I'm accessing django's built in user models and now want to access these to associate user input to the actual user. How would I go about accessing the user. So far I believe I would use django's ForeignKey, but I'm unsure on the correct reference? Thanks in advance -
When should I use annotations vs. model methods in Django?
I have a situation where I need to add additional data to the objects within a Queryset, and I have troubles understanding when it is really beneficial to perform queries that have annotations, over just implementing custom methods on the model class. As far as I know, when doing annotations all the work is done by the database engine and everything can be done in a single database hit (I think?). On the other hand, when implementing a method on the model class, additional queries might be performed if you need to get reverse lookups, or data from a foreign model. I just want to ask, is there any rule of thumb, or any guidance that you all consider for when to use one approach over the another? Especially if the annotations get really complex (e.g, using Q objects, Subqueries, GroupConcat, and so on) Thanks. -
Error occur when to register Django apps : save() got an unexpected keyword argument 'force_insert'
When I try to register, it show a error: save() got an unexpected keyword argument 'force_insert' def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Your account has been created! You are now able to login!') return redirect('users-login') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form': form}) -
Django throwing "'NoneType' object is not callable" error when trying to create an object
I've been trying to create a "Tag" object using get_or_create. When I do this, however, Django throws me a "NoneType' object is not callable" error. Below are relevant code blocks: def create_segments(self): fi = self.fi parser = self.parser self._get_soup(fi) paras = self.soup.find_all("w:p") tags = list() for para_num, para in enumerate(paras, start=1): para_object = self._create_para_object(fi, para_num, para) tags.append(self._create_tag_objects(para, para_object, fi)) <<<<<<<<<<<<<< THIS sentences = self._get_string_with_tags(paras, tags) self._create_segment_objects(sentences, parser, fi) The problem is with tags.append(self._create_tag_objects(para, para_object, fi)). para is a BeautifulSoup object, para_object is a Django Paragraph object which is created in one line above the problematic line, and fi is another Django object. Below is _create_tag_object. def _create_tag_objects(self, para, para_object, fi): tags = self._get_tag_xml(para) in_file_id = Tag.objects.filter(paragraph__projectfile=fi).count() + 1 for tag in tags: Tag.objects.get_or_create( paragraph=para_object, in_file_id=in_file_id + 1, tag_wrapper=tag[0] ) in_file_id += 1 return tags Below is the model for Tag and Paragraph. class Paragraph(models.Model): projectfile = models.ForeignKey(ProjectFile, on_delete=models.CASCADE) para_num = models.IntegerField() default_wrapper = models.TextField() class Tag(models.Model): paragraph = models.ForeignKey(Paragraph, on_delete=models.CASCADE) in_file_id = models.IntegerField() tag_wrapper = models.TextField() Below is the full traceback. Environment: Request Method: POST Request URL: http://localhost:8000/project/new Django Version: 3.1.2 Python Version: 3.8.5 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'users', 'translation', 'crispy_forms', 'storages', 'django_cleanup'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', … -
CSS, Bootstrap and Javascript is not working with Django
I'm trying to build a webapp as a final project in my degree, but I'm having problems with configuring the css with django. I already did a few recommendations on the internet without success. When I add "style" on tags it works properly, but when I tries to use the ".css" file it doesn't load. Could anyone help me please? Here is my html head: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href="{% static 'static/css/index.css' %}" rel="stylesheet" type="text/css"> <link rel="preconnect" href="{% static 'https://fonts.gstatic.com' %}"> <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script> <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDikjsB27i23XRQad382KBcFHKNxzZ--1w&callback=initAutocomplete&libraries=places&v=weekly" defer ></script> <link href="{https://fonts.googleapis.com/css?family=Roboto:400,700" rel="stylesheet"> <link href="{https://fonts.googleapis.com/css2?family=Sansita+Swashed&display=swap" rel="stylesheet"> <meta name="google" content="notranslate" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css"> <script src="{//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <title>The Queue</title> </head> My settings.py: STATIC_URL = '/static/' STATICFILES_DIRS = [(os.path.join(BASE_DIR, 'static'))] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') my urls.py: from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('queueApp.urls')), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) Directories: ├───queueApp │ │ admin.py │ │ apps.py │ │ models.py … -
Django FileNotFoundError at creating a pdf with xhtml2pdf
Im using xhtml2pdf to generate a pdf from a Django template but Im getting this error FileNotFoundError at /send-email [Errno 2] No such file or directory: 'media/test.pdf' this is the function Im using to generate the pdf def generate_pdf(template_src, context_dict={}): """ Function to generate a pdf in a static location from a django template""" template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument( BytesIO(html.encode("UTF-8")), result, link_callback=link_callback) file = open('media/test.pdf', "w+b") pisa_status = pisa.CreatePDF(html.encode('utf-8'), dest=file, encoding='utf-8') file.close() return True Im aware there is no media/test.pdf yet and I want it to create it if it doesn't exist but Im not sure how Also, I would like to be able to access the url of the file once created in order to attach it to an email I already got the sending email part but I need a url to the file I want to attach. I hope you guys can help me -
Merging list of dictionary values
I got a list of dictionary: data_list = [ { "user": "liudvikas", "virtual_devices": [ "bbfedf97-b090-416b-81bf-2f3b51eed4db" ], "power_plant": 1, "panels": [ { "panel": "Solet mono M60.6 325W WF", "max_power": 325.0, "price": 235.99, "maker": "SOLET", "panel_number": 12 } ] }, { "user": "bajarunas", "virtual_devices": [ "bbfedf97-b090-416b-81bf-2f3b51eed4db" ], "power_plant": 1, "panels": [ { "panel": "Solet mono M60.6 325W WF", "max_power": 325.0, "price": 235.99, "maker": "SOLET", "panel_number": 12 } ] }, { "user": "bajarunas", "virtual_devices": [ "7699609b-66ee-4c05-af2c-0001cabb65dc" ], "power_plant": 1, "panels": [ { "panel": "Solet mono M60.6 325W WF", "max_power": 325.0, "price": 235.99, "maker": "SOLET", "panel_number": 12 }, { "panel": "Lightway poli P60.6 275W", "max_power": 275.0, "price": 120.0, "maker": "Lightway", "panel_number": 18 } ] } ] I want to merge dictionaries that have the same username AND plant_id. The expected result: data_list = [ { "user": "liudvikas", "virtual_devices": [ "bbfedf97-b090-416b-81bf-2f3b51eed4db" ], "power_plant": 1, "panels": [ { "panel": "Solet mono M60.6 325W WF", "max_power": 325.0, "price": 235.99, "maker": "SOLET", "panel_number": 12 } ] }, { "user": "bajarunas", "virtual_devices": [ "7699609b-66ee-4c05-af2c-0001cabb65dc", "bbfedf97-b090-416b-81bf-2f3b51eed4db" ], "power_plant": 1, "panels": [ { "panel": "Solet mono M60.6 325W WF", "max_power": 325.0, "price": 235.99, "maker": "SOLET", "panel_number": 12 }, { "panel": "Lightway poli P60.6 275W", "max_power": 275.0, "price": 120.0, "maker": "Lightway", "panel_number": … -
How can i make my first form with a selected field prepopulate that field in a second form in Django
I'm new to Django, started learning it this week. I have made my models.py like so: class EmployeeTrack(models.Model): time = models.DateTimeField(default=datetime.now(), blank=False) eid = models.ForeignKey('Employee', on_delete=models.CASCADE, null=True, blank=False, verbose_name = 'Employee') tmp = models.DecimalField(max_digits=3, decimal_places=1, verbose_name='temperature') class Meta: verbose_name_plural='Employee Tracking' class Employee(models.Model): first_name= models.CharField(max_length=100, blank=False) last_name= models.CharField(max_length=100, blank=False) email= models.CharField(max_length=100, blank=False) My question now is how can I make a form, with one input field like for example id, and then enter a user id, transfer that user id to the form for the model EmployeeTrack and populate the eid field based on my previous input in the first form? -
Is there a way to delete the datas from django on a particular time when user is not using the website [duplicate]
I'm trying to delete the datas on Bangladesh time 10:00 PM with django. And i searched for it but there is no result. I'm thinking that i can solve it by datetime module, But I'm lost in this and I can't understand anything about it. I tried by this, x = datetime.datetime.now() # times = x.split(' ', 1) print(x) # I'm lost now How can i solve it? -
Listen failure while using wesocket in django says winerror 10048
Listen failure: Couldn't listen on 127.0.0.1:8000: [WinError 10048] Only one usage of each socket address (protocol/network address/port) is normally permitted. While using websocket in Django I am having above error. Not sure why it is happening. Please help me if you can. -
How to override M2M field names and models in Django with an existing database?
I'm using Django 3.1.3 and working with an existing postgresql database. Most of the models and fields names of this DB are badly chosen and/or way too long. Most of the time its easy to change them with some handy Django options like so : class NewModelName(models.Models): new_field_name = models.CharField(max_length=50, db_column='old_field_name') class Meta: managed=False db_table='database_old_table_name' But let say I want to change a M2M field name and the corresponding model name. I'd like to have something like : class Foo(models.Models): new_m2m_field_name = models.ManyToManyField('RelatedModel', blank=True, db_column='old_m2m_field_name') class Meta: managed=False db_table='foo_old_table_name' class RelatedModel(models.Models): name = models.CharField(max_length=50) class Meta: managed=False db_table='related_model_old_table_name' But if I do that, Django will throw an error stating django.db.utils.ProgrammingError: relation "foo_new_m2m_field_name" does not exist. It is like it is ignoring the db_column option. Any idea how I could get to a similar result ? Thanks! -
Where in Django can I run startup to load data?
I have a django application that loads a huge array into memory after django is started for further processing. What I do now is , after loading a specific view, I execute the code to load the array as follows: try: load_model = load_model_func() except: #Some exception The code is now very bad. I want to create a class to load this model once after starting django and I want to be able to get this model in all other this model in all other methods of the application So, is there a good practice for loading data into memory after Django starts? -
How to Access Digital Oceans private file on Django
I can upload files but how can i download a file from Digital Oceans Spaces which is private on Django? A public file can be accessed by the path below. https://"Project".ams3.digitaloceanspaces.com/"Project path"/"File name" Accessing a private path would however require an AWS3 signature using Boto3 AWS_S3_REGION_NAME = 'xxxx', AWS_S3_ENDPOINT_URL = 'xxxxxxxxxx', AWS_ACCESS_KEY_ID ='xxxxxxxxx', AWS_SECRET_ACCESS_KEY ='xxxxxxxxxxxxxxxxxxxxxxxxx') But how do you actually implement this to download a file from spaces? Any help would be appreciated -
Field 'id' expected a number but got '-'
I'm basically new to the Django and got such ValueError. I have a basic user model inheriting from AbstractUser class. Also I have Profile model (in separate app), which also contain OneToOneField refering to my User model. First of all, lets take a look on my Profile model: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile') country = models.ForeignKey('Country', on_delete=models.SET_DEFAULT, default='-') full_name = models.CharField(max_length=32, default='-') about = models.TextField(max_length=1000, default="User don't set any information about") register_date = models.DateField(auto_now=True) image = models.ImageField(upload_to='images/', default='images/no_avatar.png') active = models.BooleanField(default=False) website = models.URLField(default='-') github = models.URLField(default='-') twitter = models.URLField(default='-') instagram = models.URLField(default='-') facebook = models.URLField(default='-') Secondly when I create a new User I have to also create his own profile (model instance refering to the user instance). Let's look on my view.py where I creating a new user. class SignupView(View): def get(self, request): """ :param request: :return: Register page """ return render(request, "login/register.html", { 'form': SignupForm() }) def post(self, request): """ Tests data validity,creating user if everything is ok. :param request: :return: Particular user page if data is valid, otherwise it will return couple of mistake messages """ form = SignupForm(request.POST) if form.is_valid(): username = form.cleaned_data['username'] email = form.cleaned_data['email'] password1 = form.cleaned_data['password'] password2 = form.cleaned_data['confirm_password'] if password1 … -
Admin register CustomUser model gives error in Django
I'm trying to register my CustomUser model that I've created and it gives me this error but I verified the files for many times and I don't understand why I'm getting this error @admin.register(CustomUser) class CustomUserAdmin(UserAdmin): model = CustomUser add_form = CustomUserCreationForm fieldsets = ( *UserAdmin.fieldsets, ( 'Mobile Phone', { 'fields': ( 'mobile_phone' ) }, 'Email Status', { 'fields': ( 'do_not_marketing_email', 'email_verified' ) } ) ) error: <class 'users.admin.CustomUserAdmin'>: (admin.E009) The value of 'fieldsets[4]' must be of length 2. -
what is the use of request.META.get('HTTP_REFERER', '/') in django
My question is plain and simple,i just want to know what it does. What does it mean if i return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/')) in one of my views in django?? -
Best theorically way to integrate some standalone apps into a web environment?
I've developed some python standalone apps that now I want to integrate into a web environment in order to make them more user friendly for my workmates, whom aren't used to CLI and the command shell. I've thought in remaking those apps as Django apps, using the Django REST framework, but I'm not sure if that way is the theoretically correct given the REST API meaning. For giving some examples, one of my apps takes some geometries from a geopackage, which is a kind of compact format for transferring geospatial information that could acts as a database for itself, and does some QA processes in order to ensure the geometries and data quality. Another of my apps takes some more geometries from the same geopackage and converts them into shapefiles or CAD files. In brief, my question is that it is theoretically correct to remake those apps as Django apps, using the Django REST framework, or maybe exists another options or framework that are more suitable to what I want to approach. -
This field is required. Dajngo rest framework
I'm trying to send put request on my Django rest API server. but my rest API server is giving me this exception again and again {'user': ['This field is required.']} what should i do? Django rest framework serializer.py class UserProfileSerializer(CountryFieldMixin, serializers.ModelSerializer): user = UserSerializer() avatar = AvatarSerializer(read_only=True) class Meta: model = Profile fields = "__all__" read_only_fields = ("username",) def update(self, instance, validated_data): user_validated_data = validated_data.pop('user') profile = Profile.objects.filter(id=instance.id).update(**validated_data) user = User.objects.filter(id=instance.user.id).update(**user_validated_data) return Profile.objects.filter(id=instance.id).first() django rest framework views.py class UserProfileRetrieveUpdateAPIView(RetrieveUpdateAPIView): serializer_class = UserProfileSerializer def get_user_or_404(self): return get_object_or_404(User, id=self.request.user.id) def get_object(self): obj = get_object_or_404(Profile, user=self.get_user_or_404()) return obj function that is sending put request. def edit_specific_profile(request, form): token = request.session.get('access') data = { "id": None, "user": { "email": form.cleaned_data.get("email"), "first_name": form.cleaned_data.get("first_name"), "last_name": form.cleaned_data.get("last_name") }, "headline": form.cleaned_data.get("headline"), "maiden_name": form.cleaned_data.get("maiden_name"), "company_name": form.cleaned_data.get("company_name"), "proposal_comments": form.cleaned_data.get("proposal_comments"), "associations": form.cleaned_data.get("associations"), "interests": form.cleaned_data.get("interests"), "website": form.cleaned_data.get("website"), "location": form.cleaned_data.get("location"), "bio": form.cleaned_data.get("bio"), "state": form.cleaned_data.get("state"), "country": form.cleaned_data.get("country"), "date_of_birth": form.cleaned_data.get("date_of_birth"), } print(data) url = settings.AUTHENTICATION_HOST + "accounts/profile/" response = requests.put(url, data = data, headers = {"Authorization": f"Bearer {token}"}) print(response.json()) and in Django rest framework web interference in raw data Django rest framework is expecting { "user": { "username": "admin", "email": "itshamzamirchi@gmail.com", "first_name": "Hamza2", "last_name": "Lachi" }, "headline": "Test", "maiden_name": "test", "company_name": "t", "proposal_comments": "", "associations": … -
Migrating data to a ManyToMany Field in django
There already exists a model called Team and an email field users. Later it is converted to a ManyToMany Field. Is it possible to migrate the data from the email field to the ManyToMany field by scripts. Currently the users list is saved in the string format. After converting it to the list format and then adding it to the ManyToMany field is possible? class User(models.Model): email = model.EmailField() class Team(models.Model): users = models.EmailField() members = models.ManyToManyField(User, related_name='teams') And I tried with the following code to restore the data, but it is not getting restored def team_member_update(apps, schema_editor): team_list = Team.objects.all() for team in team_list: list_users = team.users # converting to list for user in list_users: team_user = User.objects.create(email=list_users) team.members.add(team_user) team.save() -
Why does Django test fail if user is authenticated
I am trying to test a Django view that requires that the user be logged in urls.py path('', BooksListView.as_view(), name='book_list'), views.py from django.contrib.auth.mixins import LoginRequiredMixin from django.views.generic import ListView from .models import Book class BooksListView(LoginRequiredMixin, ListView): model = Book template_name = 'books/book_list.html' login_url = 'account_login' tests.py class BooksTests(TestCase): def setUp(self): self.user = get_user_model().objects.create_user( username='reviewuser', email='reviewuser@email.com', password='testpass123' ) def test_book_list_view_for_logged_in_user(self): self.client.login(email='reviewuser@email.com', password='testpass123') response = self.client.get(reverse('book_list')) print(self.user.username, self.user.is_authenticated, response.status_code) self.assertEqual(response.status_code, 200) This fails because response.status_code returns 302 The output of the print statement is reviewuser True 302 In testing the web site a logged in user is able to access the page Where does the 302 come from? -
how to pass variable from views in one app to another app in django?
The app in my project have the following views(view1.py) def check(req): userid = req.POST['userid'] pwd = req.POST['password'] return render(req, 'success.html', {'username': username}) I need to use the same username variable in the views in another app of same project(view2.py) def edit_parameter_view(req): return render(req, 'edit_parameter.html',username) Both views are in different apps of the same project -
How to include a Django logging.FileHanler with Celery on ElasticBeanstalk
If I do not include logging I have an Django application with Celery working fine on ElasticBeanstalk using AWS SQS. When I include logging with a 'logging.FileHandler' celery gets permission denied error because it doesn't have permission rights for my log files. This is my error ValueError: Unable to configure handler 'celery_file': [Errno 13] Permission denied: '/opt/python/log/django.log' This is my logging setup LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse' } }, 'handlers': { 'console': { 'level': 'INFO', 'class': 'logging.StreamHandler' }, 'file': { 'level': log_level, 'class': 'logging.FileHandler', #'filters': ['require_debug_false'], 'filename': os.environ.get('LOG_FILE_PATH', LOG_FILE_PATH + '/var/log/django.log') }, 'mail_admins': { 'level': 'ERROR', #'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler' }, 'cqc_file' :{ 'level': log_level, 'class': 'logging.FileHandler', #'filters': ['require_debug_false'], 'filename': os.environ.get('LOG_FILE_PATH', LOG_FILE_PATH + '/var/log/cqc.log') }, 'null': { 'class': 'logging.NullHandler', }, 'celery_file': { 'level': 'INFO', 'class': 'logging.FileHandler', 'filename': os.environ.get('LOG_FILE_PATH', LOG_FILE_PATH + '/var/log/celery.log'), } }, 'loggers': { '': { 'level': 'WARNING', 'handlers': ['file'], }, 'debug' : { 'level': log_level, 'handlers': ['file'], }, 'django.security.DisallowedHost': { 'handlers': ['null'], 'level' : 'CRITICAL', 'propagate': False, }, 'django.request': { 'handlers': ['file','mail_admins'], 'level': 'DEBUG', 'propagate': True, }, 'cqc_report' : { 'level' : 'INFO', 'handlers' : ['cqc_file'] }, 'celery.task' : { 'handlers': ['console', 'celery_file'], 'level': 'INFO', 'propagate': True, } } } … -
Uncaught reference error when calling a javascript function
I am trying to run a javascript function when control comes out of a field(AWSID). Getting the following error: Uncaught ReferenceError: getCustomerName is not defined at HTMLInputElement.onblur (ipwhitelistindex:12) onblur @ ipwhitelistindex:12 Please help me out. {% extends 'base.html' %} <html> <body> <script type ="text/javascript"> function getCustomerName() { alert('get customer name called....'); } </script> {% block content %} <h1>IP Whitelisting</h1> <form name = "ipwhitelistindex" action = 'ipwhitelisting' method = "post"> {% csrf_token %} <center> <table> <tr><td>Enter AWS Account Id </td><td>:</td><td><input type = 'text' name = AWSID onblur="getCustomerName()"></td></tr> <tr><td>Customer Name </td><td>:</td><td><input type = 'text' name = CUSTNAME style = "background-color : lightgrey" readonly></td></tr> <tr><td>Enter list of IPS seperated with(,) </td><td>:</td><td><input type = 'text' name = IPS></td></tr> <tr><td>Enter description </td><td>:</td><td><input type = 'text' name = DESC></td></tr> </table><br> <input type = 'submit' value = 'submit'> </center> </form> {% endblock %} </body> </html> -
How to create field in Django model that refers to another field in the same model
I want to create field in my Model that refers to another field (in the same model) and modifies it. My code: class Result(models.Model): score = models.IntegerField(default=10) rank = models.IntegerField(score/2) // how to point to score from the same model (Result)?