Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django admin site m sending email.html to user
\\admin from django.template.loader import render_to_string @admin.register(ParentsProfile) class ParentsProfile(admin.ModelAdmin): list_display = ('Father_Email','Fathers_Firstname' , 'Fathers_Middle_Initial', 'Fathers_Lastname', 'Request') ordering = ('Request',) search_fields = ('Request',) actions = ['Send_Email','Send_Email_Disapproved'] def Send_Email(self, request, queryset): html_content = render_to_string('Homepage/email.html') for profile in queryset: send_mail(subject="Invite", message=html_content, from_email=settings.EMAIL_HOST_USER, recipient_list=[profile.Father_Email]) i receive and email.txt not email.html, i dont know why.. please help me for this issue.. Email -
How to limit admin input after certain number of entries in Django admin?
I have been learning django for about 1 month while coming to django admin I want to limit data entries from admin not more than 5 so that when I want to display the model db on webpage be not more than 5, can you help me in this sorry if this too basic My model is class Top_5_Restaurants(models.Model): Restaurants=models.CharField(max_length=20) def __str__(self): return( self.Restaurants) class Meta: verbose_name = 'Top 5 Restaurant' verbose_name_plural = 'Top_5_Restaurants' Now I don't want more than 5 entries of Restaurants from admin interface, if admin tries entering more than 5 entries I want the entry option to blocked till admin deletes one of the entered database. -
'Category' object has no attribute 'post_set'
so I am trying to add a category system for posts by following a tutorial on this website https://djangopy.org/how-to/how-to-implement-categories-in-django/ (I changed my code up a little) Everything works like creating categories, adding a post, viewing a post, but if I try to go to the category page to view posts only in that category so /category/CATNAME but it shows me this error 'Category' object has no attribute 'post_set' models.py from django.db import models from django.contrib.auth.models import User from django.utils.text import slugify from markdownx.models import MarkdownxField from markdownx.utils import markdownify from taggit.managers import TaggableManager class Category(models.Model): name = models.CharField(max_length=100) short_desc = models.CharField(max_length=160) slug = models.SlugField() parent = models.ForeignKey('self', blank=True, null=True, related_name='children', on_delete=models.CASCADE) class Meta: unique_together = ('slug', 'parent',) verbose_name_plural = "Categories" def __str__(self): full_path = [self.name] k = self.parent while k is not None: full_path.append(k.name) k = k.parent return ' -> '.join(full_path[::-1]) def save(self, *args, **kwargs): value = self.title self.slug = slugify(value, allow_unicode=True) super().save(*args, **kwargs) class Thread(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=150) content = MarkdownxField() tags = TaggableManager() slug = models.SlugField(unique=True) category = models.ForeignKey('Category', null=True, blank=True, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.title class Meta: verbose_name_plural = 'Threads' def get_cat_list(self): k = self.category breadcrumb = … -
a request with pandas importing is running on django, but all other requests involved with pandas are blocking
windows + apache2.4 + django 2.1.10 + python 3.7 apache conf is followed `Listen 80 ServerName xxx.xxxx.cn Alias /static/ "F:/PivotWeb/pivot/static/" Require all granted WSGIScriptAlias "/" "F:/PivotWeb/apache/django_python_web.wsgi" WSGIApplicationGroup %{GLOBAL} Require all granted ` WSGIApplicationGroup %{GLOBAL} is added to solve the first sub interpreter issue. The request involve many complex pandas manipulations. a request with pandas importing is running on django, but all other requests involved with pandas are blocking. It seems that pandas module could only process on request per time. -
How to assign permission to a group in views using django-guardian
Currently using django-guardian. I am not sure of what i am doing wrong but i am unable to add the permissions below to a group not saving it. I have created one group and a few users via ADMIN. I have added users to the group now I want to add the permission 'can_play_piano' to the group. models.py class Task(models.Model): task_group = models.ForeignKey(Group, on_delete=models.CASCADE, related_name='task_groups') slug = models.SlugField(unique=True, max_length=200, db_index=True, blank=True) content = models.CharField(max_length=230) created = models.DateTimeField(auto_now_add=True) is_active = models.BooleanField(default=True) class Meta: permissions = ( ('can_play_piano', 'Can play piano'), ) def __str__(self): return self.task_group.name def save(self, *args, **kwargs): self.slug = slugify(self.task_group.name) super(Task, self).save(*args, **kwargs) views.py def detail_page(request, id): # Get the group id group = get_object_or_404(Group, id=id) # Get the task id task = get_object_or_404(Task, id=id) add_task_to_group = assign_perm('can_play_piano', group, task) add_task_to_group.save() # this is not saving print(add_task_to_group) context = {'group': group} return render(request, 'snippet/detail.html', context) I have intentionally not included request.method == 'POST' just for the sake of the question. result of 'print(add_task_to_group) in terminal' wiki is just a name placeholder wiki | wiki | can_play_piano I would appreciate any help. -
django Custom Template is not rendering for password_change_form.html
I have a password_change_form.html which is custom formatted on the website. I'm overriding the Django default template with my template. But, it is not rendering my template. It just rendering the default template. I have created a custom formated template base.html <div class="dropdown-menu dropdown-menu-right" aria-labelledby="navbarDropdown"> <a class="dropdown-item" href="{% url 'password_change' %}">Change password</a> <div class="dropdown-divider"></div> password_change_form.html {% extends 'home/base.html' %} {% block body %} <h2> Change password </h2> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit" class="btn btn-primary">Change password</button> </form> {% endblock %} urls.py from django.contrib import admin from django.urls import path, include from Shopping.cart import urls urlpatterns = [ path('', include('Shopping.cart.urls')), path('accounts/', include('django.contrib.auth.urls')), path('admin/', admin.site.urls), ] I wanted to see my template overrides the Django default template -
django admin send email to user
\admin.py @admin.register(ParentsProfile) class ParentsProfile(admin.ModelAdmin): list_display = ('Father_Email','Fathers_Firstname' , 'Fathers_Middle_Initial', 'Fathers_Lastname', 'Request') ordering = ('Request',) search_fields = ('Request',) actions = ['Send_Email','Send_Email_Disapproved'] def Send_Email(self, request, queryset): html_content = "Your Registration has been approved.\n\nPlease use this %s as your username and %s as your password. \nYou may now start enrolling your student using this link https://...../Plogin_form/ \n\n\n REGISTRAR " for profile in queryset: send_mail(subject="Invite", message=html_content %(profile.Father_Email,profile.Parent_Password), from_email=settings.EMAIL_HOST_USER, recipient_list=[profile.Father_Email]) # use your email function here def Send_Email_Disapproved(self, request, queryset): # the below can be modified according to your application. # queryset will hold the instances of your model for profile in queryset: send_mail(subject="Invite", message="Our Apology,\n\n Your Registration has been Disapproved " + profile.Father_Email + "\n\n\n REGISTRAR" + "", from_email=settings.EMAIL_HOST_USER, recipient_list=[profile.Father_Email]) i have this code to send an email to user, how do i convert my html_content into HTML? so that i can design my message to user? -
Django Custom user model creation NOT NULL constraint failed error
Im creating a custom user model with AbstractUser on django and i get that error when i create new user. Im using shell for create user: CustomUser.objects.create(email="testmaiil2323@gmail.com", name="test name aasxs", business_name="asdkasdk sl", password="testpass234") Im succefull created superuser with command createsuperuser, but when i make a new users django tells me: django.db.utils.IntegrityError: NOT NULL constraint failed: apirest_customuser.business_id from django.db import models from django.contrib.auth.models import AbstractUser from django.contrib.auth.base_user import BaseUserManager from django.utils.translation import ugettext_lazy as _ class Business(models.Model): name = models.CharField(max_length=150, unique=True) def __str__(self): return self.name class Profile(models.Model): name = models.CharField(max_length=150, unique=True) def __str__(self): return self.name class CustomUserManager(BaseUserManager): """ Custom user model manager where email is the unique identifiers for authentication instead of usernames. """ def create_user(self, email, password, **extra_fields): """ Create and save a User with the given email and password. """ if not email: raise ValueError(_('The Email must be set')) if not extra_fields.get('business_name'): raise ValueError(_('The Business name must be set')) if not extra_fields.get('name'): raise ValueError(_('The Name must be set')) if not password: raise ValueError(_('The Passowrd must be set')) email = self.normalize_email(email) business = Business.objects.create(name=extra_fields.get('business_name')) profile = Profile.objects.create(name=extra_fields.get('name')) user = self.model(email=email, business=business, profile=profile, **extra_fields) user.set_password(password) user.save() return user def create_superuser(self, email, password, **extra_fields): """ Create and save a SuperUser with the … -
How can I use the static images in ReactJS connected to Django?
I have configured Django and ReactJS and I want the static images to be loaded as well as the CSS and js files from ReactJS components to be loaded during the development. I have added a webpack.config.js file for configuration but it's not providing the result. This is the webpack.config.js file module.exports = { module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: { loader: "babel-loader" } }, { test: /\.css$/, use: "css-loader" }, { test: /\.(jpe?g|png|gif|woff|woff2|eot|ttf|svg)(\?[a-z0-9=.]+)?$/, loader: "url-loader?limit=100000" } ] } }; When I run npm run dev, this is what I get. Also when I run the python manager.py runserver for starting the local server and try the link out, I'm getting only the HTML content and not the HTML with styling and the images are not embedded. This is the file structure and you can see the hash of the image being outputted. What should I do in order to get the output correctly? -
Implementing Jupyter notebook into Django web app
I would like to know if there's a way to show a jupyter notebook on a Django page? The reason for this is, I would like to create a few live Data Analytic scenarios and showcase it on my Django site where each of these projects gathers data from source stores the info into an SQLite database for later use in a Machine learning project that I can showcase also on my Django site I've looked around I have not come across any scenarios like this. If you have any ideas feel free to post them :) Kind Regards Faz -
Django formset - custom input HTML
I need to expand a formset's field, so instead of {{ form.name }} I'm using something like <input type="text" name="{{ form.name }}" ... > My custom implementation does not print the formset prefix, so the HTML I get is <input type="text" name="name" ... > But what I would need to have the form working properly with formset is <input type="text" name="attachments-3-name" ... > where attachments-x is automatically added. How can I get that? I noted there's an helper for ID (auto_id) which prints something similar: id_attachments-3-name; is there something similar for names? -
why does not show the view content in template with {{ xxx }}
I want do learn & practice python w Django. Therefore I am trying to Code a simple app, translating some text from DE to EN and give the EN text to index.html. But the view content {{ eng_text }} does not Show up in the html template. This is the views.py from django.shortcuts import render from textblob import TextBlob # Create your views here. def index(request): return render(request, 'index.html') DEtext = 'das ist ein deutscher text, der übersetzt werden soll' print (DEtext) def translate(request): tb = TextBlob(DEtext) ENtext = tb.translate(to="EN") print(ENtext) dict = {'eng_text': DEtext} return render(DEtext, 'index.html', context=dict) -
How can I specify between models of different apps but the same name, in the same view
I have a separate Django app for two different cities. I have models of the same name, for each of those cities, and would like to bring them into the same view. When i import the models of both apps, the data doesnt render, i assume because Django doesnt know which one to use. When I import just corpus_christi, the template renders the data just fine, and vice versa. How can I specify from which app i want to bring these models? Here is my view from django.shortcuts import render from django.http import HttpResponse from corpus_christi.models import Service, Member from lake_charles.models import Service, Member def index(request): return render(request, 'pages/index.html') def corpuschristi(request): residential = Service.objects.filter(service_type="Residential") commercial = Service.objects.filter(service_type="Commercial") prelisting = Service.objects.filter(service_type="Pre Listing") members = Member.objects.all() context = { 'members': members, 'residential': residential, 'commercial': commercial, 'prelisting': prelisting } return render(request, 'pages/corpuschristi.html', context) def lakecharles(request): return render(request, 'pages/lakecharles.html') -
Getting User information from FB allauth authentication using cookiecutter django
I recently used cookiecutter django from Two Scoops of django and implemented user login/creation using oauth. Problem is that I have no idea how to get the authenticated users' extra data as I do see it in the admin as a dict. All the tutorials out there only touches on how to use oauth login but not attaining data. from django.contrib.auth.models import AbstractUser from django.db.models import CharField from django.urls import reverse from django.utils.translation import ugettext_lazy as _ class User(AbstractUser): # First Name and Last Name do not cover name patterns # around the globe. name = CharField(_("Name of User"), blank=True, max_length=255) def get_absolute_url(self): return reverse("users:detail", kwargs={"username": self.username}) This is the default User model from the cookiecutter template, how do I then attain the last_name and first_name from fb? I know I can add first_name fields, that means the views.py file have to have a user creation view but it doesn't and I can't wrap my head around on how the allauth is able to create this user. Thank you! -
Can VS Code Debug Django Templates on a Remote Server?
I've begun using VS Code to edit a Django project running on a remote server and it works pretty well. However, I'm trying to debug a Django template and I'm finding that if I set a breakpoint on a template tag and refresh the web page, the debugger doesn't halt on my tag as the documentation says it should: {% for member in new_members %} # <- Breakpoint set here {{ member.user.username }} {% endfor %} Here is my launch profile: { "version": "0.2.0", "configurations": [ { "name": "Python: Django", "type": "python", "request": "launch", "program": "${workspaceFolder}/manage.py", "args": [ "runserver", "--noreload" ], "django": true } ] } When I start the debugger, I can see the Django development server starting on the remote host in the Code Terminal and the page refreshes but the debugger doesn't stop on the {% for... %} tag. Is there anything else I need to do or is remote template debugging not supported? -
How to make key field to appear in Django forms using inline formsets
When I use a single model for an object (say, a "Plant") I can make the key field (say, plant_id) to appear in the "UpdateView". For this purpose I use the following form: class PlantForm(forms.ModelForm): class Meta: model = Plant fields = ('__all__') Using the above ModelForm when I use UpdateView, the key field (plant_id) shows up in the form. And (of course) there I have the additional task of "disabling" the key field (plant_id) from being open to editing. Now if I use an inline formset using two models (Plant and PlantAsset), by design I need to use the formset something like: PlantAssetsChange = inlineformset_factory( Plant, PlantAsset, form=PlantAssetForm, can_delete=True, min_num=0, validate_min=True, max_num=100, extra=1) OR PlantAssetsChange = inlineformset_factory( Plant, PlantAsset, fields=......., can_delete=True, min_num=0, validate_min=True, max_num=100, extra=1) In this case, by design I need to use a form based on the related model (PlantAsset) (OR use its fields) to construct the inline formset. In this scenario, I find the key field of the parent model (Plant) i.e. plant_id does not show up on the page. How do I make the key field (plant_id) to appear on the page? -
Django CSP is refusing to load a certain JS file despite the 'self' directive being enabled
I'm currently in the process of implementing CSP headers via django-csp, and for the most part everything seems to be in working order. One of the things I'm trying to debug right now is why a certain JS file,'multilanguage.js' is being rejected. To the best of my knowledge I have allowed scripts to be run if it's provided from my site via the self directive. Despite this I am not sure why it's not working as intended. According to chrome it seems to fail in this following line: $("#"+ elem).append(eval(elem)[language]); JS file in question: var m=new Date(); if ( m.getHours() == 0 ){ degHour = 0 ; } else { degHour = 30 * (m.getHours()%12); } degMin = 6 * m.getMinutes(); $('.hour-block').css("transform", "rotate("+degHour+"deg) scale(1,0.7)"); $('.min-block').css("transform", "rotate("+degMin+"deg) scale(1,1)"); $.getScript("/static/js/language.js", function(){ $('.check-item li').click(function (){ localStorage.setItem('language', $(this).attr('id')); location.reload(); }); var language = localStorage.getItem('language'); if ( language == null ) { localStorage.setItem('language', 'English'); var language = localStorage.getItem('language'); } $(arrayElements).each(function(i,elem) { $("#"+ elem).append(eval(elem)[language]); **FAILING HERE** }); $("#selected_lan_img").attr("src","/static/css/languages/"+ language +".svg"); $('#'+ language).hide(); $('.country-selection').click(function (){ $('.check-item').toggle(); }); }); My Django CSP settings # Django CSP Settings CSP_DEFAULT_SRC = ("'self'",) CSP_STYLE_SRC = ("'self'", 'cdnjs.cloudflare.com', 'https://use.fontawesome.com', 'https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css','fonts.googleapis.com', 'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css') CSP_SCRIPT_SRC = ("'self'","'sha256-VhNEptbDobqL5kYATr7A4mMh2PwDxbBXvt8R+yP5Bn0='","'sha256-4dBfmKQVHKo3lG/03tkNCWveHZb3v0bNQwXDNyYuryU='",'www.google-analytics.com', 'www.googletagmanager.com', 'https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js', 'https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.8.0/js/bootstrap-datepicker.min.js', 'https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js','https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js','ajax.googleapis.com',) CSP_FONT_SRC = ("'self'", 'use.fontawesome.com', … -
django query model A and exclude some items from related model B
I'm new to Django and I'm facing a question to which I didn't an answer to on Stackoverflow. Basically, I have 2 models, Client and Order defined as below: class Client(models.Model): name = models.CharField(max_length=200) # .. class Order(models.Model): Client = models.ForeignKey(ModelA, on_delete=models.CASCADE, related_name='orders') is_delivered = models.BooleanField(default=False) # .. I would like my QuerySet clients_results to fulfill the 2 following conditions: Client objects have a name equal to 'Doe' Order objects I can access by using the orders relationship defined in 'related_name' are only the one that are not delivered. I could do this directly in the template but I feel this is not the correct way to do it. Additionally, I read in the doc that Base Manager from Order shouldn't be used for this purpose. Finally, I found a question relatively close to mine using Q and F, but in the end, I would get the order_id while, ideally, I would like to have the whole object. Could you please advise me on the best way to address this need? Thanks a lot for your help! -
How do I pass objects to my Django template?
I think what I'm trying to do could be explained as trying to pass all of my Genre objects to my template for display. I want to display all of my columns and their entries for my Genre model on my template page table_home. Presently, when I navigate to the table_home.html page, I get NameError at /generators/table_home name 'genre' is not defined I want to do the same thing again with the System model when its working. Can someone explain what is broken with my code and where I can do some reading on passing values from views to templates? It seems mystical to me and I don't know where to go for self-help, partially because I don't know what terminology to search. In the table_home view I tried to mimic what was working in both the table view and then what seems to be working in the index view. Neither worked, and I'm not quite sure why. My views.py: from tablib import Dataset from .models import Genre, D100Generator, System def index(request): latest_table_list = D100Generator.objects.order_by('-d_100_id')[:5] context = { 'latest_table_list': latest_table_list } return render(request, 'generators/index.html', context) def table(request, table_slug): table = get_object_or_404(D100Generator, pk=table_slug) return render(request, 'generators/table.html', {'table': table}) def table_home(request): global_table_list … -
Matching model to ForeignKey based on Foreign Model's date range
Say I have two models. class ModelA(models.Model): name = models.CharField(max_length=200) start_date = models.DateField() end_date = models.DateField() def __str__(self): return '%s (%s) -> (%s)' % (self.name,self.start_date,self.end_date) class ModelB(models.Model): modelA = models.ForeignKey(ModelA,on_delete=models.SET_NULL,null=True,) name = models.CharField(max_length=150) email = models.EmailField(max_length=50) phone = models.CharField(max_length=10) date = models.DateField('Date submitted',auto_now_add=True) Given say, 10 ModelA objects, with varying date ranges, how would you match ModelB to a ModelA on form submission based on ModelB's date? -
I/O operation on closed file with print statement
I recently migrated a Django app from a provider to AWS (elastic beanstalk). It worked well for a while, but not once in a while I need to restart my server due to an error that reads I/O operation on closed file The culprit, every time, is a print statement in one of my views or functions. I don't work with files in my code and don't ever open / close files. All the other errors like this that I researched are caused with a file being open somewhere, but I never open or work with files so I am very confused. Is there anything happening in the background of a print statement (which can sometimes be as easy as print('test') to cause the error I/O operation on closed file ?? It doesn't seem to be about the structure of the code, but maybe the Python install on the server or folder permissions ? -
Connecting Django, Celery and SQS
I want to use Celery and SQS for periodic tasks in my Django application.I'm following the documentation and a couple of tutorials "Using Django 2 with Celery and SQS" and "Using Amazon SQS with Django and Celery". I think my issues is with BROKER_URL. Example AWS_SECRET_ACCESS_KEY 1xxxxa/ABCDE/FGH56/IJKL123 I tried as per the documentation: BROKER_URL = 'sqs://'+AWS_ACCESS_KEY_ID+':'+AWS_SECRET_ACCESS_KEY+'@ I printed BROKER_URL and got: 1xxxxa/ABCDE/FGH56/IJKL123 But got: ValueError: invalid literal for int() with base 10: '1xxxxa' I tried: BROKER_URL = 'sqs://{0}:{1}@'.format( urllib.quote(AWS_ACCESS_KEY_ID, safe=''), urllib.quote(AWS_SECRET_ACCESS_KEY, safe='') ) And get: AttributeError: module 'urllib' has no attribute 'quote' I tried: BROKER_URL = 'sqs://{0}:{1}@'.format( urllib.parse.quote(AWS_ACCESS_KEY_ID, safe=''), urllib.parse.quote(AWS_SECRET_ACCESS_KEY, safe='') ) And BROKER_URL is printed: 1xxxxa%ABCDE%FGH56%IJKL123 and when I run the worker I get: Access to the resource https://queue.amazonaws.com/ is denied. I'm thinking the reason is that the BROKER_URL is being passed as 1xxxxa%ABCDE%FGH56%IJKL123 instead of 1xxxxa/ABCDE/FGH56/IJKL123. But for the methods I tried that print the BROKER_URL as 1xxxxa/ABCDE/FGH56/IJKL123, I get the invalid literal error. How can I fix this? -
How to update choices for forms.ChoiceFiled in Django?
I have field in forms.py: main_choices = ((1,'option 1'),(2,'option 2'),(3,'option 3')) sub_choices = ((1,'PlaceHolder')) class MainForm(forms.Form): type = forms.ChoiceField(choices=main_choices) sub_type = forms.ChoiceField(choices=sub_choices) HTML: <form action="{% url 'app:get_url' %}" method="POST"> {% csrf_token %} {{ form.type }} {{ form.sub_type }} <button type="submit" class="app">GET</button> </form> view.py def get_ajax(request): if request.is_ajax(): data = request.POST.copy() if 'type' in data: type = int(data['type']) if type == 2: sub_choices = ((1,'Folder 1'),(2,'Folder 2')) elif type ==3: print('getCollectionList by username') sub_choices = ((1,'Collection 1'),(2,'Collection 2')) return HttpResponse() Currently, server catches ajax post data from the type field. I don't know how to put sub_choices from get_ajax action to sub_type field in forms. Can anyone explain how to do that? -
Data not displaying when I loop through with Django Template Tags
I'm pretty stumped. When I go to loop through each "Service", nothing shows in the browser. I've checked to make sure the data I've entered through the admin area is actually in the database (Postgres), and it is. Maybe i have a syntax issue somewhere? models.py from django.db import models class Service(models.Model): name = models.CharField(max_length=50) service_type = models.CharField(max_length=50) price = models.DecimalField(max_digits=4, decimal_places=2) is_published = models.BooleanField(default=True) def __str__(self): return self.name views.py from django.shortcuts import render from django.http import HttpResponse from corpus_christi.models import Service, Member, Area def corpuschristi(request): services = Service.objects.all() context = { 'services': services } return render(request, 'pages/corpuschristi.html', context) And this is my For Loop in the html page: {% for service in services %} <div class="col s12 m6"> <li class="service"> {{ service.name }} </li> </div> {% endfor %} -
My bytes input is INCORRECT (can't convert to JSON) in Python
Basically, I have this API end point that will be called if you make a POST request to it. The problem is for some reason, I can't convert the bytes to JSON so I can access the data. My code: @api_view(['POST']) def create_user(request): """ POST = Create user. """ # Check that a username with this email doesn't already exist try: data = {} print("IS IT WORKING...?") print(type(request.body)) print(request.body) # Use double quotes to make it valid JSON my_json = request.body.decode('utf8').replace("'", '"') print("MY_JSON:") print(my_json) data = json.loads(my_json) print("DATA:") print(data) s = json.dumps(data, indent=4, sort_keys=True) print("s:") print(s) except User.DoesNotExist: print("PLS WORK ON CONSOLE") return Response(status=status.HTTP_409_CONFLICT) I try to make a POST request to my path users/create/ using Postman, but when I print request.body to see the contents of my POST request, it is formatted incorrectly with a lot of random numbers and dashes. This is preventing me from converting it to JSON. It's a simple POST request with email and password fields. This is what the weird formatting looks like: https://gyazo.com/fa1cc2f04637c02f79fe59790153ae40 This is what the "json" looks like after I have decoded it and converted with double quotes (Notice the weird dashes and numbers): https://gyazo.com/3ca41106117a4e9acdd96929469313a1 After that, it ERRORS because of …