如何在Angular 6中检索和提交由Django模板生成的表单 [英] How to retrieve and submit a form in Angular 6 that has been generated by a Django template

查看:55
本文介绍了如何在Angular 6中检索和提交由Django模板生成的表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Angular 6应用,正在尝试显示和提交从Django生成的表单.我检索表单并使用innerHtml显示它.它显示的很好,但是当我单击提交"按钮时,它没有调用我已附加到该函数的函数.如果我复制并粘贴生成的html,则提交"按钮可以正常工作(尽管我认为由于复制和粘贴CSRF令牌而收到403响应).这是我的Angular组件和模板文件以及Django模板的代码:

I have an Angular 6 app and am trying to display and submit a form that is generated from Django. I retrieve the form and display it using innerHtml. It shows up fine but when I click on the Submit button it doesn't call the function that I have attached to it. If I copy and paste the generated html then the submit button works fine (although I get a 403 response I think because of copying and pasting the CSRF token). Here is the code for my Angular component and template files and also the Django template:

login.component.html

login.component.html

<div *ngIf="!loggedIn; else successMessage" [innerHTML]="loginForm"></div>

<ng-template #successMessage>
  Logged in
</ng-template>

login.component.ts

login.component.ts

import { Component, Input, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {

  @Input() loggedIn: boolean;
  id_username: string;
  id_password: string;

  loginForm: SafeHtml;

  constructor(private router: Router, private httpClient: HttpClient, private sanitizer: DomSanitizer) {
  }

  ngOnInit() {
    this.getLoginForm();
  }

  getLoginForm() {
    this.httpClient.get('https://myserver/account/login/', { responseType: 'text' }).subscribe(res => {
      this.loginForm = this.sanitizer.bypassSecurityTrustHtml(res);
      console.log(this.loginForm);
    });
  }

  login() {
    console.log("Logging in user");
    var response = this.httpClient.post('https://myserver.com/account/login/', {
      id_username: this.id_username,
      id_password: this.id_password
    }).subscribe(res => {
      this.loggedIn = true;
    });
  }
}

form.html Django模板

form.html Django template

{% extends "share/base.html" %}
{% block content %}
<div>
{% if form %}
    {% if form.errors %}
        <font color="red">{{ form.errors }}</font>
    {% endif %}
    <form #bdmForm="ngForm">
        {% csrf_token %}
        {% for field in form %}
            <div class="form-group">
                {{ field.label_tag }}
                {{ field }}
            </div>
        {% endfor %}
        <button type="button" class="btn btn-default" (click)="login()">Submit</button>
    </form>
{% endif %}
</div>
{% endblock %}

forms.py(包括字段) #--编码:utf-8-- 从未来导入unicode_literals 从Django导入表格中

forms.py (To include the fields) # -- coding: utf-8 -- from future import unicode_literals from django import forms

class Login(forms.Form):
    username = forms.CharField(required=True, widget=forms.TextInput(attrs={'[(ngModel)]': 'id_username'}))
    password = forms.CharField(required=True, widget=forms.PasswordInput(attrs={'[(ngModel)]': 'id_password'}))

我也尝试过在表单标签中使用(ngSubmit)="login()"包含login()函数,但这也不起作用.

I have also tried including the login() function using (ngSubmit)="login()" in the form tag but that isn't working either.

我对Angular比较陌生,有人在Django方面工作.我不确定我是否只需要进行少量更改,或者我们的整体方法是否错误,但是任何输入都会很棒!

I am relatively new to Angular and someone else is working on the Django side. I'm not sure if I just need to make a small change or if our whole approach is wrong but any input would be great!

推荐答案

我将尝试将按钮更改为<input type="submit" .... >,然后在与[innerHtml]绑定的元素上使用(submit)进行连接,所以基本上我d利用事件冒泡.

I'd try to change the button to <input type="submit" .... > and then hook up with (submit) on the element you bound with [innerHtml] So basically I'd utilize event bubbling.

但是,老实说,这是一种不好的做法,您不应该在Angular Component中从服务器接收html.简而言之,您应该在Angular中设计表单并发送POST HTTP请求,并在Angular组件中对响应做出相应的反应.

But to be honest it's bad practice and you shouldn't receive html from your server in your Angular Component. Shortly speaking, you should design your form in Angular and send a POST HTTP Request and react to the response accordingly in your Angular Component.

如果不可能的话,我认为可以通过事件冒泡或在运行时通过document.getElementBySomething对其进行引用并为事件分配回调来连接innerHtml中的内容.

If it's not possible I think the way to hook up to stuff in your innerHtml is via event bubbling or in runtime via referencing it through document.getElementBySomething and assigning callbacks to events.

两种方式都让人感觉很古怪

Both of the ways feel kind of hacky

这篇关于如何在Angular 6中检索和提交由Django模板生成的表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆