I can't Create Second Video in the Django-Rest-Framework - reactjs

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)

Related

Creating a simple messaging function (NOT REAL TIME) using Django

Please I'm trying to implement a SIMPLE messaging function (NOT A REAL TIME CHAT)
But I keep getting this error message I understand what it says or mean but I'm not sure why I am unable to establish this relationship
Please I need help to alternative if I can't do things this way
This is my profile(Engineer) models
class Engineer(AbstractUser):
username = models.CharField(max_length=200, null=True)
email = models.EmailField(unique=True, null=True)
bio = models.TextField()
avatar = models.ImageField(default="profile.png")
country = models.CharField(max_length=200)
years_of_experience = models.PositiveIntegerField(null=True, blank=True)
tech_stack = models.CharField(null=True, blank=True, max_length=300)
inbox = models.ForeignKey(Inbox, null=True, on_delete=models.CASCADE)
USERNAME_FIELD = "email"
REQUIRED_FIELDS = ["username"]
def __str__(self):
return self.username
and this is my Inbox models
class Inbox(models.Model):
sender = models.ForeignKey(Engineer, null=True, on_delete=models.CASCADE, related_name='mail_sender')
receiver = models.ForeignKey(Engineer, null=True, on_delete=models.CASCADE, related_name="mail_receiver")
message = models.CharField(max_length=500)
updated = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ["-created"]
def __str__(self):
return self.sender.username
Just make the Engineer import as follows
sender = models.ForeignKey('Engineer', null=True, on_delete=models.CASCADE, related_name='mail_sender')
receiver = models.ForeignKey('Engineer', null=True, on_delete=models.CASCADE, related_name="mail_receiver")

Please explain the _set.all() method in django>

I have this models and the view for user profile.
class Room(models.Model):
admin = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
topic = models.ForeignKey(Topic, on_delete=models.SET_NULL, null=True)
group_photo = models.ImageField(null=True, upload_to = 'images/', default='avatar.svg')
name = models.CharField(unique=True, max_length=100)
description = models.TextField(null=True, blank=True)
members = models.ManyToManyField(User, related_name='members', blank=True)
created = models.DateTimeField(auto_now_add=True)
views.py
#login_required(login_url= 'login')
def userprofile(request, pk):
user = User.objects.get(username=pk)
#groups = user.room_set.all()
groups = Room.objects.filter(admin=user)
all_groups = Room.objects.filter(members=user)
return render(request, 'base/profile.html', {'user':user, 'groups':groups, 'all_groups':all_groups})
Please explain how _set.all method filter method are doing the same job.
I don't understand where the room is coming from (there is only (Room) model.
explain the mechanism of user.room_set.all line respect to filter;

Django Post request for many to many field ValueError

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]
}

Using Sorted on a set of a QuerySet

I have this Page model:
class BlogPostPage(Page):
date_published= models.DateField('Published date', blank=True, null=True)
intro= models.CharField(max_length=250)
body = RichTextField(blank=True)
header_image = models.ForeignKey('wagtailimages.Image', blank=True, null=True,
on_delete=models.SET_NULL, related_name='+')
tags = ClusterTaggableManager(through='blog.BlogPageTag', blank=True)
categories = ParentalManyToManyField('blog.BlogCategory', blank=True)
def get_context(self, request):
context = super().get_context(request)
all_categories = []
for post in self.get_siblings(inclusive=True):
all_categories +=post.specific.categories.all()
all_categories = sorted(set(all_categories))
context['all_categories']= all_categories
return context
When the page is access I get a TypeError:
TypeError at /blog/xxx/
'<' not supported between instances of 'BlogCategory' and 'BlogCategory'
Inputs on why this is happening and how it can be avoided are requested.
You can define the key parameter for sorted, according to key functions.
But I am not sure, is + allowed in: all_categories +=post.specific.categories.all()?

POST request to update data fields - AngularJS, Django

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

Resources