Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Change field value in clean() after negative validation
I have a problem that I don't know how to solve. I don't know if that's even possible :( I have a form that has four fields for simplicity (check, select, time1, time2). When the checkbox is active, the time field is displayed, otherwise select (using JS). class Form(forms.Form): check = forms.BooleanField(required=False, initial=False, widget=forms.CheckboxInput(attrs={'style':'width:20px;height:20px;'})) select = forms.ChoiceField(choices=[], required=False) time1 = forms.TimeField(required=False) time2 = forms.TimeField(required=False) def __init__(self, *args, **kwargs): select = kwargs.pop('select', None) super(Form, self).__init__(*args, **kwargs) self.fields['select'].choices = select def clean(self): cleaned_data = super(Form, self).clean() time1 = cleaned_data.get("time1") time2 = cleaned_data.get("time2") select = cleaned_data.get("select") check = cleaned_data.get("check") if check: if time1 is None or time2 is None: raise forms.ValidationError( {'time1': ["error!", ], 'time2': ["error!", ]} ) else: if select is None: raise forms.ValidationError( {'select': ["error!", ]} ) I don't know how to change the value of the check field to True when the time fields are not filled.I can't use cleaned_data["check"] = True with return because it won't throw an exception -
Can't pass project ID to function
I have the below view: def gdpr_status(request, orgid, pid, status): user = request.user if people.objects.filter(orgid=org.objects.get(orgid=orgid), personid=user).count() > 0: t = project.objects.get(projectid=project.objects.get(projectid=pid), orgid=org.objects.get(orgid=orgid)) t.status = status t.save() url_to_redirect = '/projects/'+orgid return redirect(url_to_redirect) and the below URLs path('gdpr_status/<orgid>/<pid>/<status>', views.gdpr_status, name='gdpr_status'), when I pass the URL 'http://localhost:8082/gdpr_status/1/5/rejected', I get the below error: Field 'projectid' expected a number but got <project: project object (5)>. I don't understand because the project ID is project 5, i'm not passing an object, I am passing an ID for the record I want to update. Can anyone help me please? -
Factory-boy fuzzy DateTimeField always the same date when using create_batch
I am using factory-boy for creating instances of a Django model, and I am always getting the same value returned when using factory.fuzzy.FuzzyDateTime. Minimal example: # factory class class FooFactory(DjangoModelFactory): class Meta: # models.Foo has a dt_field that is a DateTimeField model = models.Foo # creation of object, in unit tests # I can't move the dt_field declaration # into the factory definition since different # unit tests use different start / end points # for the datetime fuzzer now = datetime.datetime.now(tz=pytz.timezone("America/New_York")) one_week_ago = now - datetime.timedelta(days=7) FooFactory.create_batch( 10, dt_field=factory.fuzzy.FuzzyDateTime( start_dt=one_week_ago, end_dt=now ) ) When inspecting the Foo models after factory creation, the dt_field has the same date: >>> [r.dt_field for r in Foo.objects.all()] >>> [datetime.datetime(2022, 12, 10, 20, 15, 31, 954301, tzinfo=<UTC>), datetime.datetime(2022, 12, 10, 20, 15, 31, 961147, tzinfo=<UTC>), datetime.datetime(2022, 12, 10, 20, 15, 31, 967383, tzinfo=<UTC>), ...] -
Check if logged in user is the author of a post | Django | If-else doesn't work
I want to check if the logged in user is the author of a post in my Forum. I have written some code to figure that out: <div class="right-section-posts"> user: {{ user }} <!--Output: Admin--> author: {{ post.author }} <!--Output: Admin--> {% if user == post.author %} <form action="DELETE"> {% csrf_token %} <button type="submit" class="delete-btn" name="post-id" value="{{ post.id }}">Delete</button> </form> <a href=""><button class="edit-btn">Edit</button></a> {% endif %} </div> They both output the same but the statement returns false! Why? Models.py class Post(models.Model): vote_count = models.IntegerField(default=0) id = models.BigAutoField(primary_key=True) created_at = models.DateField(default=date.today) title = models.CharField(max_length=100) description = models.CharField(max_length=1000) tags = models.CharField(max_length=200) author = models.CharField(max_length=100, default="none") def __str__(self): return str(self.id) + ' ' + self.title I tried different ways to get the Current user and the author. Doesn't work to. (I think you might say that I should use ForeignKey instead of ´CharField´, when using that I get this Error: ERROR: Column forum_app_post.author_id does not exist. LINE 1: ...app_post". "description", "forum_app_post". "tags", "forum_app... ^ HINT: Perhaps the intention was to refer to the "forum_app_post.author" column. ) -
How do I use Django's Related Lookups?
I notice that Django's relational fields register 7 lookups: fk.get_lookups() 'in' : <class 'django.db.models.fields.related_lookups.RelatedIn'>, 'exact' : <class 'django.db.models.fields.related_lookups.RelatedExact'>, 'lt' : <class 'django.db.models.fields.related_lookups.RelatedLessThan'>, 'gt' : <class 'django.db.models.fields.related_lookups.RelatedGreaterThan'>, 'gte' : <class 'django.db.models.fields.related_lookups.RelatedGreaterThanOrEqual'>, 'lte' : <class 'django.db.models.fields.related_lookups.RelatedLessThanOrEqual'>, 'isnull' : <class 'django.db.models.fields.related_lookups.RelatedIsNull'>} defined in https://github.com/django/django/blob/stable/3.2.x/django/db/models/fields/related_lookups.py registered in https://github.com/django/django/blob/stable/3.2.x/django/db/models/fields/related.py I'm familiar with how to use __exact (aka =), __in, and __isnull with relations, but there's no mention in the docs of what it means to apply lt / lte / gt / gte to a relation. Are they set comparisons? -
How can I set the Type of an Unpickled Object?
I am unpickling an object (chocolate) that belongs to the class Food via: chocolate = pickle.loads(chocolate_pickled) Assuming I have a Food import at the top of my file, how can I tell python that chocolate belongs to the Food class? -
Getting error in my resume field in django in admin panel when made even made it optional
I have to input a resume field in a interview form website using django which is optional in the form and the form is getting submitted well on the front end but when I am opening the admin panel it is showing errors in the registation in the admin panel if the resume is not uploaded. ` admin.py: class RegAdmin(ImportExportModelAdmin, admin.ModelAdmin): list_display = ('name', 'email', 'branch', 'phone_number', 'terms_confirmed') search_fields = ('name', 'email', 'branch', 'phone_number') def resume_url(self, instance): resume = instance.resume.url if resume: return mark_safe('<a target="_blank" href="%s">Resume Link</a>' % (resume)) else: return '-' ` forms.py resume = models.FileField( upload_to='resumes/', validators=[ file_size, FileExtensionValidator(allowed_extensions=["pdf", "docx"]) ], blank=True, null=True) -
getting an error while trying to start psql server
Hello I'm getting the below error while trying to start psql server on win 10 is there any recommendation? pg_ctl -D C:\Users\Islam.Fayez\AppData\Local\Programs\pgsql\pgdata -l logfile start unrecognized win32 error code: 123unrecognized win32 error code: 123unrecognized win32 error code: 123unrecognized win32 error code: 123waiting for server to start....Access is denied. stopped waiting pg_ctl: could not start server Examine the log output. -
how can i render base.html in one app's view?
i want create a footer info model and use base.html in static folder and why its not work? models.py class FooterContactInfo(models.Model): phoneumber1=models.CharField(max_length=15) phoneumber2=models.CharField(max_length=15) email_help =models.EmailField() address=models.CharField(max_length=100) views.py def FooterContactInfo_view(request): footer = FooterContactInfo.objects.all().last() return render(request, 'base.html',context={'footer':footer}) base.html <li> <a href="#0"><i class="fas fa-phone-alt"></i>{{footer.phoneumber1}}</a> </li> <li> -
Django: LoginView redirects me to accounts/profile instead of the previous page
My page has a navigation bar that is visible on all pages. There is a "Sign In/Sign Up" button. After signing in I would like to redirect the user to the previous page. Example: I'm currently looking to buy vinyl at http://127.0.0.1:8000/vinyls/. I press "Sign In" and I type my credentials. After clicking the Submit button, I would like to get back to /vinyls/. The same goes for /record_labels/, /events/ etc. I tried using <input type="hidden" name="next" value="{{ next }}"> in my sign-in template but I get redirected to /accounts/profile. Then I tried using <a id="nav-a" href="{% url 'sign in' %}?next={{ request.path }}">Sign Up/Sign In</a> but I'm redirected to /accounts/profile. This is my SignInView: class SignInView(auth_views.LoginView): template_name = 'sign-in.html' This is my sign-in.html: <h1>Sign in</h1> <form method="post" action="{% url 'sign in' %}"> {{ form.as_p }} <input type="hidden" name="next" value="{{ next }}"> <p> <button type="submit">Sign in</button> {% csrf_token %} </p> <p>Not a member? <a href="{% url 'sign up' %}">Sign up now</a></p> </form> -
Matching query doesn't exist error when logging in as different user on different tabs on a browser
I am currently work on small project on djnago and it's almost finished. But from the beginning I have been facing a problem that, when I run the webpage on multiple tabs and logs in, only the last logged in user's full data is seen, when I go to the previously logged in user's tab it throws "MATCHING QUERY DOESN'T EXIST!". This makes me to log in with that particular user's data to be seen simultaneously the last logged in user's tab throws the previously mentioned error. My requirement is "It should be able to login different users on different tabs on same browsers and without any error on djnago framework". Please let me know if there is any way. Thanks in advance -
Django is unable to use the SMTP server in the tests environment
I am running a Django (4.1) app in Docker. As part of our test suite, I would like to make use of a development SMTP server which is also running in a Docker container (see docker-compose.yml below). I am using a Selenium driver to run the tests against a Django LiveServer instance. I am also using 1secmail as a temporary mailbox for the tests. The SMTP server is working nicely with Django (i.e. Django is able to send emails with it) only if Django is not running from a LiveServer. Whenever I try to programmatically test a scenario where SMTP is involved (with a Selenium driver), the email never gets sent (see the failing test below). The question is simple: how do I make Django and the SMTP server talk to each other in the tests environment? My docker-compose.yml version: '3.8' services: myapp: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - ./:/usr/src/app/ ports: - 8009:8000 env_file: - ./.env.dev links: - selenium-chrome - dev-smtp-server myapp-db: image: postgres:14-alpine volumes: - postgres_data:/var/lib/postgresql/data/ environment: - POSTGRES_USER=blabla - POSTGRES_PASSWORD=blabla - POSTGRES_DB=blabla selenium-chrome: image: selenium/standalone-chrome ports: - 4444:4444 # actual Selenium - 5900:5900 # VNC server dev-smtp-server: image: bytemark/smtp restart: always volumes: postgres_data: My test … -
Issues with poetry when deploying Django app to Render
I am following the “Getting Started With Django on Render” tutorial (https://render.com/docs/deploy-django#update-your-app-for-render) and all was going well until I got to “Configure Django for PostgreSQL”. I have everything copied correctly but I am getting errors now when I run python manage.py runserver this is the error: File "/Users/user/Desktop/First_Program/Portfolio_Projects/Charter_Django_App/Charter_Django_App/config/settings.py", line 14, in <module> import dj_database_url ModuleNotFoundError: No module named 'dj_database_url' even though when I run poetry show it clearly says it is installed asgiref 3.5.2 ASGI specs, helper code, and adapters brotli 1.0.9 Python bindings for the Brotli compression library dj-database-url 1.0.0 Use Database URLs in your Django Application. dj-email-url 1.0.6 Use an URL to configure email backend settings in your Django Application. django 3.2.16 A high-level Python Web framework that encourages rapid development and clean, pragmatic design. django-cache-url 3.4.2 Use Cache URLs in your Django application. environs 9.5.0 simplified environment variable parsing gunicorn 20.1.0 WSGI HTTP Server for UNIX marshmallow 3.19.0 A lightweight library for converting complex datatypes to and from native Python datatypes. packaging 22.0 Core utilities for Python packages psycopg2-binary 2.9.5 psycopg2 - Python-PostgreSQL Database Adapter python-dotenv 0.21.0 Read key-value pairs from a .env file and set them as environment variables pytz 2022.6 World timezone definitions, modern and … -
TypeError. can only concatenate str (not "User") to str
How do I convert request.user.username to a string So far ive tried username = str(request.user.username), username = request.user.get_username() -
Function for returns X times same result
Im new at python and django, i need this function for work if someboyd can help me i'll appreciate it so much. This function has to return in a json file all the different results with the function 'for' but instead it returns 1 result X times the same one X times. @login_required def oferta_reporte_json(request): ofertas_efectiva = OfertaEfectiva.objects.count() ofertas_efectivas = OfertaEfectiva.objects.filter(oferta__completa=True, oferta__activa=True, oferta__finalizada=True) nombre_ofertas = [] # ocurrencias = 0 for efectiva in ofertas_efectivas: nombre_oferta = dict() postulado = dict() entrevistado = dict() seleccionado = dict() entrevistados = [] postulados = [] seleccionados = [] cand_seleccionados = ListaFinal.objects \ .filter(interesado__id_oferta=efectiva.oferta.id) seleccionados_ids = cand_seleccionados.values_list('interesado_id', flat=True) cand_postulados = Postulados.objects \ .filter(interesado__id_oferta=efectiva.oferta.id) \ .exclude(interesado_id__in=seleccionados_ids) postulados_ids = cand_postulados.values_list('interesado_id', flat=True) cand_entrevistados = Entrevistados.objects \ .filter(interesado__id_oferta=efectiva.oferta.id) \ .exclude(interesado_id__in=postulados_ids) #DATOS #MÉTODO PARA VER CUANTAS OFERTAS NO TIENEN 1 ATRIBUTO# # if efectiva.oferta.region is None: # print(efectiva.oferta.id), # print(efectiva.oferta.titulo), # print(efectiva.oferta.nombre_empresa) # ocurrencias = ocurrencias + 1 # print("TOTAL = " + str(ocurrencias)) nombre_oferta['id_oferta'] = efectiva.oferta.id nombre_oferta['titulo_oferta'] = efectiva.oferta.titulo nombre_oferta['nombre_completo_owner'] = efectiva.oferta.owner.first_name + ' ' + efectiva.oferta.owner.last_name nombre_oferta['descripción'] = efectiva.oferta.descripcion nombre_oferta['cargo'] = efectiva.oferta.cargo nombre_oferta['vacantes'] = efectiva.oferta.vacantes nombre_oferta['nombre_empresa'] = efectiva.oferta.nombre_empresa nombre_oferta['descripción_empresa'] = efectiva.oferta.descripcion_empresa nombre_oferta['cultura'] = efectiva.oferta.cultura_empresa nombre_oferta['negocio'] = efectiva.oferta.negocio_empresa nombre_oferta['funciones'] = efectiva.oferta.principales_funciones nombre_oferta['industria'] = efectiva.oferta.industria.nombre nombre_oferta['linea_funcional'] = efectiva.oferta.linea_funcional.nombre nombre_oferta['nivel_cargo'] … -
Django for loop working on one template page, but disappears elsewhere?
I have written a Django for loop that iterates over each instance of my Supplier model to render each instance in my navigation bar. However for some reason it only outputs on one of my templates and not the main page. This is the loop in question: <ul class="nav-drop"> {% for supplier in suppliers %} <li> <a href="{% url 'supplier' pk=supplier.pk %}">{{ supplier.name }}</a> </li> {% endfor %} </ul> here is my views.py file: from django.shortcuts import render from . models import Supplier # Create your views here. def suppliers(request): suppliers = Supplier.objects.all() context = {'suppliers': suppliers} return render(request, 'suppliers/suppliers.html', context) def supplier(request, pk): supplier = Supplier.objects.get(id=pk) context = {'supplier': supplier} return render(request, 'suppliers/supplier.html', context) from django.urls import path from . import views urlpatterns = [ path('suppliers/', views.suppliers, name='suppliers'), path('supplier/<str:pk>/', views.supplier, name='supplier') ] and the model in question: class Supplier(models.Model): name = models.CharField(max_length=200, blank=True, null=True) logo_image = models.ImageField(null=True, blank=True, upload_to='models/', default="models/default.jpg") marketing_image = models.ImageField(null=True, blank=True, upload_to='models/', default="models/default.jpg") description = models.TextField(blank=True, null=True) short_description = models.TextField(max_length=200, blank=True, null=True) social_facebook = models.CharField(max_length=200, blank=True, null=True) social_twitter = models.CharField(max_length=200, blank=True, null=True) social_instagram = models.CharField(max_length=200, blank=True, null=True) social_youtube = models.CharField(max_length=200, blank=True, null=True) social_linkedin = models.CharField(max_length=200, blank=True, null=True) social_website = models.CharField(max_length=200, blank=True, null=True) created = models.DateTimeField(auto_now_add=True) id … -
Is it a good practice to use variables by 'with' tag in django template on global scope
I need to use more times some custon variables (e.g. one of them) with total=business.employees.count But I have a very lot of lines in my code and I think is constant use of them in different parts is not good. So is it good to insert these tags at the very beginning and close at the very end of the file? For example {% load static %} {% with total=business.employees.count %} <html> a lot of lines of code </html> {% endwith %} I need some advice -
Is there a solution to "does not appear to have any patterns in it." problem?
Have a nice day! While I was building my django project, I faced this error. Error: The included URLconf '<module 'posts.urls' from "D:\Created apps\My project\posts\urls.py">' does not appear to have any patterns in it. If you see the 'urlpatterns' variable with valid patterns in the file then the issue is probably caused by a circular import. So, here's given my project files. -------- posts/urls.py: ---------- ` from django.urls import path from .views import BlogListView, BlogDetailView url_patterns = [ path('', BlogListView.as_view(), name='index'), path('post/<int:pk>/', BlogDetailView.as_view(), name='post_detail'), ] ` ----------- posts/views.py: ----------- ` from django.shortcuts import render from django.views.generic import ListView, DetailView from .models import Post class BlogListView(ListView): model = Post template_name = 'index.html' class BlogDetailView(DetailView): model = Post template_name = 'post_detail.html' ` ------------- config/urls.py: ---------- ` """config URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/4.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) … -
how do I get value of dictionary 1 by key of dictionary 2 in Django templates
I have 2 dictionaries dict1 and dict2. I'm trying to get the value by the dict1 key to the dict2 key but it getting nothing, is there any way to get the value of dict2 by the dict1 key? always both dictionaries will be the same length? dict1 = {0:[1,2,3],1:[4,5,6]} dict2 = {0:'data1',1:'data2'} {% for key, value in dict1.items %} {{dict2.key}} {% endfor %} -
I ruined the admin page, how do I fix it? ( Django 4.1 )
I have followed the steps from the django tutorial ( https://docs.djangoproject.com/en/4.1/intro/tutorial01/ ) and once I'd finished all the steps I stopped developing the project for 2 weeks at least without giving it much thought. Once I've decided to check how the pages were looking like that's when I found this: The admin page And I don't know how I did it. Here's how the documentation looks like: meuSite/ __init__.py settings.py urls.py asgi.py wsgi.py polls/ migrations/ static/ templates/ admin/ base.html polls/ detail.html index.html results.html __init__.py admin.py apps.py models.py tests.py urls.py views.py db.sqlite3 manage.py SETTINGS: meuSite/settings.py INSTALLED_APPS = [ 'polls.apps.PollsConfig', "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", ] URLS: # meuSite/urls.py from django.contrib import admin from django.urls import include, path urlpatterns = [ path("admin/", admin.site.urls), path("polls/", include('polls.urls')), ] # polls/urls.py from django.urls import path from . import views app_name = 'polls' urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('<int:question_id>/', views.DetailView.as_view(), name='detail'), path('<int:question_id>/results/', views.ResultsView.as_view(), name='results'), path('<int:question_id>/vote/', views.vote, name='vote') ] If there's something else that I didn't show that may have the root of the problem, please tell me I tried solving it by deleting the templates/admin directory, but it didn't change how the page looks -
How can I send verification email on Django when user update email id using signals.py
how can I send verification emails on django using signals.py when a user updates the email id on the Custom profile model? This is my signals.py for updating the User model. I want to send a confirmation email when the user updates their email id. @receiver(post_save, sender=models.Profile_user) def update_auth_user_model_handler(sender, instance, created, **kwargs): if created: return user_instance = instance.user user_instance.first_name = instance.first_name user_instance.last_name = instance.last_name user_instance.email = instance.email user_instance.save() I want to send confirmation email to the new email when an user updates his email id before saving it to the User model on Django -
is there an efficient way of preventing the same email addresses registered with the different capitalizations sign up in django?
In views.py if User.objects.filter(email = email).exists(): messages.info(request, 'Email already in use') return redirect('signup') Django only checks if the exact email with the exact capitalization exists so for example if there is johndoe@yahoo.com in the user object and I signup with jOHNDoe@yahoo.com instead of telling it that email already in use it creates another user for the gmail with it's unique capitalization. admin user panel -
How to delete follow id base on both user_id and following_user_id using Django Rest Framework?
Okay, here's the thing I'm already able to create userfollowing relationship based on both the current user(user_id) and the user that is being followed (following_user_id). But what I want to do is to be able to delete a specific user_id and following_user_id following relationship by the id that was generated when the relationship was first established. Here's my code for better understanding. Thanks in advance for your help, which I will really appreciate. My UserFollowing Model class UserFollowing(models.Model): user_id = models.ForeignKey( User, on_delete=models.CASCADE, related_name="following") following_user_id = models.ForeignKey( User, on_delete=models.CASCADE, related_name="followers") created = models.DateTimeField(auto_now_add=True) class Meta: constraints = [ models.UniqueConstraint(fields=['user_id','following_user_id'], name="unique_followers") ] ordering = ["-created"] def __str__(self): return f"{self.user_id.name} follows {self.following_user_id.name}" My UserFollowing Views class UserFollowingView(generics.ListCreateAPIView): # permission_classes = (IsAuthenticatedOrReadOnly,) serializer_class = UserFollowingSerializer queryset = UserFollowing.objects.all() class DeleteFollowView(generics.RetrieveDestroyAPIView): # permission_classes = (IsAuthenticatedOrReadOnly,) serializer_class = UserFollowingSerializer queryset = UserFollowing.objects.all() -
Page not found 404 django
Tengo este problema enter image description here y no se que hacer, he intentado algunas cosas pero no ha funcionado. Este es el archivo urls.py: enter image description here Creo que el problema esta en ese archivo pero no sabría como solucionarlo -
IntegrityError at /signup/ UNIQUE constraint failed: accountss_doctor.user_id
I'm trying to signup as Doctor but I got the following issue . raise dj_exc_value.with_traceback(traceback) from exc_value File "C:\Users\rachi\AppData\Local\Programs\Python\Python310-32\lib\site-packages\django\db\backends\utils.py", line 89, in _execute return self.cursor.execute(sql, params) File "C:\Users\rachi\AppData\Local\Programs\Python\Python310-32\lib\site-packages\django\db\backends\sqlite3\base.py", line 477, in execute return Database.Cursor.execute(self, query, params) django.db.utils.IntegrityError: UNIQUE constraint failed: accountss_doctor.user_id this is my models.py class User(AbstractUser): is_doctor = models.BooleanField(default=False) is_patient = models.BooleanField(default=False) class Doctor(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, primary_key=True) number_phone = models.CharField( _('االهاتف :'), max_length=50, blank=True, null=True) last_login = models.DateTimeField(auto_now_add=True) name = models.CharField(_('الاسم :'), max_length=50) surname = models.CharField(_(' اللقب :'), max_length=50) subtitle = models.CharField(_('نبدة عنك :'), max_length=50) address = models.CharField(_("المحافضة :"), max_length=50) this is my views.py class DoctorSignupForms(UserCreationForm): username = forms.CharField(label="الاسم") first_name = forms.CharField(label="الاسم الاول") last_name = forms.CharField(label=" الاسم الاخير") number_phone = forms.CharField(label=" الهاتف") email = forms.EmailField(label="البريد الالكتروني") password1 = forms.CharField( label=" كلمة المرور", widget=forms.PasswordInput(), min_length=8) password2 = forms.CharField( label="تاكيد كلمة المرور", widget=forms.PasswordInput(), min_length=8) class Meta(UserCreationForm.Meta): model = User fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2', 'number_phone') @transaction.atomic def save(self): user = super().save(commit=False) user.email = self.cleaned_data.get('email') user.is_doctor = True user.save() doctor = Doctor.objects.create(user=user) doctor.username = self.cleaned_data.get('username') doctor.number_phone = self.cleaned_data.get('number_phone') doctor.save() return doctor I heard that it's because of the relation which it has to be foreinkey instead of one to one but I want every doctor have …