Home > other >  I cant figure out how to post angular's input form data in database (mongodb) using Django Rest
I cant figure out how to post angular's input form data in database (mongodb) using Django Rest

Time:05-23

I cant figure out how to post angular's input form data in database (mongodb) using Django Rest API. There are not enough tutorials and documentations on the internet regarding the set of django and angular along with mongodb. or maybe im tunnel visioned now. If anyone has a link which might solve my problem it would be great.

Below is my angular's html file where you can see the form

<form (ngSubmit)="onSubmit()">
            <div >
              <label for="InputAttackTitle">Attack Title</label>
              <input ngModel type="text"  name="AttackTitle" id="InputAttackTitle" placeholder="Enter Attack Title">
            </div>
            <div >
              <label for="InputAttackDescripton">Attack Description</label>
              <textarea ngModel  name="AttackDescription" id="InputAttackDescripton" placeholder="Enter Attack Description" ></textarea>
            </div>
            <button type="submit" >Submit</button>
          </form>
          <br>
          </div>

Here you can see component.ts file

export class IconsComponent implements OnInit {
  form: FormGroup;
  constructor(config: NgbModalConfig, private modalService: NgbModal,private http:HttpClient, public fb:FormBuilder) 
  { 
    config.backdrop = 'static';
    config.keyboard = false;
    this.form = this.fb.group({
      AttackTitle: [''],
      AttackDescription: [null]
    })
  }
  AttackTitle:any;
  AttackDescription:any;
onSubmit(){

  var formData:any = new FormData();
  formData.append("AttackTitle",this.form.get('AttackTitle').value);
  formData.append("AttackDescription",this.form.get('AttackDescription').value);
  this.http.post('http://127.0.0.1:8000/attackinfo', formData).subscribe(
      (response) => {
      return console.log(response);
    },
      (error) => console.log(error)
    )

Below is the django's models class

class AttackInfo(models.Model):
AttackTitle=models.CharField(max_length=70, blank=False)
AttackDescription = models.TextField(default='',blank=False)

And Below is the view file

@csrf_exempt
def AttackInfoAPI(request,id=0):
    if request.method=='GET':   
        attackinfo = AttackInfo.objects.all()
        attackinfo_serializer=AttackInfoSerializer(attackinfo,many=True)
        return JsonResponse(attackinfo_serializer.data,safe=False)
    elif request.method=='POST':
        attackinfo_data=JSONParser().parse(request)
        attackinfo_serializer=AttackInfoSerializer(data=attackinfo_data)
        if attackinfo_serializer.is_valid():
            attackinfo_serializer.save()
            return JsonResponse("Added Successfully",safe=False)
        return JsonResponse("Failed to Add",safe=False)

One more thing, The get request is working fine, Im only facing problems with Post request, probably because im just starting as a beginner (so im sorry XD)

Below is the URL code

urlpatterns=[
   re_path(r'^attackinfo$',views.AttackInfoAPI),
   re_path(r'^attackinfo/([0-9] )$',views.AttackInfoAPI),

CodePudding user response:

As you didn't add logging showing an error, the following is based on assumptions....

In Django you expect the body to be in JSON format, the FormData that is used in the http.post call should also be in JSON format. Probably it can be achieved by changing the post call to:

this.http.post('http://127.0.0.1:8000/attackinfo', JSON.stringify(formData)).subscribe

  • Related