Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
TinyMCE GET 404
I installed TinyMCE and it was working fine on the local server. I deploy the site to Heroku and host the static files on Amazon S3 and now TinyMCE is not working. Other static files are served correctly. This is the Heroku log. 2020-04-15T07:19:17.547578+00:00 app[web.1]: - [15/Apr/2020:07:19:17 +0000] "GET /static/tiny_mce/tiny_mce.js HTTP/1.1" 404 3012 "https://...herokuapp.com/.../" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.39 Safari/537.36" This is the folder structure of my site: . ├── Procfile ├── db.sqlite3 ├── mysite │ ├── __init__.py │ ├── __pycache__ │ ├── asgi.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── manage.py ├── media │ ├── images │ └── js ├── requirements.txt ├── runtime.txt ├── static │ └── readme.txt ├── staticfiles │ └── readme.txt └── myapp ├── __init__.py ├── __pycache__ ├── admin.py ├── apps.py ├── forms.py ├── migrations ├── models.py ├── static └── myapp └── tiny_mce ├── templates ├── tests.py ├── urls.py └── views.py This is my URL configs: STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') TINYMCE_JS_URL = os.path.join(STATIC_URL, "tiny_mce/tiny_mce.js") TINYMCE_JS_ROOT = os.path.join(STATIC_URL, "tiny_mce") TINYMCE_DEFAULT_CONFIG = { 'theme': 'advanced', 'relative_urls': False, 'theme_advanced_buttons1': 'bold,italic,underline,bullist,numlist,link,unlink,styleselect,fontselect,fontsizeselect', } Any ideas? Thank you! -
Control object creation flow in Django inheritance models
I have been read some Django document about inheritance models and parent_link. Suppose that I have these models: class Parent(models.Model): #Some field goes here! class Child(Parent): #Some field goes here! I have 3 questions about this pattern: What should I do if I want to create new child object and pass id of existing parent to that? What should I do if I want to create just new child object and after a while create parent object for that child? Also I din't understand this document about parent_link: OneToOneField.parent_link When True and used in a model which inherits from another concrete model, indicates that this field should be used as the link back to the parent class, rather than the extra OneToOneField which would normally be implicitly created by subclassing. Thanks for your help! -
I'm trying to save django form in json format in mongodb without using models & model forms. My form is working, but I am stuck how to save the form
I want to save the form data submitted by the user in JSON format in mongo database. My form is getting submitted when I submit the form but I couldn't understand how to store the submitted form in MongoDB JSON format. Kindly do help with the supporting code. forms.py class appointment(forms.Form): name = forms.CharField(max_length=100, label="Name") gender = forms.ChoiceField(widget=forms.RadioSelect, choices=G_CHOICES) age = forms.CharField() phone_number = forms.CharField() email_id = forms.EmailField(max_length=250) country = CountryField().formfield() department = forms.ChoiceField(choices=D_CHOICES) reports = forms.ImageField() views.py def appointmentform(request): if request.method == "POST": form = appointment(request.POST, request.FILES) if form.is_valid(): form.save() print(form.cleaned_data) print(form.cleaned_data.get("name")) print(form.cleaned_data.get("gender")) print(form.cleaned_data.get("age")) print(form.cleaned_data.get("phone_number")) print(form.cleaned_data.get("country")) print(form.cleaned_data.get("department")) print(form.cleaned_data.get("reports")) form = appointment return render(request, "appointment.html", {"form": form}) -
Perform JOIN in tables django
Perform JOIN on in django fetching related date in reverse relationship. There are three models. Following is code for models class Question(models.Model): title = models.CharField(max_length=255 ) description = models.TextField(max_length=300) class Quiz(models.Model): name = models.CharField(max_length=225,blank=False ) quiz_type =models.IntegerField(choices=QUIZ_TYPE,default=0) questions = models.ManyToManyField( Question, through='QuestionQuiz', related_name="quiz_question") categories= models.ManyToManyField(Category,through='CategoryQuiz',related_name='quiz_category') class QuestionQuiz(models.Model): quiz = models.ForeignKey(Quiz,on_delete=models.CASCADE) question = models.ForeignKey(Question,on_delete=models.CASCADE) correct =models.DecimalField(max_digits=4, decimal_places=3) incorrect= models.DecimalField(max_digits=4, decimal_places=3) class Meta: unique_together = ('quiz','question') In this the questions are added to the quiz using model Question Quiz. Here , QuizQuestion has foreign key relationship with the question. I need to fetch all from question JOIN and records from QuestionQuiz with a particular quiz_id. Suppose quiz_id =3 Then I will fetch all questions with correct and incorrect. if that quiz id is added to the question then it will display correct incorrect else these would be blank. question_id | title|description|correct|incorrect|quesquizid 1 | Q1 |Q1desc |2 | -2 | 1 2 | Q2 |Q2desc | | | ques_id =1 added to quiz_id=3 .ques_id=2 not added to quiz_id=3.So, correct incorrect are blank. I tried following but it fetches all question and related quizes scores irrespective of their occurrence in current quiz : Question.objects.prefetch_related('questionquiz_set').all() The result should be similar to following query Select * … -
how to send data in GET request header using react and axios to Django rest framework?
i am new to react and axios and i want to know how to send data in my headers using get request i tried this but it didn't work ** i observed that the request type changed to options in django terminal window ** export const getUserOrders=(userID)=>{ return dispatch=>{ dispatch(getUserOrdersStart()) axios.defaults.headers={ 'Content-Type':'application/json', id:userID } axios.get('http://127.0.0.1:8000/admindashboard/userorders/') .then(res=>{ const order=res.data dispatch(getUserOrdersSuccess(order)) }).catch(err=>{ getUserOrdersFail(err) }) } } -
ERD Diagram for a school management system automatically generated using postgresql as my dbms
I'm currently building a school management system with modules that include: admin, students, parents, teachers and fees management. I am using django for my back-end development for my app. I've already created these models on my models.py file in my app and configured my postgresql into my settings.py file. How can i generate an automatic ERD Diagram without having to draw it myself? -
Can I use NGINX to proxy_pass to Django project's WSGI server
I have deployed the Django on Amazon AWS EC2 services. It is woking fine when I use proxy_pass except it does not return errors and message which are being returned on Postman. I am getting only following error. Access to XMLHttpRequest at 'http://ec2-18-191-33-108.us-east-2.compute.amazonaws.com/api/token/' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. How to retreive all 4** and 5** errors and messages from NGINX which is serving as reverse proxy. my nginx.conf location / { add_header 'Access-Control-Allow-Origin' '*'; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PATCH, PUT, DELETE'; add_header 'Access-Control-Allow-Credentials' 'true'; add_header 'Access-Control-Allow-Headers' 'Authorization,Accept,Origin,DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range'; if ($request_method = 'OPTIONS') { add_header 'Access-Control-Allow-Origin' '*'; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PATCH, PUT, DELETE'; # # Custom headers and headers various browsers *should* be OK with but aren't # add_header 'Access-Control-Allow-Headers' 'Authorization,Accept,Origin,DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range'; # # Tell client that this pre-flight info is valid for 20 days # add_header 'Access-Control-Max-Age' 1728000; add_header 'Content-Type' 'text/plain; charset=utf-8'; add_header 'Content-Length' 0; return 204; } proxy_pass http://app; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } -
Create virtual wallet in Django
I have a plan to develop betting app in Django , I haven't an idea how to make virtual wallet , like on Upwork or Freelancer.com , Can I make it with Stripe ? Is there any solutions ? -
Can I use JWTAuthentication twice for a login authentication?
In my login First place I wanted to send OTP and second place I wanted to verify the OTP and then return the token. I am using rest_framework_simplejwt JWTAuthentication. First place I just verifying the user and sending OTP, not returning the token and second place I am verifying the OTP and returning the token. Let me know I this is the correct way to use? If not how can I implement this using JWTAuthentication. -
Do I need to know Postgres if I want to use it in Django?
I have been developing backend for like 8 months and have done quite a few big projects, but in all of them I used sqlite database. I understand that using sqlite at production level is a bad idea. hence I want to use a Postgres database since I deploy my apps at heroku and it uses Postgres database. But if I do start using Postgres do I need to be able to use it, or would everything work just as the ORM would work with the sqlite database? I just know the basics of database, their relations and some basic SQL. Do I really need to learn more? Or should I just plug n play a database? -
how can i use different bootstrap version in template inheritance? - Django
base.html '''' <head> {% block csslink %}<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">{% endblock csslink %} {% block cssfile %} {% endblock cssfile %} <title>{% block title %} Base {% endblock title %}</title> </head> <body> {% include 'navbar.html' %} <br> {% block content %} {% endblock %} </body> Contact.html '''' {% extends 'base.html' %} {% load static %} {% block csslink %} <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> {% endblock csslink %} {% block cssfile %}<link rel="stylesheet" type="text/css" href="{% static 'css/contactstyle.css' %}"> {% endblock cssfile %} {% block title %}Contact {% endblock title %} {% block content %} Any one suggest how can add this versions without changing styles? -
This field cannot be blank django Testing
In my models (Home), there are fields as follows. class Home(TitleSlugDescriptionModel): seller= models.ForeignKey("data.seller", null=True, on_delete=models.SET_NULL) date = models.DateField() picture = models.ImageField(upload_to="images") data.seller Different model Home. I have models.py (Data) class Data(models.Model): name = models.CharField(max_length=255) images = models.ImageField() class Seller(models.Model): name = models.CharField(max_length=255) data= models.ForeignKey(Data, on_delete=models.SET_NULL, null=True) In my test.py class HomeTestCase(TestCase): def test_random(self): with open("img/no-image.jpg", "rb") as f: for home in range(10): G(Home, picture=ImageFile(f), seller=F(name="test1"), I have a problem when I test. It alerts that: django_dynamic_fixture.ddf.InvalidConfigurationError: ('homes.models.Home.seller', BadDataError('data.models.Seller', ValidationError({'data': ['This field cannot be blank.']}))) I don't know how to fix it. Can someone recommend me? Thank you very much -
Angle Brackets in JSON
I am following the solution posted on: Sum database on location and time However, when I do a print(locations.values()) this is returned: ('Liberty City', <Location: 07:00 116 Liberty City 08:00 120 Liberty City ...>)]) models.py class Location: def __init__(self, name): self.name = name self.times = list() def __str__(self): s = ['{}\t{}\t{}'.format(k, t[k], self.name) for t in self.times for k in t.keys()] return '\n'.join(s) def add_time(self, hour, people): existing_people_for_hour = None for t in self.times: # loop existing times, looking for the hour existing_people_for_hour = t.get(hour) if existing_people_for_hour is not None: t[hour] += people break # found the hour to update, so break the loop if existing_people_for_hour is None: # if the hour was never found, add to the times list self.times.append({hour : people}) Things I've tried: print(repr(locations.values())) However, this still gives me angle brackets. What does the angle brackets (<>) means? And how can I access the values? -
Unable to setup celery-progress in Django
I'm trying to setup a celery-progress as per an answer to an old stackoverflow question. I'm following the documentation of enter link description here. I also tried to configure the sample project linked in documentation. But failed, as it requires Redis server setup, which is again a new thing for me. Can anybody help me find a simple working example? And please, don't close this question as a duplicate, as the existing questions are older and didn't resolve my problem. -
When I edit a single record into a template by use django form it is not edited
I have two models child and academy by which these two models have relationship to each other here is child models from django.db import models class Child_detail(models.Model): Firstname = models.CharField(max_length = 50) Lastname = models.CharField(max_length = 50) Tribe = models.CharField(max_length = 50) def __str__(self): return self.Firstname Here is academy model from django.db import models from child.models import Child_detail class Academic(models.Model): Student_name = models.ForeignKey(Child_detail,on_delete = models.CASCADE) Class = models.CharField(max_length = 50) Average_grade = models.CharField(max_length = 10) def __str__(self): return str(self.Student_name) Here is my views.py file that contain edit functionality,into the template it does not show the fields to edit so i have to write those fields again and even that it does not edit anything def edit(request,pk): child=get_object_or_404(Child_detail,pk=pk) form=ChildForm(request.POST or None,instance=child) if form.is_valid(): form.save() return redirect('child') context={ 'form':form, 'child':child } return render(request,'functionality/edit.html',context) -
Getting an error in my django application " ModuleNotFoundError: No module named 'django.wsgi'". I have this error. I am not able to fix it
I am running a web application. It is working in my local development server without any error but when I deployed it to Heroku, it has to build successfully. When I opened my application URL then it is giving application error. After viewing Heroku logs I found it is saying that ModuleNotFoundError. here is the complete log of Heroku: 2020-04-15T04:37:07.706710+00:00 app[web.1]: self.halt(reason=inst.reason, exit_status=inst.exit_status) 2020-04-15T04:37:07.706715+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/arbiter.py", line 342, in halt 2020-04-15T04:37:07.706919+00:00 app[web.1]: self.stop() 2020-04-15T04:37:07.706920+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/arbiter.py", line 393, in stop 2020-04-15T04:37:07.707137+00:00 app[web.1]: time.sleep(0.1) 2020-04-15T04:37:07.707141+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/arbiter.py", line 242, in handle_chld 2020-04-15T04:37:07.707307+00:00 app[web.1]: self.reap_workers() 2020-04-15T04:37:07.707311+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/arbiter.py", line 525, in reap_workers 2020-04-15T04:37:07.707552+00:00 app[web.1]: raise HaltServer(reason, self.WORKER_BOOT_ERROR) 2020-04-15T04:37:07.707581+00:00 app[web.1]: gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3> 2020-04-15T04:37:09.000000+00:00 app[api]: Build succeeded 2020-04-15T04:37:14.867490+00:00 heroku[web.1]: State changed from starting to crashed 2020-04-15T04:37:14.641214+00:00 app[web.1]: [2020-04-15 04:37:14 +0000] [4] [INFO] Starting gunicorn 20.0.4 2020-04-15T04:37:14.641835+00:00 app[web.1]: [2020-04-15 04:37:14 +0000] [4] [INFO] Listening at: http://0.0.0.0:37686 (4) 2020-04-15T04:37:14.641995+00:00 app[web.1]: [2020-04-15 04:37:14 +0000] [4] [INFO] Using worker: sync 2020-04-15T04:37:14.646404+00:00 app[web.1]: [2020-04-15 04:37:14 +0000] [10] [INFO] Booting worker with pid: 10 2020-04-15T04:37:14.663560+00:00 app[web.1]: [2020-04-15 04:37:14 +0000] [10] [ERROR] Exception in worker process 2020-04-15T04:37:14.663563+00:00 app[web.1]: Traceback (most recent call last): 2020-04-15T04:37:14.663580+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker 2020-04-15T04:37:14.663581+00:00 … -
Syntax Error when trying to makemigrations in django
I am a newbie in web design and I'm trying to design a web server using sentdex's Django Web Development video series. I am running the web server on a Raspberry Pi B+ with all the most recent software. I have followed sentdex's every step so far. The only difference is I was told to use a virtual enviroment when using django on a Pi so that's my only difference(other than updated software). In 12:37 of his second video when he uses the command "python manage.py makemigrations" (after adding the app name to the settings.py) his command prompt comes up with no errors while mine gives the error: Error Message Snip I have looked into adding django to the PYTHONPATH but I've also seen conflicting posts. Any help would be appreciated, thank you. Link for Video: https://www.youtube.com/watch?v=aXxIjeGR6po&list=PLQVvvaa0QuDe9nqlirjacLkBYdgc2inh3&index=2 -
How to display the youtube url stored in django database to display in template,here is the stuff i have done i am getting error of no videos yet
I have been following django-embed-video tutorial by jazzband and everything is setup and i uploaded url in my database ,but when running the database no any videos is displaying in my template .It's throwing error file "\env\lib\site-packages\embed_video\templatetags\embed_video_tags.py", line 196, in embedbackend = cls.get_backend(url, context=context, **options) File "\env\lib\site-packages\embed_video\templatetags\embed_video_tags.py", line 174, in get_backend else detect_backend(str(backend_or_url)) File "\env\lib\site-packages\embed_video\backends.py", line 64, in detect_backend raise UnknownBackendException embed_video.backends.UnknownBackendException here is /app/models.py class youtube(models.Model): video = EmbedVideoField(default="") def __str__(self): return self.video /app/views.py from .models import youtube def display_video(request): videos = youtube.objects.all() context = {'video': videos} return render (request, 'library.html', context) library.html {% load embed_video_tags %} {% video item.video 'small' %} {% block content %} {% if videos %} {% for v in videos %} {{ v.video }} {% endfor %} {% else %} <p>No videos yet</p> {% endif %} {% endblock %} /myproject/settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app', 'embed_video', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['template'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', **'django.contrib.messages.context_processors.messages',** ], }, }, ] STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR,'media') MEDIA_URL = '/media/' Thank you so much for help -
Django HttpResponse working with latin encode
I'm passing a json to the HttpResponse and I'm having problems with some special characters like 'ñ' or 'á'. this is my code in the views.py file: def count_depto(request): time = datetime.now() - timedelta(days=1) df = pd.DataFrame.from_records(RayosDepto.objects.filter(tiempo__gte=time).values()) grouped = df.groupby('dpto').size().to_frame() grouped.columns=[grouped[0].sum()] grouped.rename_axis('Total',inplace=True) grouped=grouped.transpose() grouped = grouped.to_json(orient='records',force_ascii=False) return HttpResponse(grouped,content_type='json') and this is my actual result: is there a way to fix this?Django version:3.0.5, pandas version:1.0.3 -
How to make all the 'inlines' collapsible items in Django Admin to default open?
I am new to Django and Python programming and I have looking in circles to solve this problem I have. I wrote following codes...whenever the below codes were executed, the inline filter is always default as 'close'. How can I default to 'open' or 'show' instead of default 'close'? Thank you. class ArInvoiceSimpleInlineForeign(admin.TabularInline): model = ArInvoice extra = 2 classes = ('collapse open',) inline_classes = ('collapse open',) -
How to set the templates directory in django .?
I am having a hard time finding the explanation how to set templates directory in django settings.py. -
Using Django settings file configurations dynamically in case of muliple settings file
So, I have multiple environment specific settings file in my Django project which has different values for "TYPE" in each one of them. The value of TYPE is being used in some of my python files and don't want to import different settings files to use the value of "TYPE" while running in different environments. Are there any possible ways to do this? Any links to resources will be good too. -
Getting error NoReverseMatch at / Reverse for 'login' with no arguments not found. 1 pattern(s) tried: ['accounts/$login/$']
URLS.PY from django.conf.urls import url from django.contrib.auth import views as auth_views from . import views app_name = 'accounts' urlpatterns = [ url(r'^login/$',auth_views.LoginView.as_view(),name='login'), url(r'^logout/$',auth_views.LogoutView.as_view(),name='logout'), url(r'^signup/$',views.SignUp.as_view(),name='signup'), ] base.html <!DOCTYPE html> {% load staticfiles %} <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Star Social</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous"> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script> <link href="https://fonts.googleapis.com/css?family=Roboto&display=swap" rel="stylesheet"> <link rel="stylesheet" href="{% static 'simple_clone/css/master.css' %}"> </head> <body> <nav class="navbar mynav" role="navigation" id="navbar"> <div class="container"> <a class="navbar-brand" href="{% url 'home' %}">Star Social</a> <ul class="navbar-nav ml-auto"> {% if user.is_authenticated %} <li class="nav-item"> <a class="nav-link" href="#">Post</a> </li> <li class="nav-item"><a class="nav-link" href="#">Groups</a> </li> <li class="nav-item"><a class="nav-link" href="#">Create Group</a> </li> <li class="nav-item"><a class="nav-link" href="{% url 'accounts:logout' %}">Logout</a> </li> {% else %} <li class="nav-item"><a class="nav-link" href="#">Groups</a> </li> <li class="nav-item"><a class="nav-link" href="{% url 'login' %}">Log In</a> </li> <li class="nav-item"><a class="nav-link" href="{% url 'accounts:signup'%}">Sign Up</a> </li> {% endif %} </ul> </div> </nav> {% block content%} {% endblock %} </body> </html> On trying to access http://127.0.0.1:8000/ Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 1.11.29 Exception Type: NoReverseMatch Exception Value: Reverse for 'login' with no arguments not found. 1 pattern(s) tried: ['accounts/$login/$'] -
Python Django: Ho to pass modelsdata to Admin default Startpage (index.html)?
I have created a Python Django application and would like to build a kind of dashboard on the ADMIN startpage/defaultpage (index.html). For this purpose I want to display e.g. different data of my models. I have tried to access the data of my models outside the admin area and to display them as I like. It worked there. However, it did not work with the same code in the admin area on the default startpage. I don't know how to access my models/objects in the index.html/Admin startpage. I am grateful for any help. -
Problem with Django One-to-One Table Primary Key Assignment - "ID" not found and "NOT NULL CONSTRAINT FAILED"
I'm going crazy trying to figure this out. I simply have a table with a one-to-one relationship with the User table. The code for the model, in part, is: class Client(models.Model): user = models.OneToOneField(User, primary_key=True, on_delete=models.CASCADE) When the table is created and I try to access the table information from within admin, it says no "id" is assigned, but it does assign a field that it generates automatically called 'user_id' and that field is populated with the primary key. It just doesn't seem to be recognizing it as the primary key, or accessing data because the "id" is not found. When I delete primary key=True, and leave it as a OnetoOneField without assigning it as the primary key,as follows class Client(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) it doesn't save and I get an Integrity error: IntegrityError at /client_intake/1/ NOT NULL constraint failed: intake_client.user_id Apparently without the primary key set it tries to save the user_id field as a null value. So, I cannot set the OnetoOne as primary key and I can't set it without it being the primary key without getting an error. It only saves when the primary key is true but then I can't access the data even though …