Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Timezone Aware Input Form Setting DateTime In Wrong Timezone
I have a model called Order, which has an DateTimeField. In forms, I use a DateTimeInput widget to allow the user to select a DateTime. I also followed the Django documentation for allowing a user to select their local timezone, for the purpose of submitting DateTimes. These are stored in UTC, but rendered to the user in their local timezone. The problem is, when an order is created with a DateTime, it's interpreted as being in UTC instead of the local timezone. So for example, if the user is in the New York timezone, and creates a new Order at 12:00 AM April 6th New York time, it will actually be stored as 12:00 AM April 6th UTC. Thus, when it's rendered back to the user, the Order has a DateTime of 8:00 PM April 5th New York time. This is incorrect. I want the Order to be stored as 4:00 AM April 6th UTC, so that it's rendered back to the user as being created at 12:00 AM New York time. I've combed the web for days now, but I can't seem to find a solution for this issue. I've posted some of my code below: Order Model class … -
Couldn't setup Django
Django was working before, but when I reinstall Django, I enter py manage.py startapp myapp command, an error occurred: 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? I tried to find the problem, but still not fix. Python and Django keep up to date, and I really sure system variable is available(Path: C:\Users\YYJ\AppData\Local\Programs\Python\Python310\ and Scripts) -
templates inside application in django
I am working on a django project. I am getting TemplateDoesNotExist error in my browser window. I think django unable to find templates inside application in django project. I am unable to figure it out what is wrong in my code. project structure is something like that - schoolproject | |______ course | |______ fees | |______ schoolproject | |______ manage.py schoolproject/schoolproject/urls.py course application folder - course | |___ templates | | | |____ allcourse.html | | | |____ course.html | |___ admin.py | |___ apps.py | |___ models.py | |___ tests.py | |___ urls.py | |___ views.py schoolproject/course/views.py def course(request): return render(request, 'allcourse.html') def course_python(request): return render(request, 'course.html') schoolproject/course/urls.py from . import views urlpatterns = [ path('', views.course), path('course-python/', views.course_python) ] schoolproject/schoolproject/urls.py import course import fees urlpatterns = [ path('admin/', admin.site.urls), path('course/', include('course.urls')), path('fees/', include('fees.urls')), ] On hitting :- 127.0.0.1:8000/course/ And on hitting:- 127.0.0.1:8000/course/course-python/ -
Best way to implement view count logic in Django
I've been building my personal blog using Django and I must say that I'm learning a great deal. One of those things being the fact that the implementing the view count logic is not as simple as doing view_count += 1. So far, I've done some research and narrowed my options to Using Django's F-expression Using django-hitcount module Learn more about how sessions work and see if I can make it work with Django's sessions. The reason I ask this is that I want to implement a more Youtube like logic for my posts. Users must view the article for a certain length (time or word wise). What do you think is the best way to go about this? Any references to helpful articles are greatly appreciated. Thanks! -
Is request.data mutable by default in Django REST Framework 3.13.1?
I am using a DRF view function (with an @api_view(["POST"]) decorator) to use user posted data to create a new database record for a model Product. I have in my model definition Meta unique_together = ["user", "name"]. I would like to ensure that this unique together constraint is checked in a serializer validation itself, so as to avoid raising an integrity error at the time of saving. So what I used to try earlier was request.data["user"] = request.user.id, before passing request.data to the model serializer, then calling serializer.is_valid(), and finally serializer.save(). However, this used to raise some error to the effect that request.data was not modifiable when I was using some DRF 3.12.x (and Django 3.2). This was a minor inconvenience as I had to create a copy of request.data to modify the posted data. This kind of thing is described in multiple places, for e.g., here on SO and elsewhere. But I have since upgraded to DRF 3.13.1 and I noticed that now I am able to modify request.data in ways that I was not able to earlier (both, to add a new key-value pair and to edit the value for an existing key). I am testing using Postman: … -
Bootstrap Studio with Django
I recently learned Django and I wanted to make also a simple frontend. Is there a tool to convert the HTML to Django html? I tried BSS tools BSS but they seem not to work -
how do I get foreighkey of foreighkey without a loop in django?
It is a Django project, I am trying to create a wishlist (many-to-many will not help because I need DateTime of getting that wished item in the wishlist). class Client(models.Model): name = models.CharField(max_length=100) user = models.ForeignKey(User, on_delete=models.CASCADE) class Product(models.Model): name = models.CharField(max_length=100) price = models.DecimalField() class WishItem(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) client = models.ForeignKey(Client, related_name="wishlist", on_delete=models.CASCADE) added_at = models.DateTimeField(auto_now_add=True) What I could do is only this: wishlist = Client.objects.wishlist.select_related('product').all() wish_products = [item.product for item in wishlist] But I need something like this, without a loop but with a single SQL query and single line wishlist = Client.objects.wishlist.product.all() When I try to run this code I get an error AttributeError: 'RelatedManager' object has no attribute 'product' -
How to replace django template variable from another file?
I have a django template as: Templates/example.html: <html> {{ variable_1 }} {{ variable_2 }} {{ variable_3 }} </html> And I want to fill these variables from another python file and then use this html file (with filled variables) somewhere. Something like: from Templates import example.html as t t.variable_1 = "abc" t.variable_2 = "xyz" t.variable_3 = "pqr" And then use t somewhere. I haven't worked with Django templates before, and therefore, has no idea how to proceed with this. It would be great if someone could help. Thanks. -
heroku logs --tail - Django application
I always take this msg ERR when I try to deploy my django app : Application error An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details. You can do this from the Heroku CLI with the command heroku logs --tail this the result of heroku logs --tail : 2022-04-07T06:27:04.000000+00:00 app[api]: Build succeeded 2022-04-07T06:28:21.017217+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=app-gvt.herokuapp.com request_id=aa717d10- c1e0-4410-91b9-46f19155ce48 fwd="105.129.236.200" dyno= connect= service= status=503 bytes= protocol=https 2022-04-07T06:28:21.636539+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=app-gvt.herokuapp.com request_i d=ec7fc31b-4163-4054-b729-4b214e46a869 fwd="105.129.236.200" dyno= connect= service= status=503 bytes= protocol=https -
Need to populate the Project manager field based on the project select on the Timelog Model using django rest framework
models.py class User(AbstractBaseUser, PermissionsMixin): BLOOD_GROUP_CHOICES = ( ('a+','A+'), ('a-','A-'), ('b+','B+'), ('b-','B-'), ('ab+','AB+'), ('ab-','AB-'), ('o+','O+'), ('o-','O-') ) BILLABLE_and_NON_BILLABLE_CHOICES=( ('Billable','Billable'), ('Non-Billable','Non-Billable') ) username = models.CharField(max_length=30, unique=True,default=None) email = models.EmailField(max_length=250, unique=True) first_name = models.CharField(max_length=30, blank=True, null=True) last_name = models.CharField(max_length=30, blank=True, null=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=True) is_superuser = models.BooleanField(default=False) date_joined = models.DateTimeField(default=timezone.now) dob=models.DateField(max_length=8,default=None,null=True, blank=True) pancard=models.CharField(max_length=25,default=None,null=True, blank=True) aadhar=models.CharField(max_length=20,default=None,null=True, blank=True) personal_email_id=models.EmailField(max_length=254,default=None,null=True, blank=True) phone = PhoneNumberField(default=None,null=True, blank=True) emergency_contact_no=models.IntegerField(default=None,null=True, blank=True) emergency_contact_name=models.CharField(max_length=100,null=True, blank=True) relation=models.CharField(max_length=25,default=None,null=True, blank=True) blood_group=models.CharField(max_length=25,choices=BLOOD_GROUP_CHOICES,null=True,blank=True) designation=models.ForeignKey(Designation,on_delete=CASCADE,related_name="designations",default=None,null=True, blank=True) billable_and_non_billable=models.CharField(max_length=25,choices=BILLABLE_and_NON_BILLABLE_CHOICES,default='Billable',null=True, blank=True) joining_date=models.DateField(max_length=15,null=True, blank=True) relieving_date=models.DateField(max_length=15,null=True, blank=True) is_manager=models.BooleanField(default=False) reporting_manager = models.ForeignKey('self', null=True, blank=True, on_delete=models.CASCADE) objects = UserManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email', ] class Project(models.Model): project_code = models.CharField(primary_key=False, max_length=10,default=None,null=True,unique=True) project_name = models.CharField(max_length=50,unique=True,default=None) client= models.ForeignKey(Client,on_delete=CASCADE,related_name="Client1",default=None) user=models.ManyToManyField(User,related_name='users',default=None) project_manager = models.ForeignKey(User,on_delete=models.PROTECT,related_name="project_manager",default=None,limit_choices_to = {'is_manager': True},null=True,blank=True) description=models.TextField() type=models.TextField() #dropdown start_date = models.DateTimeField(max_length=10) end_date=models.DateTimeField(max_length=10) technical_contact_name = models.CharField(max_length=30) email=models.EmailField(max_length=254,default=None) phone = PhoneField(blank=True) delivery_head_contact_name=models.CharField(max_length=30) class Meta: db_table ='Project' def __str__(self): if self.client is not None: return f'{self.client.client_code }{self.project_code}-{self.project_name}' else: return self.project_code class Timelog(models.Model): STATUS_CHOICES = [ ('created','Created'), ('submitted', 'Submitted'), ('approved', 'Approved'), ] project = models.ForeignKey(Project,on_delete=CASCADE,related_name='project2',default=None) user= models.ForeignKey(User,on_delete=CASCADE,related_name='user2',default=None,blank=True,null=True) project_manager = models.ForeignKey(Project,on_delete=CASCADE,related_name='project_manager2',default=None,blank=True,null=True) job=ChainedForeignKey(Job,chained_field="project", chained_model_field="project",show_all=False, auto_choose=True, sort=True) date= models.DateField(default = datetime.date.today) hours=models.DurationField(default=datetime.timedelta(),null=True) status = models.CharField(max_length=20, choices=STATUS_CHOICES,null=False, default='Created') def save(self, *args, **kwargs): if not self.project_manager: self.project_manager = self.project.project_manager return super().save(*args, **kwargs) class Meta: db_table ='Timelog' def __str__(self): return '{}'.format(self.date) As per … -
Why does the script connect every other time?
Please tell me, what could be the problem of not connecting the script? the cache is disabled. ... </div> {% endblock content %} {% block scripts %} <script src="{% static 'js/sorting_columns.js' %}"></script> {% endblock scripts %} </body> </html> When the page is updated, then it is connected, then it is not connected. If you update 2-3 times to connect. -
how to create forgot password using email OTP in django
In my project I have created custom user model and use default forgot password method it forgot password via link but I need to change it, how to forgot password using OTP method -
Timeout server-side while exporting data
I built a website with Django/Python server-side and jQuery client-side. I have an Export Page on my website where there is a link to confirm that links to a view/python function that performs several long operations. At the beginning I had a timeout client-side problem that I simply solved $.ajaxSetup({ type: 'POST', timeout: 300000, ... setting the timeout var into $.ajaxSetup. So far once the request via Ajax is done I show a loading image into a DIV and the user knows he has to wait until file is done. However, for very long server-side operations I end up getting Bad gateway response on NGinx and a timeout on testing server. How would you handle this problem in the easiest way possible? I can't send an email with a file link and I want to preserve the UX where the user clicking the link gets its export file . I am on my own server with my own NGinx so I can eventually work on server-side too if nothing can be done via django/python. Thank you. -
Facing routing error on running my application
Iam facing this error on running my django application. I tried developing a chat app. Iam facing some issues regarding routing. HTTP GET /chat/ 200 [0.06, 127.0.0.1:33094] HTTP GET /chat/jkhkjk/?username=jkjk 200 [0.04, 127.0.0.1:33094] WebSocket HANDSHAKING /ws/jkhkjk/ [127.0.0.1:33104] WebSocket CONNECT /ws/jkhkjk/ [127.0.0.1:33104] urls.py from django.contrib import admin from django.urls import path, include from .views import * from app import views urlpatterns = [ path('', home, name='home'), path('student/', student, name='student'), path('logout/', logout, name='logout'), path('signup/', signup, name='signup'), path('volunteer/', volunteer, name='volunteer'), path('chat/',index, name='chat'), path('chat/<str:room_name>/', room, name='room'), ] routing.py from django.urls import path from . import consumers websocket_urlpatterns = [ path('ws/<str:room_name>/', consumers.ChatConsumer.as_asgi()), # Using asgi ] -
Django graphql auth failing and user getting disabled
In my project I am using django graphql auth as shown in below link https://django-graphql-auth.readthedocs.io/en/latest/quickstart/ When I tried to run updateAccount with below query, mutation MyMutation { updateAccount(lastName: "John"){ success errors } } It shows response as, { "data": { "updateAccount": { "success": false, "errors": { "userId": [ { "message": "This field is required.", "code": "required" } ] } } } } Which shows userId is required. Then I pass the userId to the same, mutation MyMutation { updateAccount(userId: "8c8b1c0c-9460-4930-b263-1c0776f86d63", lastName: "John"){ success errors } } First request was successful however same request sent again has failed. { "errors": [ { "message": "User is disabled", "locations": [ { "line": 2, "column": 3 } ], "path": [ "updateAccount" ] } ], "data": { "updateAccount": null } } An error occurred while resolving field Mutation.updateAccount Traceback (most recent call last): File "/usr/local/lib/python3.10/site-packages/graphql/execution/executor.py", line 452, in resolve_or_error return executor.execute(resolve_fn, source, info, **args) File "/usr/local/lib/python3.10/site-packages/graphql/execution/executors/sync.py", line 16, in execute return fn(*args, **kwargs) File "/usr/local/lib/python3.10/site-packages/graphql_jwt/middleware.py", line 72, in resolve user = authenticate(request=context, **kwargs) File "/usr/local/lib/python3.10/site-packages/django/views/decorators/debug.py", line 42, in sensitive_variables_wrapper return func(*func_args, **func_kwargs) File "/usr/local/lib/python3.10/site-packages/django/contrib/auth/__init__.py", line 76, in authenticate user = backend.authenticate(request, **credentials) File "/usr/local/lib/python3.10/site-packages/graphql_jwt/backends.py", line 14, in authenticate return get_user_by_token(token, request) File "/usr/local/lib/python3.10/site-packages/graphql_jwt/shortcuts.py", line 21, … -
Django model manager queryset not updating until server restarts
I have a program that lets users upload data files and lookup tables (both which are ID'd to a specific company) and map them together. One page lets users choose which company they want to map data for by looking at which companies have both data files and lookup tables, which I use a queryset/model manager for. The problem is if I load a new data file and hierarchy the queryset doesn't pick them up until the server restarts. The queryset returns all the companies that have a data file and hierarchies at the time the server starts, but not anything that's added afterwards. I think this must be because the queryset is defined at startup, but I'm not sure. Is there a way to work around this? forms.py class CompanySelectionForm(forms.Form): companies = RawData.objects.get_companyNames(source="inRDandH") companiesTuple = makeTuple(companies) print(companiesTuple) company = forms.ChoiceField(widget=forms.Select(attrs={'class': 'form-select'}), choices=companiesTuple) managers.py class RawDataManager(models.Manager): def get_queryset(self): return RawDataQuerySet(self.model, using=self._db) def get_companyNames(self, source): return self.get_queryset().get_companyNames(source) class RawDataQuerySet(models.QuerySet): def get_companyNames(self, source): if (source == 'inRDandH'): distinct_companiesRD = self.filter(fileType=0).values_list('companyName', flat=True).distinct() distinct_companiesH = self.filter(fileType=1).values_list('companyName', flat=True).distinct() distinct_companies = set(distinct_companiesRD).intersection(set(distinct_companiesH)) else: distinct_companies = self.values_list('companyName', flat=True).distinct() return distinct_companies -
I'm trying to input data, save it and display it in my view page. I'm not sure what I'm missing
I'm writing a simple product input app, where a user can input their product details, save it in the database and view it in another page. Everything seems to be going fine, no error messages when I run the server. However, when I put in the product details and submit, the page just refreshes and all the information disappears. Nothing shows up in the product list page. I've read a couple articles but not sure what exactly I'm missing. It seems like I've hit an invisible wall. Please assist. Thank you forms.py class ProductForm(forms.ModelForm): class Meta: model = Product fields = ['SKU', 'Category','Name', 'Platform', 'Price','Discount', 'Date','Cost'] widgets = { 'SKU': forms.TextInput(attrs={ 'class': 'form-control', 'id': 'SKU' }), 'Category': forms.TextInput(attrs={ 'class': 'form-control', 'id': 'Category' }), 'Name': forms.TextInput(attrs={ 'class': 'form-control', 'id': 'Name' }), 'Platform': forms.TextInput(attrs={ 'class': 'form-control', 'id': 'Platform' }), 'Price': forms.NumberInput(attrs={ 'class': 'form-control', 'id': 'Price' }), 'Discount': forms.NumberInput(attrs={ 'class': 'form-control', 'id': 'Discount' }), 'Date': forms.DateInput(attrs={ 'class': 'form-control', 'id': 'Date' }), 'Cost': forms.NumberInput(attrs={ 'class': 'form-control', 'id': 'Cost' }), } views.py # Product views @login_required(login_url='login') def create_product(request): forms = ProductForm() if request.method == 'POST': forms = ProductForm(request.POST) if forms.is_valid(): forms.save() return redirect('product-list') context = { 'form': forms } return render(request, 'store/create_product.html', context) class ProductListView(ListView): … -
How can I create a model entry from a search result in Django?
I hope this doesn't get overcomplicated, I'll try my best to keep it streamlined. I'm trying to put the results from querying an external database to populate fields in my model. Think of it as having a local library and asking the user for an ISBN, and getting the author, genre, etc from Amazon, and then storing it in my db. The flow of what I'm trying to accomplish is: Show the user a search field > get the query (this will be a unique ID) > call an external script with that query, pull the data of the one entry > break down the data to match the form fields (dict?) > pre fill form > show user the pre filled form to review > user submits (or doesn't). I know how to make a functioning search that looks in MY db for stuff and returns a list template with the context, and I know how to make a CreateForm for the user to input an entry manually, but not how to mix them, or how to even add stuff to the context if I wanted to. The back and forth of context data in django between templates and … -
What is the best practice to pass F401 (imported but unused) from flake8 with django?
I have a django-project. Typical structure of an app is: admin views models __init__.py foo.py bar.py init.py from .foo import FooModel from .bar import BarModel I am new in linters and tried wemake-python-styleguide Question: should I ignore the error F401 or add all=[...] or mark #noqa or add init.py to per-file-ignores in setup.cfg? -
Pruning PostgreSQL Tables and Store in JSON files
For my Django application I am using PostgreSQL and there are tables to store log entries such as Webhook events, email logs etc. I would like to keep these event logs only for 30 days and move the older logs to JSON file stored in Google Storage Bucket. Is there any recommended way to do this operation on a periodic basis? Essentially I would like to prune old records and store them in a JSON file periodically. -
How To Create Social Application Tokens With Django
I'm Successfully With This Tutorial : https://www.section.io/engineering-education/django-google-oauth/ In this tutorial, she's created how to login with google. I Just Started To Learn Back End With Django, And i Want to send this data with django rest api. My Friend is Front End and he need my user data. He said create the tokens. Im Confused to create the tokens. And i see in the table there is a name "Social Application Tokens". My Question is: How To Create Social Application Tokens Automaticly when user login with Google?, And Whats the tools to create that ? -
request.POST does not contain clicked button information
This is the code I have in forms.py class RsaForm(forms.Form): primeP = forms.IntegerField(label='Prime number (p)', required=True) primeQ = forms.IntegerField(label='Prime number (q)', required=True) clearText = forms.CharField(label='Cleartext', widget=forms.Textarea, required=False) cipherText = forms.CharField(label='Ciphertext', widget=forms.Textarea, required=False) And this is the code I have in views.py that I am using with my template rsa.html def rsaView(request): # if this is a POST request we need to process the form data if request.is_ajax and request.method == 'POST': # create a form instance and populate it with data from the request: form = RsaForm(request.POST) # check whether it's valid: if form.is_valid(): # process the data in form.cleaned_data as required pParam = form.cleaned_data['primeP'] qParam = form.cleaned_data['primeQ'] cleartextParam = form.cleaned_data['clearText'] ciphertextParam = form.cleaned_data['cipherText'] print(request.POST) pubkey, privkey = rsa.gen_keys(pParam, qParam) if 'encryptinput' in request.POST: # Encriptacion RSA print('Encriptado.') ciphertext = rsa.encrypt(cleartextParam, pubkey) return JsonResponse({"ciphertext": ciphertext}, status=200) elif 'decryptinput' in request.POST: # Desencriptacion RSA print('Desencriptado.') cleartext = rsa.decrypt(ciphertextParam, privkey) return JsonResponse({"cleartext": cleartext}, status=200) else: return JsonResponse({"error": "Hubo un error."}, status=200) else: print("Invalid form.") # if a GET (or any other method) we'll create a blank form else: form = RsaForm() thisCryptosystem = Cryptosystem.objects.get(name="RSA") template = loader.get_template('cryptogyapp/rsa.html') context = { 'thisCryptosystem': thisCryptosystem, 'form': form } return HttpResponse(template.render(context, request)) And this is my … -
How to compute unified diff in queryset order in django template
[statistic.html] test: {% for h in research.history %} {% ifchanged h.summary_json.field_summary.teacher %} {% if h.summary_json.field_summary.teacher|length > 0 %} {{ h.summary_json.field_summary.teacher|after_teacher }} {% endif %} {% endifchanged %} {% endfor %} test: ['who'] ['Haily', 'mark'] ['Haily'] ['Haily', 'mark'] ['Haily', 'Aden'] I am trying to combine the results of 5 querysets into (1,2) (2,3) (3,4) (4,5) and print the comparison values of the results of the queryset using unified_diff of the difflib module. example) +++ @@ -1,2 +1,2 @@ Haily -mark +Aden I would appreciate it if you could tell me how to apply them in order. [teampltetag.py] def compare_teacher(v1, v2): for diff in difflib.unified_diff(v1, v2): return str(diff) [statistic.html] {% compare_teacher ?? ?? %} -
Django Admin error referencing wrong column in ForeignKey
I've setup a relationship using django's ForeignKey against 2 unmanaged tables like so: class Product(BaseModel): publish_name = models.CharField(unique=True, max_length=40) # this works: associated_country = models.ForeignKey('geonames.Countryinfo', models.DO_NOTHING, db_column='published_country', blank=True, null=True) # this doesn't: associated_continent = models.ForeignKey('geonames.Continentcodes', on_delete=models.DO_NOTHING, db_column='published_continent' blank=True, null=True) class Meta: managed = True db_table = 'product' class Continentcodes(models.Model): code = models.CharField(max_length=2, primary_key=True, unique=True) name = models.TextField(blank=True, null=True) geoname_id = models.OneToOneField('Geoname', models.DO_NOTHING, blank=True, null=True, unique=True) class Meta: managed = False db_table = 'geoname_continentcodes' class Countryinfo(models.Model): iso_alpha2 = models.CharField(primary_key=True, max_length=2) country = models.TextField(blank=True, null=True) geoname = models.ForeignKey('Geoname', models.DO_NOTHING, blank=True, null=True) neighbours = models.TextField(blank=True, null=True) class Meta: ordering = ['country'] managed = False db_table = 'geoname_countryinfo' verbose_name_plural = 'Countries' I've written some unit tests that pass for inserting and retrieving the foreign key values for the Continentcodes and Countryinfo relationships in the Product model, but when I go to edit an entry in the django admin interface I see this: The above exception (column geoname_continentcodes.geoname_id_id does not exist LINE 1: ...ntcodes"."code", "geoname_continentcodes"."name", "geoname_c... ^ HINT: Perhaps you meant to reference the column "geoname_continentcodes.geoname_id" It looks like it's trying to reference geoname_continentcodes.geoname_id_id for some reason. I have tried adding to='code' in the ForeignKey relationship, but it doesn't seem to effect anything. Additionally, the … -
Factory Boy not correctly generating one to one relationship
I have two factories. class ProfileFactory(DjangoModelFactory): class Meta: model = Profile user = factory.SubFactory(UserFactory) id = Faker('uuid4') first_name = Faker('first_name') last_name = Faker('last_name') class UserFactory(DjangoModelFactory): id = Faker('uuid4') email = Faker('email') password = Faker('password') class Meta: model = User These correspond to a couple models: class User(AbstractUser): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) class Profile(UUIDModel): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="profile") first_name = models.CharField(max_length=25, null=True, blank=True) last_name = models.CharField(max_length=30, null=True, blank=True) I would like to be able to call ProfileFactory() and a profile and user be generated. However I am currently getting an error: users.models.User.profile.RelatedObjectDoesNotExist: User has no profile. How do i correctly create both items?