Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AttributeError: module 'quizbot.quiz.models' has no attribute '_meta'
Trying to figure out why I am getting this error and how to fix it. Trying to use django import-export library for importing files into the database. I have no idea what to try but have looked it up with nothing to give. I used the django-import -export documentation but did not help solve this issue. from django.db import models # from django.utils.translation import ugettext as _ # Create your models here. class Question(models.Model): # For Translation # title = models.CharField(_(""), max_length=255) # JUST PUT _ before any " " areas objects = None LEVEL = ( (0, ('Any')), (1, ('Beginner')), (2, ('Intermediate')), (3, ('Advanced')), (4, ('Expert')), ) # sets the amount of chars for the max length title = models.CharField(("title"), max_length=255) # This is used to make the points system points = models.SmallIntegerField("points") # This is used to make the difficulty settings difficulty = models.IntegerField(('Difficulty'), choices=LEVEL, default=0) # This question is shown be default is_active = models.BooleanField(("Is Active"), default=True) # When the question was created created_at = models.DateTimeField(("Created"), auto_now=False, auto_now_add=True) # When the question was last updated updated_at = models.DateTimeField(("Updated"), auto_now=True, auto_now_add=False) def __str__(self): return self.title class Answer(models.Model): # the first field in ForeignKey is identifying the table we … -
Upgrading Redis to 7.0.11 results in TypeError at /login/ __init__() got an unexpected keyword argument 'ssl_cert_reqs'
We use redis with django-rq to manage queues on our project. Heroku has recently forced upgrades to Redis 7.0.11 and that requires TLS. Per their docs we need to set 'ssl_cert_reqs'=None in order to make sure redis is using TLS but not looking for a cert. CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": os.environ.get('REDIS_URL'), "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", "CONNECTION_POOL_KWARGS": { "ssl_cert_reqs": None }, } } } Setting the above in my project's settings.py results in the following error: TypeError at /login/ __init__() got an unexpected keyword argument 'ssl_cert_reqs' Other settings like "max_connections": 5 don't cause an error. I've been searching and I haven't seen anyone else with this issue. Has anyone else run across this issue and hopefully a fix? We're using: Django==2.2.28 django-redis==5.2.0 django-rq==2.8.1 redis==4.5.5 rq==1.15.1 It also fails on another build we have: Django==3.0.14 django-redis==5.2.0 django-rq==2.8.1 redis==4.6.0 rq==1.15.1 We've tried configuring our project with multiple builds of Django, django-redis, django-rq, redis, and rq with no luck: -
How to find product name from category?
I have created three models Main Category , Category and Product Category model contains the Foreign Key of main category and product model contains the Foreign Key of main category and category model Product model contains the product details. models.py class BaseModel(models.Model): id = models.UUIDField(primary_key=True, unique=True, editable=False, default=uuid.uuid4) created_at = models.DateTimeField(auto_now_add=True) class Meta: abstract = True class MainCategory(BaseModel): name = models.CharField(max_length=100) def __str__(self): return self.name class Category(BaseModel): main_category = models.ForeignKey( MainCategory, on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length=100) def __str__(self): return self.main_category.name + "---" + self.name class Product(BaseModel): name = models.CharField(max_length=100) description = models.TextField() main_category = models.ForeignKey( MainCategory, on_delete=models.CASCADE, related_name='main_category') category = models.ForeignKey( Category, on_delete=models.CASCADE, related_name='category', null=True, blank=True) slug = models.SlugField(unique=True, max_length=100, null=True, blank=True) def save(self, *args, **kwargs): self.slug = generate_slug(self.name) super(Product, self).save(*args, **kwargs) views.py def categories(request): main_categories = MainCategory.objects.all() context = { 'main_categories': main_categories } return render(request, 'allProducts.html', context) def showProductsMainCategoryWise(request): main_category = request.GET.get('main_category') if main_category == None: products = Product.objects.order_by('id') else: products = Product.objects.filter(main_category__name=main_category) main_categories = MainCategory.objects.all() context = { 'products': products, 'main_categories': main_categories } return render(request, 'allProducts.html', context) def showProductsCategoryWise(request): main_category = request.GET.get('main_category') category = request.GET.get('category') if main_category == None and category == None: products = Product.objects.order_by('id') else: products = Product.objects.all().filter( Q(main_category__name=main_category), Q(category__name=category)) main_categories = MainCategory.objects.all() categories = … -
Heroku deleted my google_application_credentials.json
I created google_application_credentials.json with heroku bash but the file was deleted, how best can I handle this ? -
Django: How to prevent a page from reloading when I click button with Ajax/Javascript? (not jQuery)
In the home.html page (index.html > login.html > home.html) i have a combobox (independent, not connected to the database but to a list), a textarea and a button. When I click the button, it prints some text in the textarea (using a condition found in views.py). Very simple. Problem: The problem is that when I click the button, the page reloads and then prints in the textarea. How can I prevent the page from loading when I click the button (without using jQuery)? Important: bearing in mind that I will have to add many comboboxes, so I would like to manage them as best as possible. Is it possible to manage the code as much as possible in the py files and not split it too much in the js file or js tag? P.S: I searched many questions on stackoverflow or various tutorials, but I couldn't solve. Apparently, even though these are similar questions, each solution is a different case with different problems and solutions. CODE home.html (index > login > home) index.html is 127.0.0.1:8000/. Home.html will only open after successful login. The address of when I view the forms is 127.0.0.1:8000/home and when I click Submit I still … -
Why am I getting "The model User is not registered" in Django
I'm following a tutorial on building a social network app with Django. I'm getting an error even though I'm following the tutorial. Error: django.contrib.admin.sites.NotRegistered: The model User is not registered admin.py from django.contrib import admin from django.contrib.auth.models import User from .models import Profile # Register your models here. class ProfileInline(admin.StackedInline): model = Profile class UserAdmin(admin.ModelAdmin): model = User fields = ["username"] inlines = [ProfileInline] #so we can edit users and profiles in one place since we're profile should be extending User. admin.site.unregister(User) admin.site.register(User, UserAdmin) The error is complaining about the line that says "admin.site.unregister(User)". models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) follows = models.ManyToManyField("self", related_name="followers", symmetrical=False, blank=True) #symmetrical=False so that user can follow someone without them following back #blank=True means field can remain empty, user doesn't have to follow anyone. When I comment out the admin.site.unregister(User) line, I get the following error: django.contrib.admin.sites.AlreadyRegistered: The model User is already registered with 'auth.UserAdmin'. Which is weird to me because didn't it just say that the model User was not registered? -
Setting up Django application on Hetzner Managed Server
I have a managed server from Hetzner for my wordpress websites and now I want to deploy a django application on it without renting a cloud server from hetzner. The application runs on my computer with localhost on the browser, but on the server it only shows the index.html page with the right css styling. When I try to use e.g. buttons on the page it throws me "The requested URL was not found on this server." because the links are with "/reg/" and when the django isn't running right it can't access the other pages. I've set up a cronjob on the server "'/usr/bin/python3 /usr/home/username/public_html/testbox/manage.py'" and that seems to work fine according to the hetzner dashboard. In addition, Python and django are installed on the subdomain. Is there another thing e.g. docker or nginx that I am missing? Thanks in advance. -
How to run a telegram bot in django?
I want to run a telegram bot in django and have it run with the command "python manage.py runserver". I tried to do this with subprocess, but it gives an error and because of this there is a conflict with the launch of several bots. Is there an alternative solution? #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import subprocess import sys from subprocess import call def main(): """Run administrative tasks.""" os.environ.setdefault("DJANGO_SETTINGS_MODULE", "djangoProject7.settings") try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc subprocess.Popen(["python", "main.py"]) execute_from_command_line(sys.argv) if __name__ == "__main__": main() -
Stripe Portal url not secure Python
I'm working on a Django application integrated with Stripe, and I'm facing a security issue related to user subscription management through the Stripe portal. Currently, I provide a simple link for users with subscriptions to access the portal. However, I've noticed that if I copy the link from the browser tab that the view generate and paste it into a private tab in another browser, the portal loads up, allowing access to someone else's subscription details. an example of the url generated : https://billing.stripe.com/p/session/test_YWNjdF8xSGFuNG5KV3p0WnBRQUJ4LF9POHM5UWlrYlhtM0FadVZmV3NUU3hQFMrgrrgg0HK1DtM1hxe This presents a significant security concern since an unauthorized user who obtains the URL could potentially manipulate the billing information of a subscriber. so my view : def customer_portal(request): # Authenticate your user. customer_id = request.user.customer.id # Create a session. session = stripe.billing_portal.Session.create( customer=customer_id, return_url='http://127.0.0.1:8000/account/billing/', ) # Directly redirect the user to the portal. return redirect(session.url) the link : <h4><a href="{% url 'subscriptions:customerPortal' %}">Manage Billing</a></h4> the urls : path('billing/portal/', customer_portal, name='customerPortal'), I'm doing something wrong ? -
Dajngo: Pagination in search results with Class-based views
I want to paginate by keywords that I enter in the form. I use the following class def pageNotFound(request, exceprion): return HttpResponseNotFound("<h2>Page not found</h2>") def get_quotes(): top_tags = get_top_tags() context = { "top_tags": top_tags, "functional_menu": functional_menu, } return context class Main(ListView): model = Quote paginate_by = 10 template_name = "quotes/index.html" context_object_name = "quotes" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context.update(get_quotes()) return context class SearchedResults(ListView): model = Quote paginate_by = 10 template_name = "quotes/index.html" context_object_name = "quotes" def get_queryset(self): query = self.request.GET.get("search_query") if query: queryset = Quote.objects.filter( Q(quote__icontains=query) | Q(tags__name__icontains=query) | Q(author__fullname__icontains=query) ).distinct() else: queryset = super().get_queryset() return queryset def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) return context The problem is that when you go to the next page, the form field is cleared and the query takes the value None query=None. The entire pagination becomes undefined. How to save queryset when crossing pages in pagination? -
Django returns TemplateDoesNotExist for namespaced app templates which are rendered by class views but works for plain function views
I'm new to Django and have a project myproject and inside is an app, users. I can't figure out why name spacing the my templates in a subdirectory inside of a folder called templates within the users apps (so the path is myproject/users/templates/users/) does not work for class based views but it works fine for regular function views. When using a class based view I get error message Templateloader postmortem saying: django.template.loaders.app_directories.Loader: /home/me/projectmainfolder/myproject/users/templates/signup_form.html (Source does not exist) django.template.loaders.app_directories.Loader: /home/me/projectmainfolder/penv/lib/python3.10/site-packages/django/contrib/admin/templates/signup_form.html (Source does not exist) django.template.loaders.app_directories.Loader: /home/me/projectmainfolder/penv/lib/python3.10/site-packages/django/contrib/auth/templates/signup_form.html (Source does not exist) When I move the template out of the name spaced sub-directory and into templates it works fine. users/urls.py is: from django.urls import path, include from . import views app_name = "users" urlpatterns = [ path("accounts/", include("django.contrib.auth.urls")), # works fine path("accounts/test", views.testdef, name="test"), #doesn't work path("accounts/signup/user", views.UserSignupView.as_view(), name="signup_form"), ] The regular function testdef is : def testdef(request): return render(request, "users/test.html") The class view UserSignupView is: class UserSignupView(CreateView): model = CustomUser form_class =UserProfileSignupForm template_name = 'signup_form.html' def somefunction(self, **kwargs): ... Any idea how to resolve this is very appreciated. I would like to keep things name spaced according to Django's docs. I tried moving the files around and found success that way but … -
Django ORM: have model field always return a constant
I am extending Django model into a few child classes: Model –> SampleModel –> SampleModelA –> SampleModelB –> SampleModelC –> SampleModelD All child models (A,B,C,D) have field SampleType as Integer. Models A and B may have different SampleTypes (1–5), whereas for models C and D, SampleType is always the same: 1 and 2, respectively. I must preserve SampleType field in all child models for polymorphism purposes, but need models C and D always return 1 and 2, respectively for that field in any record, no matter what query. What is the simplest way to do that? (preferably without taking up disk space for the field) -
How to know if a user is previously loged in in django but with firebase database
how do we know this in HTML and python both? When we open the django website it should show different things for logged user. please give some examples with a code with comments but dont use django authtentcation system .. -
Django Authentication Form not working properly
I am trying to create a very basic login system (just to grasp Django's authentication system, nothing fancy). Thing is, when I use the following code (i.e. don't validate authentication form submission), everything works perfectly. The views.py file: from django.shortcuts import render, redirect from django.http import request from django.contrib.auth.decorators import login_required from .forms import UserRegistrationForm from django.contrib import messages from django.contrib.auth import authenticate, login, logout from django.contrib.auth.forms import AuthenticationForm @login_required(login_url="accounts/login") def home(request): return render(request, "main/home.html") def register_user(request): if request.method == "POST": reg_form = UserRegistrationForm(request.POST) if reg_form.is_valid(): user = reg_form.save() messages.success(request, f'You have successfully registered!') return redirect("login") else: messages.error(request, "Some problem occured") else: reg_form = UserRegistrationForm() return render(request, template_name='main/register.html', context={"form":reg_form}) def login_view(request): if request.method == "POST": username = request.POST.get("username") password = request.POST.get("password") user = authenticate(request, username = username, password = password) if user is not None: login(request, user) messages.success(request, f"You logged in as: {username}") return redirect("home") else: messages.error(request, "Invalid username or password") return redirect("login") else: auth_form = AuthenticationForm() return render(request, "registration/login.html", context={"form":auth_form}) def logout_request(request): logout(request) messages.success(request, f"You have logged out.") return redirect("login") However, when I insert authentication form validation and population, user is not authenticated and None is returned instead. For the purpose of simplicity I am adding the 'login_view' only … -
Vue Django app Forbidden (CSRF cookie not set.): 403 Forbidden
I suppose this would actually be a django question as I think there's something wrong with the backend. I have my Vue code in frontend/ (127.0.0.1:8080) and django code in backend/ (127.0.0.1:8000). I've followed the django docs on CORS and CSRF Tokens but I get Forbidden (CSRF cookie not set.): when trying to make a post request to the django server. I'm trying to reset password via email. backend/settings.py ... CORS_ALLOW_ALL_ORIGINS = True # If this is used then `CORS_ALLOWED_ORIGINS` will not have any effect CORS_ALLOW_CREDENTIALS = True CSRF_TRUSTED_ORIGINS = [ 'http://127.0.0.1:8080', ] CORS_ALLOWED_ORIGINS = [ 'http://127.0.0.1:8080', ] # SESSION_COOKIE_SAMESITE = 'None' # CORS_ALLOW_CREDENTIALS = True EMAIL_BACKEND = 'django.core.mail.backends.filebased.EmailBackend' EMAIL_FILE_DIR = BASE_DIR / 'emails' # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'corsheaders', 'djoser', 'product', 'order', 'email_app' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ... backend/urls.py: urlpatterns = [ path('admin/', admin.site.urls), path('api/v1/', include('djoser.urls')), path('api/v1/', include('djoser.urls.authtoken')), path('api/v1/', include('product.urls')), path('api/v1/', include('order.urls')), path('api/v1/', include('email_app.urls')) ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) backend/email_app/urls.py: from django.urls import path from email_app import views urlpatterns = [ path('reset_password/', views.ResetPasswordEmail), ] backend/email_app/views.py: ... from rest_framework.decorators import api_view from django.views.decorators.csrf import csrf_exempt from .serializers import ResetPasswordEmail @api_view(['POST']) @csrf_exempt def reset_password(request): … -
Get webpage path useing django
When user login iwant to redirect him to user page with the same language This is what i tried to do if request.path == '/classgate/log-ar/' : messages.success(request,f'مرحبا !{request.user.username} استمتع بوقتك') return redirect('user-ar') elif request.path == '/classgate/log/' : messages.success(request,f'Welcome {request.user.username} enjoy your time') return redirect('userr') But when i did it with request.META.get('HTTP-REFERRER') It worked -
When using custom AuthBackend, unable to use request.user.is_authenticated or @login_required decorator
Firstly I'm coming from a PHP background and new to Django. And I'm trying to upgrade a webapp from a PHP framework to Django, keeping the database unchanged. The built-in authentication in Django is bit confusing, as my User table is different to what is expected in django's auth.User modal. In my usecase, I have an Employee entity whose login account is created at the instance of creating the Employee itself. The authentication part I managed to complete by implementing a custom AuthBackend. But now, I'm unable to use the @login_required decorator for other views post-login, because it throws and error 'User' object has no attribute 'is_authenticated'. In order to use is_authenticate method my User modal must then extend from auth.AbstractUser or auth.AbstractBaseUser. How can I keep the original table structure for User modal, but still get around these authentication functions in django? -
URL shortner app django based doesnt open the intended url
i was building a url shortner app in django and i am facing a problem that when i am putting the url it gets short but does not opens the url it was intended to and i cannot detect where the problem is i tried re directing the url to intended url path in my views but it doe=sent work i am expecting that if i am putting a long url in the box it shortens it and opens the url i asked for like full_url= https://stackoverflow.com/questions/ask short_url = stackoverflow and still opens this page -
Getting '502 Bad Gateway' error when accessing TensorFlow Django app deployed on the Google App Engine Flexible Environment
I am trying to deploy my Django app, which includes TensorFlow, on the Google App Engine Flexible Environment. The deployment was successful, but I encountered warnings and errors related to TensorFlow: 2023-06-25 11:24:30 default[20230625t180702] 2023-06-25 18:24:30.097285: W tensorflow/compiler/tf2tensorrt/utils/py_utils.cc:38] TF-TRT Warning: Could not find TensorRT 2023-06-25 11:24:32 default[20230625t180702] 2023-06-25 18:24:32.252226: I tensorflow/tsl/cuda/cudart_stub.cc:28] Could not find cuda drivers on your machine, GPU will not be used. 2023-06-25 11:24:34 default[20230625t180702] 2023-06-25 18:24:34.264702: I tensorflow/tsl/cuda/cudart_stub.cc:28] Could not find cuda drivers on your machine, GPU will not be used. 2023-06-25 11:24:34 default[20230625t180702] 2023-06-25 18:24:34.294337: I tensorflow/core/platform/cpu_feature_guard.cc:182] This TensorFlow binary is optimized to use available CPU instructions in performance-critical operations. 2023-06-25 11:24:34 default[20230625t180702] To enable the following instructions: AVX2 FMA, in other operations, rebuild TensorFlow with the appropriate compiler flags. I cannot find any other errors in my app besides this one, so I assume that this error is causing the application to fail and resulting in a "502 Bad Gateway" error. This my app.yaml: runtime: python env: flex entrypoint: daphne -p $PORT api.asgi:application env_variables: DJANGO_SETTINGS_MODULE: "api.settings" beta_settings: cloud_sql_instances: PROJECT_ID:REGION:INSTANCE_NAME runtime_config: operating_system: "ubuntu22" runtime_version: "3.10" Daphne worked fine without any errors, but it is unable to return anything. 2023-06-25 11:38:40 default[20230625t180702] "GET /" 502 2023-06-25 11:38:51 … -
Not able to set cookie using django set_cookie
I am trying to set cookie using django set_cookie. I am converting dict to string and then setting it in a cookie named 'blah'. The cookie gets set, but I see that the commas are replaced with \054. Python code x = { "key1": "value1", "key2": "value2", "key3": "value3", } response.set_cookie('blah', json.dumps(x)) return response How I see it in chrome: "{\"key1\": \"value1\"\054 \"key2\": \"value2\"\054 \"key3\": \"value3\"}" Any pointer what am I missing - please suggest. django==4.2 -
How to include custom model method in Django admin custom filter?
What I am trying to do: I am trying to make custom filter in Django admin using SimpleFilter for using in list_filter. What I tried: Below is the code that I wrote down in admin.py file. I used SimpleFilter for creating custom filter called RoomScoreFilter. RoomScoreFilter filters that if average score is 1.00 to 1.99, it will filter as Very poor and so forth. class RoomScoreFilter(admin.SimpleListFilter): title = _("Room Score") parameter_name = "score" def lookups(self, request, model_admin): return [ ("1", _("Very poor")), ("2", _("Poor")), ("3", _("Normal")), ("4", _("Good")), ("5", _("Excellent")), ] def queryset(self, request, queryset): if self.value() == "1": return queryset.filter(get_average_rating__gte=1, get_average_rating__lt=2) @admin.register(Review) class ReviewAdmin(admin.ModelAdmin): empty_value_display = "-----" fieldsets = [ ("Room & Customer", {"fields": ["room", "customer"]}), ( "Evaluation", {"fields": ["get_average_rating", "comment"], "classes": "wide"}, ), ( "Individual Scores", { "fields": [ "cleanliness", "accuracy", "location", "communication", "check_in", "value", ] }, ), ] list_display = ( "room", "customer", "cleanliness", "accuracy", "location", "communication", "check_in", "value", "get_average_rating", "comment", ) list_display_links = ("room",) list_per_page = 20 list_filter = [RoomScoreFilter] search_fields = ("room", "user") search_help_text = _("Searchable by room name and user ID.") readonly_fields = ("room", "customer", "comment", "get_average_rating") and below is my model. class Review(CommonDateTimeModel): """Review model Definition""" cleanliness = models.PositiveSmallIntegerField( validators=[MinValueValidator(1), MaxValueValidator(5)], verbose_name=_("Cleanliness"), help_text=_("How … -
In Django, after extending the User model, how to add values to the new model?
I have extended the User model in Django with a profile model named "Account" as per 4.2 version. The Django administration panel successfully lists the "Account" model as a section, and it works wonderfully in Django Adminstration panel. I want to set a value of "mobile_number" in Account model while the user signup. Right now I can do that manually in Django Admin Panel, but I need to update that while user signup. I am using following code: user = User.objects.create_user(username=username, first_name=first_name, last_name=last_name, email=email, password=password) mobile_number = user.Account.mobile_number user.save(); And I get error: AttributeError at /accounts/create 'User' object has no attribute 'Account' -
Django and react browser router shows only css
views.py def home(request): return render(request, 'index.html') def home4(request): return render(request, 'index.html') urls.py path('a/',views.home,name='home'), path('b/',views.home4,name='home4'), App.js import './App.css' ... <BrowserRouter> <Route path='/a' element={<Form/>} /> </BrowserRouter> When I got to /a it doesn't show the form component(it is just a form) but the css works. -
how to use context procesors
i want to use context processor in html template witch shows some information but dont know why doesn't it work properly ? models class Info(models.Model): phone_number = models.CharField(max_length=28) email_address = models.EmailField() locations = models.TextField(null=True, blank=True) context processor from Blog.models import Info def info_returner(request): return {'number':Info.phone_number, 'address': Info.locations} template HTML <div class="content"> <ul> <li> <h5>{{ number }}</h5> <span>PHONE NUMBER</span> </li> <li> <h5>{{ email }}</h5> <span>EMAIL ADDRESS</span> </li> <li> <h5>{{ location }}</h5> <span>STREET ADDRESS</span> </li> </ul> </div> as said I was trying to show user some info by context processors but don't know what's wrong with above code -
Data is not storing in django database
This is the code in views.py. def thanks(request): if request.method == 'POST': name = request.POST['name'] email = request.POST['email'] phone= request.POST['phone'] doctor = request.POST['doctor'] msg = request.POST['reason'] print(name, email, phone, msg) appointment_db = appointment(name=name, email=email, phone=phone, doctor=doctor, message=msg) appointment_db.save() return render(request, "thanks.html", {"name": name}) rest of the code is working. the only error is in the second-last and third-last line. appointment_db = appointment(name=name, email=email, phone=phone, doctor=doctor, message=msg) appointment_db.save() this is the error: appointment_db = appointment(email=email, phone=phone, doctor=doctor, message=msg) TypeError: appointment() got an unexpected keyword argument 'name' The model is also registered and it is showing in the admin panel. However, when I try to store data in it via forms, it throws an error.