Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
trying to use channels in Django caused these errors
I was trying to use channels in Django, To do that I followed a tutorial and made these changes in the asgi.py file from channels.routing import ProtocolTypeRouter application = ProtocolTypeRouter( { "http":get_asgi_application() }) and these in the settings.py file ASGI_APPLICATION = 'lostAndFound.wsgi.application' after that, i restarted the server and got an internal server error, and the error in the terminal `Exception inside application: WSGIHandler.__call__() takes 3 positional arguments but 4 were given Traceback (most recent call last): File "/home/alaa/.local/lib/python3.10/site-packages/channels/staticfiles.py", line 44, in call return await self.application(scope, receive, send) TypeError: WSGIHandler.call() takes 3 positional arguments but 4 were given` can anyone plese help me with this -
Django many-to-many model generation
I am making an offer creation module in Django, I have a product and a variant object, the product variant is connected with a many-to-many relationship. What I want to do is to save the products by selecting them while creating the offer, but at the same time to offer the option to choose the variants under the products. The problem here is that the products and variants are not separate. model.py class offerProductVariant(models.Model): offerProduct = models.ManyToManyField(product) offerVariant = models.ManyToManyField(variant) class offer(models.Model): offerName = models.CharField(max_length=50) offerCustomer = models.ForeignKey(customer,on_delete=models.CASCADE,null=True,blank=True) offerCompany = models.ForeignKey(company,on_delete=models.CASCADE,blank=True) offerDate = models.CharField(max_length=40) offerProductVariantMany = models.ManyToManyField(offerProductVariant,blank=True) views.py def teklifsave(request): if not request.user.is_authenticated: return redirect('login') if request.method == 'POST': form = offerCreate(request.POST) form2 = offerCreateProduct(request.POST) if form.is_valid(): m = offer( offerName = form.cleaned_data['offerName'], offerCompany = form.cleaned_data['offerCompany'], offerCustomer = form.cleaned_data['offerCustomer'], offerDate = form.cleaned_data['offerDate'] ) m.save() if form2.is_valid(): op = offerProductVariant() op.save() fproducts = form2.cleaned_data['offerProduct'] print(fproducts) fvariants = form2.cleaned_data['offerVariant'] print(fvariants) for fproduct in fproducts: print(fproduct) op.offerProduct.add(fproduct) op.save() for fvariant in fvariants: print(fvariant) op.offerVariant.add(fvariant) op.save() m.offerProductVariantMany.add(op) return redirect('offer') return redirect('offer') -
Problems with Django forms and Bootstrap
Im making a form in django, were I style it with Widgets: from django.forms import ModelForm, TextInput, EmailInput, NumberInput from .models import * class DateInput(forms.DateInput): input_type = 'date' class PatientForm(ModelForm): class Meta: model = Patient fields = ['fornavn', 'efternavn', 'email', 'birthday', 'id_nr'] widgets = { 'fornavn': TextInput(attrs={ 'class': "form-control", 'style': 'max-width: 300px;', 'placeholder': 'Fornavn' }), 'efternavn': TextInput(attrs={ 'class': "form-control", 'style': 'max-width: 300px;', 'placeholder': 'Efternavn' }), 'email': EmailInput(attrs={ 'class': "form-control", 'style': 'max-width: 300px;', 'placeholder': 'Email' }), 'birthday': DateInput(attrs={ 'format':'DD/MM/YYYY', 'class': "form-control", 'style': 'max-width: 300px;', 'placeholder': 'dd/mm/yyyy', }), 'id_nr': NumberInput(attrs={ 'class': "form-control", 'style': 'max-width: 300px;', 'placeholder': 'Ønsket patientnummer' }), } However when inserting the form in the template with a Bootstrap Card styling, the form isnt rendering, and I'm left with only the names of the input fields, no fields for input and even missing the submit button. Template as follows: {% load crispy_forms_tags %} {% block content %} <div class="container p-5"> <div class="row p-5"> <div class="card p-3" style="width: 40rem;"> <h3 class="p-2 m-1">Opret patient</h3> <hr> <form action="" method="post" class=""> {% csrf_token %} {{ form|crispy }} <input type="submit" name="Opret" class="float-end"> </form> </div> </div> </div> {% endblock %} Any suggestions? -
How to make model.ImageField as mandatory in django admin?
I need to make upload image in django admin panel as a mandatory field, is there any possibility? Here what i did. **Model.py** class ContentData(models.Model): title = models.CharField(max_length=100,null = True) description = models.TextField(null=True) image = models.ImageField(upload_to="uploads", blank=True) is_active = models.IntegerField(default = 1, blank = True, null = True, help_text ='1->Active, 0->Inactive', choices =( (1, 'Active'), (0, 'Inactive') )) created_on = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title -
Django graphene: add field resolver with saving of the type inherited from the model
I have a node inherited from the model: class OrderModel(models.Model): FAILED = "failed" REQUIRES_PAYMENT_METHOD = "requires_payment_method" ORDER_STATUSES = ( (FAILED, FAILED), (REQUIRES_PAYMENT_METHOD, REQUIRES_PAYMENT_METHOD), ) STATUSES_MAP_FOR_NOT_ADMINS = { REQUIRES_PAYMENT_METHOD: FAILED, } status = models.CharField(_('status'), choices=ORDER_STATUSES, default=NEW_ORDER, max_length=255) class Meta(object): db_table = 'order' verbose_name = _('order') verbose_name_plural = _('orders') class OrderNode(PrimaryKeyMixin, DjangoObjectType): status = graphene.String def resolve_status(self, info): if info.context.user.is_admin: return self.status return self.STATUSES_MAP_FOR_NOT_ADMINS.get(self.status, self.status) class Meta: model = OrderModel filter_fields = GrantedOrderFilter.Meta.fields interfaces = (relay.Node, ) I want to add a custom status resolver to map statuses displayed for the users. But with the current implementation, I'm losing the typing for the status field. Is there any way I can save typing generated from the model and add the custom resolver? -
connection to server at "localhost" , port 5432 failed: Connection refused Is the server running on that host and accepting TCP/IP connections?
I am doing a project using django rest framework. It was working ok, but at the moment I am getting error connection to server at "localhost"(127.0.0.1), port 5432 failed: Connection refused Is the server running on that host and accepting TCP/IP connections? I knew that the problem with postgresql. Because I've tried to connect it with pgadmin, and also gives me this error. I am using Ubuntu OS, when I checked ubuntu not listening port 5432. postgresql.conf # - Connection Settings - listen_addresses = '*' # what IP address(es) to listen on; # comma-separated list of addresses; # defaults to 'localhost'; use '*' for > # (change requires restart) port = 5432 # (change requires restart) max_connections = 100 # (change requires restart) #superuser_reserved_connections = 3 # (change requires restart) #unix_socket_directories = '/var/run/postgresql' # comma-separated list > # (change requires restart) When I run service postgresql status, it says following. ● postgresql.service - PostgreSQL RDBMS Loaded: loaded (/lib/systemd/system/postgresql.service; enabled; vendor pr> Active: active (exited) since Tue 2022-05-17 09:22:03 +05; 1h 9min ago Process: 6270 ExecStart=/bin/true (code=exited, status=0/SUCCESS) Main PID: 6270 (code=exited, status=0/SUCCESS) May 17 09:22:03 mirodil-vivobook systemd[1]: Starting PostgreSQL RDBMS... May 17 09:22:03 mirodil-vivobook systemd[1]: Finished PostgreSQL RDBMS. Here is … -
How to get ETA when fetch data from postgres?
I have Django project and in some view users can select what data their want to fetch from DB. But when query is large and fetching take some time ~ 10min users dont know there is an error or just fetching time. How can i get aproximatelly execution time when fetching data from postgres? And how can i display that? -
Django | Not Found issue while updating record
Other Coding I did ***urls.py of web app path adding ***: path('update/updaterecord/int:id', views.updaterecord, name='updaterecord'), views.py file of web app : update coding info: def updaterecord(request, id): first = request.POST['first'] last = request.POST['last'] member = Members.objects.get(id=id) member.firstname = first member.lastname = last member.save() return HttpResponseRedirect(reverse('index')) -
Python Django Rest - Return extra field with lowest, highest and average values of some other field
I'm new to Django and APIs in general and I want to create a Django based API using Django Rest Framework. Here's what I want to do: Endpoint to age range report: curl -H 'Content-Type: application/json' localhost:8000/reports/employees/age/ Response: { "younger": { "id": "1", "name": "Anakin Skywalker", "email": "skywalker@ssys.com.br", "department": "Architecture", "salary": "4000.00", "birth_date": "01-01-1983"}, "older": { "id": "2", "name": "Obi-Wan Kenobi", "email": "kenobi@ssys.com.br", "department": "Back-End", "salary": "3000.00", "birth_date": "01-01-1977"}, "average": "40.00" } Endpoint to salary range report: curl -H 'Content-Type: application/json' localhost:8000/reports/employees/salary/ Response: { "lowest ": { "id": "2", "name": "Obi-Wan Kenobi", "email": "kenobi@ssys.com.br", "department": "Back-End", "salary": "3000.00", "birth_date": "01-01-1977"}, "highest": { "id": "3", "name": "Leia Organa", "email": "organa@ssys.com.br", "department": "DevOps", "salary": "5000.00", "birth_date": "01-01-1980"}, "average": "4000.00" } I have two apps, employees and reports. Here's employees/models.py: class Employee(models.Model): name = models.CharField(max_length=250, default='FirstName LastName') email = models.EmailField(max_length=250, default='employee@email.com') departament = models.CharField(max_length=250, default='Full-Stack') salary = models.DecimalField(max_digits=15, decimal_places=2, default=0) birth_date = models.DateField() Here's employees/serializers.py: class EmployeeSerializer(serializers.ModelSerializer): class Meta: model = Employee fields = ['id', 'name', 'email', 'departament', 'salary', 'birth_date'] I'm not sure how to create my views and serializers for my report app. How should I approach this? How can I return an extra field with a calculation between values of another … -
Django Views filter objects by user from custom model
I've created custom user model, and i'm trying to filter data in views.py by that user. The error i get is: 'SomeClassView' object has no attribute 'user' My goal is to 'encapsulate' data for each user. user model: class CustomUserManger(BaseUserManager): use_in_migrations = True def create_user(self, email, username, password, **other_fields): email = self.normalize_email(email) user = self.model(email=email, username=username, **other_fields) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, password, **other_fields): other_fields.setdefault('is_staff', True) other_fields.setdefault('is_superuser', True) other_fields.setdefault('is_active', True) if other_fields.get('is_staff') is not True: raise ValueError('Superuser must be assigned to staff') if other_fields.get('is_superuser') is not True: raise ValueError('Superuser must be assigned to superusers') return self.create_user(email, username, password, **other_fields) class User(AbstractUser, PermissionsMixin): username = models.CharField(_('username'), max_length=20, unique=True) email = models.EmailField(unique=True) password = models.CharField(max_length=128) is_staff = models.BooleanField(default=True) is_active = models.BooleanField(default=True) objects = CustomUserManger() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] def __str__(self): return self.username Views: class SomeClassView(viewsets.ModelViewSet): user = SomeClass.user serializer_class = WagonSerializer authentication_classes = (SessionAuthentication, ) @login_required def get_queryset(self): user = self.request.user return SomeClass.objects.filter(user=user) -
django-auth-ldap - modify debug messages / adding IP adress
Is it possible to somehow modify django-auth-ldap messages logged in log? I need to log IP adress alongside user if login failed: 2022-05-17 12:54:08 [DEBUG] Authentication failed for yyyyy: failed to map the username to a DN. 2022-05-17 12:54:32 [DEBUG] Authentication failed for xxxxx: user DN/password rejected by LDAP server. -
Connectivity issues to Sybase database as a secondary database with Django
I can connect to sybase database with FreeTDS and pyodbc as follows: # hello_sybase.py import pyodbc try: con = pyodbc.connect('Driver={FreeTDS};' 'Server=10.60.1.6,2638;' 'Database=blabla;' 'uid=blabla;pwd=blabla') cur = con.cursor() cur.execute("Select * from Test") for row in cur.fetchall(): print (row) cur.close() con.close() except Exception as e: print(str(e)) I tried to connect in a django view as follows: import pyodbc CONN_STRING = 'Driver={FreeTDS};Server=10.60.1.6,2638;Database=blabla;uid=blabla;pwd=blabla' def my_view(request): with pyodbc.connect(CONN_STRING) as conn: cur = conn.cursor() cur.execute('SELECT * FROM test') rows = list(cur.fetchall()) return render(request, 'my_template.html', {'rows': rows}) When I run python manage.py runserver and run the code in the above view. I have this error message '08001', '[08001] [FreeTDS][SQL Server]Unable to connect to data source (0) (SQLDriverConnect)') I tried to put TDS_Version=7.4 as was mentioned here in the comment, but it didn't helped. Is it possible that these are issues with the threading as is said in that comment? How can I fix it? The code works without django, but with python manage.py runserver it doesn't work. -
Django_jsonform not detecting changes, when attempting to makemigrations
I've added explanation to JSON form but when i attempt python manage.py makemigrations questions, says no changes detected in app "questions" I've added questions to INSTALLED_APPS in settings.py This only happens when i edit the JSON form. If i edit outside, then makemigrations work? class NewQuiz(models.Model): ITEMS_SCHEMA = { 'type': 'array', 'items': { 'type': 'object', 'properties': { 'question_english': { 'type': 'string' }, 'answers': { 'type': 'array', 'items': { 'type': 'object', 'properties': { 'answer_english': { 'type': 'string' }, 'is_correct': { 'type': 'boolean', 'title': 'Is correct', 'default': False, } } } }, 'explanation_english': { 'type': 'string' }, } } } How do i solve? -
isADirectoryError [Errno 21] while trying to render custom select form field
I am working with Python framework Django v2.2. I am trying to add custom attributes to <option> elements so that they are constructed as <option ext='xx'>. The forms are generated with Django admin templating and I am trying to extend them rather than creating completely new ones. My code: class CustomFormatSelect(forms.Select): def __init__(self, attrs=None, choices=(), disabled_choices=()): super(forms.Select, self).__init__(attrs, choices=choices) def create_option(self, name, value, label, selected, index, subindex=None, attrs=None): if index: dataformat = DataFormat.objects.get(id=index) extension = dataformat.ext option = super(forms.Select, self).create_option(name, value, label, selected, index, subindex, attrs) option['attrs']['ext'] = extension return option format = forms.ModelChoiceField(queryset=DataFormat.objects.all(), required=True, widget=CustomFormatSelect(attrs={'class':'file_formats'})) I am using Django debug mode and after this chunk is executed I get error: [Errno 21] Is a directory: '.../miniconda3/envs/migrator_admin/lib/python3.7/site-packages/django/contrib/admin/templates' Further messages: In template .../templates/django/forms/widgets/select.html, error at line 3 And it points to line in template: 3 {% include option.template_name with widget=option %}{% endfor %}{% if group_name %} I am pretty new one to Django, so my question is should I do it this way (if it is solvable), or should I create completely new template which is separated from Django admin ? -
Django view not rendering - sidebar & header loads fine but main content does not load
I've been through so many different things and I just can't work it out; need a fresh set of eyes haha My view does not render and this seems to be the case across my apps and landing page - the sidebar and header loads fine, footer looks to partially load but I believe this is due to the fact the main content does not load. Current HTML page screenshot - not rendering view views.py from django.shortcuts import redirect, render from django.views import View from django.views.generic.base import TemplateView from django.contrib.auth.mixins import LoginRequiredMixin from django.core.paginator import Paginator from django.http import request from django.http.response import HttpResponse from django.conf import settings # Form Imports from .models import NewRecipeForm ######################################### # Form Pages # ######################################### # Recipe View class RecipesView(LoginRequiredMixin, View): def get(self, request): content = {} content['heading'] = "Recipes Database" content['pageview'] = "Recipes & Formulations" return render(request, 'nf_recipes/recipes-database.html', content) ######################################### # Form Pages # ######################################### # Add New Recipe Form class AddNewRecipeForm(LoginRequiredMixin, View): def get(self, request): add_new_recipe_form = NewRecipeForm() content = {} content['heading'] = "Add New Recipe" content['pageview'] = "Recipes & Formulations" content['add_new_recipe_form'] = add_new_recipe_form return render(request, 'nf_recipes/add-new-recipe.html', content) def post(self, request): if "add-new-recipe-submit" in request.POST: add_new_recipe_form = NewRecipeForm(request.POST) add_new_recipe_form.save() return redirect("/nf_recipes/recipe-db") # … -
Django db_router does not exclude app models as expected
I am trying to create an application where one server communicates with many other worker servers. Those servers will each have their own DB which should only contain the tables for their own models. I have created a database router which unfortunately does not work as the migrate command continues to create auth, contenttypes and virtually all Django application models in the database that as per the router, should contain none of that and only the worker server specific models. Expected in database: Worker Server Model 1 Actually produced in database: Worker Server Model 1 auth_group auth_group_permissions auth_permission auth_user auth_user_groups all the rest of the django models Code in Settings: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'server_1_db', 'USER': 'postgres', 'PASSWORD': 'admin', 'HOST': '127.0.0.1', 'PORT': '5432', } } DATABASE_ROUTERS = ['ApplicationServer_2.db_routers.RestRouter'] Router code: class RestRouter: app_labels = {"DoNOTadd", "auth", "admin", "sessions", "contenttypes"} def db_for_read(self, model, **hints): if model._meta.app_label not in self.app_labels: return 'default' return "For read db" def db_for_write(self, model, **hints): if model._meta.app_label not in self.app_labels: return "default" return "For write db" def allow_relation(self, obj1, obj2, **hints): if ( obj1._meta.app_label not in self.app_labels or obj2._meta.app_label not in self.app_labels ): return True return None def allow_migrate(self, db, app_label, model_name=None, **hints): … -
Want to build custom Audit logging
We have a enterprise application in django, want to do few enhancements Enhancements : i don't want to save log change data in django_admin_logs table in db, instead of this , we have a external service where we want to append all the logs there , There is a history page in django when we click on the models data , on history page what we want is to show data on that page by making a get call to audit service When we changed something in the entry we want to make a post call to audit service and with old and new data Can someone explain how can i achieve that -
How to get users spent time on a task with Djanog?
I have Django project and several views. In one view i want to track users spent time. How can i do that? Maybe some libraries or django built in methods? Little bit more about view: when user open view he can see many photoes, and then he need to choose similar and save. Then page reloads with new photoes and task is similar, find similar photoes and submit. I need to track and store that time what each user spent on this task. If i check users time when he open view i don't know when she close it, and also user can just open view and chill, without doing something. How or with i can realize it? -
How do I include a Django project's README.md in a template?
I want to add the text of the readme to a custom index template in admin. So I have the following relevant paths in the project: ./README.md ./impact_api/templates/admin/index.html And in the project settings I have TEMPLATES = [ { 'DIRS': [BASE_DIR / 'templates'], ...}] So in the index.html file I want to do something like this: {% include "../../README.md" %} But that raises an error: TemplateSyntaxError at /admin/ The relative path '"../../README.md"' points outside the file hierarchy that template 'admin/index.html' is in. The only things I can think of are a) to move the README into the body, which I'm not sure I can do without losing the display on Github and seems like a bad idea even if I can, or to change the templates lookup path to the entire project, which also seems like a terrible idea. Is there a more sensible option? -
IndexError: list index out of range Django and Postgresql DB
I'm getting mad with this issue, so please help hahahahaha. the error i have is IndexError: list index out of range, when i try do an insert to in table of my DB. I'm trying insert a svc document with only 30 rows. any idea? class CamerasBaleares(TimeStampedModel, SoftDeletableModel): title = models.CharField(max_length=50, blank=True) lat = models.FloatField(blank=True, null=True) lon = models.FloatField(blank=True, null=True) url = models.URLField(blank=True) is_removed = models.BooleanField(default=False) def __str__(self): return self.title def load_data(self): import csv self.file = open(r'/home/elsamex/Documentos/CamarasBaleares.csv') self.row = csv.reader(self.file, delimiter='"') self.list = list(self.row) self.tupla = tuple(self.list) def save_data(self): import psycopg2 self.connection = psycopg2.connect("dbname=camarasdgt user=******* password=++++++++") self.cursor = self.connection.cursor() self.cursor.executemany ("INSERT INTO api_camerasbaleares (title, lat, lon, url) VALUES (%s, %s, %s, %s)", self.tupla) self.connection.commit() self.cursor.close() self.connection.close() def select (self): self.load_data() self.save_data() self.cursor = self.connection.cursor() self.cursor.execute("""SELECT * FROM api_camerasbaleares""") self.rows = self.cursor.fetchall() self.cursor.close() self.connection.close() return self.rows ins_db= CamerasBaleares() ins_db.load_data() ins_db.save_data() ins_db.select() -
Django Bootstrap 5 - Custom styling
I am using django-bootstrap5 in a Django project. According to the docs, for customization, I can add the following to settings.py: BOOTSTRAP5 = { "css_url": {}, # I could add a custom URL here "theme_url": "..." # Or I could override the theme here } Which seems overkill for only a few customizations. How can I customize something like the primary colour of Bootstrap? Do I have to use Sass/Scss, and if so, how does one do this in Django? -
django when viewing other users profile i get the logged user's profile
New to Django and i can't figure out why i keep getting the profile view of the user I logged in with when i try to view other user's profile. HTML: {% extends "Portfolio/base.html" %} {% block content %} <body> <a href=""><i class="bi bi-pencil"></i>Send Message</a> {% for message in message_list %} <article class="media content-section"> <img class="rounded-circle article-img" src="{{ message.sender_user.profile.image.url }}" alt=""> <div class="media-body"> <div class="article-metadata"> <a class="mr-2" href="{% url 'profile-detail' message.sender_user.id %}">{{message.sender_user.username}}</a><small class="text-muted">&emsp; {{message.date_posted}}</small></p> {# |date:"F d, Y" #} </div> <p class="article-content mb-4">{{message.content|safe}}</p> </div> </article> <p>{{message.seen}}</p> {% endfor %} Model: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' Views: ''' User Profile ''' class ProfileDetailView(DetailView): template_name = 'user/profile_detail.html' # <app>/<model>_<viewtype>.html model = Profile fields=('image') def form_valid(self, form): form.instance.user = self.request.user return super().form_valid(form) URLs path('profile/<int:pk>', user_views.ProfileDetailView.as_view(), name='profile-detail'), -
How to deploy Django Based Server and Laravel Project Simultaneously on a Single Droplet
I am new to Digital Ocean and was wondering on how to deploy Django and Laravel code side-by-side. The code works fine locally but I don't know how to deploy the both sources over Digital Ocean droplet. We bought cloudways server but it doesn't offer anything other than PHP which was the limitation. So, we don't have any experience with deployment on Digital Ocean. Is there anyone who can help me with this? Thank you! -
How to send parameter from Django to JavaScript function
I would like to know how I can send a parameter value from Django (View, Form, etc) to JavaScript function in js file. I have a Contact app: Models.py class Contact(models.Model): firstname = models.CharField(max_length=100, verbose_name='Nombre') lastname = models.CharField(max_length=100, verbose_name='Apellidos') email = models.EmailField(max_length=100, verbose_name='eMail') message = models.TextField(max_length=1000, verbose_name='Mensaje') created = models.DateTimeField(auto_now_add=True, verbose_name='Creado') updated = models.DateTimeField(auto_now=True, verbose_name='Editado') class Meta(): verbose_name = 'Contacta Mensaje' verbose_name_plural = 'Contacta Mensajes' ordering = ['-created'] def __str__(self): return str(self.email) Forms.py class ContactForm(forms.ModelForm): class Meta: model = Contact fields = ("firstname", "lastname", "email", "message") widgets = { 'firstname': forms.TextInput(attrs={'class':'form-control', 'id': 'id_firstname'}), 'lastname': forms.TextInput(attrs={'class':'form-control', 'id': 'id_lastname'}), 'email': forms.EmailInput(attrs={'class':'form-control', 'id': 'id_email'}), 'message': forms.Textarea(attrs={'class':'form-control', 'id': 'id_message'}), } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) View.py class ContactView(CreateView): form_class = ContactForm template_name = 'core/contact.html' JS function in theme.js forms: function () { (function() { "use strict"; window.addEventListener("load", function() { var forms = document.querySelectorAll(".needs-validation"); var validation = Array.prototype.filter.call(forms, function(form) { form.addEventListener("submit", function(event) { if(form.checkValidity() === false) { event.preventDefault(); event.stopPropagation(); } form.classList.add("was-validated"); if(form.checkValidity() === true) { event.preventDefault(); form.classList.remove("was-validated"); // Send message only if the form has class .contact-form var isContactForm = form.classList.contains('contact-form'); console.log(isContactForm); if(isContactForm) { var data = new FormData(form); var alertClass = 'alert-danger'; fetch("", { method: "post", body: data }).then((data) => { if(data.ok) { … -
Django Unknown column in field list error
I am unsure why I am getting this error when I load order_processing.html django.db.utils.OperationalError: (1054, "Unknown column 'orchestration_ce_base.model' in 'field list'") In models.py, I have just added the these: model = models.CharField(max_length=200, null=True, choices=ROUTER_MODELS) region = models.CharField(max_length=200, null=True, choices=REGION) I assume they have not been created in the database. I have tried running makemigrations/migrate, but no changes are detected. When the html page is loaded it is throwing an error. models.py from django.db import models from django.contrib.auth.models import User from django.forms import ModelForm class Order(models.Model): order_name = models.CharField(max_length=100, unique=True)#, null=True, blank=True) created_by = models.ForeignKey(User, related_name='Project_created_by', on_delete=models.DO_NOTHING) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.order_name class Ce_Base(models.Model): ROUTER_MODELS = ( ('CISCO2901', 'CISCO2901'), ('ISR4331', 'ISR4331'), ('CISCO1921', 'CISCO1921'), ('ISR4351', 'ISR4351'), ('ISR4451', 'ISR4451'), ('ISR4231', 'ISR4231'), ('ISR4431', 'ISR4431'), ('ISR4461', 'ISR4461'), ) REGION = ( ('1', '1'), ('2', '2'), ('3', '3'), ('4', '4'), ('5', '5'), ('6', '6'), ('7', '7'), ) ce_hostname = models.CharField(max_length=15) new = models.BooleanField() location = models.TextField(null=True, blank=True) model = models.CharField(max_length=200, null=True, choices=ROUTER_MODELS) region = models.CharField(max_length=200, null=True, choices=REGION) order_reference = models.ForeignKey(Order, null=True, on_delete=models.CASCADE) views.py from django.shortcuts import render from django.contrib.auth.decorators import login_required from django.shortcuts import render from .models import Order from .models import Ce_Base from .forms import OrderForm #from .tables import OrderTable #from django_tables2 import …