Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How would I ensure that only authorised users are able to access this class based view
I have a risk entry view that only project managers are able to access and no other user group how would I ensure that only this user group is able to access this view? Risk page class-based view @method_decorator(decorators, name='dispatch') class Risk_entry_page(View): template_name = 'risk/riskEntry.html' def get(self, request, *args, **kwargds): return render(request, self.template_name) Risk Urls urlpatterns = [ path('', views.Solution_area_home_page.as_view(), name='risks-home-page'), path('risk/', views.Risk_entry_page.as_view(), name='risk-entry-page'), path('assumption/', views.Assumption_entry_page.as_view(), name='assumption-entry-page'), path('issue/', views.Issue_entry_page.as_view(), name='issue-entry-page'), path('dependency/', views.Dependency_entry_page.as_view(), name='dependency-entry-page'), path('logout/', views.Logout.as_view(), name='logout-view'), ] -
Custom Mixin to get verbose name not rendering when called in Django DetailView
I have created a custom mixin GetVerboseNameMixin in order to get the verbose name of model fields, and then display these in my html template using a DetailView. However, whenever I try and render the list of verbose names nothing is returned, and I cannot work out why. Any help would be much appreciated. Mixin.py: class GetVerboseNameMixin: def get_verbose_name(model, fields=[]): verbose_names = [] for field in fields: verbose_names.append(str(model._meta.get_field(field))) return verbose_names View: class ShowProfileView(GetVerboseNameMixin, DetailView): model = Profile template_name = 'profiles/user_profile.html' verbose_model_fields = GetVerboseNameMixin.get_verbose_name(model=Profile, fields=['first_name', 'surname', 'date_of_birth', 'phone_number', 'bio', 'gender', 'emergency_contact_name', 'emergency_contact_number']) def get_context_data(self, *args, **kwargs): context = super(ShowProfileView, self).get_context_data(*args, **kwargs) user_profile = get_object_or_404(Profile, id=self.kwargs['pk']) context["user_profile"] = user_profile return context def get_object(self, *args, **kwargs): obj = Profile.objects.filter(id=self.kwargs['pk']).values('first_name', 'surname', 'date_of_birth', 'phone_number', 'bio', 'gender', 'emergency_contact_name', 'emergency_contact_number') # list of dictionaries object = obj[0] return object Html template: {% extends "base.html" %} {% block content %} <h1>Profile</h1> <br/><br/> {% csrf_token %} <ul> {% for v in object.values %} {% for field_name in verbose_model_fields %} <p>{{field_name}}: {{ v }}</p> {% endfor %} {% endfor %} </ul> <a href='{% url "profiles:edit_profile" pk=user.profile.id %}'>Edit Profile</a> {% endblock %} Even if I just render: {{ verbose_model_fields }} In my html file nothing is being displayed. This leads me … -
Django sessionid for SessionAuthentication not set
I am using Django 4.1.1 with rest_framework.authentication.SessionAuthentication if i try to log in via my frontend i get the following response: but the usersessionid cookie do not apeare in the application tab in my browser. The next call fails with detail: "Authentication credentials were not provided." Any ideas ? I tried different cookie settings but nothing woks. -
How to queue requests to Django backend server to fit API rate limit
I have a web project which is based on some API from RapidAPI. This API has 10 requests/sec rate limit. All the requests to this API are processed by server side using Django with Rest framework library. Front-end is based on Vue. So this is kind of simple web app. The problem is that I need to somehow queue all the requests from website users to not exceed rapidapi rate limit, because if I do - some pages wouldn't load some content because the api returns 429 error. Usually it happens when some component needs to load data from 3+ different api endpoints. Also this would relate to situation when we have for example 10 online users who are actively clicking on page components which needs to fetch some data so I want to find some way to resolve it. Any advice would be appreciated -
Django Dynamically Add Forms Based On Key Value Pairs List
Is there a way to dynamically create formsets based on an API response. This would easily be done in JS, however, the app is running Django's MVT and I would like to create the form dynamically within python. models.py class Item(models.Model): name = models.CharField(max_length=50) class ItemAspect(models.Model): name = models.CharField(max_length=50) value = models.CharField(max_length=50) item = models.ForeignKey(Item, on_delete=models.CASCADE) API resposne: { { "key": "Name", "value_list": [ "value0", ... ] }, ... } Desired form: <form> ... <label for="{{ name-0 }}"> {{ key }}</label> <select name="name-0" id="name-0"> <option value="{{ value_list[0] }}"> {{ value_list[0] }} </option> ... </select> ... </form> My best guess is that it could be done with crispy's form_helper in a view after the API response is received. -
How to get live values from database in Djnago?
I want to get live values from database without reloading the page, I know it can be done with Ajax, but how, I don't really know. I have for example value {{points}} that is requested in view and rendered into html. I am updating it automatically every 5 seconds with some script. I want it to be shown on page without refreshing the page. How I render value into html: def main(request): points = Customer.objects.filter(name__id=request.user.id).values("points").first())["points"] context = {'points':points} return render(request, 'profile.html', context) How I request this value from view, but to see the updates I need to refresh the page: <div class="value">{{points}}</div> -
Django EmailBackend ConnectionRefusedError from app on PythonAnywhere
My password reset feature was working fine in development, sending a password reset email, but now that I have deployed to PythonAnywhere, I am getting a ConnectionRefusedError, specifically: ConnectionRefusedError at /reset_password [Errno 111] Connection refused Request Method: POST Django Version: 4.1 Exception Type: ConnectionRefusedError Exception Value: [Errno 111] Connection refused Exception Location: /usr/local/lib/python3.10/socket.py, line 833, in create_connection Raised during: django.contrib.auth.views.PasswordResetView Python Executable: /usr/local/bin/uwsgi Python Version: 3.10.5 Python Path: ['/var/www', '.', '', '/var/www', '/usr/local/lib/python310.zip', '/usr/local/lib/python3.10', '/usr/local/lib/python3.10/lib-dynload', '/home/gridsquid/.virtualenvs/myvirtualenv/lib/python3.10/site-packages', '/home/gridsquid/gridsquid'] Server time: Sat, 12 Nov 2022 16:45:30 +0000 I have verified the user is a valid user with a working email address. in settings.py: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.sendgrid.net' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = 'apikey' # Name for all the SenGrid accounts EMAIL_HOST_PASSWORD = os.getenv('SENDGRID_API_KEY') in urls.py path("reset_password", auth_views.PasswordResetView.as_view(template_name="gridsquid/reset-password.html"), name="password_reset"), path("reset_password_sent", auth_views.PasswordResetDoneView.as_view(template_name="gridsquid/reset-password-sent.html"), name="password_reset_done"), path("reset/<uidb64>/<token>", auth_views.PasswordResetConfirmView.as_view(template_name="gridsquid/reset.html"), name="password_reset_confirm"), path("reset_password_complete", auth_views.PasswordResetCompleteView.as_view(template_name="gridsquid/reset-password-complete.html"), name="password_reset_complete"), Again, everything is working in my development environment. What could be wrong here? -
What is best way to check expire date in django?
I have a project that a user can subscribe a product for a duration and after that the subscription should become expired. I need to check expire date every hour. what is best way to do that? I have searched and it seems I should use django-background-tasks but I wonder should I make a task to search through all products and run it one startup or should I make a task for each subscription on create? Or should I do something completely diffrent? -
Create empty dictionaries from a list of strings
If I have a list of strings like variations = ['color','size','quantity'] Is it someway possible to convert the strings in a list to empty dictionaries? The result I want is color = {} size = {} quantity = {} -
How to hide a category without articles?
I have articles combined by categories. Here are data models: class Category(models.Model): name = models.CharField(max_length=200, verbose_name='Наименование') slug = models.SlugField(max_length=250, verbose_name='URL') created = models.DateTimeField(auto_now_add=True, verbose_name='Добавлено') objects = models.Manager() class Meta: ordering = ('name',) verbose_name = 'категорию' verbose_name_plural = 'Категории' def __str__(self): return self.name def get_absolute_url(self): return reverse('main:article_list_by_category', args=[self.slug]) class Article(models.Model): STATUS_CHOICES = ( ('draft', 'Черновик'), ('published', 'Опубликовано'), ) TYPE_ARTICLE_CHOICES = ( ('Руководство', 'Руководство'), ('Инструкция', 'Инструкция'), ) title = models.CharField(max_length=250, verbose_name='Заголовок') slug = models.SlugField(max_length=250, unique_for_date='publish', verbose_name='URL') type_article = models.CharField(max_length=15, choices=TYPE_ARTICLE_CHOICES, default='Инструкция', verbose_name='Тип статьи') category = models.ForeignKey(Category, related_name='article', on_delete=models.CASCADE, verbose_name='Категория') author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts', verbose_name='Автор') body = RichTextUploadingField(verbose_name='Статья') publish = models.DateTimeField(default=timezone.now, verbose_name='Опубликовано') created = models.DateTimeField(auto_now_add=True, verbose_name='Добавлено') updated = models.DateTimeField(auto_now=True, verbose_name='Обновлено') status = models.CharField(max_length=12, choices=STATUS_CHOICES, default='draft', verbose_name='Статус') tags = TaggableManager() private = models.BooleanField(default=False, verbose_name='Приватная статья') objects = models.Manager() published = PublishedManager() class Meta: ordering = ('-publish',) verbose_name = 'статью' verbose_name_plural = 'Статьи' index_together = (('id', 'slug'),) indexes = [GinIndex(fields=['title'])] def __str__(self): return self.title Here is the output template: <div class="container my-container-style"> <div class="row"> <div class="col-md-3"> <h4 class="mb-4 category">Категории</h4> <div id="sidebar"> <ul> <li {% if not category %} class="selected" {% endif %}> <a href="{% url 'main:articles_list' %}">Все</a> </li> {% for c in categories %} <li {% if category.slug == c.slug %} class="selected" {% endif … -
How to add dynamic field in model or database using django
I want have created a table but I want to create fields from frontend by using HTML form. In that HTML form I am giving table name , field name, datatype, max length. If user add any field then it should update table and add that field to database. -
Angular map flower (celery+django) return to list of tasks
I want to map the return of the flower libary (/api/tasks) to a list of objects. Currently it returns multiple objects, but without the "list wrapper", so it's not possible to iterate that. API: https://flower.readthedocs.io/en/latest/api.html#get--api-tasks Return is for example: HTTP/1.1 200 OK Content-Length: 1109 Content-Type: application/json; charset=UTF-8 Etag: "b2478118015c8b825f7b88ce6b660e5449746c37" Server: TornadoServer/3.1.1 { "e42ceb2d-8730-47b5-8b4d-8e0d2a1ef7c9": { "args": "[3, 4]", "client": null, "clock": 1079, "eta": null, "exception": null, "exchange": null, "expires": null, "failed": null, "kwargs": "{}", "name": "tasks.add", "received": 1398505411.107885, "result": "'7'", "retried": null, "retries": 0, "revoked": null, "routing_key": null, "runtime": 0.01610181899741292, "sent": null, "started": 1398505411.108985, "state": "SUCCESS", "succeeded": 1398505411.124802, "timestamp": 1398505411.124802, "traceback": null, "uuid": "e42ceb2d-8730-47b5-8b4d-8e0d2a1ef7c9", "worker": "celery@worker1" }, "f67ea225-ae9e-42a8-90b0-5de0b24507e0": { "args": "[1, 2]", "client": null, "clock": 1042, "eta": null, "exception": null, "exchange": null, "expires": null, "failed": null, "kwargs": "{}", "name": "tasks.add", "received": 1398505395.327208, "result": "'3'", "retried": null, "retries": 0, "revoked": null, "routing_key": null, "runtime": 0.012884548006695695, "sent": null, "started": 1398505395.3289, "state": "SUCCESS", "succeeded": 1398505395.341089, "timestamp": 1398505395.341089, "traceback": null, "uuid": "f67ea225-ae9e-42a8-90b0-5de0b24507e0", "worker": "celery@worker1" } } Any ideas how to do that? I've tried the following thing: export interface Tasks { tasks: TaskWrapper[] } export interface TaskWrapper { [uuid: string]: Task } export interface Task { uuid: string, state: string, received: string, } -
Creating list of verbose field names to iterate through in Django template, but nothing rendering
I am creating a profile page for a web application. I am displaying a users profile, which is an instance of my profile model, matched based on the Users pk. Within the html, I want this to render as follows: verbose_field_name: field_value Or for example: First Name: John Surname: Lewis I had it so that it was rendering the actual field name, for example: first_name: John surname: Lewis Which worked, however as soon as I have tried to add in and iterate through the verbose field names, it is not working. My model is: class Profile(models.Model): # Get access to create profile by default MALE = 'M' FEMALE = 'F' OTHER = 'O' UNSPECIFIED = "U" GENDER_CHOICES = [ (MALE, 'Male'), (FEMALE, 'Female'), (OTHER, 'Other'), (UNSPECIFIED, 'Prefer not to say'), ] user = models.OneToOneField(User, on_delete=models.CASCADE) phone_number = models.CharField(verbose_name='Mobile Phone Number', max_length=20) bio = models.TextField(verbose_name='Bio', max_length=500, blank=True, null=True) # profile_image = models.ImageField(blank=True, null=True) date_of_birth = models.DateField(verbose_name='Date of Birth', blank=True, null=True) first_name = models.CharField(verbose_name='First Name', max_length=255, blank=True, null=True) surname = models.CharField(verbose_name='Surname', max_length=255, blank=True, null=True) gender = models.CharField(verbose_name='Gender', max_length=255, choices=GENDER_CHOICES, blank=True, null=True) emergency_contact_name = models.CharField(verbose_name='Emergency Contact Name', max_length=255, blank=True, null=True) emergency_contact_number = models.CharField(verbose_name='Emergency Contact Number', max_length=20, blank=True, null=True) business = models.ForeignKey(BusinessProfile, null=True, blank=True, … -
Hello everybody, I'm learning django and creating the review system. I think someting with Html is wrong
I created the form and added it to view, how I must add it to html form? index.html <form action="." method="post"> {{ form.as_p }} {% csrf_token %} <p><input type="submit" value="Add comment"></p> </form> <h1 style="margin:0 57%">Reviews</h1> <input type="hidden" name="parent" id="contactparent" value=""> <div class="dfv" style="display:flex; padding: 5%; justify-content: space-around; flex-wrap: wrap;align-items:center; box-shadow:4px 4px 16px gold;width: 80%;margin:8% 18% 0"> <div class="form-group editContent"> <label for="contactcomment" class="editContent" placeholder=" Message" > Your reviews * </label> I added action through url but it didn't worked -
Django REST Framework AttributeError: 'MCQ_Exam' object has no attribute 'questions'
I am trying to build a serializer for my database in django using the django rest framework but i want to add one model as a field to the serializer of another model and somehow it worked for one model serializer but not the other. so for the "Question" model, i was able to add the serializer of the "Answer" model as a field and it worked perfectly. the "MCQ_Exam" model on the other hand gives me an AttributeError: Serializer object has no attribute "questions" whenever i try to open the url. I added the "many=True" field to all the serializer variables as you can see and yet it still works for one model and not the other -
Django views are not rendering in template
Can someone tell me what I'm doing wrong here? The 1st function(all_products) renders in template perfectly, but the last 2 does not. models.py # TABLE BRAND class Brand(models.Model): name = models.CharField(max_length = 50) # TABLE PRODUCT class Product(models.Model): title = models.CharField(max_length = 100) brand = models.ForeignKey(Brand, on_delete = models.CASCADE) image = models.ImageField(null = False, blank = False, upload_to ="images/",) price = models.DecimalField(max_digits = 100, decimal_places = 2, ) created = models.DateTimeField(auto_now_add = True ) the functions in the views.py def all_products(request): products = Product.objects.all() return render(request, 'store/home.html', {'products': products}) def newest_products(request): sixNewestProduct = Product.objects.all().order_by('-created')[:6] return render(request, 'store/home.html', {'sixNewestProduct': sixNewestProduct}) urls.py from django.urls import path from . import views urlpatterns = [ path('', views.all_products, name= 'all_products'), path('', views.newest_products, name= 'newest_products'), path('', views.newest_discount, name= 'newest_discount'), ] the template part look like this: {% for new in sixNewestProduct %} <a href="#" class=""> <div class="newProduct"> <img src="{{new.image.url}}" alt=""> </div> <h5>{{new.brand.name}}</h5> <h4>{{new.title}}</h4> <p>{{new.price}} GNF</p> </a> {% endfor %} -
How to write relation where first model is connected to exactly four instances of another in Django?
Let's say I have two very basic model classes - for simplicity let's name them a Plan and a Task. My goal is to force every plan to have exactly 4 distinct tasks (order doesn't matter). Is there some good practice for this "many-to-many with a fixed quantity of related instances" case? from django.db import models class Task(models.Model): name = models.CharField(max_length=20) class Plan(models.Model): name = models.CharField(max_length=20) # four_tasks = ? I searched through Django documentation but there's no answer there (or maybe I didn't know how to search for it). I thought of 4 separate foreign keys (which should be possible by setting related_name for those) in Plan, or maybe standard many-to-many many relations. Both solutions require additional checks to ensure that there are actually 4 different tasks and they look ugly to me. -
How can I print values from the data base
So I want to print values that was in the database repeatedly when ever it is updated. Like lets say a client payed 30$ from the total amount of his service which is 50$, he will be left With 20$. Something that looks like this: (service price = 50$ first payment= 30$ balance= 20$ Date = 11/12/2022) So the next time he comes to pay for the rest, its shown what he paid last time with the date. The 2nd payment: (service price = 50$ first payment= 30$ balance= 20$ Date = 11/12/2022 service price = 50$ Second payment= 20$ balance= 0$ Date = 11/22/2022) so on with his transactions regarding that service. I'm kind losing my mind because I don't know where to move with this, so help! this is the code : models.py class Appointment(models.Model): patient = models.ForeignKey(Patient, on_delete = models.CASCADE) doctor_of_appointment = models.ForeignKey(Doctor, on_delete = models.CASCADE, related_name='doctor_of_appointment') receptionist_of_appointment = models.ForeignKey(Doctor, on_delete = models.CASCADE, related_name='receptionist_of_appointment') appointment_date = models.DateField(null=False, blank=False) #appointment_timeslot = models.ForeignKey(TimeSlot, on_delete = models.CASCADE) appointment_timeslot = models.CharField(max_length=100, default='') appointment_description = models.CharField(max_length=1000, null=True, blank=True) examine_result = models.CharField(max_length=1000, default='', null=True, blank=True) drugs = models.CharField(max_length=1000, default='', null=True, blank=True) appointment_status = models.CharField(max_length=10, choices=(('Pending', 'Pending'), ('Completed', 'Completed'), ('Canceled', 'Canceled')), default='Pending') #Invoicing Section … -
OperationalError in Django while updating model
I am facing OperationalError while updating the model in an existing Django project. These are my installed apps in settings INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "admin1_app.apps.Admin1AppConfig", ] This is code in admin from django.contrib import admin from admin1_app.models import Product class Product_admin(admin.ModelAdmin): list_display=["product_name","product_price","product_qty","product_category"] admin.site.register(Product,Product_admin) models.py from django.db import models class Product(models.Model): product_name=models.CharField(max_length=30) product_price=models.IntegerField() product_qty=models.IntegerField() product_category=models.CharField(max_length=35) def __str__(self): return self.product_name Iniatially a program was created with only 3 columns i.e., product_name, product_price, product_qty, and everything was done correctly. Later, I added product_category to this existing project and I also ran makemigrations and migrate commands. But I'm experiencing an OperationalError. OperationalError at /admin/admin1_app/product/ (1054, "Unknown column 'admin1_app_product.product_category' in 'field list'") Request Method: GET Request URL: http://127.0.0.1:8080/admin/admin1_app/product/ Django Version: 4.1.2 Exception Type: OperationalError Exception Value: (1054, "Unknown column 'admin1_app_product.product_category' in 'field list'") Exception Location: C:\Users\narendra\anaconda3\lib\site-packages\pymysql\err.py, line 143, in raise_mysql_exception Raised during: django.contrib.admin.options.changelist_view Python Executable: C:\Users\narendra\anaconda3\python.exe Python Version: 3.9.12 I tried using the python manage.py migrate --fake command . I don't know how it works but just copied it from some other similar error solution in Stack Overflow, however there is no result I even tried deleting the 0001_initial.py file in the migrations folder and then repeated the makemigrations command, … -
Django admin button for fields to trigger action
In the Django admin change form of my model I would like to be able to add a button next to any field. Clicking this button should call some function with the current form data as input. Once the function returns, the Django admin form should be updated by the return values of the function. I know of one way to add a button at the very bottom of the admin model change pape, right below the save button, but this is not what I want. The button should be right next to the specific input field. Currently, I have no idea where to start and conceptionally how this is achieved. I googled a lot, but couldn't find a solution yet. I thought of creating a new form widget that I could assign to an inputfield, but buttons in forms are not available in django. -
Change Django theme based on logged in, profile, or toggle
I would like to allow the user to have the ability to change the theme based on the following factors: Anonymous Check localStorage and if empty use default else use localStorage Authenticated Check localStorage and if empty use user profile setting I have it all working except for Authenticated users, I don't know how to check localStorage. {% if user.is_authenticated %} <body class="theme-{{user.profile.theme}}"> // How can I check localStorage.getItem('theme') and if null use {{user.profile.theme}} {% else %} <body> <script> var theme = localStorage.getItem('theme') if(theme == 'light'){ document.body.classList.add("theme-light") } else if (theme == 'dark'){ document.body.classList.add("theme-dark") } else { document.body.classList.add("theme-light") } </script> {% endif %} -
run a script to fill in a model
I have a script that fills a model (a table) with data. To run the script I do python manage.py shell < script.py it worked correctly several times but there it no longer fills the table I don't know why. import names from app.models import Employee, Sector from random import randint s1 = Sector.objects.create(namesector="marketing", codesector="MKT"); s1.save() for i in range(10): n = names.get_full_name().split(" ") p = Employee.objects.create_user(firstname=n[0], name=n[1], regID=str(i).zfill(2), codesector="MKT", password=str(i).zfill(2)) p.save() Only s1 is added to the Sector table, the employee table remains empty. When i write line by line directly in the shell the data is added correctly for the employee table. -
Normalize string before saving it in third-party model field
I'm looking for a way to modify a string before saving it in a third-party model field. IMPORTANT: The field should be unique, eg. has unique=True Let's say I have a function that makes string lowercase and removes dashes. def normalize(string:str): return string.lower().replace('-','') I want to make sure that only strings that went through this function are stored in the field (I don't expect using Model.update()) This solution looks good but has a big disadvantage: @receiver(pre_save, sender=TheThirdPartyModel) def normalize_the_field(sender, instance, **kwargs): instance.the_field = utils.normalize_the_field(instance.the_field) this way I can be sure there are only normalized strings in the DB but as it's unique=True ModelForm and admin doesn't raise validation errors when saving it. If there is already "xxx" in a DB and I type "XXx" (different case) - Django admin doesn't raise validation error, rather it returns an exception which I don't want. Is there a way to make it work? I can't redefine the field dynamically as migrations would be created in the third-party directory in virtual environment. -
Display verbose name on profile page Django DetailView (specific model instance)
I am working on a page to display a users profile. I have successfully rendered an instance of the users profile, which looks as shown in the screenshot below. The thing I want to change, is to display the verbose name of the field names, rather than the actual field name. I have done some research but am not sure how to implement this with my current set up. My models.py: class Profile(models.Model): MALE = 'M' FEMALE = 'F' OTHER = 'O' UNSPECIFIED = "U" GENDER_CHOICES = [ (MALE, 'Male'), (FEMALE, 'Female'), (OTHER, 'Other'), (UNSPECIFIED, 'Prefer not to say'), ] user = models.OneToOneField(User, on_delete=models.CASCADE) phone_number = models.CharField(verbose_name='Mobile Phone Number', max_length=20) bio = models.TextField(verbose_name='Bio', max_length=500, blank=True, null=True) date_of_birth = models.DateField(verbose_name='Date of Birth', blank=True, null=True) first_name = models.CharField(verbose_name='First Name', max_length=255, blank=True, null=True) surname = models.CharField(verbose_name='Surname', max_length=255, blank=True, null=True) gender = models.CharField(verbose_name='Gender', max_length=255, choices=GENDER_CHOICES, blank=True, null=True) emergency_contact_name = models.CharField(verbose_name='Emergency Contact Name', max_length=255, blank=True, null=True) emergency_contact_number = models.CharField(verbose_name='Emergency Contact Number', max_length=20, blank=True, null=True) business = models.ForeignKey(BusinessProfile, null=True, blank=True, on_delete=models.SET_NULL) creation_date = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.user) Views.py: class ShowProfileView(DetailView): model = Profile template_name = 'profiles/user_profile.html' def get_context_data(self, *args, **kwargs): context = super(ShowProfileView, self).get_context_data(*args, **kwargs) # super gives access to parent class methods user_profile = … -
KeyError: 'use_threading' not letting me runserver
I'm new to coding in Python so bear with my errors. I keep encountering this error even when I haven't added anything into the code yet. Any help is much appreciated! `` Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users[Name]\AppData\Local\Programs\Python\Python38\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Users[Name]\AppData\Local\Programs\Python\Python38\lib\threading.py", line 870, in run self._target(self._args, self._kwargs) File "C:\Users[Name]\AppData\Local\Programs\Python\Python38\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users[Name]\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\commands\runserver.py", line 127, in inner_run threading = options["use_threading"] KeyError: 'use_threading' note: i did migrations and makemigrations just in case but i still get the same error.