Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to set checkbox on each element of list in Django
I'd like to set a checkbox from Django form on each element of a list in settings but I don't know how to do that. I have this list in settings: COOP_CMS_TEST_EMAILS = [ '"Your name" <coop_cms@mailinator.com>', '"Test Test" <test@test.test>' ] forms.py: class NewsletterHandleRecipients(forms.Form): check = forms.BooleanField() def __init__(self, *args, **kwargs): super(NewsletterHandleRecipients, self).__init__(*args, **kwargs) dests = settings.COOP_CMS_TEST_EMAILS for dest in dests: ... I want to have a checkbox at the left of the string for each element in my list. But I'm blocked, can anyone help me please ? Thanks. -
Django 1.11 showing Warnings message
When I'm running a Django test server locally with ./manage.py runserver, lots of warnings are showing up (DeprecationWarning, RemovedInDjango20Warning), even if they shouldn't be there by default (https://docs.djangoproject.com/en/2.2/releases/1.11/#deprecating-warnings-are-no-longer-loud-by-default). I've put this code in a Django command : import warnings warnings.simplefilter("ignore", DeprecationWarning) warnings.simplefilter("ignore", RemovedInDjango20Warning) and it's hiding the warnings on that command, but I don't know where to put it so that it hide all warnings globally (I've tried in manage.py, settings.py, models.py,...) I've also tried to run python -W ignore manage.py runserver which is supposed to tell python not to show warnings, but it still display a lot of warnings. Warnings look like that : /.../venv/lib64/python3.6/site-packages/review/templatetags/review_tags.py:11: RemovedInDjango20Warning: assignment_tag() is deprecated. Use simple_tag() instead @register.assignment_tag or /.../models/results.py: RemovedInDjango20Warning: on_delete will be a required arg for ForeignKey in Django 2.0. Set it to models.CASCADE on models and in existing migrations if you want to maintain the current default behavior One possibility would be to update Django version and make all change suggested by warnings but it would be too long and I just want to hide those warnings. -
Django does not use variables from local_settings.py
i split my settings file into local_settings (not versioned) and settings (versioned). unfortunately the locally defined variables are not used in a call, although they are successfully overwritten. settings.py MY_GLOBAL = 'i am drawn from the settings.py' try: from .local_settings import * except ImportError: raise Exception('import local_settings.py failed') local_settings.py MY_GLOBAL = 'i am from local_settings.py' in my view i've tried smth like that: show_my_setting.py from my_app import settings print(MY_GLOBAL) I expect "i am from local_settings.py" but get "i am drawn from the settings.py" -
bootstrap django using collapse within a for loop
I'm iterating through the event_list and want to display info for each entry. But my html only shows the first entry despite whatever entry I click on. i.e If i click on green event it expands the my wedding card-body. I want it to expand separate event details for each separate entry. How do I do that? index.html {% extends 'event/eventAdminBase.html' %} {% load static %} {% block content %} {% if event_list %} {% for events in event_list %} <div id="accordion"> <div class="card"> <div class="card-header" id="headingOne"> <h5 class="mb-0"> <button class="btn btn-link" data-toggle="collapse" data-target="#collapseOne" aria-expanded="false" aria-controls="collapseOne"> Event Name :{{ events.event_name }} </button> </h5> </div> <div id="collapseOne" class="collapse " aria-labelledby="headingOne" data-parent="#accordion"> <div class="card-body"> <ul> <li> <p> Event Name :{{ events.event_name }}</p> <p>Venue:${{ events.event_venue }}</p> <p>Type:{{ events.event_type }} </p> <form action="{% url 'event:event-delete' events.id %}" method="post" style="display: inline;"> {% csrf_token %} <button type="submit" class="btn btn-default btn-sm">Delete</button> </form> <form action="{% url 'event:event-update' events.id %}" method="post" style="display: inline;"> {% csrf_token %} <button type="submit" class="btn btn-default btn-sm">Update</button> </form> </li> </ul> </div> </div> </div> </div> {% endfor %} {% else %} <h1>No event entries found on the database.</h1> {% endif %} {% endblock %} -
Django deploy in shared hosting server(Hostgator)
How can i setup my django project into hostgator server which i'm using shared hosting. Is python is setup default or it will need to setup in my server (hostgator server)? Please help me -
Allow all active user to login to django admin site
I am trying to allow all active user to login to admin site because as a default just staff and superusers are able to login to admin site. I've tried to overwrite clean method in my custom crate/change forms but it didn't help # First Name and Last Name do not cover name patterns # around the globe. name = models.CharField(_("Name of User"), blank=True, max_length=255) def get_absolute_url(self): return reverse("users:detail", kwargs={"username": self.username}) @admin.register(User) class UserAdmin(GuardedModelAdminMixin, auth_admin.UserAdmin): form = UserChangeForm add_form = UserCreationForm fieldsets = FIELDSETS list_display = ["username", "name", "is_active", "is_superuser", "is_staff"] search_fields = ["name", "username"] class UserChangeForm(forms.UserChangeForm): class Meta(forms.UserChangeForm.Meta): model = User class UserCreationForm(forms.UserCreationForm): error_message = forms.UserCreationForm.error_messages.update( {"duplicate_username": _("This username has already been taken.")} ) class Meta(forms.UserCreationForm.Meta): model = User def clean_username(self): username = self.cleaned_data["username"] try: User.objects.get(username=username) except User.DoesNotExist: return username raise ValidationError(self.error_messages["duplicate_username"])``` -
Django create multiple tables with different name for the same model
I have a system for a network connected vending machine. My team decided to use MySql Master Slave replication to stored the data to the local device. I am trying to find a way to create multiple product tables base on a model with different table name base on the remote device. Eg: remote devide 12 have a seperate table with the name "device_12_product_table" I want to have a way to create a new table when create a new remote device, a way to make GRUD action to a table when i specify a remote machine. Below is the model of my remote machine and the product model class RemoteVendingMachine(models.Model): devicePrivateKey = models.TextField(help_text='RSA private key is big') deviceName = models.CharField(max_length=100, help_text='Device Name') deviceSid = models.CharField(max_length=100) isActive = models.BooleanField(default=True) id = models.AutoField(primary_key=True) product_table_name = models.CharField(max_length=255) def save(self, **kwargs): self.product_table_name = Utils.generate_product_table_name_by_remote_pos(self) class Product(models.Model): productName = models.ForeignKey(ProductName, on_delete=models.CASCADE) price_tag = models.ForeignKey(ProductPrice, on_delete=models.DO_NOTHING, null=True) # A product can be sold at different prices across many machines vendingMachine = models.ForeignKey(RemoteVendingMachine, on_delete=models.CASCADE) # Image should be cache on the client side anyway url = models.CharField(max_length=50, help_text='Product image URL') discountAmount = models.FloatField(default=1) discountExpired = models.DateTimeField(default=None) -
controlling to access files in Django on windows server 2012
i create a website with django 2.2 for sell some files (zip, rar, video , music) and i forced run my website on windows server 2012 , now i want to create a Private link just for a user who buy special files.and user can download that files with private link for 24 hours and Then the private link expires... anonymous user or visitor should not be able to download files or direct access to them !. Just for user who buy them. now How can I implement this scenario with ِDjango? which package in django i need ? or which config i should to do ?? how can i preventing direct access to files? -
get_object_or_404 stops after a single loop
I am trying to extract objects from a model based on another model: Code def financials (request): finance = list(Quiz.objects.filter(owner=request.user.pk).values_list('id', flat=True)) print('finance', finance) invoice_list = [] for i in finance: print('i',i) invoice_object = get_object_or_404(Invoice, invoice_quiz_id=i) invoice_list.append(invoice_object) but it stops after a single loop, any help is appreciated. -
django choose template from admin panel without restarting server
I'm trying to create a website with multiple template for all pages. I've created a templates folder and there are 3 folders in it. each folder contains base.html, home.html, etc. Admin can choose each template from admin panel and in my view load template like this. class HomeView(TemplateView): default_template = CustomTemplate.objects.first().name template_name = default_template + '/home.html' The problem is I have to restart server to apply admin's changes. Is there any way to do this without restarting server? I've also tried to enable / disable loader cache but I guess the problem is not depends to cache system. Any idea would be solution. Thanks in advanced. -
Reverse for 'edit' with no arguments not found. 1 pattern(s) tried: ['employees\\/edit\\/(?P<pk>[0-9]+)\\/$']
Building an Employee application, After updating an Employee using a form, it just shows this error and the Url seems correct so I can really say where the error is coming from I've crosschecked all my url patterns my views and my url in the form and also tried using the solution in this question, this gives me a bigger error urls.py urlpatterns = [ path('edit/<int:pk>/', views.edit, name = 'edit'), ] views.py @login_required(login_url='/accounts/login') def edit(request, pk): employ = get_object_or_404(Employee, id=pk) logging.info(type(employ)) departments = Department.objects.all() context = { 'employ': employ, 'departments':departments } if request.method == "POST": first_name = request.POST['first_name'] last_name = request.POST['last_name'] name = last_name +' '+first_name employee_id = request.POST['employee_id'] email = request.POST['email'] department = Department.objects.get(dept_name = request.POST['department']) address = request.POST['address'] employment_type = request.POST['employment_type'] employment_status = request.POST['employment_status'] role = request.POST['role'] marital_status = request.POST['marital_status'] gender = request.POST['gender'] join_date = request.POST['join_date'] end_date = None if len(request.POST['end_date']) ==0 else request.POST['end_date'] location = request.POST['location'] credentials = request.POST['credentials'] passport = request.POST['passport'] hod = request.POST['hod'] phone_number = request.POST['phone_number'] date_of_birth = request.POST['date_of_birth'] date_added = datetime.now() if Employee.objects.filter(employee_id = employee_id).exists() or Employee.objects.filter(email = email).exists(): messages.error(request, 'That ID/Email is Taken') return redirect('edit') else: employee = Employee(first_name='first_name',last_name='last_name',email='email', employee_id='employee_id',department='department',address='address',employment_type='employment_type', employment_status='employment_status',role='role',marital_status='marital_status',gender='gender',join_date='join_date', end_date='end_date',location='location',credentials='credentials',passport='passport',hod='hod', phone_number='phone_number',date_added='date_added',date_of_birth='date_of_birth') employee.save() messages.success(request, 'Employee Created') return redirect('all') return render(request, 'employees/edit.html', context, … -
Create HTTP Server in Python
I am trying to create a django app in which I need to create a server on my PC and fetch data from a website or IP on the internet. The data i will fetch should be in the form of XML document. How shall I write a code in Python in order to establish a connection with the IP and fetch its data and display it on my localhost. -
What does [::1] mean in ALLOWED_HOSTS in Django?
I was going through the documentation for Django's ALLOWED_HOSTS here I came across a string ['localhost', '127.0.0.1', '[::1]'] in the ALLOWED_HOSTS. Everything looks fine except the '[::-1]' part. I can't find a realtime scenario where '[::-1]' is used. Can someone please explain in which use case we will use this [::-1] -
Django 2 apps same urls
i have 2 apps Post and espor i want like this; example.com/blog-post (post app) example.com/sk-telecom-vs-team-solomid (espor app) blog.urls path('',include('post.urls')), path('',include('espor.urls')), However, i got error. (If I combine 2 apps in a single app, it's okay, but I want to separate it.) -
ODBC Driver Manager Data source name not found and no default driver specified
I have problem connecting my 64 bit laptop with a database. I am working in a django project and my database (sql server 32 bit) is in a separate server. I have included the following in my settings file in Django. DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'sales', 'USER': '*******', 'PASSWORD': '*********', 'PORT': '1433', 'HOST': 'xx.xx.xxx.xxx', 'OPTIONS': { 'driver': 'SQL Server Native Client 11.0', }, } } I have tried installing "ODBC Driver 11 for SQL Server" in my laptop. (since the server also has the same driver installed). But when I make migrations, I get an error, django.db.utils.InterfaceError: ('IM002', '[IM002] [Microsoft][ODBC Driver Manag er] Data source name not found and no default driver specified (0) (SQLDriverCon nect)') Am I getting the problem due to the different versions (64 bit & 32 bit) installed in my laptop and server? If so how can I handle this without changing the entire laptop system to 32 bit?Also, I haven't installed sql server in my laptop. Should I need to install sql server in my laptop also? -
How to get json from queryset?
This class has query for database: class arizakestirimi_func(ListAPIView): serializer_class = arizakestirimiserializer def get_queryset(self): queryset = isyeriarizabilgileri.objects.raw(""" SELECT M.id as id,M.isyeri as isyeri, DATE_PART('day',(M.tarih)::timestamp - (D.mindate)::timestamp) * 24 + DATE_PART('hour',(M.tarih)::timestamp - (D.mindate)::timestamp) + DATE_PART('minute',(M.tarih)::timestamp - (D.mindate)::timestamp) / 60 as zamanfarki FROM arizakestirimi_isyeriarizabilgileri M INNER JOIN (SELECT DISTINCT ON (isyeri) isyeri,id as id,durustahmini,tarih as mindate FROM arizakestirimi_isyeriarizabilgileri WHERE durustahmini='MEKANIK ARIZA' AND isyeri='15400001' ORDER BY isyeri, tarih ASC) D ON M.isyeri = D.isyeri AND M.durustahmini = D.durustahmini ORDER BY M.tarih ASC """) return queryset This is the serializer class, I have defined it in serializer.py: class arizakestirimiserializer(serializers.Serializer): isyeri = serializers.CharField(max_length=30) zamanfarki= serializers.FloatField() When ı use django rest framework ı got this json: [ { "isyeri": "15400001", "zamanfarki": 0.0 }, { "isyeri": "15400001", "zamanfarki": 7.0 }, { "isyeri": "15400001", "zamanfarki": 603.0 }, { "isyeri": "15400001", "zamanfarki": 607.0 }, { "isyeri": "15400001", "zamanfarki": 1655.0 }, { "isyeri": "15400001", "zamanfarki": 1661.0 } ] I want to use this json directly inside "get_queryset" method. How can convert queryset result to json with given field name like "serializers.py". Thanks -
Heroku Django ModuleNotFoundError
I'm a first timer working with Django and now trying to deploy to Heroku. I am able to push to heroku and their service recognizes my application as a python application. However, when I navigate to my application I get 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 checking the logs I get the following: 2019-07-09T06:00:29.052294+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2019-07-09T06:00:29.052301+00:00 app[web.1]: ModuleNotFoundError: No module named 'xxxx' 2019-07-09T06:00:29.052738+00:00 app[web.1]: [2019-07-09 06:00:29 +0000] [10] [INFO] Worker exiting (pid: 10) 2019-07-09T06:00:29.198426+00:00 app[web.1]: [2019-07-09 06:00:29 +0000] [4] [INFO] Shutting down: Master 2019-07-09T06:00:29.198530+00:00 app[web.1]: [2019-07-09 06:00:29 +0000] [4] [INFO] Reason: Worker failed to boot. 2019-07-09T06:00:29.314321+00:00 heroku[web.1]: State changed from up to crashed 2019-07-09T06:00:29.296331+00:00 heroku[web.1]: Process exited with status 3 2019-07-09T06:00:29.937311+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=murmuring-dusk-96030.herokuapp.com request_id=38020b2b-dc63-42aa-91e6-63e1c377eadd fwd="155.93.179.40" dyno= connect= service= status=503 bytes= protocol=https 2019-07-09T06:00:30.382887+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=murmuring-dusk-96030.herokuapp.com request_id=133a6de4-be78-4ac9-9fcf-f65e74c41de3 fwd="155.93.179.40" dyno= connect= service= status=503 bytes= protocol=https I'm not 100% sure but I think the issue has to do with how I'm serving static files? … -
Obtaining queryset based on unrelated models
I've got the following models. I need to obtain a queryset of orders where the user's userprofile.setupstatus == 1. Is this possible or should I just add a foreign key field on the Order model to the UserProfile? class Order(models.Model): user = models.ForeignKey(UserCheckout, null=True, on_delete=models.CASCADE) class UserCheckout(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=True) class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) setupstatus = models.IntegerField(default=0) -
How to display form errors properly?
Here i am trying to display form's errors and the below code works also but the problem with this is when the form throws the field errors it also clears all the the previously added value from form.I looked through all the solution in this link https://docs.djangoproject.com/en/2.2/topics/forms/ but all the solution works as same. What i really want is to throw the field errors like the django {{form.as_p}} or {% bootstrap_form form %} throws, in my own custom forms.How it can be possible ? {% for field in form %} {% if field.errors %} <div class="alert alert-danger"> {{ field.label }}: {{ field.errors|striptags }} </div> {% endif %} {% endfor %} <div class="box-body"> <div class="row"> <div class="col"> <form action="{% url 'do_something' %}" method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="form-group"> <b>Name</b> <div class="controls"> {{# form.name.errors #}} <input type="text" name="name" class="form-control"> </div> </div> <div class="form-group"> <b>Address</b> <div class="controls"> <input type="text" name="address" class="form- control"> </div> </div> -
How I add totals row to django admin that show an admin method total
I get sum of other table records with an admin method. No I want to sum this virtual column in total row. I used. Django-admin-totals .but it can't sum virtual fields. What can I do to do that? -
Receiving error "This backend doesn't support absolute paths." when overwriting file in S3
I'm trying to implement crop and upload feature as per this blog post: https://simpleisbetterthancomplex.com/tutorial/2017/03/02/how-to-crop-images-in-a-django-application.html When attempting to save the cropped photo I get the error: "NotImplementedError: This backend doesn't support absolute paths." forms.py class LetterPictureModelForm(forms.ModelForm): picture = forms.ImageField( label='Picture', widget=ClearableFileInput(attrs={ 'class': 'form-control', 'placeholder': 'Picture' }) ) x = forms.FloatField(widget=forms.HiddenInput()) y = forms.FloatField(widget=forms.HiddenInput()) width = forms.FloatField(widget=forms.HiddenInput()) height = forms.FloatField(widget=forms.HiddenInput()) class Meta: model = LetterPicture fields = ['picture', 'x', 'y', 'width', 'height', ] widgets = { 'letter': forms.HiddenInput(), 'slot': forms.HiddenInput() } def save(self): letter_picture = super(LetterPictureModelForm, self).save() x = self.cleaned_data.get('x') y = self.cleaned_data.get('y') w = self.cleaned_data.get('width') h = self.cleaned_data.get('height') image = Image.open(letter_picture.picture) cropped_image = image.crop((x, y, w + x, h + y)) resized_image = cropped_image.resize((200, 200), Image.ANTIALIAS) resized_image.save(letter_picture.picture.path) return letter_picture settings.py STATICFILES_STORAGE = 'custom_storages.StaticStorage' custom_storages.py from django.conf import settings from storages.backends.s3boto3 import S3Boto3Storage class StaticStorage(S3Boto3Storage): location = settings.STATICFILES_LOCATION class MediaStorage(S3Boto3Storage): location = settings.MEDIAFILES_LOCATION As you can see I'm using S3 to save media files, which has been working as expected so far. Can anyone tell me what's causing this error? I don't understand what it means. -
How can i Post value in radio button and also show available value in database?
HTML CODE- $("#id_emp").empty(); var countemp = 1; $(comjsonemp).each(function (index, item) { var itemnameemp_v = comjsonemp[index].itemid__item_name; var requiredemp_v = comjsonemp[index].required; var statusemp_v = comjsonemp[index].status; var itemidemp_v = comjsonemp[index].itemid; var remarksemp_v = comjsonemp[index].remarks; /* alert(itemnameemp_v); */ var html_emptb; if(comjsonemp.toString().length > 0) { /* alert("in emplo"); */ $("#div_empfolder").show(); if (requiredemp_v.trim()=='T') { html_emptb += "<td ><input type='checkbox' name='empreq' id='id_empreq' class='form-control' checked /><label for='option'></label></td>" ; } else { html_emptb += "<td><input type='checkbox' name='empreq' id='id_empreq' class='form-control' /><label for='option'></label></td>" ; } countemp += 1; if(statusemp_v.trim() =='T') { html_emptb +="<td> <input name='empreceived" +countemp+"' type='radio' id='id_empreceived_y" +countemp+"' class='with-gap radio-col-teal' checked/><label for='id_empreceived_y" +countemp+"'>Received</label><br><input name='empreceived" +countemp+"' type='radio' id='id_empreceived_n" +countemp+"' class='with-gap radio-col-teal' /><label for='id_empreceived_n" +countemp+"'>Not Received</label> </td>"; } else { html_emptb +="<td> <input name='empreceived" +countemp+"' type='radio' id='id_empreceived_y" +countemp+"' class='with-gap radio-col-teal'/><label for='id_empreceived_y" +countemp+"'>Received</label><br><input name='empreceived" +countemp+"' type='radio' id='id_empreceived_n" +countemp+"' class='with-gap radio-col-teal' checked /><label for='id_empreceived_n" +countemp+"'>Not Received</label> </td>"; } html_emptb +=" <td>" + itemnameemp_v + "</td>" ; html_emptb +="<input type='hidden' name='hid_Empitemid_v' id='id_hid_Empitemid_v' value='" + itemidemp_v + "' /></td>"; html_emptb +="<td><textarea rows='2' class='form-control' name='emp_check' id='id_empcheck' value='" + remarksemp_v + "' > </textarea> </td>" ; } $("<tr/>").html(html_emptb).appendTo("#id_emp"); }); VIEWS- comstatus = [(n, v) for n, v in request.POST.items() if n.startswith('hid_cklistcomid')] #comstatus = [name for name in request.POST.keys() if name.startswith('comreceived')] # print(comstatus) for i in comstatus: print(comstatus) comstatus_id … -
Is there a way to get foreign key instance from the QuerySet?
I trying to get the foreign key instance stored in the CandidateSkill model(In[5]) but want to avoid using loop. I have tried values() it only return the actual candidate_id(int) stored in Candidate model and not the instance. models.py class Candidate(models.Model): candidate_id = models.AutoField(primary_key = True) name = models.CharField(max_length = 255, null = False) class CandidateSkill(models.Model): candidate_id = models.ForeignKey('hr.Candidate', on_delete = models.CASCADE) skill = models.CharField(max_length = 255) Django Shell In [1]: from hr.models import CandidateSkill as cds In [2]: a = cds.objects.filter(skill__icontains = 'py') In [3]: a Out[3]: <QuerySet [<CandidateSkill: CandidateSkill object (1)>, <CandidateSkill: CandidateSkill object (2)>, <CandidateSkill: CandidateSkill object (3)>, <CandidateSkill: CandidateSkill object (4)>, <CandidateSkill: CandidateSkill object (10)>]> In [4]: a[0] Out[4]: <CandidateSkill: CandidateSkill object (1)> In [5]: a[0].candidate_id Out[5]: <Candidate: Clayton Cote> So I there a way to get only the foreign key instance and avoid using the loop. -
How to create a Django REST Framework View instance from a ViewSet class?
I'm trying to unit test Django REST Framework view set permissions for two reasons: speed and simplicity. In keeping with these goals I would also like to avoid using any mocking frameworks. Basically I want to do something like this: request = APIRequestFactory().post(…) view = MyViewSet.as_view(actions={"post": "create"}) self.assertTrue(MyPermission().has_permission(request, view)) The problem with this approach is that view is not actually a View but rather a function which does something with a view, and it does not have certain properties which I use in has_permission, such as action. How do I construct the kind of View object which can be passed to has_permission? The permission is already tested at both the integration and acceptance level, but I would like to avoid creating several complex and time-consuming tests to simply check that each of the relevant actions are protected. -
is there any way for using csrf token in rest api without using front end in django?
i am using django framework for making a rest api for registration but when i do that csrf token is not set since front end is not set. So it causes post request not to execute in POSTMAN. i want some way to make my rest api without disabling the csrf in my program. i tried to copy the csrf token into cookie and access those cookie to verify from POSTMAN that but it is not working for POST request also i tried to set header in postman but it also turn up to be GET request only. from django.views.decorators.csrf import ensure_csrf_cookie @ensure_csrf_cookie '''@csrf_exempt''' def addToTable(request): response = HttpResponse('blah') response.set_cookie('csrftoken', get_token(request)) c = get_token(request) response.set_cookie('csrftoken', c) d = request.COOKIES['csrftoken'] if request.method == 'POST': row_data = request.read() data = json.loads(row_data) a = data['MyName'] b = data['MyPassword'] post = Post() post.MyName = a post.MyPassword = b post.save() response.delete_cookie('csrftoken') return JsonResponse({'My Name ':a+ "and " + c + " is added to database and it is a post request."}) else: response.delete_cookie('csrftoken') return JsonResponse({'username ': d + " Data is not added to database and it is a get request." + c}) return 0 i want my rest api work for registration when i …