Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django project deployed with zappa: Forbidden (403) CSRF verification failed
I've posted similar post here last week regarding a different error in the same area of my website. I've been working on my first website with django, it's deployed to aws with zappa. The page is using Lambda, S3, Apigateway and cloudfront. I've had issues with the links, for some reason the {%url 'contact'%} link for example changes the url to: https://mywebsite.com/website_project_1/contact when it should be https:/mywebsite.com/contact. In cloudfront I have put the origin path to website_project_1 'cause otherwise the whole site would be forbidden. Which has forced me to put the basebath in zappa_settings.json to website_project_1. When I get the api url from my terminal after deployment/update the form works fine. But when I try to send the form from my actual website urls I've set up in aws the website throws the following error: Forbidden (403) CSRF verification failed. Request aborted. Reason given for failure: Referer checking failed - https://mywebsite/contact does not match any trusted origins. My settings.py looks like this: import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = os.environ['SECRET_KEY'] # SECURITY WARNING: don't run with debug turned on in production! DEBUG = os.environ['DEBUG'] # EMAIL_HOST = ALLOWED_HOSTS = ['127.0.0.1', '(my_api_numbers).execute-api.eu-west-1.amazonaws.com', 'mywebsite.co/'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', … -
To what extent can python be integrated with web?
Sorry for this naive question, this is just to decide how an ongoing project should go on, consider having a .py python file (an input/output program that's made such as to run through the console) and a website coded with text boxes, buttons and such, how easy is it to make inputs/outputs on the website map to variables in the python script? I know this might vary depending on what tool is used (Django, Flask....etc) -
Django Error: Url matching query does not exist
I try to get all the links that I have / url_qs And then I want to get all url addresses / url_w The error comes back: Url matching query does not exist from django.shortcuts import render from django.db import IntegrityError from scraping.utils import * from scraping.models import * def home(request): city = City.objects.get(name='Lviv') speciality = Speciality.objects.get(name='Python') url_qs = Url.objects.filter(city=city, speciality=speciality) site = Site.objects.all() url_w = url_qs.get(site=site.get(name='Work.ua')) jobs = [] jobs.extend(work(url_w.url_address)) for job in jobs: vacancy = Vacancy(city=city, speciality=speciality, url=job['href'], title=job['title'], description=job['descript'], company=job['company']) try: vacancy.save() except IntegrityError: pass return render(request, 'base.html', {'jobs': jobs}) -
Django blog post by authors
I am building a blog in django 3. I want to filter all posts by author and display the results in author page. I can't seem to figure what is wrong with my code. Please help. If i can get an explaination on what is wrong with my code, that will be appreciated. Views.py class AuthorPostListView(ListView): model = Post paginate_by = 5 template_name = 'author_post.html' def get_queryset(self): return Post.objects.filter(author = self.request.user).order_by('created_on').reverse() def get_context_data(self): context = super(AuthorPostListView, self).get_context_data(**kwargs) context['authorpost_list'] = Post.objects.all() return context Models.py class Post(models.Model): title = models.CharField(max_length=200) post_slug = models.SlugField(max_length = 200, unique = True) body = models.TextField() created_on = models.DateTimeField(auto_now_add=True) last_modified = models.DateTimeField(auto_now = True) author = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name = 'blog_posts', ) post_picture = models.ImageField( upload_to = 'post_picture', null = True, blank = True, default='/media/post_picture/2.jpg', ) approved_comment = models.BooleanField(default=True) tags = TaggableManager() categories = models.ManyToManyField('Category', related_name = 'posts') def approve(self): self.approved_comment = True self.save() class Meta: ordering = ['created_on'] def __str__(self): return self.title def get_absolute_url(self): return reverse('post_detail', args=[str(self.id)]) def save(self, *args, **kwargs): self.slug = slugify(self.title) super(Post, self).save(*args, **kwargs) Template {% for object in authorpost_list %} {{ object.title }} {% endfor %} urls.py urlpatterns = [ path('author_post/', views.AuthorPostListView.as_view(), name = 'author_posts'), ] -
Updating GenericForeignKey in Django
I have a GenericForeignKey in my Django model: class LicensePool(models.Model): license = models.OneToOneField( License, on_delete=models.CASCADE, related_name="license_pool" ) owner_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) owner_id = models.PositiveIntegerField() owner = GenericForeignKey("owner_type", "owner_id") class Supplier(models.Model): name = models.CharField(max_length=250) parent = models.ForeignKey( "self", on_delete=models.SET_NULL, related_name="child", null=True, blank=True, ) licenses = GenericRelation( "license.LicensePool", content_type_field="owner_type", object_id_field="owner_id", related_query_name="supplier", ) class Meta: ordering = ("name",) def __str__(self): # pragma: no cover return "pk: {} - name: {}".format(self.pk, self.name) When I try to update the owner I get following error: AttributeError: 'GenericRel' object has no attribute 'get_db_prep_save' Can't find this error online, so thought of making a question. Here is the code in my view where I try to update the objects: transfered_licenses = LicensePool.objects.filter( supplier=parent_supplier, ).values("pk")[:total_licenses] LicensePool.objects.filter(pk__in=transfered_licenses).update( supplier=child_supplier ) -
How to update two models in a single update api in djago rest framework?
I have two models: First one is product model: class ProductModel(basemodel.BaseModel): company = models.ForeignKey(CompanyModel, on_delete=models.PROTECT) tax = models.ForeignKey( TaxModel, on_delete=models.PROTECT, null=True, blank=True ) .... and the other one is product detail model: class ProductDetailModel(basemodel.BaseModel): product = models.OneToOneField( ProductModel, on_delete=models.PROTECT, related_name='product_detail' ) assets = jsonfield.JSONField(null=True, blank=True) products_in_box = jsonfield.JSONField(null=True, blank=True) downloads = jsonfield.JSONField(null=True, blank=True) .... and as you can see they are linked with one to one field. Now on calling update api user can update product as well as product detail model. How can I achieve this? My Product Serializr is : class ProductUpdateSerializer(serializers.ModelSerializer): class Meta: model = ProductModel fields = ( 'id', 'company', 'tax', 'brand', 'unit', 'buyer_groups', 'product_type', 'sales_channel', 'name', 'mrp', 'selling_price', 'upc', 'dimensions', 'weight', 'sku', 'one_line_description', 'ean_number', 'isbn_number', 'hsn_number', 'highlights', 'variant_values', 'featured_images', 'offers', 'tags', 'specifications', 'configurations', 'is_archived', 'is_active', 'is_disabled', 'is_grouped_product', 'created_by', 'last_modified_by', 'created_at', 'updated_at', 'owner' ) read_only_fields = ( 'id', 'company', 'created_by', 'owner', 'created_at', 'is_archived', 'is_active' ) -
django pass none type variable [closed]
hey guys i am trying to make a website with Django that intergrate with mikrotik api but i kind of confused right now cus it seems that when i try to pass the variable (the api) through the url it returned a none type variable can anyone give me explanation and help me why it return that? (and sorry English with my poor English) here is my url urlpatterns = [ path("dashboard/<api>",views.dashboard,name="dashboard"), path("mikrotiklogin",views.mikrotikapi,name="mikrotik"), ] here is my view def api(request): if request.method == "POST": username = request.POST['username'] password = request.POST['password'] iprouter = request.POST['iprouter'] try: con = routeros_api.RouterOsApiPool(host=iprouter,username=username,password=password,plaintext_login=True) api = con.get_api() return redirect("dashboard/{}".format(api)) except: messages.info(request,"gak bisa login mas") return redirect("mikrotiklogin") else: return render(request,"loginmikro.html") def dashboard(request,api): resource = request.POST.get("api") print(type(resource)) resource_log = resource.get_resource("log") content_log = resource_log.get() resource_user = resource.get_resource("/ip/hotspot/user") content_user = resource_user.get() all_user = len(content_user) total_user = 0 if all_user <= 0: total_user = 0 else: total_user = all_user resource_active_user = resource.get_resource("/ip/hotspot/active") content_user_active = resource_active_user.get() all_user_active = len(content_user_active) total_user_active = 0 if all_user_active <= 0: all_user_active = 0 else: total_user_active = all_user_active return render(request,"dashboard.html",{"content_log":content_log, "content_user_active":total_user_active ,"content_user":total_user}) -
DJANGO - AttributeError: 'NoneType' object has no attribute 'get' - How to solve it when I even have the data and no field is None?
this is the 7th or 8th error in a row I am facing while creating the Django app and this is making me fed up. I will write the short summary of the system how it works and then I will share my code. Well, basically when user (student) go to the performance_calculator.html he/she will see a textbox where he/she has to enter the relevant subject name. After entering the subject name, he/she will click 'Calculate' button, on the other side (server-side) the entered name will be taken and will search the detail (progress) of that subject of that user (student) from the Detail Model using the subject name and that user name as filters. After getting the the progress detail, each value in the detail will be assigned to a single variable. Those variables will be passed a s parameters to fuzz_algo() function (a Fuzzy Logic Algorithm to calculator Performance), after getting the result, result will be forward to Client Side (Front End) using Django Messages Module. This was the summary, now I get the error at the step when the system tries to get the progress details of the subject (whose name was entered by user) of the … -
What is difference between self.get_serializer and Serializer object in Django rest framework?
Currently I have started learning django rest framework and I came accross below kind of code for getting serializer object. 1)serializer = self.get_serializer(queryset, many=True) 2)serializer = MyDataTypeSerializer(queryset, many=True) By using above two method I am able to get almost same kind of output so I have tried to find difference between those but not able to find any. Please if anyone knows let me know difference between these two methods and how to decide which method to use in which condition. Thanks, -
Django S3 pre signed URL
I am storing media files on S3 and I have used Django Storages for this. I need to keep the files private and I am able to automatically get signed URLs for all files. But the problem is that authentication credentials are unique for each file. I need to get some credentials to access all the files for some time. The problem is that I am using some javascript libraries that take path of one file which I can sign but then they call more files from within the same or different folder. So for example I can give the signed URL for: folder/file1 but then it will also call from within javascript: folder/file2 folder/another_folder/file3 Can I get the same credentials for all files? Like file?creds -
why I am getting this output in djangorestframework-jwt
hello I have implemented JWT in my test project using this package "djangorestframework-jwt" I have generated the token by giving my "username" and "password" but the problem is that I am getting this output bypassing my token with the endpoint I am using postman to test API,Django=2.2.12, python 3.7.6 I am not getting my data from the database {"eno":["This field is required."],"ename":["This field is required."],"esal":["This field is required."],"eaddr":["This field is required."]} -
Django: use Form tabs in User change Form
I use Suit for django admin site. I want to override UserAdmin to use form tabs in admin site. according to Form tabs in Suit documentation: https://django-suit.readthedocs.io/en/develop/form_tabs.html# -
TinyMCE widget insert media Source from local/browse option in Django-tinyMCE4
I searched stackoverflow for this requirement, though there are plenty for vanilla TinyMCE but not a clear thread for Django TinyMCE. I require this upload button on django-tinymce4-lite. I have tried official docs suggetion and I found in tinyMCE > settings.py and has USE_FILEBROWSER = getattr(settings, 'TINYMCE_FILEBROWSER', 'filebrowser' in settings.INSTALLED_APPS) which recommends, django-filebrowser or django-filebrowser-no-grappelli, which I have installed and registerd on settings.py > INSTALLED_APPS = [ ..., filebrowser ] and added FILEBROWSER_DIRECTORY = 'uploads/' FILEBROWSER_EXTENSIONS = { 'Image': ['.jpg','.jpeg','.gif','.png','.tif','.tiff'], 'Document': ['.pdf','.doc','.rtf','.txt','.xls','.csv'], 'Video': ['.mov','.wmv','.mpeg','.mpg','.avi','.rm'], 'Audio': ['.mp3','.mp4','.wav','.aiff','.midi','.m4p'] } in settings.py Please provide a solution for Django version of TinyMCE to get that browse button on the TinyMCE widget -
Django: how to make booking view
hi working on project …where user create a post and driver see that post and give the user a price of their ride ..when user accept their offer the page will show a order id and confirmation of booking but i tried some code to do that ,but its not working .. this is my models.py of booking class Booking(models.Model): order_id = models.AutoField b_price = models.ForeignKey(price, on_delete=models.CASCADE, related_name='b_prices') b_post = models.ForeignKey(Loader_post, on_delete=models.CASCADE, related_name='b_posts') booked_at = models.DateField(auto_now=True) user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, default='') status = models.BooleanField(default=False) approved_price = models.BooleanField(default=False) def __str__(self): return str(self.order_id) def approve(self): self.approved_price = True self.save() so my question is what will be the view(class) of that model and create a booking confirmation with unique order id where user can track his/her order.how to do that -
How to route domain name to a specific view?
In our site we are going to introduce a feature that would allow users who own a domain name of their own to link it to their organization id in our site. That way they can bootstrap their organization site through our tools and link different relevant pages to their domain. We'd provide default content so they have an organization page based on their organization information we already have in our site right off the bat. Basically, using an example, if an organization admin user registers their organization with id 12345 to a domain name they specify, domain.org, we would automatically register it in DigitalOcean and requests made to that domain should be mapped to the corresponding organization on our end as follows: domain.org/ -> oursite.org/organization/12345 domain.org/dashboard -> oursite.org/organization/12345/dashboard domain.org/about -> oursite.org/organizatin/12345/about I am not sure if this is a common problem but I am not sure how to set it up. Perhaps the way to go is to set a root handler: urlpatterns = patterns('', (r'^$', root), ... ) And that root view would have the responsibility of looking up the organization id that corresponds to the URL's domain which can be accessed with request.get_host(). is this a valid … -
RuntimeError: Unable to open C:\Users\В\PycharmProjects\SiteOfRecognition\SiteR\MyApp\shape_predictor_68_face_landmarks.dat
Problem I am making a site and I need to recognize people face parts. I writing in Django. I want to run python file using cmd in MyApp views.py, but I get an error that unable to open shape_predictor_68_face_landmarks.dat. This is full Traceback Traceback (most recent call last): File "C:\Users\В\PycharmProjects\SiteOfRecognition\SiteR\MyApp\static\MyApp\pythonHair\face_parts_detection.py", line 25, in <module> predictor = dlib.shape_predictor(args["shape_predictor"]) RuntimeError: Unable to open C This is my project pathes This is part of my views.py else: import os os.system('cmd/k "python C:\\Users\\В\\PycharmProjects\\SiteOfRecognition\\SiteR\\MyApp\\static\\MyApp\\pythonHair\\face_parts_detection.py --shape-predictor C:\\Users\\В\\PycharmProjects\\SiteOfRecognition\\SiteR\\MyApp\\shape_predictor_68_face_landmarks.dat --image images/face2.jpg "') return render(request, 'MyApp/DressPage.html') This is face_parts_detection.py from imutils import face_utils import numpy as np import argparse import imutils import dlib import cv2 from matplotlib import pyplot as plt # construct the argument parser and parse the arguments ap = argparse.ArgumentParser() ap.add_argument("-p", "--shape-predictor", required=True, help="path to facial landmark predictor") ap.add_argument("-i", "--image", required=True, help="path to input image") args = vars(ap.parse_args()) # initialize dlib's face detector (HOG-based) and then create # the facial landmark predictor detector = dlib.get_frontal_face_detector() predictor = dlib.shape_predictor(args["shape_predictor"]) # load the input image, resize it, and convert it to grayscale image = cv2.imread(args["image"]) image = imutils.resize(image, width=500) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # detect faces in the grayscale image rects = detector(gray, 1) eyeBrows = 0 # … -
Django rest_framework add filter to all views even if filter_backends is specified
I am writing a Django Rest Framework application. In all views that I have to check a condition based on user to filter customer contents: if user is admin, do not filter content, if user is normal show only customer data and show none if anonymous. I created a Filter to do that. class SessionCustomerFilter(filters.BaseFilterBackend): def filter_queryset(self, request: Request, queryset: QuerySet, view: View) -> QuerySet: if not request.user or request.user.is_anonymous: return queryset.none() if request.user.i_am_god: return queryset.all() return queryset.filter(customer=request.user.customer) I have to add this filter to all Views in the project like below, in the filter_backends section. class MyClass1_ViewSet(viewsets.ReadOnlyModelViewSet): queryset = MyObjClass1.objects.all() serializer_class = MyObjClass1Serializer filter_backends = [SessionCustomerFilter] class MyClass2_ViewSet(viewsets.ReadOnlyModelViewSet): queryset = MyObjClass2.objects.all() serializer_class = MyObjClass2Serializer filter_backends = [AnotherFilter, SessionCustomerFilter] What i want to achieve is that, if SessionCustomerFilter not specified in filter_backends, the view content is applied. class MyClass1_ViewSet(viewsets.ReadOnlyModelViewSet): queryset = MyObjClass1.objects.all() serializer_class = MyObjClass1Serializer filter_backends = None # have to be applied here class MyClass2_ViewSet(viewsets.ReadOnlyModelViewSet): queryset = MyObjClass2.objects.all() serializer_class = MyObjClass2Serializer filter_backends = [AnotherFilter,] # and applied here I have tried to implement a DefaultFilterBackend but I have a bit of issues make it work in both cases, with and without filter_backends specified, how can do it? Is this … -
How to fetch data from the database in Django on clicking submit?
I need to get database objects on the HTML only when the the SUBMIT is clicked and not on page load. I currently have an AJAX script running on the same form where it returns the text entered in textbox onto the HTML when submit is clicked. I want this feature to stay as well as add a new feature of retrieval of data. Below are some of the code snippets I am using: views.py @csrf_exempt def chat(request): resps = Responses.objects.all() context = {'resps' : resps} return render(request, "chat.html", context) urls.py path('chat/', views.chat, name='chat'), chat.html <form id="testForm" name="test-form" class="test-form" action="" method="POST">{% csrf_token %} <input id="texting" name="texting" type="text" class="test-text" placeholder="Test here"/> <div class="footer"> <input type="submit" value="SEND"> </form> </div> {% for r in resps %} <div> <p>{{r.response}}</p> </div> {% endfor %} ................................................ <script type="text/javascript"> $(document).on('submit','#testForm', function(e){ e.preventDefault(); $.ajax({ type : 'POST', url : '/chat/', data :{ text : $('#texting').val(), csrfmiddlewaretoken: $('input[text=csrfmiddlewaretoken]').val() }, success : function(){ // alert("Done!"); document.getElementById("userSpeaks").innerHTML = document.getElementById('texting').value; } }); }); </script> Any help would be appreciated. I just need a way out to print the model objects on each click of the submit button and not automatically on page load. Thanks in advance. -
how to migrate this page based pagination into cursor based pagination, python, Shopify
i want to upgrade to api_version '2019-07' or higher and the app uses this sync method to fetch store's products with deprecated page based pagination try: store = Store.objects.get(slug=store_slug) limit = 250 shopify.ShopifyResource.clear_session() with shopify.Session.temp(store.url, '2019-04', store.token): counts = shopify.Product.count() print(counts) pages_count = counts // limit + 1 shopify_products = [] for i in range(pages_count): shopify_products.append(shopify.Product.find( limit=limit_pages, page=i) shopify_products = list( itertools.chain.from_iterable(shopify_products)) products_db = Product.objects.filter(store=store) products_shopify_id = [p.id for p in shopify_products] products_db_id = [p.shopify_id for p in products_db.all()] to_add_to_db = list( set(products_shopify_id).difference(set(products_db_id))) How to Properly implement the cursor based pagination here ? -
How to order queryset with lookup fields?
I want to order my users with their full_name from profile model. How can I do it here ? views CustomUser.objects.filter(is_active=True).order_by('profile.full_name') models class Profile(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE) full_name = models.CharField(max_length=255) -
combining __startswith and __in not working
I have a QuerySet and an array of strings that I want to test against the QuerySet. The problem is the values I want to check are foreignKeys and the important characters of the foreignKey are in the beginning. The query I thought would work is this: materials_comparison_list.extend(materials_non_eu.filter(code__code__startswith__in=headings_list)) materials_non_eu is the QuerySet, headings_list is the array However when running that it returns the following error: django.core.exceptions.FieldError: Unsupported lookup 'startswith' for CharField or join on the field not permitted, perhaps you meant startswith or istartswith I tried to change the place or __startswith and __in but that produces the same error (different words) The models for materials looks like this: class Materials(models.Model): id = models.AutoField(primary_key=True) row = models.IntegerField(null=True) code = models.ForeignKey('HS_code', on_delete=models.CASCADE, null=True) ... The model for the code looks like this: class HS_Code(models.Model): id = models.AutoField(primary_key=True) code = models.CharField(max_length=10, unique=False) .... The complete console output: Traceback (most recent call last): File "/Users/5knnbdwm/Python_env/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Users/5knnbdwm/Python_env/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/5knnbdwm/Python_env/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/5knnbdwm/Python_env/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/Users/5knnbdwm/Python_env/lib/python3.8/site-packages/django/views/generic/base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File … -
Create records in two models by Nested serializer with two foreign keys pointing same model in Django
Make two records on the same table Department by foreingn key relation using nested serializer. ,this Department two records are creating at same time the People table created class Department(BaseModel): name = models.CharField(max_length=50) age = models.PositiveIntegerField() class People(BaseModel): teacher = models.ForeignKey(Department, on_delete=models.PROTECT,related_name='teacher') student = models.ForeignKey(Department, on_delete=models.PROTECT, related_name='student') available_seats = models.PositiveIntegerField(default=0) class DepartmentSerializer(serializers.ModelSerializer): class Meta: model = Department fields = '__all__' class PeopleSerializer(WritableNestedModelSerializer): teacher = DepartmentSerializer(many=True, write_only=True) student = DepartmentSerializer(many=True, write_only=True) available_seats = models.PositiveIntegerField() class Meta: model = People fields = '__all__' Here I need to accept this input and create records in People and Department table Input { "available_seats":100, "teacher": [{ "name": John, "age" : 37 }], "student": [{ "name": John, "age" : 37 }] } But i am getting this error "Direct assignment to the reverse side of a related set is prohibited. Use student.set() instead." thanks in advance -
Django Rest Framework, error while image upload
I have a model that contain file field, when I upload image through browsable API, it successfully added and I can retrieve the image from Javascript frontend. When I POST same image from Javascript frontend I gets error "The submitted data was not a file. Check the encoding type on the form.' Shall I correct frontend or backend to debug this error ? As browsable API capable to upload image successfully, I hope backend may be correct. -
How can I see the size of my django/python database or database tables?
I would like to see the size of the database I created with django. This is for a project. How do I go about that? I have looked at stackoverflow answers, and I found this answer: $ python manage.py shell >>> import sys >>> from myapp.models import MyModel >>> my_model = MyModel() >>> total_size = sys.getsizeof(my_model) * MyModel.objects.count() This however always gives a size of 24 bytes, while the tables I put into it have completely different amounts of fields. I suspect this is wrong. Thanks in advance. -
Is viewsets and routers absolutely necessary (specifically in the case of nested serializers)?
I am trying to extend my accounts table with the help of serializers.HyperlinkedModelSerializer. While doing so, I am trying to create my custom views. But while passing the data in postman to register the users, I encounter the following error. ImproperlyConfigured at /accounts/register/ Could not resolve URL for hyperlinked relationship using view name "account-detail". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field. My serializers looks as: class AccountProfileSerializer(serializers.ModelSerializer): url = serializers.CharField(source='get_absolute_url', read_only=True) # id = serializers.IntegerField(required=False) class Meta: model=AccountProfile fields = ['is_operation_manager', 'is_godown_manager', 'is_accountant', 'user_id'] read_only_fields = ['user'] class RegistrationSerializer(serializers.HyperlinkedModelSerializer): profile = AccountProfileSerializer() password2 = serializers.CharField(style={'input_type':'password'}, write_only=True) class Meta: model = Account fields = ['url', 'email', 'password', 'password2', 'phone_number', 'first_name', 'last_name', 'profile'] extra_kwargs = { 'password' : {'write_only': True}, #'users': {'lookup_field': 'user'} } @transaction.atomic def create(self, validated_data): profile_data = validated_data.pop('profile') password = self.validated_data['password'] password2 = self.validated_data['password2'] if (password != password2): raise serializers.ValidationError({'Password Error' : 'Passwords do not match. Please try again'}) check = validated_data.pop('password2') db_password = validated_data.pop('password') account = Account(**validated_data) account.set_password(db_password) account.save() # return profile_data AccountProfile.objects.create(user=account, **profile_data) return account And my view looks as: class UserRegistration(APIView): permission_classes = [AllowAny] @transaction.atomic def post(self, request): if request.method == 'POST': …