Image upload crud operations in django-restframework - python-3.x

Im new to django, i want to create API for image upload CRUD in drf.
i have done create and read images , it works but dont know how to update and delete it by using id
models.py
class File(models.Model):
file = models.FileField(blank=False, null=False)
def __str__(self):
return self.file.name
serializers.py
class FileSerializer(serializers.ModelSerializer):
class Meta:
model = File
fields = "__all__"
views.py
class FileUploadView(ListAPIView):
parser_class = (FileUploadParser,)
serializer_class = FileSerializer
def get_queryset(self):
queryset = File.objects.all()
return queryset
def post(self, request, *args, **kwargs):
print(request.data)
file_serializer = FileSerializer(data=request.data)
print(file_serializer)
if file_serializer.is_valid():
file_serializer.save()
return Response(
file_serializer.data,
status=status.HTTP_201_CREATED
)
else:
return Response(
file_serializer.errors,
status=status.HTTP_400_BAD_REQUEST
)
i want to know how update and delete works

Thank you #manpikin, by doing this way, we can solve it easly
class FileViewSet(viewsets.ModelViewSet):
queryset = File.objects.all()
serializer_class = FileSerializer
but in my case there is some hidden code in between so i have done it in this way, i hope this will help some one facing same problem like me
views.py
class FileUploadView(ListAPIView):
parser_class = (FileUploadParser,)
serializer_class = FileSerializer
def get_queryset(self):
queryset = File.objects.all()
return queryset
def post(self, request, *args, **kwargs):
print(request.data)
file_serializer = FileSerializer(data=request.data)
print(file_serializer)
if file_serializer.is_valid():
file_serializer.save()
return Response(
file_serializer.data,
status=status.HTTP_201_CREATED
)
else:
return Response(
file_serializer.errors,
status=status.HTTP_400_BAD_REQUEST
)
def put(self, request):
imageid = self.request.POST.get('id')
f_obj = File.objects.filter(id=imageid) #File is my model name
file_serializer = FileSerializer(f_obj, data=request.data)
print(file_serializer)
if file_serializer.is_valid():
file_serializer.save()
return Response(
file_serializer.data,
status=status.HTTP_201_CREATED
)
else:
return Response(
file_serializer.errors,
status=status.HTTP_400_BAD_REQUEST
)
def delete(self, request):
imageid = self.request.POST.get('id')
f_obj = File.objects.filter(id=imageid) #File is my model name
if f_obj.exists():
f_obj.delete()
return Response(
{
"Status": True,
"Message": "image deleted"
}
)
update and delete will work in this way

Related

How to select related objects with only one query

Models:
class Tag(BaseModel):
tag_name = models.CharField(max_length=250)
slug = models.SlugField()
def save(self, *args, **kwargs):
self.slug = slugify(self.tag_name)
super(Tag, self).save(*args, **kwargs)
def __str__(self):
return str(self.tag_name)
class Tags(BaseModel):
filtertype = models.CharField(max_length=250)
tags = models.ManyToManyField(Tag)
My current solution:
def get(self,request,version):
filtertype = request.query_params.get('filtertype', '')
filtertypes = filtertype.split(",")
tagsList = Tags.objects.filter(filtertype__in=filtertypes).values_list('tags', flat=True).distinct()
queryset = Tag.objects.filter(id__in=tagsList)
context = {"request": request}
serialized = TagListSerializers(queryset, many=True, context=context)
return Response(serialized.data)
Im trying to get all the relevant Tag base on Tags/filtertype. Im wondering how can I do it with only one query.
you can do the query part with this code:
queryset = Tag.objects.filter(tags__filtertype__in=filtertypes)

Django duplicate file to all the records with M2M which is self referencing

I have a Serializer & APIview where i upload a file it should be uploaded to other related records as well.
class Record(models.Model):
name = models.CharField(max_length = 122)
related_records = models.ManyToManyField('self', null = True)
class RecordDocument(models.Model):
record = models.ForeignKey(Record, related_name = 'documents', null = True,
blank= True )
file = models.FileField(max_length=255, blank=True, null=True)
class RecordDocumentSerializer(serializers.ModelSerializer):
save_documents_to_related_records = serializers.BooleanField()
class Meta:
model = RecordDocument
fields = ( 'save_documents_to_related_records', 'file',
'record' )
class RecordDocumentUploadView(APIView):
def post(self, request, *args, **kwargs):
'how do i get serializers field **save_documents_to_related_records** and save
the file on **related_records** which is not used in serializer till now if
there are any inside it'
You can try this.
class RecordDocumentUploadView(APIView):
def post(self, request, *args, **kwargs):
serializer = RecordDocumentSerializer(data = request.data)
if serializer.is_valid():
input_data = serializer.validated_data
flag = input_data.pop('save_documents_to_related_records')
new_document = RecordDocument.objects.create(**input_data)
if flag:
...
else:
return Response(status = status.HTTP_400_BAD_REQUEST)

date updated as many times, should not created another entry for date in DB

Models.py
class FreezePrimaryCategory(models.Model):
freeze_date = models.DateField(default=datetime.datetime.now)
updated_date = models.DateTimeField(auto_now=True)
def __str__(self) -> str:
return str(self.freeze_date)
Views.py
class FreezePrimaryCategory(APIView):
permission_classes = (IsAuthenticated,)
#checkToken
def post(self, request):
data = request.data
freeze_date = request.data.get("freeze_date")
data = {
'freeze_date': freeze_date,
}
serializer = FreezeCategorySerializer(data=data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Serializers.py
class FreezeCategorySerializer(serializers.ModelSerializer):
class Meta:
model = FreezePrimaryCategory
fields = ['freeze_date']
def validate(self, data):
today = date.today()
if data['freeze_date'] >= today:
raise serializers.ValidationError('Date cannot be greater than current Date')
return data
I want date api entry in db should be only once and updated as many times.

filter ManyToManyField(**), by user in form selection

I need to add songs to my Playlist - but I want that only the user can add your registered songs, not all songs.
I have this:
models
class Song(models.Model):
user = models.ForeignKey(User, default=1)
title=models.CharField(max_length=500)
artist = models.CharField(max_length=250)
audio = models.FileField(default='')
def __str__(self):
return self.title
class List(models.Model):
user_list = models.ForeignKey(User, default=User)
title_list=models.CharField(max_length=500)
songs = models.ManyToManyField(Song)
def __str__(self):
return self.title_list
forms
class SongForm(forms.ModelForm):
class Meta:
model = Song
fields = ['title', 'artist', 'audio']
class ListForm(forms.ModelForm):
#songs=forms.MultipleChoiceField(Song.objects.all(), widget=forms.CheckboxSelectMultiple)
#songs= forms.MultipleChoiceField( widget=forms.CheckboxSelectMultiple)
#songs=forms.ModelMultipleChoiceField(queryset=Song.objects.all(), widget=forms.CheckboxSelectMultiple) #here i dont know why the form dont save data
#I want this
songs=forms.ModelMultipleChoiceField(queryset=Song.objects.filter(user=actualuser),widget=forms.CheckboxSelectMultiple)
class Meta:
model = Lista
fields = ['title_list','songs']
#views
def new_list(request):
form=ListForm(request.POST or None, request.FILES or None)
if form.is_valid():
lista = form.save(commit=False)
lista.user_list = request.user
lista.save()
context = {
'username': request.user.username,
'lista': lista,
}
return render(request,'MyMusic/list_detail.html',context)
context={
'form':form,
'error_message': 'Error ',
}
return render(request,'MyMusic/list_form.html',context)
in forms view I need only see and I want select only my own registered songs, also I want can see a check box not the actual (widget=forms.CheckboxSelectMultiple), but actully this does not save the data.
the solution for me.
**Forms**
class ListForm(forms.ModelForm):
def __init__(self,user, *args, **kwargs):
super(ListForm, self).__init__(*args, **kwargs)
self.fields['songs'] = forms.ModelMultipleChoiceField(queryset=Song.objects.filter(user=user)
,required=False,widget=forms.CheckboxSelectMultiple)
class Meta:
model = Lista
fields = ['title_list','songs']
in views
def new_list(request):
form=ListForm(request.user,request.POST or None, request.FILES or None)
if form.is_valid():
lista = form.save(commit=False)
lista.user_list = request.user
lista.save()
lista.canciones = form.cleaned_data['songs'] # avoid conflict to save checkbox
context = {
'username': request.user.username,
'lista': lista,
}
return render(request,'MyMusic/list_detail.html',context)
context={
'form':form,
'error_message': 'Error ',
}
return render(request,'MyMusic/list_form.html',context)

Cannot submit the form with foreign key in Django

I can't submit the form with foreign key. Is it anything with foreign key?
I always redirect to the destination_list since the form is not saving.
No error is showing.
models.py
class Region(models.Model):
region = models.CharField("Region",max_length=45,blank=True)
status = models.CharField("Status",max_length=45,blank=True)
selected_region = models.CharField("Selected Region",max_length=45,blank=True)
def __str__(self):
return self.region
def get_absolute_url(self):
return reverse('update2', args=[str(self.id)])
def get_delete_url(self):
return reverse('delete2', args=[str(self.id)])
class Destination(models.Model):
region1 = models.ForeignKey(Region)
destination = models.CharField("destination",max_length=30,blank=False,unique=True)
status = models.CharField("status",max_length=30,blank=False,unique=True)
selected_destination = models.CharField("select destination",max_length=30)
def __str__(self):
return self.destination
forms.py
class DestinationForm(forms.ModelForm):
class Meta:
model = Destination
fields = [ 'region1','destination','status','selected_destination']
def __init__(self, *args, **kwargs):
super(DestinationForm, self).__init__(*args, **kwargs)
for key in self.fields:
self.fields[key].widget.attrs['class'] = 'form-control'
views.py
(I have redirect to destination_list if form is not submitted)
def add_destination(request):
form = DestinationForm()
context = {
"form": form
}
if request.method == 'POST':
form = DestinationForm(request.POST)
if form.is_valid():
form.save()
else:
return redirect(destination_list)
return render(request,'adddestination.html',context)

Resources