I am trying to make it so that I can POST and update database rows from my angularJS app but I seem to be having trouble adding new entries to my database.
Things are posted without error but when I go and check the database then all added data is "None".
I have written this method to save Notes with a corresponding Lecture ID, where Lecture is an attribute of Notes.
saveNotes: function(notes, lecture_id, callback) {
$http({
method: 'POST',
url: apiRoute + 'notes/',
data: {
"notes": notes,
"lecture_id": lecture_id
}
}).success(callback);
}
I have written these views:
class LectureViewSet(viewsets.ModelViewSet):
serializer_class = LectureSerializer
def get_queryset(self):
course_id = self.request.query_params.get('course',False)
if course_id:
lectures = Lecture.objects.filter(course=course_id)
else:
lectures = Lecture.objects.all()
return lectures
class NotesViewSet(viewsets.ModelViewSet):
queryset = Notes.objects.all()
serializer_class = NotesSerializer
And these serializers:
class LectureSerializer(serializers.ModelSerializer):
class Meta:
model = Lecture
fields = ('id', 'lecture_no', 'title', 'youtubeLink', 'course', 'keywords')
class NotesSerializer(serializers.ModelSerializer):
lecture = LectureSerializer(read_only=True, many=True)
class Meta:
model = Notes
fields = ('id', 'notes', 'lecture')
Can anyone spot the error that is causing this addition of "None" values? Also, is there a way to make these fields update instead of post new ones?
Thanks!
Included models:
class Lecture(models.Model):
lecture_no = models.IntegerField(null=True)
title = models.CharField(max_length=128, unique=True, null=True)
youtubeLink = models.CharField(max_length=128, unique=True, null=True)
course = models.ForeignKey(Course, null=True)
keywords = models.TextField(max_length=300, null=True)
#Could add Next Rerun Date & Time
def __str__(self):
return self.title
class Notes(models.Model):
notes = models.TextField(null=True)
lecture = models.ForeignKey(Lecture, null=True)
def __str__(self):
return str(self.notes)
Related
I'm using the Django and React to create YouTube clone.
And when the user is creating second video, it giving the bad request error:
<QueryDict: {'title': ['Edit Test56'], 'description': ['is It working1643'], 'user': ['3'], 'image': [<TemporaryUploadedFile: slackphot.png (image/png)>], 'video': [<TemporaryUploadedFile: video-for-fatube.mp4 (video/mp4)>]}>
Bad Request: /api/admin/create/
When I tried to make post request in postman, it gave me
views.py Views of the api.
class CreateVideo(APIView):
#permissions_classes = [IsAuthenticated]
parser_classes = [MultiPartParser, FormParser]
def post(self, request, format=None):
print(request.data)
serializer = VideoSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_200_OK)
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
serializer.py Video Serailzier.
class VideoSerializer(serializers.ModelSerializer):
user_name = CharField(source="user.user_name", read_only=True)
class Meta:
model = Video
fields = ["id", "title", "image", "video", "description", "date_added", "is_active", "user", "user_name", "likes"]
models.py Model of the Video
class Video(models.Model):
title = models.CharField(max_length=50)
image = models.ImageField(_("Image"), upload_to=upload_to, default="videos/default.jpg")
video = models.FileField(_("Video"), upload_to=upload_to, default="videos/default.mp4")
user = models.OneToOneField(
settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="user_channel"
)
description = models.CharField(max_length=255)
likes = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='video_post', null=True, blank=True)
date_added = models.DateTimeField(default=timezone.now)
is_active = models.BooleanField(default=True)
If you want to look at the whole project, here is github: https://github.com/PHILLyaHI/diplom-work
You are using One2One Field, that's why it's causing an error, use foreign key in User column
class Video(models.Model):
title = models.CharField(max_length=50)
image = models.ImageField(_("Image"), upload_to=upload_to, default="videos/default.jpg")
video = models.FileField(_("Video"), upload_to=upload_to, default="videos/default.mp4")
user = models.ForiegnKey(
settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="user_channel"
)
description = models.CharField(max_length=255)
likes = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='video_post', null=True, blank=True)
date_added = models.DateTimeField(default=timezone.now)
is_active = models.BooleanField(default=True)
models file
class Posting(models.Model):
company = models.CharField(max_length=250)
recruiter = models.CharField(max_length=250)
image = models.ImageField(upload_to='postings/%Y/%m/%d/', null=True)
description = models.TextField()
position_title = models.CharField(max_length=150)
## Based on LinkedIn
# Auto adds creation date
creation_date = models.DateTimeField(auto_now_add=True)
# If 0, unpaid; if more than 0, paid (can be used to diffrentiate in postings frontend)
pay_range = models.CharField(max_length=250)
location = models.CharField(max_length=1000)
# Number of current applicants (can be used to encourage people)
num_applicants = models.IntegerField(default=0)
def __str__(self):
return self.position_title
class Question(models.Model):
qTypes=[('T','text'),('TA','textarea'),('C','choice')]
question=models.CharField(max_length=10000)
type=models.CharField(max_length=10,choices=qTypes)
post=models.ForeignKey(Posting,on_delete=models.CASCADE)
choices=models.TextField(null=True,blank=True)
serializer
class QuestionSerializer(serializers.ModelSerializer):
class Meta:
model = Question
fields = ('id','type','question','post')
class PostingSerializer(serializers.ModelSerializer):
question=QuestionSerializer(many=False)
class Meta:
model = Posting
fields = ('id', 'company', 'recruiter', 'image', 'description', 'creation_date', 'pay_range', 'location', 'num_applicants', 'position_title','question')
i want to retrieve the post with it's questions like this i could retrieve the data of the question with its post but i dont want that
I am working on a post request in which the user chooses from a list of tags and makes combinations of tags. The combination of tags should then be posted. Nothing should get changed in the Tag table.
These are the models:
models.py
class Tag(models.Model):
name = models.CharField(max_length=256)
language = models.CharField(max_length=256)
objects = models.Manager()
def __str__(self):
"""Return a human readable representation of the model instance."""
return self.name or ''
#property
def tags(self):
tags = self.tagging.values('tag')
return tags.values('tag_id', 'tag__name', 'tag__language')
class Combination(models.Model):
user = models.ForeignKey(CustomUser, on_delete=models.SET_NULL, null=True)
gameround = models.ForeignKey(Gameround, on_delete=models.CASCADE, null=True)
resource = models.ForeignKey(Resource, on_delete=models.CASCADE, null=True)
tag_id = models.ManyToManyField(Tag, null=True)
created = models.DateTimeField(editable=False)
score = models.PositiveIntegerField(default=0)
objects = models.Manager()
def __str__(self):
return str(self.tag_id) or ''
This is the serializer for Combination.
serializers.py
class CombinationSerializer(serializers.ModelSerializer):
tag_id = TagWithIdSerializer(many=True, required=False, write_only=False)
resource_id = serializers.PrimaryKeyRelatedField(queryset=Resource.objects.all(),
required=True,
source='resource',
write_only=False)
gameround_id = serializers.PrimaryKeyRelatedField(queryset=Gameround.objects.all(),
required=False,
source='gameround',
write_only=False)
user_id = serializers.PrimaryKeyRelatedField(queryset=CustomUser.objects.all(),
required=False,
source='user',
write_only=False)
class Meta:
model = Combination
depth = 1
fields = ('id', 'user_id', 'gameround_id', 'resource_id', 'tag_id', 'created', 'score')
def create(self, validated_data):
user = None
request = self.context.get("request")
if request and hasattr(request, "user"):
user = request.user
score = 0
tag_data = validated_data.pop('tag_id', None)
combination = Combination(
user=user,
gameround=validated_data.get("gameround"),
resource=validated_data.get("resource"),
created=datetime.now(),
score=score
)
combination.save()
for tag_object in tag_data[0]:
combination.tag_id.add(tag_object)
return combination
def to_representation(self, instance):
rep = super().to_representation(instance)
rep['tag_id'] = TagWithIdSerializer(instance.tag_id.all(), many=True).data
return rep
I have tried posting the following JSON object to the database:
{
"gameround_id": 2015685170,
"resource_id": 327888,
"tag_id": [{"id": 2014077506, "name": "corwn","language": "en"}]
}
I am getting a ValueError: Field 'id' expected a number but got 'name'.
How can I fix this issue?
you need to provide tag id for each tag not all tag data,
Try like this
{
"gameround_id": 2015685170,
"resource_id": 327888,
"tag_id": [2014077506,2014077507]
}
I have a model "Interview" and a model "Notes". Interview is a foreign key of Notes.
class Notes(models.Model):
notes = models.TextField(null=True)
interview = models.ForeignKey(Interview, null=True)
def __str__(self):
return self.interview
I am using http requests to GET and POST to the server.
How can I post notes to the server exactly since interview is a foreign key? Currently my post function looks like this:
saveNotes: function(interview, notes) {
$http({
method: 'POST',
url: apiroute + '/notes',
data: {
"notes": notes,
"interview": {
//attr of interview
}
}
}).success(callback);
}
And this looks to be correct but I am being met with:
POST http://127.0.0.1:8000/app/api/notes 500 (INTERNAL SERVER ERROR)
I used "notes/" as my url and I got:
POST http://127.0.0.1:8000/student/api/notes/ 400 (BAD REQUEST)
Can someone give a guess as to what my issue might be?
Thanks!
EDIT: Here are my serializer files. Interview is replaced by Lecture
class LectureSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Lecture
fields = ('id', 'lecture_no', 'title', 'youtubeLink', 'course', 'keywords')
class NotesSerializer(serializers.HyperlinkedModelSerializer):
lecture = LectureSerializer(read_only=True, many=True)
class Meta:
model = Notes
fields = ('id', 'notes', 'lecture')
api views:
class LectureViewSet(viewsets.ModelViewSet):
serializer_class = LectureSerializer
def get_queryset(self):
course_id = self.request.query_params.get('course',False)
if course_id:
lectures = Lecture.objects.filter(course=course_id)
else:
lectures = Lecture.objects.all()
return lectures
class NotesViewSet(viewsets.ModelViewSet):
queryset = Notes.objects.all()
serializer_class = NotesSerializer
you need only to send the interview_id value:
data: {
"notes": notes,
"interview_id": interview_id
}
and in serializers.py define your serializers as follow:
class InterviewSerializer(serializers.ModelSerializer):
class Meta:
model = Interview
class NoteSerializer(serializers.ModelSerializer):
interview = InterviewSerializer(read_only=True, many=True)
class Meta:
model = Note
I have two models:
class Lecture(models.Model):
lecture_no = models.IntegerField(null=True)
title = models.CharField(max_length=128, unique=True, null=True)
youtubeLink = models.CharField(max_length=128, unique=True, null=True)
course = models.ForeignKey(Course, null=True)
keywords = models.TextField(max_length=300, null=True)
#Could add Next Rerun Date & Time
def __str__(self):
return self.title
class Notes(models.Model):
notes = models.TextField(null=True)
lecture = models.ForeignKey(Lecture, null=True, related_name='lecture')
def __str__(self):
return self.notes
These serializers:
class NotesSerializer(serializers.ModelSerializer):
lecture = LectureSerializer(read_only=True, many=True)
class Meta:
model = Notes
fields = ('id', 'notes', 'lecture')
class KeywordSerializer(serializers.ModelSerializer):
lecture = LectureSerializer(read_only=True, many=True)
class Meta:
model = Keyword
fields = ('id', 'notes', 'lecture')
and these views:
class LectureViewSet(viewsets.ModelViewSet):
serializer_class = LectureSerializer
def get_queryset(self):
course_id = self.request.query_params.get('course',False)
if course_id:
lectures = Lecture.objects.filter(course=course_id)
else:
lectures = Lecture.objects.all()
return lectures
class NotesViewSet(viewsets.ModelViewSet):
queryset = Notes.objects.all()
serializer_class = NotesSerializer
and I'm trying to make it so that I can update the "notes" field for a specific lecture. Currently I'm using a POST http request:
saveNotes: function(notes, lecture_id, callback) {
$http({
method: 'POST',
url: apiRoute + 'notes/',
data: {
"notes": notes,
"lecture_id": lecture_id
}
}).success(callback);
}
But this just adds a new row to the database every time. How do you update fields instead?
Thanks