Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Query using related name in django
I've two models: class User(models.Model): email = models.EmailField() name = models.CharField(max_length=255) password = models.CharField(max_length=255) class Profile(models.Model): group = models.ForeignKey(User, related_name='profiles') image = models.ForeignKey(Media, on_delete=models.CASCADE) #more attributes I've user's id and I want to get his image. user = User.objects.get(id=id) image = user.profiles.image This is throwing error. How can I do it? Thanks in advance. -
Static files 404 django (docker+nginx)
Whats wrong in settings of static files? If start without docker and nginx - works fine. I trieed mannually collectstatic, but its not help settings.py import os from pathlib import Path, PurePath BASE_DIR = Path(__file__).parent.parent STATIC_ROOT = PurePath(BASE_DIR.parent, "static/") STATIC_URL = "/static/" nginx.conf events { worker_connections 1024; } http { sendfile on; upstream app_server { server django:8000; } server { server_tokens off; listen 80; add_header Access-Control-Allow-Origin * always; add_header Access-Control-Allow-Methods GET,POST,DELETE,PUT,PATCH,OPTIONS; add_header Access-Control-Allow-Headers X-Requested-With,Content-Type; location /static/ { alias /static/; expires 1y; access_log off; add_header Cache-Control "public"; include /etc/nginx/mime.types; } location / { root /var/www/contacts/static/; index index.html; } location ~ ^/(manage|categories|events|persons|swagger|redoc|events) { proxy_pass http://app_server; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } } } part of docker-compose django: tty: true build: context: ../backend dockerfile: Dockerfile command: bash -c "poetry run gunicorn -c /etc/gunicorn/gunicorn.conf.py project.wsgi:application & poetry run python manage.py makemigrations & poetry run python manage.py migrate & poetry run python manage.py rundramatiq" container_name: contacts_django env_file: ../secrets/django.env depends_on: - postgresql image: contacts_django networks: - contacts_app_to_db ports: - 8000:8000 restart: unless-stopped volumes: - ../static:/static nginx: tty: true build: context: ../services/nginx/ dockerfile: Dockerfile container_name: contacts_nginx depends_on: - django env_file: ../secrets/nginx.env image: contacts_nginx networks: - contacts_nginx_to_app ports: - … -
django-simple-history3.1.1 error when cascade deletion
For a Django project I work on, I use django-simple-project to get a history of each of my models. Everything works very well when I create, modify or delete an object, the library generates a <HistoricalObject> each time. My problem is when I perform a cascade deletion. For example, I have a table B that inherits a table A. When I delete an object from my table A, it also deletes all its related objects in table B. Django-simple-history generates a <HistoricalObject> for my table A's object but for the B's it is a "corrupted" object with "formating error" because the deleted B object refers to an A object that no longer exists and this create an error. I can't even read the <HistoricalObject> of B when i query it. The error is : MyApp.models.tableA_object.DoesNotExist: tableA_object matching query does not exist. I haven’t found anything on the forums about it and it really blocks me, I can’t do without cascade deletion and django-simple-history meets all my needs except this one. Some infos : Django 4.0.3 django-simple-history 3.1.1 MySql Python 3.9.7 Thank you for your help -
Convert file path to url using CharField
I have a charfield model. All of charfields is a path to some file how to convert this paths to url. The path is relative to the media folder. Thanks in advance!!! -
Django - how to persist selected language throughout session?
I have a multi-page art gallery app that supports Japanese and English with Japanese being the default language on startup. In the header I have a button that should append the url with the selected language between English and Japanese. When the button is clicked, my app redirects to the homepage and displays the page with the new translated content. However, while in that new language, when I navigate to a different page within my app, it renders the page in Japanese, even if English was chosen. How can I persist the chosen language throughout the session regardless of where I navigate to? Do I need to pass the language as a parameter in my view? If so, how to do that? I've read the relevant Django docs but they didn't have an answer to this kind of problem. Thank you! index.html a tag button: {% get_current_language as LANGUAGE_CODE %} {% if LANGUAGE_CODE == 'ja' %} <a href="/en/" role="button"> English </a> {% else %} <a href="/ja/" role="button"> 日本語 </a> {% endif %} Main Project urls.py: urlpatterns += i18n_patterns ( path('', include('Art_Gallery_App.urls')), path('admin/', admin.site.urls), prefix_default_language=True ) Art_Gallery_App urls.py: urlpatterns = [ path('', views.index, name='index'), # by default, URL looks like this: … -
How to add headers into iframe src?
I have html like this: <iframe src="https://google.com" width="450" height="200" frameborder="0"></iframe> I need to add headers into src. How to do it? My app in Django. -
Cant delete folder after creating it with PyPDF2 - Python 3.10.1 and Django 4.0.6
Im creating a folder with PDF Files in it. Im using PyPDF2 in Django. It works all fine, the folder with the files in it is created. But after that, i cant delete it without stopping the running server. It throws an error saying the file is used by another application. Do anyone know how i can fix that problem? Here is the code snippet, which creates the folder with the pdf files in it: # Merge Befunde for folder in os.listdir(os.getcwd()): mergeFile = PyPDF2.PdfFileMerger() for filename in os.listdir(os.getcwd() + "\\" + folder): if filename.endswith(".pdf"): file = os.getcwd() + "\\" + folder + "\\" + filename try: mergeFile.append(PyPDF2.PdfFileReader(file)) except: print("Error in", file) else: continue mergeFile.write(folder + ".pdf") mergeFile.close() -
Using timezone with openpyxl
I need to add a date in an excel file. I use timezones on these dates. It works very well with django rest framework. (My GET requests return the date with this format: 2022-07-23T13:19:59+02:00) Same in Django admin, the Europe/Paris timezone is well taken into account (+02:00). However, when I use openpyxl, the indicated time is 2h late (it takes the UTC timezone). sheet.append([date_recorded.strftime("%d/%m/%Y %H:%M:%S")]) Same thing if I print this date in console. (2022-07-11 15:19:50+00:00) How to correct this? -
Speed up the nginx response
I'm using nginx + uwsgi + Django to start my service. The related config are showed as below: uwsgi config [uwsgi] pythonpath=/path/to/pythonpath chdir=/path/to/chdir env=DJANGO_SETTINGS_MODULE=conf.settings module=moudle.wsgi master=True pidfile=logs/pidfile.pid vacuum=True max-requests=1000 enable-threads=true processes = 4 threads=8 listen=1024 daemonize=logs/wsgi.log http=0.0.0.0:10205 buffer-size=32000 socket-timeout=1500 harakiri=1500 http-timeout=1500 nginx config nginx.conf worker_processes 12; events { use epoll; worker_connections 65535; } http { include mime.types; include log_format.conf; include upstream.conf; default_type application/octet-stream; sendfile on; tcp_nopush on; keepalive_timeout 1800; server_tokens off; client_max_body_size 100m; gzip on; gzip_min_length 1k; gzip_buffers 4 16k; gzip_comp_level 5; gzip_types text/plain application/json application/javascript application/x-javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg image/gif image/png; gzip_vary off; include "site-enabled/*.conf"; proxy_buffering on; proxy_buffer_size 4k; proxy_buffers 8 1M; proxy_busy_buffers_size 2M; proxy_max_temp_file_size 0; } log_format.conf log_format upstream '$remote_addr - $host [$time_local] "$request" ' '$status $body_bytes_sent $request_time $upstream_response_time ' '"$http_user_agent" "$http_x_forwarded_for" '; `upstream.conf upstream my_service { server host:16020 weight=50; server host:16020 weight=50; keepalive 100; } site-enabled/my_service.conf server { listen 7020; server_name my-service.xxx.cn; client_max_body_size 100M; access_log logs/my_service_access.log upstream; root /path/to/my_service/dist; location ^~ /api/base_api { proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_read_timeout 90; proxy_pass http://my_service; uwsgi_buffering on; uwsgi_buffers 8 8k; uwsgi_buffer_size 8k; } location / { try_files $uri /index.html =404; } } When I make a request, the response returned from uwsgi … -
MySQL Connection Error with Cpanel Hosting
I'm trying to connect my application with MySQL Database engine on Cpanel hosting platform but every time I tried to run makemigrations there's always this long error: Traceback (most recent call last): File "/home2/cmsmcsc1/virtualenv/cmsmcs/3.9/lib/python3.9/site-packages/django/db/backends/base/base.py", line 244, in ensure_connection self.connect() File "/home2/cmsmcsc1/virtualenv/cmsmcs/3.9/lib/python3.9/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/home2/cmsmcsc1/virtualenv/cmsmcs/3.9/lib/python3.9/site-packages/django/db/backends/base/base.py", line 225, in connect self.connection = self.get_new_connection(conn_params) File "/home2/cmsmcsc1/virtualenv/cmsmcs/3.9/lib64/python3.9/site-packages/mysql/connector/django/base.py", line 366, in get_new_connection cnx = mysql.connector.connect(**conn_params) File "/home2/cmsmcsc1/virtualenv/cmsmcs/3.9/lib64/python3.9/site-packages/mysql/connector/pooling.py", line 286, in connect return CMySQLConnection(*args, **kwargs) File "/home2/cmsmcsc1/virtualenv/cmsmcs/3.9/lib64/python3.9/site-packages/mysql/connector/connection_cext.py", line 101, in __init__ self.connect(**kwargs) File "/home2/cmsmcsc1/virtualenv/cmsmcs/3.9/lib64/python3.9/site-packages/mysql/connector/abstracts.py", line 1099, in connect self._post_connection() File "/home2/cmsmcsc1/virtualenv/cmsmcs/3.9/lib64/python3.9/site-packages/mysql/connector/abstracts.py", line 1071, in _post_connection self.set_charset_collation(self._charset_id) File "/home2/cmsmcsc1/virtualenv/cmsmcs/3.9/lib64/python3.9/site-packages/mysql/connector/abstracts.py", line 1016, in set_charset_collation ) = CharacterSet.get_charset_info(charset) File "/home2/cmsmcsc1/virtualenv/cmsmcs/3.9/lib64/python3.9/site-packages/mysql/connector/constants.py", line 775, in get_charset_info info = cls.get_default_collation(charset) File "/home2/cmsmcsc1/virtualenv/cmsmcs/3.9/lib64/python3.9/site-packages/mysql/connector/constants.py", line 746, in get_default_collation raise ProgrammingError(f"Character set '{charset}' unsupported") mysql.connector.errors.ProgrammingError: Character set '255' unsupported The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home2/cmsmcsc1/cmsmcs/manage.py", line 22, in <module> main() File "/home2/cmsmcsc1/cmsmcs/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home2/cmsmcsc1/virtualenv/cmsmcs/3.9/lib/python3.9/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/home2/cmsmcsc1/virtualenv/cmsmcs/3.9/lib/python3.9/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home2/cmsmcsc1/virtualenv/cmsmcs/3.9/lib/python3.9/site-packages/django/core/management/base.py", line 414, in run_from_argv self.execute(*args, **cmd_options) File "/home2/cmsmcsc1/virtualenv/cmsmcs/3.9/lib/python3.9/site-packages/django/core/management/base.py", line 460, in execute output = self.handle(*args, **options) File "/home2/cmsmcsc1/virtualenv/cmsmcs/3.9/lib/python3.9/site-packages/django/core/management/base.py", line 98, in wrapped res = … -
Django - module 'pymysql._auth' has no attribute 'scramble_old_password'
I am trying to connect mysql DB in django application. But it is throwing error- module 'pymysql._auth' has no attribute 'scramble_old_password'. -
Django 500 Internal Server Error only on log in success page
Request URL: http://35.239.95.43:8080/timetracker/login_success/ this is login succes url after providing credentials it has to show login succes page but giving this error.however on localhost everything working fine -
Return erroneous data with serializer error
Got user serializer for insert multiple users at once. class CreateUserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ( 'username', 'email', 'first_name', 'last_name', 'is_active', ) Passing data from request to serializer to create users payload = [ { "username": "johndoe", "email": "john@doe.com", "first_name": "John", "last_name": "Doe", "is_active": true }, { "username": "janedoe", "email": "jane@doe.com", "first_name": "Jane", "last_name": "Doe", "is_active": true }, { "username": "johndoe", "email": "james@doe.com", "first_name": "James", "last_name": "Doe", "is_active": true } ] While inserting payload via serializer, is_valid returns false because same username used twice in payload. def create_user(request): data = request.data["payload"] serialized_data = CreateUserSerializer(data=data, many=is_many) if serialized_data.is_valid(): serialized_data.save() else: return serialized_data.errors The method above is returns [{'username': [ErrorDetail(string='user with this username already exists.', code='unique')], }] error but not indicates which data is erroneous. Is there a way to detect erroneous data and attach data to serialize error in any way? -
I added In-Reply-To and References in my headers while sending Email through SendGrid, however it doesn't work
So I am sending an email reply through SendGrid and I have a message object something like this: message = { "personalizations": context["personalizations"], "from": {"email": context["sender_email"]}, "subject": context["subject"], "content": [{"type": MimeType.html, "value": context["body"]}], "reply_to": {"email": context["reply_to"]}, "headers": {"In-Reply-To": "<Prev-Message-ID>", "References": "<Prev-Message-ID>", } } sg = SendGridAPIClient(os.environ.get("SENDGRID_API_KEY")) sg.send(message) Now when I go to the 'Show Original' in Gmail, the email does have References and In-Reply-To in headers. Something like this: Content-Transfer-Encoding: quoted-printable Content-Type: text/html; charset=us-ascii Date: Thu, 04 Aug 2022 05:47:05 +0000 (UTC) From: test.Taylor-Hood_b56ef494-4d5e-4568-bcf5- bc68d489f86b@hirecinch.com Mime-Version: 1.0 Message-ID: <3S2bF8n9Rj-0eNQWf172Gw@geopod-ismtpd-4-0> Subject: Hakunamatata!!! Reply-To: 3b0b71af9b8ba94577730eb010f0887e@mailer.local.hirecinch.com In-Reply-To: <CABQc7oqgKENUUAz6Mg4kdS7ZS8Q3Wq95DPNo-O2- 18wyaVaXgw@mail.gmail.com> References: <CABQc7oqgKENUUAz6Mg4kdS7ZS8Q3Wq95DPNo-O2- 18wyaVaXgw@mail.gmail.com> However, the email I send is never appended as a reply and always makes a new thread. What am I doing wrong?? Is it about the subject of the email which I send in reply?? I have tried doing Re: The Subject, but it still doesn't work. I have to display the whole conversation as a thread having sub-threads in my product and I'm stuck. -
set accept-ranges of django app on pythonanywhere
I'm deploying django app to the "pythonanywhere". I have the middleware to set accept-ranges to bytes and it work perfactly well in my localhost, but not in pythonanywhere server. Is there another way to set accept-ranges in my pythonanywhere server? -
Masonite Invalid CSRF token
Invalid CSRF Token raise InvalidCSRFToken("Invalid CSRF Token") After running the command "python craft serve" it is showing this error. -
Create new schema in django migration file
How to create a new schema using Django migration file? I dont see any migrations.CreateSchema() option just like there is migrations.CreateModel() Currently the way I do this is in my migration file I write custom sql: operations = [ migrations.RunSQL('create schema if not exists schema1;'), ] -
django.db.utils.DatabaseError: ORA-00932: inconsistent datatypes: expected - got NCLOB
Getting this error on django-Oracle database while fetchinfg queryset on .distinct() filtering. -
Django Many to many how to give input to 3rd table
class Author(models.Model): name = models.CharField(max_length = 100) def __str__(self): return self.name class Book(models.Model): title = models.CharField(max_length = 100) authors = models.ManyToManyField(Author) def __str__(self): return self.title In [5]: Author.objects.all() Out[5]: <QuerySet [<Author: Shanmukh>, <Author: Shyam>, <Author: sai>, <Author: VICKYS>, <Author: Himayu>, <Author: Himanya>, <Author: Srinivas>, <Author: LASKARATOYIBA>, <Author: ISI>, <Author: JAMI>]> please help in solving this i dont understand how do i give data to 3rd table which is a combination of id bookid and authorid -
Django raises the exception for error wont override for HttpResponse
I am using the Django to create my custom error page handler for 400, 403, 404 ,500. But for some reason, when the page return HttpResponse error, it wont direct me to my django custom error template page, instead of, it shows this. This django can find the url and go in the view function, but we return HttpResponse 404 it is not found. For example, http://127.0.0.1:8000/404/ , this will go to the customize page because Django cannot find this url in our project ### views.py from django.shortcuts import render def page_not_found_view(request, exception): return render(request, 'error.html',status = 404,context = { 'status_code' : 404, 'message' : "The page you were looking for doesn't exist anymore.", 'title' : "Page Not Found" }) def internal_server_error_view(request, *args, **argv): return render(request, 'error.html',status = 500,context = { 'status_code' : 500, 'message' : "500 Internal Server Error.", 'title' : "Internal Server Error" }) def forbidden_error_view(request, exception): return render(request, 'error.html',status = 403,context = { 'status_code' : 403, 'message' : "403 Forbidden Error.", 'title' : "Forbidden Error" }) def bad_request_error_view(request, exception): return render(request, 'error.html',status = 400,context = { 'status_code' : 400, 'message' : "400 Bad Request Error.", 'title' : "Bad Request" }) ### urls.py hanlder400 = "gotani.views.bad_request_error_view" handler404 = … -
Persisting session data across sign up
My website has a need similar to this question, but slightly different. Plus I am hoping maybe something has changed in 10 years. I am using Django 4.0.2, Python 3.8. Normal functionality - works fine Users sometimes upload content on the website (nothing sensitive). The website processes that content and emails back the results to the users Sometimes people will upload when they're not logged in. In that case, any values saved in the session are still accessible after the login (different behavior than the linked question above was experiencing). Everything works fine. New users - functionality gap - need ideas Sometimes visitors will upload content before creating an account After the upload, they're directed to create an account (which requires email verification, implemented through AllAuth) When they come back the session data is all lost Is there a way the website could recognize it's the same user post account creation / verification / login? Is setting a cookie my only option (if even that), or is there a more Django way of doing this using sessions? -
My model is not saving with in my database
VIEWS from django.shortcuts import render from django.views.generic import(ListView, CreateView) from models import UserProfileInfo from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib.auth.models import User from forms import UserForm # Create your views here. class UserCreateView(CreateView): template_name = "message_app/post_list.html" form_class = UserForm model = UserProfileInfo FORMS from django import forms from models import UserProfileInfo class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput()) class Meta(): model = UserProfileInfo fields = "__all__" POST_LIST.html <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title></title> </head> <body> <h1>Please Sign Up</h1> <form method="post "> {{ form.as_p }} {% csrf_token %} <input type="submit" value="SignUp"> </form> <a href="{% url 'admin:index' %}">Admin</a> </body> </html> When I go inside my admin site I can't see an of this information saved Isn't the create class view already supposed to automatically save it or am I missing something -
Django form class and view class connected
Hi in my code(not written by me) i have django form class and views class. I dont know how this is connected each other. Can anyone tell me how this is connected? Also can any one please tell me how this messege : Credential is in use by {0} collections that are turned on and " "{1} collections that are turned off. Be mindful that over-using " "credentials may result in collecting being rate limited by the " "social media API is displayed, i mean if i need to change the alignment of this text where i should change? My code classes are : from forms.py : class CollectionTwitterSearch2Form(BaseCollectionForm): incremental = forms.BooleanField(initial=True, required=False, label=INCREMENTAL_LABEL, help_text=INCREMENTAL_HELP) def __init__(self, *args, **kwargs): super(CollectionTwitterSearch2Form, self).__init__(*args, **kwargs) self.helper.layout[0][5].extend(('incremental',)) if self.instance and self.instance.harvest_options: harvest_options = json.loads(self.instance.harvest_options) if "incremental" in harvest_options: self.fields['incremental'].initial = harvest_options["incremental"] def save(self, commit=True): m = super(CollectionTwitterSearch2Form, self).save(commit=False) m.harvest_type = Collection.TWITTER_SEARCH_2 harvest_options = { "incremental": self.cleaned_data["incremental"], } m.harvest_options = json.dumps(harvest_options, sort_keys=True) m.save() return m from views.py : def _get_credential_use_map(credentials, harvest_type): credential_use_map = {} if harvest_type in Collection.RATE_LIMITED_HARVEST_TYPES: for credential in credentials: active_collections = 0 inactive_collections = 0 for collection in credential.collections.all(): if collection.is_on: active_collections += 1 else: inactive_collections += 1 if active_collections == 0 … -
How do I resolve BulkwriteError when using MongoDb with djangorestframework-simplejwt?
I am using MongoDB and SimpleJWT in DjangoREST to authenticate and authorize users. I tried to implement user logout, whereby in SimpleJWT it's basically blacklisting a user token. When the first user logs in, everything seems okay and their refresh token is added to the Outstanding token table. But when I try to log in a second user, I get the below error: raise BulkWriteError(full_result) pymongo.errors.BulkWriteError: batch op errors occurred, full error: {'writeErrors': [{'index': 0, 'code': 11000, 'keyPattern': {'jti_hex': 1}, 'keyValue': {'jti_hex': None}, 'errmsg': 'E11000 duplicate key error collection: fsm_database.token_blacklist_outstandingtoken index: token_blacklist_outstandingtoken_jti_hex_d9bdf6f7_uniq dup key: { jti_hex: null }', 'op': {'id': 19, 'user_id': 7, 'jti': '43bccc686fc648f5b60b22df3676b434', 'token': 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoicmVmcmVzaCIsImV4cCI6MTY1OTY1NDUzNCwiaWF0IjoxNjU5NTY4MTM0LCJqdGkiOiI0M2JjY2M2ODZmYzY0OGY1YjYwYjIyZGYzNjc2YjQzNCIsInVzZXJfaWQiOjd9.aQmt5xAyncfpv_kDD2pF7iS98Hld98LhG6ng-rCW23M', 'created_at': datetime.datetime(2022, 8, 3, 23, 8, 54, 125539), 'expires_at': datetime.datetime(2022, 8, 4, 23, 8, 54), '_id': ObjectId('62eb00064621b38109bbae16')}}], 'writeConcernErrors': [], 'nInserted': 0, 'nUpserted': 0, 'nMatched': 0, 'nModified': 0, 'nRemoved': 0, 'upserted': []} The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\MR.Robot\.virtualenvs\fsm-GjGxZg3c\lib\site-packages\djongo\cursor.py", line 51, in execute self.result = Query( File "C:\Users\MR.Robot\.virtualenvs\fsm-GjGxZg3c\lib\site-packages\djongo\sql2mongo\query.py", line 784, in __init__ self._query = self.parse() File "C:\Users\MR.Robot\.virtualenvs\fsm-GjGxZg3c\lib\site-packages\djongo\sql2mongo\query.py", line 869, in parse raise exe from e djongo.exceptions.SQLDecodeError: Keyword: None Sub SQL: None FAILED SQL: INSERT INTO "token_blacklist_outstandingtoken" ("user_id", "jti", "token", "created_at", "expires_at") VALUES (%(0)s, … -
TypeError at /dashboard/profiles/create/ path_and_rename() missing 2 required positional arguments: 'instance' and 'filename'
I am trying to save information from the form created out of the Django model. I am really not much experienced as this is my second project, Please help where you can. Thanks here is my view def profile_create_view(request): form = ProfileCreateForm(request.POST or None) if form.is_valid(): form.save form = ProfileCreateForm() context = { 'form':form } return render(request, 'users/profile', context) my form is here class ProfileCreateForm(forms.ModelForm): class Meta: model = Profile fields = [ 'avatar', 'user_type', 'first_name', 'last_name', 'gender', 'email', 'phonenumber', 'birth_date',] and then my model is here class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) avatar = models.ImageField(upload_to = '', default = path_and_rename, blank=True) provider = 'provider' requester = 'requester' user_types = [ (provider, 'provider'), (requester, 'requester'), ] user_type = models.CharField(max_length=155, choices=user_types, default=requester) first_name = models.CharField(max_length=255, default='') last_name = models.CharField(max_length=255, default='') GENDER_MALE = 'Male' GENDER_FEMALE = 'Female' OTHER = 'Other' GENDER_CHOICES = [ (GENDER_MALE, 'Male'), (GENDER_FEMALE, 'Female'), (OTHER, 'Other'), ] gender = models.CharField(max_length=15, choices=GENDER_CHOICES, blank=True) email = models.EmailField(default='none@email.com') phonenumber = models.CharField(max_length=15, default='') birth_date = models.DateField(default='1975-12-12') Thank you