Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to show detailed view of phonebook?
I am trying to show a detailed view of the contacts stored in a phonebook. The PhoneBook(id, name) is one of my models which is a foreign key to model Contact(id, first_name, last_name, phone_number, phone_book). In my index page, there is a button which opens the phone book. After that, I want it such that the user may click on a phone book and the detailed view(first_name, last_name, phone_number) would be shown to them. In view.py, I have a function which captures all the phonebook, passes it through context(dict). In my template, I have used a for loop to go through all the phonebooks and print them. I am unable to direct the page to detailed view. How do I get the phonebook the user clicked on? And how to direct the page from ./view to ./detail # view.py def view_phone_book(request): all_phone_books = PhoneBook.objects.all() context = { 'all_phone_books': all_phone_books } return render(request, "CallCenter/view_phone_book.html", context) def detailed_view_phone_book(request): all_contacts = Contact.objects.all().filter(phone_book=phone_book_user_clicked_on) context = { 'all_contacts': all_contacts } return render(request, "CallCenter/detailed_view_phone_book.html", context) # urls.py urlpatterns = [ path('', index, name="index"), path('create/', create_phone_book, name="create"), path('add/', add_to_phone_book, name="add"), path('view/', view_phone_book, name="view"), path('detail/', detailed_view_phone_book, name="detailed_view") ] html5 <!--view_phone_book.html--> <table> <tr> <th>Phone Book</th> </tr> {% for phone_book … -
Image not displaying in django react framework
I am integrating an django e-commerce into rest react framework. On the products page I am able to view the product title, description, add to cart button, and slug but the image will not display. There are no errors in terminal or console.log. When i go to console.log I can see the image url, further when i go to my the MEDIA folder I can see the product image has been uploaded yet it is not displaying. I've included the files where i believe the issue is happening below. This line is suppose to display the image <Item.Image src={item.image} /> ProductList.js: import React from 'react' import axios from 'axios' import { Button, Container, Dimmer, Icon, Image, Item, Label, Loader, Message, Segment } from 'semantic-ui-react' import {productListURL} from "../constants"; class ProductList extends React.Component { state = { loading: false, error: null, data: [] } componentDidMount() { this.setState({loading: true}); axios .get(productListURL) .then(res => { console.log(res.data); this.setState({data: res.data, loading: false}); }) .catch(err =>{ this.setState({error: err, loading: false}); }); } render() { const {data, error, loading} = this.state; return ( <Container> {error && ( <Message error header='There was some errors with your submission' content={JSON.stringify(error)} /> )} {loading && ( <Segment> <Dimmer active inverted> <Loader … -
Printing to PDF Django & ReportLab
I currently have this view in Django, which renders a bunch of records on my html page perfectly def patient_page(request, id): pat = models.patient.objects.get(pk=id) # Goes to patient models returns pk according to page rec = models.record.objects.all().filter(patient_assign__pk=id).order_by('-date') return render(request=request, template_name = 'main/patient_page.html', context = {"pats":pat, "rec":rec } ) I also have this code which prints perfectly, I could easily insert a variable. def write_pdf_view(textobject): #Need to play with filename. response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'inline; filename="txt_obj.pdf"' buffer = BytesIO() my_canvas = canvas.Canvas(buffer) # Create textobject(s) textobject = my_canvas.beginText(30 * mm, 65 * mm) textobject.setFont('Times-Roman', 8) textobject.textLine(text="+ Hello This text is written 30mm in and 65mm up from the mark") my_canvas.drawText(textobject) title = "this is my title" my_canvas.setTitle(title) my_canvas.showPage() my_canvas.save() pdf = buffer.getvalue() buffer.close() response.write(pdf) return response My Question, does anyone have an idea of how I might render to pdf AND print to PDF, i.e. next to the record on the html I have a print button which currently runs my print to pdf script. -
How to make virtualenv Django server work? // 'missing attribute' according to command prompt
after wasting saturdays eve googling for a solution to finally make a Django server work, i need your assistance.. I first of all want to set up my project in that way that http://127.0.0.1:8000/ redirects me to the index.html site. But somehow I am not able to run the Django server within my virtualenv (access denied). I handled error over error in the past few hours (inserted a Secret key, inserted silenced_system_checks since E408/09/10 occured as errors before the current error) and here I stuck now. I am not capable to understand the prompt error at all. I assume that Django wants to start the server but can't find a file/html to return? Console output: Console output + project structure Settings.py import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = "censored" ALLOWED_HOSTS = [''] SILENCED_SYSTEM_CHECKS = [ 'admin.E408', 'admin.E409', 'admin.E410', ] DEBUG = 'TRUE' ROOT_URLCONF = 'dasocc_site.urls' INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'dasocc_app', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, '/dasocc_site/dasocc_app/templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] MIDDLEWARE_CLASSES = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] STATIC_URL = '/static/' urls.py // dassocc_app dir from django.urls … -
How to make a website based on python program?
I made a python program that changes outputs every week (this week it might output 1, next week 2, etc). I wanted to make a website that had the result of the python program. I had a few ideas on how to make it, but didn't know which way was the best and could work. I don't need to make a big website, just something that could run with local files. Here are my ideas Write the output of the program onto a text file, and use Javascript to read the file, and display it on a website. Make some skeleton HTML code, and write the output to the .html file using python. Use django (I've never used it before, so I don't know if it will work) I don't need the program to be run on the website, since the program doesn't need user input. All I need is to get the output from python onto a website (.html). There would be 50 lines in the text file if I used that method. I tried the first method, but reading from the file didn't work (it couldn't access the text file, and said that XMLHttpRequest was deprecated). I looked … -
Django: ModelForm ChoiceField choices is not submitting the selected value to the object
I'm having issues with my ModeForm ChoiceField and posting the values accordingly. It's a bit tricky. I wish to post the value of the choice selected into my Comment table from the same form that updates my Evaluation form. I believe that right now it is trying to post the selected value into my evaluation table, which is not possible because it only has the FK to my Comment table. How would I go about doing this? Evaluation Model class Evaluering(models.Model): id = models.AutoField(primary_key=True) ma = models.ForeignKey('Medarbejder', on_delete=models.CASCADE, null=True) fagnavn = models.ForeignKey('Fag', on_delete=models.CASCADE, null=True) delingnavn = models.ForeignKey('Deling', on_delete=models.CASCADE, null=True) aktivitetnavn = models.ForeignKey('Aktivitet', on_delete=models.CASCADE, null=True) vuderingsnavn = models.ForeignKey('Vudering', on_delete=models.CASCADE, null=True) eval_kommentar = models.ForeignKey('Kommentar', on_delete=models.CASCADE, null=True) eval_kommentar is the FK to my Comment table, kommentar = comment Kommentar/Comment Model KOMMENTAR_TITLE_CHOICES = ( ('Generel kommentar', 'Generel kommentar'), ('Ledelse i forhold til opgave', 'Ledelse i forhold til opgave'), ('GRP STD / KÆKS i forhold til opgave', 'GRP STD / KÆKS i forhold til opgave'), ('Instruktør stil i forhold til opgave', 'Instruktør stil i forhold til opgave'), ('Læringsaktivitet i forhold til læringsmål', 'Læringsaktivitet i forhold til læringsmål'), ) kommentar_title = models.CharField(max_length=50, choices=KOMMENTAR_TITLE_CHOICES, null=True) kommentar_indhold = models.TextField(null=True, blank=True) Evaluation form To elaborate on the form, the … -
Cannot use sessions when working with multiple databases
It seems impossible to use sessions in my configuration of multiple databases. For example, I always need to type username and password when I enter the admin site. How do I make sessions work? The routing middleware fully corresponds to this. Here is the settings.py: DATABASES = { 'default': {}, 'ru': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'db_ru.sqlite3', }, 'en': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'db_en.sqlite3', } } DATABASE_ROUTERS = ['me.middleware.database_routing.DatabaseRouter'] MIDDLEWARE = [ 'me.middleware.database_routing.RouterMiddleware', 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] -
Django Testing IntegrityError: duplicate key value violates unique constraint DETAIL: Key (project_id)=(1023044) already exists
I have not been able to resolve this IntegrityError issue in my Django's unittest. Here are my models: class UserProfile(models.Model): ''' UserProfile to separate authentication and profile ''' user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete = models.CASCADE, null = True, blank = True) # Note: first name and last name is in the custom User model first_name = models.CharField(max_length = 20, blank = True, null = True) last_name = models.CharField(max_length = 30, blank = True, null = True) address = models.CharField(max_length = 100, null=True, blank = True) address_city = models.CharField(max_length = 30, null = True, blank = True) metropolitan = models.CharField(max_length = 30, null = True, blank = False) class Municipality(models.Model): name = models.CharField(max_length = 50) abb = models.CharField(max_length = 5) date_created = models.DateTimeField(auto_now_add = True) date_modified = models.DateTimeField(auto_now = True) userprofile = models.ForeignKey('user_profile.UserProfile', blank = False, null = False, related_name = 'userprofile_municipalities', on_delete = models.CASCADE) class Project(models.Model): name = models.CharField(max_length = 50) logo = models.ImageField(null=True, blank = True, width_field = 'logo_width', height_field = 'logo_height') logo_height = models.IntegerField(default = 40) logo_width = models.IntegerField(default = 40) date_created = models.DateTimeField(auto_now_add = True ) date_modified = models.DateTimeField(auto_now = True ) # RELATIONSHIPS: user_profiles = models.ManyToManyField('user_profile.UserProfile', through = 'ProjectAssociation', through_fields = ('project', 'user_profile' ), blank = True, … -
Access command line parameter in Django admin
How can I access the parameters from command line in init method. Eg. "python manage.py get_poll 56" and I want 56 accessible in init method. class Command(BaseCommand): help = 'poll for voting' def __init__(self, *args, **kwargs): super().__init__() poll_count(??) def add_arguments(self, parser): parser.add_argument('poll_count', type=int) def handle(self, *args, **options): Poll_count = options["poll_count"] -
django url follow folder system
Is it possible to make URL in Django to follow folder path like in GitHub, Dropbox https://github.com/<username>/<path>/<path>/<file> Currently, I am doing it like this re_path(r'^.*', myview) then using the split('/') function in view Is there is a batter way to do that? Thanks -
instance.save() is not saving the model in ListSerializer Django Rest Framework
In Django Rest Framework ListSerializer when I want to save the validated data to the database by calling instance.save() I'm getting an error saying queryset object has no attribute save. ListSerializer class: class NoAccessDetailsListSerializer(serializers.ListSerializer): # This will be called when there is list of objects def update(self, instance, validated_data): ret = [] for index, data in enumerate(validated_data): if(instance[index].row_chosen): data = {} data["id"] = instance[index].id data["row_chosen"] = instance[index].row_chosen data["user_working"] = instance[ index].user_working # do not update the info to db # just append the data to ret ret.append(data) else: instance.id = instance[index].id instance.row_chosen = validated_data[index].get( 'row_chosen') instance.user_working = validated_data[index].get( 'user_working') print('Instance data ', instance.row_chosen, instance.user_working) ret.append(instance) instance.save() return ret Serializer Class class NoAccessDetailsSerializer(serializers.ModelSerializer): id = serializers.IntegerField(read_only=False) class Meta: model = NoAccessDetails list_serializer_class = NoAccessDetailsListSerializer fields = ("id", "row_chosen", "user_working") def update(self, instance, validated_data): instance.id = instance.id instance.row_chosen = validated_data.get( 'row_chosen') instance.user_working = validated_data.get( 'user_working ') instance.save() return instance Basically in ListSerializer I'm checking if the row is chosen already in the DB. If True then I just append the instance data to a dictionary else I want to update the data to the DB and append the updated data to a list and return it. Here in the ListSerializer I'm passing … -
Django IndexError: pop from empty list within DeleteView
I am trying to delete an Object from the database of my Django app. The idea is to get the primary from the html file and post it in a form. I am not understanding how I should pass the primary key to post my delete request in the correct way. I went to everything I found about class based views DeleteView both on stackoverflow, django doc and other sources without figuring out how this works. E.g.: Django delete FileField How to delete a record in Django models? Python Django delete current object How to delete a record in Django models? https://docs.djangoproject.com/en/2.2/topics/db/queries/ https://docs.djangoproject.com/en/2.2/ref/class-based-views/generic-editing/#django.views.generic.edit.DeleteView Below the main snippets of the code, if you are missing something needed just let me know. views.py class SelectFileDelView(TemplateView): """ This view is used to select a file from the list of files in the server. After the selection, it will send the file to the server. The server will then delete the file. """ template_name = 'select_file_deletion.html' parser_classes = FormParser queryset = FileModel.objects.all() def get_context_data(self, **kwargs): """ This function is used to render the list of files in the MEDIA_ROOT in the html template and to get the pk (primary key) of each file. """ … -
How to access object count in template using model manager?
I have a model which creates Memo objects. I would like to use a custom Model Manager's posted method to return the total number of Memo objects - then use this number within a template. I am trying to keep as much of my code as possible within my Models and Model Managers and less within my Views as I read that this was a best practice in 'Two Scoops of Django'. In the shell I can get the number of memos as such: >>> from memos.models import Memo >>> Memo.objects.all() <QuerySet [<Memo: Test Memo 2>, <Memo: Test Memo 1>]> >>> Memo.objects.all().count() 2 This is what my Model and Model Manager look like: class MemoManager(models.Manager): use_for_related_fields = True def posted(self): return self.count() class Memo(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_time = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) objects = MemoManager() def __str__(self): return self.title def get_absolute_url(self): return reverse('memos-detail', kwargs={'pk': self.pk}) I know this is clearly the wrong way to do it but I have confused myself here. So how do I use my Model Manager to get the count of objects and use it in a template like: {{ objects.all.count }}? P.S. I see other posts that show how to … -
Finding average score from all user's maximum score in django orm
I'm trying to calculate the average score from all finished exam. Users can send an exam as much as they want. So, the data of the finished exam can be like... (User, Finished exam's score) (1, 8), (1, 9), (1, 10), (2, 2), (2, 3), (3, 8) I want average score of all highest score of each user. A expected average score of above data should be 7. "(10+3+8) / 3" My django model class Exam(models.Model): title = models.TextField("Title") description = models.TextField("Description") class Question(models.Model): exam_id = models.ForeignKey("Exam", on_delete=models.CASCADE) title = models.CharField(max_length=500, verbose_name="Question") score = models.FloatField(default=1) class Answer(models.Model): question_id = models.ForeignKey("Question", on_delete=models.CASCADE) title = models.CharField(max_length=500, verbose_name="Answer") class FinishedExam(models.Model): exam = models.ForeignKey("Exam", on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) score = models.FloatField(default=0) -
Need to extract data matching child model and also the parent data linked to it
I am new to world of django and python . I have 2 models: Testing (Parent) & Heat_Status (Child): Models: class Testing(models.Model): Testing_Date = models.DateField(auto_now=False) IE_Testing = models.ForeignKey(User,on_delete=models.CASCADE) def __str__(self): return '%s %s' %(self.Testing_Date, self.Testing_Shift) class Heat_Status(models.Model): Heat_Number=models.CharField(max_length=6) Testing_Detail=models.ForeignKey(Testing,null=True,on_delete=models.CASCADE) def __str__(self): return '%s %s' %(self.Heat_Number, self.Testing_Detail.Testing_Result) Now I want to search a Heat_Number saved in database along with the details linked to its Parent in Testing model. I got a way to search the data but unable to access the foreign key. I am posting my code here. please help me with this and please try to elaborate yourself as much you can. Thanks in advance !!. Views: def status (request): if request.method=="POST": srch=request.POST['srh'] if srch: match= Heat_Status.objects.filter(Q(Heat_Number__iexact=srch)) if match: return render (request,'status.html',{'sr':match}) else: messages.error(request,'NO Heat') else: return reverse('status') return render(request,'status.html') Template <form method="POST" action="/crinsp/status"> {%csrf_token%} input type="text" name="srh" classs="form-control"> <button class="submit" class="btn btn-warning">Search</button> </form> {%if sr %} {%for k in sr%} <table> <tr> <td>Heat Number</td> <td>{{k.Heat_Number}}</td> </tr> <tr> <td>Rolled in</td> <td> {{**k.Heat_Status.Testing.Rolling_Mill**}} </td> # I need Help here </tr> </table> {%endfor%} {%endif%} Please help. it's kind of urgent. -
Request object sent to django form ok when sent via GET but empty when sent via POST
I'm trying to send the request user to a Django form, the thing is, when I sent the object trough GET metho, the Django form receives it fine, but when I do it trough POST method, the request object it's always empty, here's the code : ***************Views.py class CreateRec(BaseView): template_name = 'test/rec.html' def get(self, request, **kwargs): finding_form = RecForm(req_ses = request) return render(request, self.template_name,{ 'rec_form': rec_form, 'f_new': True, }) def post(self, request, **kwargs): user_rec = User.objects.get(username = request) profile = profile_models.RecProfile.objects.get(cnxuser = user_rec) form = RecForm(request.POST, request.FILES, req_ses = request) return render(request, self.template_name,{ 'rec_form': rec_form, 'f_new': True, }) ***********The fragment of the Form.py file: class RecForm(forms.ModelForm): def __init__(self, req_ses = None, *args, **kwargs): super(RecForm, self).__init__(*args, **kwargs) self.req_ses = kwargs.pop('req_ses', None) user_rec = User.objects.get(username = req_ses.user) profile = profile_models.RecProfile.objects.get(cnxuser = user_rec) Via GET, req_ses has the object , via POST It's says req_ses it's None.....any idea why ??, I tried to send the user_rec object too but got the same result.... -
Which web framework is best for me?
I want to learn one web framework from these: Asp.net Django Laravel Spring here,given some skill of mine: 1.core php (already done 2 dynamic web project) 2.jsp/servlet (already done 1 dynamic web project) I am confusing to decide which framework is best for me...I determined that one of them i should learn at lest one framework. Please give me suggestion. advance thanks !!!! -
django-rest-social token auth, bad request 400
I am creating my api, and I want to add login with facebook feature. I have done everything as said in docs untill 5.2 token auth: when I set my browser url to /api/login/social/token_user/, paste this: { "provider": "facebook", "code": "my own facebook App ID" } into content, browser still shows the same, but django terminal shows: Bad Request: api/login/social/token/ [28/Sep/2019 17:31:49] "POST /login/social/token/ HTTP/1.1" 400 11578 -
Pyhon background Timer for a user task - Django App
I am trying to build an efficient and resilient way for a timer on specific tasks the user begin/continues. This is for a Django/Python Web Application. Here is the scenario, Student clicks Begin Test Timer begins a countdown from N seconds. Student spends X seconds in exam. Student leaves test. Timer continues running... Student comes back after Y seconds and clicks Continue Test Timer continues conudown from N - (X+Y) seconds Student leaves test after Z seconds. Timer continues running... Timer countdown expires Task gets called to score the test. Other possible timer status Teacher can pause the test timer for the student. Teacher can reset the test timer for the student. Questions Does using the Python Thread.Timer object make sense here? Can we use Celery/Celery-beat here? In Both cases above how would I implement the pause and reset above? Is there another approach or design that you can suggest? -
Django Template DIRS TemplateDoesNotExist: Why are some templates being skipped (Skipped)?
I'm trying out the sample project for django-scheduler. When I try to load 127.0.0.1 it throws TemplateDoesNotExist for base.html. Debug = True says: Django tried loading these templates, in this order: Using engine django: django.template.loaders.filesystem.Loader: D:\Code\django-calendar-sample\django-scheduler-sample\project_sample\templates\base.html (Skipped) django.template.loaders.filesystem.Loader: D:\Code\django-calendar-sample\django-scheduler-sample\project_sample\templates\base.html (Skipped) django.template.loaders.app_directories.Loader: C:\ProgramData\Anaconda3\lib\site-packages\django\contrib\auth\templates\base.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\ProgramData\Anaconda3\lib\site-packages\django\contrib\admin\templates\base.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\ProgramData\Anaconda3\lib\site-packages\debug_toolbar\templates\base.html (Source does not exist) django.template.loaders.app_directories.Loader: D:\Code\django-calendar-sample\django-scheduler-sample\project_sample\templates\base.html (Skipped) Note the very end of the first two lines (where base.html actually exists) it shows (Skipped). Why were they skipped? -
RecursionError in views.py django
This is throwing me a recursion error. It first suggested that I put in the argument 'request' in the signup() but then I received a new error. Here is my code: from django.shortcuts import render # Create your views here. from django.http import HttpResponse from .forms import signup from django.utils.html import format_html from django.contrib import messages from .models import signup def index(request): return render(request, 'myapp/index.html') def signup(request): if request.method == 'POST': register_form = signup(request.POST) if register_form.is_valid(): post = register_form.save() message = format_html("Hi {0}, Thank you for signing up with us! See your profile <a href=''>{1}</a>".format(register_form.cleaned_data['name'], "here")) return render(request, 'myapp/register.html', {'signup':register_form, 'message': message}) else: message = register_form.errors form = signup(request) return render(request, 'myapp/register.html', {'signup':form, 'message': message}) else: form = signup(request) return render(request, 'myapp/register.html', {'signup':form}) throws: if request.method == 'POST': RecursionError: maximum recursion depth exceeded in comparison -
Is there a way to get all linked pages in Wagtail / Django?
I'm creating a blog with Wagtail / Django. I'm using a richtext field for the body of the article. On the side of the page, I'd like to have a column of "related articles" which are just the links in the article. Example: Cats (link to cat article) are not the same as dogs (link to dog article). Then, in the side bar, under related articles, I have a link to the cat and dog articles. Right now, I'm using a page chooser panel and adding related articles as necessary. But I'm looking to do something like: richtext.getLinks() for link in links: show title Is that possible with Wagtail or straight Django? If not, is there a closer way to achieving this than adding pages with a page chooser? -
I have to create multiple types of users so that when they log in they see different pages and have different functions
I have to create house rental web application multiple types of users (Owner , Tenants and Admin) so that when they log in they see different pages and have different functions. i can't find a good tutorial or video. -
filter data by date range with tastypie
I'm creating an API using tastypie. I have this model containing date field: date = models.DateField() And I want to get the input from user of two dates: date_from and date_to. How can I do this? And how can I filter my data ? I know this may sound trivial but I'm new to tastypie. Thank you for your help. -
zone-evergreen.js:2952 POST http://127.0.0.1:8000/api/users/ 404 (Not Found)
i am new to Angular and Django.I am trying to create website, which uses angular as front-end and Django as backend where angular sending Object (which contains name, email & query) to django uses DjangoRestFramework. (posting data from angular to django) sorry for my BAD ENGLISH !! HERE IS MY ANGULAR FILES contact.component.html: <form #userForm="ngForm" (ngSubmit)="onSubmit()"> <div class="form-row"> <div class="col-sm"> <ul> <li>Contact No:</li> +91 8425007230 <br><br> <li>Email:</li> sanketsbhosale@outlook.com / sanketsbhosale2016@gmail.com </ul> </div> <div class="col-sm s1"> <input type="text" required #name="ngModel" [class.is-invalid]="name.invalid && name.touched" class="form-control" placeholder="Name" name="name" [(ngModel)]=userModel.username> <small class="text text-danger" [class.d-none]="name.valid || name.untouched">Name is Required!</small> <br> <br> <input type="text" required #email="ngModel" [class.is-invalid]="name.invalid && email.touched" class="form-control" placeholder="Email" name="email" [(ngModel)]=userModel.email> <br> <br> <small class="text text-danger" [class.d-none]="email.valid || email.untouched">Email is Required!</small> </div> <div class="col-sm s1"> <textarea class="form-control" required #query="ngModel" [class.is-invalid]="query.invalid && query.touched" placeholder="Tell me your Query" style="height: 118px;" name="query" [(ngModel)]=userModel.last_name></textarea> <small class="text text-danger" [class.d-none]="query.valid || query.untouched">Please Provide Query!</small> </div> </div> <button [disabled]="userForm.form.invalid" class="btn btn-primary" style="margin-left : 330px;">Send Message</button> </form> contact.component.ts: import { Component, OnInit } from '@angular/core'; import { PostDataService } from '../post-data.service'; @Component({ selector: 'app-contact', templateUrl: './contact.component.html', styleUrls: ['./contact.component.css'], providers:[PostDataService] }) export class ContactComponent implements OnInit { userModel; constructor(private _dataPost: PostDataService) { } onSubmit(){ this._dataPost.enroll(this.userModel) .subscribe( response => { alert("Data is Submitted") }, …