Я начинаю изучать Angular2. На изображении выше я упомянул 2 формы.
1) Основная и дополнительная форма
Для этих двух я создал отдельную models.py
Мой вопрос таков:
Я использовал концепцию Один ко многим. я сопоставил MainModel_id с Sub_model (ниже я упомянул свои Model.py и Serializers.py). В этой полной форме будут добавлены первые налоговые названия и процент . Таким образом, добавляя, что он выдает 500 Ошибка ("Column 'product_id' cannot be null")
, как это. так что я не знаю, как переходит приходит эта ошибка.
Ниже я упомянул Component.ts, Service.ts, serializers.py и models.py
component.ts
import { Component } from '@angular/core';
import { ValidateForm } from './validate';
import { Router } from '@angular/router';
import { ActivatedRoute } from '@angular/router';
import { ProductsService } from "../products.service";
import { Contact } from "./new-products2.component";
import { HttpClient } from '@angular/common/http';
import { NgForm } from '@angular/forms';
import { ToasterConfig, ToasterService } from 'angular2-toaster';
import { NotificationService } from '../../services/notification.service';
import 'style-loader!angular2-toaster/toaster.css';
@Component({
selector: 'ngx-popovers',
styleUrls: ['./new-products.component.scss'],
templateUrl: './new-products.component.html',
})
export class NewProductComponent {
users: any[];
data1: any[];
data2: any[];
data3: any[];
toastConfig: ToasterConfig;
productservice: ProductsService
contacts: Array<Contact>;
register = true;
selectedFile = null;
onfileSelected(event) {
console.log(event);
this.selectedFile = <File>event.target.files[0];
}
constructor(private route: ActivatedRoute,
private router: Router,
private productService: ProductsService,
private http: HttpClient,
private notificationService: NotificationService,
private toasterService: ToasterService
) {
this.onChange;
//dropdown for Category
this.productService.get_category()
.subscribe(response => {
this.data1 = response;
}, error => {
// console.log(error);
})
//dropdown for Quanity
this.productService.get_unit()
.subscribe(response => {
this.data2 = response;
}, error => {
// console.log(error);
})
//dropdown for Tax
this.productService.get_tax()
.subscribe(response => {
this.data3 = response;
}, error => {
// console.log(error);
})
this.contacts = [];
}
createNewProduct(productForm: NgForm) {
this.productService.save_user(productForm.value)
.subscribe(response => {
const toast_parameter = this.notificationService.getToast('success', 'New Product', 'Inserted Successfully');
this.toastConfig = toast_parameter.config;
this.toasterService.popAsync(toast_parameter.toast);
},
error => {
const toast_parameter = this.notificationService.getToast('error', 'New Product', 'Error Occurred!!');
this.toastConfig = toast_parameter.config;
this.toasterService.popAsync(toast_parameter.toast);
});
}
savetax(tax, percentage) {
let taxUrl = String("http://127.0.0.1:8000/tax/" + tax.value + "/");
let obj = {
'name': taxUrl,
'percentage': percentage.value
}
var json = JSON.stringify(obj)
console.log(json)
this.productService.save_tax(json).subscribe(response => console.log('Inserted Successfully'),
error => console.log(error));
}
model: ValidateForm[] = [];
}
Service.ts
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import 'rxjs/add/observable/throw';
@Injectable()
export class ProductsService {
constructor(private http: HttpClient) { }
//Posting details to Product table
save_user(product_data: any): Observable<any[]> {
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
}),
};
return this.http.post('http://localhost:8000/product/', product_data, httpOptions)
.map(response => response)
.catch(error => Observable.throw(error.statusText));
};
//Adding Tax and percentage for Product table
save_tax(product_tax_data: any): Observable<any[]> {
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
}),
};
return this.http.post('http://localhost:8000/taxproduct/', product_tax_data, httpOptions)
.map(response => response)
.catch(error => Observable.throw(error.statusText));
};
}
models.py
class Product(models.Model):
image = models.ImageField(upload_to='myphoto/%Y/%m/%d/', null=True, max_length=255)
pro_name = models.CharField(max_length=25)
description = models.CharField(max_length=150)
category = models.ForeignKey(Category,on_delete=models.CASCADE)
sales = models.CharField(max_length=25)
cost = models.CharField(max_length=25)
taxable = models.BooleanField(default=False, blank=True)
tax_details= models.CharField(max_length=250)
type_units = models.ForeignKey(Units, on_delete=models.CASCADE)
hsn = models.CharField(max_length=10)
class Taxproduct(models.Model):
name = models.CharField(max_length=50)
percentage = models.CharField(max_length=3)
product = models.ForeignKey(Product, on_delete=models.CASCADE)
serializer.py
class TaxproductSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Taxproduct
fields = ('id','name','percentage')
class ProductSerializer(serializers.HyperlinkedModelSerializer):
tax_details = TaxproductSerializer(many=True,read_only=True, source='taxproduct_set')
type_units = serializers.CharField(source='type_units.type')
category = serializers.CharField(source='category.category')
image = serializers.ImageField(required=False, max_length=None,allow_empty_file=True, use_url=True)
class Meta:
model = Product
fields = ('id','image','pro_name','description','category','sales','cost','taxable','tax_details','type_units','hsn')