Я новичок в Angular и Django.Я пытаюсь создать сайт, который использует Angular в качестве внешнего интерфейса и Django в качестве внутреннего, где Angular отправляет объект (который содержит имя, адрес электронной почты и запрос) в Django, используя DjangoRestFramework.(отправка данных из Angular в Django)
ЗДЕСЬ МОИ УГЛОВЫЕ ФАЙЛЫ
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")
},
error => alert("Error in submitting data"),
);
}
ngOnInit() {
this.userModel = {
username : '',
email: '',
last_name: '',
}
}
}
post-data.service.ts :
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class PostDataService {
_url = 'http://127.0.0.1:8000/api/users/';
constructor(private http: HttpClient) { }
enroll(userData): Observable<any> {
return this.http.post(this._url, userData)
}
}
ЗДЕСЬIS МОИ ФАЙЛЫ DJANGO
settings.py
# here only neccesary code i have posted
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 10
}
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'corsheaders',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
]
CORS_ORIGIN_WHITELIST = [
"http://localhost:4200",
]
serializers.py
from django.contrib.auth.models import User
from rest_framework import serializers
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ['id', 'username', 'email', 'last_name']
urls.py (корневой URL-файл)
from django.contrib import admin
from django.urls import include, path
from rest_framework import routers
from sample.api import views
router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet)
urlpatterns = [
path('admin/', admin.site.urls),
path('api', include(router.urls)),
path('api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]
views.py
from django.contrib.auth.models import User
from rest_framework import viewsets
from sample.api.serializers import UserSerializer
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer