Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
"save() got an unexpected keyword argument 'commit'" error in functional view
I got this error in my functional view: save() got an unexpected keyword argument 'commit' I'm try to save one object in database. 'debtors' is Many to Many field in models.py. forms.py class ExpenseForm(forms.ModelForm): class Meta: model = Expense fields = ('amount', 'text', 'debtors', 'date', 'time',) widgets = { 'date': AdminDateWidget(), 'time': AdminTimeWidget(), 'debtors': forms.CheckboxSelectMultiple(), } views.py def expenseformview(request, pk): if request.method == 'POST': form = Expense.objects.create( expenser = request.user, amount = request.POST.get('amount'), text = request.POST.get('text'), date = request.POST.get('date'), time = request.POST.get('time'), ) form.debtors.add(request.POST.get('debtors')) formcoseshare = form.save(commit=False) formcoseshare.save() form.save_m2m() return redirect('expense_detail', pk=pk, expenseid=form.id) else: form = ExpenseForm() return render(request, 'financials/expense_form.html', {'form': form}) How can to solve this problem? -
How to use django for dapp project?
I'm trying to build an auction app with solidity and React but I need some server to handle data and internal logic and I don't know what tool to use for the backend for these reasons: when just using react and solidity it's not fast. when using Django and web3py, I can't transfer money with Metamask. I've heard about Next.js and Node.js as the backend but I cant decide. I would appreciate any help. -
Register view in Django with edited UserCreationForm not working
I am using Django to build an app for a school project. My authentication attempt using Django's auth and Usercreationform (but modifying it to include email) doesn't seem to work. I already tested my login/logout views using my admin user and that is working pretty fine, but I can't seem to save new users in my application. I had to modify the user creation form to include email because in the future I'm suppossed to filter what kind of emails people register in the app with (only institutional emails are intended to work on this app, but I haven't implemented it yet), but everytime I submit my user register form it says the form is invalid in debugging. I created a form in forms.py from django.contrib.auth.forms import UserCreationForm from django import forms from django.contrib.auth.models import User class CustomUserForm(UserCreationForm): class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] in my views.py I imported the form and set it to debug which fields are failing when the form is not valid from django.contrib.auth.forms import AuthenticationForm, UserCreationForm from .forms import CustomUserForm def register_view(request): form = CustomUserForm(request.POST) if form.is_valid(): user_obj = form.save() form.save() return redirect('/login') else: print("FORM IS INVALID.") for field in … -
How to submit the Individual Fieldset in a Form
I have a form and inside it there are 4 fieldset, what I am trying to do is that when a user click on the "Next" button in the first fieldset, the button should work as both a submit button and a next button, or it should first submit the fieldset and then move to another fieldset. I am using Bootstrap-5 and Django My code and too long so I found a similar one on the net, and it is as follows:- You can find it here here and here the code:- HTML: <!-- MultiStep Form --> <div class="container-fluid" id="grad1"> <div class="row justify-content-center mt-0"> <div class="col-11 col-sm-9 col-md-7 col-lg-6 text-center p-0 mt-3 mb-2"> <div class="card px-0 pt-4 pb-0 mt-3 mb-3"> <h2><strong>Sign Up Your User Account</strong></h2> <p>Fill all form field to go to next step</p> <div class="row"> <div class="col-md-12 mx-0"> <form id="msform"> <!-- progressbar --> <ul id="progressbar"> <li class="active" id="account"><strong>Account</strong></li> <li id="personal"><strong>Personal</strong></li> <li id="payment"><strong>Payment</strong></li> <li id="confirm"><strong>Finish</strong></li> </ul> <!-- fieldsets --> <fieldset> <div class="form-card"> <h2 class="fs-title">Account Information</h2> <input type="email" name="email" placeholder="Email Id"/> <input type="text" name="uname" placeholder="UserName"/> <input type="password" name="pwd" placeholder="Password"/> <input type="password" name="cpwd" placeholder="Confirm Password"/> </div> <input type="button" name="next" class="next action-button" value="Next Step"/> </fieldset> <fieldset> <div class="form-card"> <h2 class="fs-title">Personal Information</h2> <input type="text" … -
Django - modify url argument before calling a view (middleware?)
I need to modify URL argument before a view is called. Let's say I just want to make it UPPERCASE. As the view is from a third-party app, I decided to create a middleware for this instead of overwriting the view. class UpperCaseNameMiddleware(MiddlewareMixin): def process_view(self, request, callback, callback_args, callback_kwargs): if callback == the_third_party_view: raw_name = callback_kwargs["name"] return the_third_party_view(request, raw_name.upper()) this works but I'm afraid it doesn't continue calling other middlewares. Is there a way I can modify the name argument and continue as it would if there was no UpperCaseNameMiddleware? -
Adding images to a folder. Django
I am writing a small project on django with an app 'santechnic' and ran into a problem.to In which folder should I upload the images in the model Product so that the get request can find them? santechnic/models.py class Category(models.Model): category_name = models.CharField(max_length=200, default="", primary_key=True) category_image = models.ImageField(default="", upload_to='upload/images/categories') class Product(models.Model): product_name = models.CharField(max_length=200, primary_key=True) length = models.FloatField(default=0.0) width = models.FloatField(default=0.0) height = models.FloatField(default=0.0) product_image = models.ImageField(default="", upload_to=) category = models.ForeignKey(Category, on_delete=models.CASCADE) urls.py urlpatterns = [ path('admin/', admin.site.urls), path('santechnic/', include('santechnic.urls')) ] santechnic/urls.py app_name = "santechnic" urlpatterns = \[ path('', views.CategoryView.as_view(), name='category'), path('\<slug:category_name\>/', views.ProductsView.as_view(), name='products'), path('\<slug:category_name\>/\<slug:product_name\>/', views.ProductDetailView.as_view(), name='detail'), \] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) santechnic/views.py class CategoryView(generic.ListView): template_name = 'santechnic/home.html' context_object_name = 'category_list' model = Category class ProductsView(generic.ListView): template_name = 'santechnic/products.html' context_object_name = 'products_list' model = Product part of settings.py MEDIA_URL = '' MEDIA_ROOT = '' Directory I've tried generate path: def generate_path(instance, filename): return '%s/upload/images/products/' % instance.category.category_name But I had exception SuspiciousFileOperation. Also for example I manually add path 'toilets/upload/images/products' in upload_to and got "GET /santechnic/toilets/toilets/upload/images/products/1.png HTTP/1.1" 404 (here category_name='toilets'). If path is 'upload/images/products' I again get "GET /santechnic/toilets/upload/images/products/1.png HTTP/1.1" 404 Help me, please. How can I solve it? -
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, …