更新内容时出错

时间:2016-04-04 09:01:38

标签: javascript python ajax django reactjs

为什么我在尝试更新内容时遇到错误?我在componentDidMount函数中获取编辑的值。发布内容时没有问题但是当我尝试使用reactjs和django tastypie api更新内容时,我收到错误

" {" error_message":"指示的格式' application / x-www-form-urlencoded'没有可用的反序列化方法

我的代码

export default class RoomDetail extends Component{
    constructor(props){
        super(props);
        this.state = { rooms:[], isEditing:false };
        this.onEditClick = this.onEditClick.bind(this);
        this.onCancelClick = this.onCancelClick.bind(this);
        this.onSaveClick = this.onSaveClick.bind(this);
    }

    onEditClick(event){
        event.preventDefault();
        this.setState({ isEditing: true });
    }

    onCancelClick(){
        this.setState({ isEditing: false });
    }

    onSaveClick(event){
        event.preventDefault();
        console.log('edited property type is', this.refs.property.value);
        const newUser = [
            {
                listingName: this.refs.editlistingName.value,
                summary: this.refs.editSummary.value,
                ownerName: this.refs.editOwnerName.value,
                email: this.refs.editEmail.value,
                phoneNumber:this.refs.editphoneNumber.value,
                room:this.refs.rooms.value,
                city:this.refs.editCity.value,
                place:this.refs.editPlace.value,
                property:this.refs.property.value,
                price:this.refs.editPrice.value,
             }
        ];
        this.updateRoomToServer(...newUser);
    }

    updateRoomToServer(newUser){
        console.log('newuser from updateRoomToServer', newUser);
        this.componentDidMount(newUser);
    }

    componentDidMount(newUser){
        console.log('component updated with new user are', newUser);
        $.ajax({
            url:'/api/v1/rental/'+this.props.data.slug+'/',
            type:'put',
            dataType:'json',
            data:newUser,
            success: (data) => {
                console.log('data',data);
              },
              error: (xhr, status, err) => {
                console.error(xhr, status, err.toString());
              }
            });
    }

    componentWillMount(){
        console.log('componentDidMount');
        console.log(this.props.data.slug);
        this.loadRoomFromServer();
    }
    loadRoomFromServer(){
        $.ajax({
            url:'/api/v1/rental/'+this.props.data.slug,
            dataType:'json',
            success: (data) => {
                console.log('data',data);
                this.setState({rooms: data});
              },
              error: (xhr, status, err) => {
                console.error(xhr, status, err.toString());
              }
            });
    }

    renderRoomDetailSection(){
       let imageFile;
       let firstImage;
        if(this.state.rooms.gallery){
            firstImage = this.state.rooms.gallery[0].image;
            console.log('firstImage', firstImage);
            imageFile = this.state.rooms.gallery.map((image) => {
            return(
                    <div className="col-md-3">
                        <img src={image.image} key={image.id} className="img-fluid img-rounded" />
                    </div>
                );
            });
        }
        if (this.state.isEditing ){
            return(
                    <div className="container">
                    <div className="row">
                    <div className="col-md-6 col-md-offset-3">
                         <form onSubmit = { this.onSaveClick } >
                              <fieldset className="form-group">
                                <label htmlFor="listingName">listing Name</label>
                                <input type="text" className="form-control" id="listingName" defaultValue = {this.state.rooms.listingName} placeholder="name of your listing" ref="editlistingName" />
                              </fieldset>
                              <fieldset className="form-group">
                                <label htmlFor="summary">summary</label>
                                <input type="text" className="form-control" id="summary" defaultValue = {this.state.rooms.summary} placeholder="enter summary" ref="editSummary" />
                              </fieldset>
                              <fieldset className="form-group">
                                <label htmlFor="ownerName">owner Name</label>
                                <input type="text" className="form-control" id="ownerName" defaultValue = {this.state.rooms.ownerName} placeholder="name of owner" ref="editOwnerName" />
                              </fieldset>
                              <fieldset className="form-group">
                                <label htmlFor="email">Email</label>
                                <input type="text" className="form-control" id="email" defaultValue = {this.state.rooms.email} placeholder="enter email" ref="editEmail" />
                              </fieldset>
                              <fieldset className="form-group">
                                <label htmlFor="contact">phoneNumber</label>
                                <input type="text" className="form-control" id="phoneNumber" defaultValue = {this.state.rooms.phoneNumber} placeholder="enter phoneNumber" ref="editphoneNumber" />
                              </fieldset>
                               <fieldset className="form-group">
                                <label htmlFor="contact">Property Type</label>
                                <select className="form-control" defaultValue={this.state.rooms.property} name="Property Type" ref="property">
                                    <option value="appartment">Appartment</option>
                                    <option value="house">House</option>
                                    <option value="shop">Shop</option>
                                </select>
                              </fieldset>
                               <fieldset className="form-group">
                                <label htmlFor="contact">Room</label>
                                <select className = "form-control" defaultValue={this.state.rooms.room} name="Rooms" ref="rooms">
                                    <option value="1">1 room</option>
                                    <option value="2">2 rooms</option>
                                    <option value="3">3 rooms</option>
                                    <option value="4">4 rooms</option>
                                    <option value="5">5+ rooms</option>
                                </select>
                              </fieldset>

                              <fieldset className="form-group">
                                <label htmlFor="price">Price</label>
                                <input type="text" className="form-control" id="price" defaultValue = {this.state.rooms.price} placeholder="enter price" ref="editPrice" />
                              </fieldset>

                               <fieldset className="form-group">
                                <label htmlFor="city">City</label>
                                <input type="text" className="form-control" id="city" defaultValue = {this.state.rooms.city} placeholder="enter city" ref="editCity" />
                              </fieldset>

                               <fieldset className="form-group">
                                <label htmlFor="place">Price</label>
                                <input type="text" className="form-control" id="place" defaultValue = {this.state.rooms.place} placeholder="enter place" ref="editPlace" />
                              </fieldset>


                        </form>
                    </div>
                </div>
            </div>
                )
        }
                return(
                        <div className="detailListing">
                        <div className="container-fluid">
                            <div className="row">
                                <div className="col-sm-12">
                                    <div className="lanscapeImage">
                                        <img src={firstImage} className="img-fluid" height="400px" />
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div className="container descriptionContainer">
                            <div className="row">
                                    <div className = "aboutListing line">
                                        <div className="col-md-10 listingNameSummary">
                                            <h3>About your listing {this.state.rooms.listingName}</h3>
                                            <p>{this.state.rooms.summary}</p>
                                        </div>

                                    </div>
                                    <div className="rentInformation line">
                                        <div className="col-md-3">
                                            <h3>Rent Information</h3>
                                        </div>
                                        <div className="col-md-9">
                                            <p>Property Type: {this.state.rooms.property}</p>
                                            <p>Number of rooms/spaces: {this.state.rooms.room} room</p>
                                            <p>Price of rooms/spaces: {this.state.rooms.price} Rs/Month </p>

                                            <p>Water Facilities: {this.state.rooms.water} </p>
                                            <p>Amenities: {this.state.rooms.amenities} </p>
                                            <hr />
                                        </div>
                                    </div>

                                    <div className="location line">
                                        <div className="col-md-3">
                                            <h3>Location</h3>
                                        </div>
                                        <div className="col-md-9">
                                            <p>City: {this.state.rooms.city}</p>
                                            <p>Place: {this.state.rooms.place} </p>
                                            <hr />
                                        </div>
                                    </div>

                                    <div className="gallery line">
                                        <div className="col-md-3">
                                            <h3>Gallery</h3>
                                        </div>
                                        <div className="col-md-9">
                                             {imageFile}
                                        </div>
                                    </div>
                            </div>
                        </div>
                </div>
                )
    }

    renderUserAction(){
        if ( this.state.isEditing ){
            return(
                    <div className = "buttons">
                        <button className="btn btn-warning text-xs-left" onClick = { this.onSaveClick } >Save</button>
                        <button className="btn btn-danger text-xs-right" onClick = { this.onCancelClick } >Cancel</button>
                    </div>
                );

        }

        return(
                <div className = "buttons">
                    <button className="btn btn-warning" onClick = { this.onEditClick }>Edit</button>
                </div>
            );
        }

    render() {
        return (
            <div className = "newRoomDetail" >
                 { this.renderRoomDetailSection() }
                 { this.renderUserAction() }
            </div>
        );
    }
    }

api.py

class RentalResource(MultipartResource,ModelResource):
    gallery = fields.ToManyField('rentals.api.api.GalleryResource', 'gallery', related_name='rental',full=True)
    class Meta:
        queryset = Rental.objects.all()
        resource_name = 'rental'
        detail_uri_name = 'slug'
        allowed_methods = ['get', 'post', 'put']
        fields = ['listingName','slug','property','city','place','ownerName','room','water','amenities','price','summary','phoneNumber','email']
        filtering = { "property" : ALL , "city":ALL, "place":('exact', 'startswith',), "room":ALL,"price":ALL,"listingName":ALL,"slug":ALL}
        authorization = DjangoAuthorization()

1 个答案:

答案 0 :(得分:1)

你应该尝试用这种方式改变你的AJAX:

$.ajax({
    url:'/api/v1/rental/'+this.props.data.slug+'/',
    type:'put',
    contentType: "application/json",
    data:JSON.stringify(newUser),
      success: (data) => {
        console.log('data',data);
      },
      error: (xhr, status, err) => {
        console.error(xhr, status, err.toString());
      }
    });

您的后端可能会以这种方式反序列化数据,因为application/x-www-form-urlencoded似乎不起作用。