python django rest framework のSerializer問題
お疲れ様です。
python django rest framework を利用していますが、解決できないところがありまして、質問します。
普通にフロント側でデータを取得し、DBで保存する処理をやろうとしていますが、なぜかDBのNull制約にかかりまして、保存ができなくなっています。
エラーの様子
'/api/uploadTwit/'> null value in column "username" violates not-null constraint DETAIL: Failing row contains (37, asdfasdfa, null, null, null). [15/Aug/2019 13:43:17] "POST /api/uploadTwit/ HTTP/1.1" 200 14
フロント側から、バックエンド側に値の遷移はきちんとできていますが、
Serializer処理で、usernameだけが、Nullになってしまいます。
原因を教えていただけませんか。
[15/Aug/2019 13:52:20] "OPTIONS /api/uploadTwit/ HTTP/1.1" 200 0
serializer----1---- {'twit_text': 'asdfasdfaaaa', 'username': 'admin'}
True
serializer---2---- {'twit_text': 'asdfasdfaaaa'}
フロント
import React,{useState} from 'react';
import axios from 'axios';
import {connect} from 'react-redux';
import 'bulma/css/bulma.css';
import '../../../css/css/all.css';
import TwitterFileUpload from './TwitterFileUpload';
import getCookie from '../../../shared/GetCookie';
const TwitterText = (props) => {
const [text,textState] = useState("");
const uploadTwit = (e) => {
e.preventDefault();
const cookieInfo = getCookie();
upload(cookieInfo.account.token);
}
const upload = async (token) => {
const URL = "http://127.0.0.1:8000/api/uploadTwit/";
const config = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Token '+ token
},
}
console.log("##",props.id)
let params = new URLSearchParams();
params.append('twit_text', text);
params.append('username', props.id);
console.log("#params",params)
console.log("url",URL)
console.log("config",config);
await axios.post(URL, params, config).then(
json => {
console.log(json);
}
).catch(err => console.log(err));
}
const getFile = (files) =>{
console.log(files)
}
return (
<div className="column">
<article className="media">
<figure className="media-left">
<p className="image is-64x64">
<img src="https://bulma.io/images/placeholders/128x128.png" />
</p>
</figure>
<div className="media-content">
<div className="field">
<p className="control">
<textarea
className="textarea is-small has-fixed-size"
rows="3"
placeholder="Add a comment..."
value={text}
onChange = {e => textState(e.target.value)} />
</p>
</div>
<nav className="level">
<div className="level-left">
<TwitterFileUpload
getFile={getFile}/>
</div>
<div className="level-right">
<div className="level-item" onClick={uploadTwit}>
<label className="checkbox">
<a className="button is-info">Submit</a>
</label>
</div>
</div>
</nav>
</div>
<div className="media-right">
<a className="button">
<span className="icon">
<i className="fas fa-smile"></i>
</span>
</a>
</div>
</article>
</div>
)
}
const mapStateToProps = (reduxState) =>{
return{
id : idSelector(reduxState)
}
}
const idSelector = (reduxState) => {
return reduxState.account.account.id;
}
export default connect(mapStateToProps, null) (TwitterText);
バックエンド
model
class AuthUser(models.Model):
password = models.CharField(max_length=128)
last_login = models.DateTimeField(blank=True, null=True)
is_superuser = models.BooleanField()
username = models.CharField(unique=True, max_length=150)
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=150)
email = models.CharField(max_length=254)
is_staff = models.BooleanField()
is_active = models.BooleanField()
date_joined = models.DateTimeField()
class Meta:
managed = False
db_table = 'auth_user'
class Twit(models.Model):
twit_id = models.AutoField(primary_key=True)
twit_text = models.CharField(max_length=300, blank=True, null=True)
twit_content = models.CharField(max_length=700, blank=True, null=True)
username = models.ForeignKey('AuthUser', db_column='username', on_delete=models.SET_NULL, null=True)
up_time = models.DateTimeField(blank=True, null=True)
class Meta:
managed = False
db_table = 'twit'
serializer
class TwitSerializer(serializers.HyperlinkedModelSerializer):
#username = AuthUser.objects.get(usernmae=request.username)
#username = serializers.CharField()
#username = serializers.ReadOnlyField()
#username = serializers.PrimaryKeyRelatedField(read_only=True)
#username = serializers.PrimaryKeyRelatedField(many=True, read_only=True)
#username = serializers.PrimaryKeyRelatedField(queryset=AuthUser.objects.all(), many=True,required=False)
#username = serializers.StringRelatedField( many=False)
#username = serializers.SlugRelatedField(slug_field=AuthUser.username, required=False, read_only=True)
#username = serializers.OneToOneField(AuthUser, verbose_name="user details")
#username = serializers.SlugRelatedField(many=False, read_only=True, slug_field='Twit.username')
# username = serializers.RelatedField(source='username', read_only=True)
#username = serializers.PrimaryKeyRelatedField(many=True, read_only=True)
'''
twit_id = serializers.IntegerField(read_only=True)
twit_text = serializers.CharField(required=False, allow_blank=True, max_length=100)
twit_content = serializers.CharField(required=False, allow_blank=True, max_length=100)
username = serializers.RelatedField()
up_time = serializers.RelatedField()
'''
twit_id = serializers.IntegerField(read_only=True)
twit_text = serializers.CharField(required=False, allow_blank=True, max_length=100)
twit_content = serializers.CharField(required=False, allow_blank=True, max_length=100)
username = serializers.RelatedField(read_only=True)
up_time = serializers.RelatedField(read_only=True)
class Meta:
model = Twit
fields = (
'twit_id',
'twit_text',
'twit_content',
'username',
'up_time',
)
※serializerで各種Serializerを利用してみましたが、解決できなかったです。
view
class UploadTwit(APIView):
serializers_class = TwitSerializer
permission_class = (IsAuthenticated,)
def post(self, request, format=None):
serializer = TwitSerializer(data=request.data.dict())
#serializer = TwitSerializer(data=request.data)
#print("serializer----1----",serializer.initial_data)
#print(serializer.is_valid())
#print("serializer---2----",serializer.data)
if serializer.is_valid():
serializer.save()
print("serializer-----------------",serializer.data)
print(serializer.errors)
return Response(serializer.data, status=status.HTTP_201_CREATED)
print("serializer", serializer)
print(serializer.errors)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
開発環境
Python 3.7
Django 2.1.1
React 16.8.6
Postgres:11.2