Django Class based views and Simple Image Upload - django

When trying out a simple image upload I'm getting an error:
TypeError at /upload/
__init__() got an unexpected keyword argument 'instance'
Here are the snippits of relevant code (If you need more, let me know!):
# Models
class Photo(models.Model):
created_at = models.DateTimeField(auto_now_add=True, editable=False)
title = models.CharField(max_length=255)
image = models.ImageField(upload_to='photos/'+str(uuid.uuid4())+'/')
# Views
class PhotoUploadView(CreateView):
model = Photo
form_class = PhotoUploadForm
template_name = 'upload.html'
success_url = '/thanks/'
# Forms
class PhotoUploadForm(forms.Form):
image = forms.ImageField()
title = forms.CharField(max_length=255)
# Urls
urlpatterns = patterns('',
url(r'^upload/', views.PhotoUploadView.as_view()),
)

You're getting an exception because you've specified a "model" attribute in your View class which implements the SingleObjectMixin. However, you're not giving it an instance of your Photo model to render.
Since you just want to create a new photo, you should remove the model attribute from your View class:
# views.py
from django.views.generic import CreateView
from myapp.forms import PhotoUploadModelForm
class PhotoUploadView(CreateView):
form_class = PhotoUploadModelForm
template_name = 'upload.html'
success_url = '/thanks/'
And modify your form class to inherit from a ModelForm:
# forms.py
from django import forms
from myapp.models import Photo
class PhotoUploadModelForm(forms.ModelForm):
class Meta:
model = Photo
fields = ['image', 'title']

Related

How to link to URL of related object in DRF

I’m making a music player with a DRF backend.
I have two models, one is Song and the other is TrackQueue
In the browser, the “nowplaying” instance of TrackQueue shows the meta of the queued song with a link to the file in its meta.
What I need now is a url that always produces that instance of the “nowplaying” TrackQueue (id=1)
What would that url be and how can I create it?
Thank you
models.py
class Song(models.Model):
title = models.CharField(max_length=24)
file = models.FileField()
def __str__(self):
return self.title
class TrackQueue(models.Model):
title = models.CharField(max_length=64)
is_song = models.OneToOneField(Song, on_delete=models.CASCADE)
def __str__(self):
return self.title
Serializers.py
from rest_framework import serializers
from .models import Song, TrackQueue
class SongSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Song
fields = ('id' ,'title', 'file')
class TrackQueueSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = TrackQueue
fields = ('id' , 'title', 'is_song')
views.py
from django.shortcuts import render
from .serializers import SongSerializer
from rest_framework import viewsets
from .models import Song, TrackQueue
from music.serializers import SongSerializer, TrackQueueSerializer
class SongView(viewsets.ModelViewSet):
serializer_class = SongSerializer
queryset = Song.objects.all()
class TrackQueueView(viewsets.ModelViewSet):
serializer_class = TrackQueueSerializer
queryset = TrackQueue.objects.all()

How to prevent IntegrityError in a django model

I am learning django and I follow this blog project on codemy youtube channel: https://www.youtube.com/watch?v=_ph8GF84fX4&ab_channel=Codemy.comCodemy.com
And I wanted to improve my code with ForeignKey but I got stuck.
I want to add a Category into my Post model. So I used the ForeignKey. Not every post has a categroy since I added this model just recently, but I used the default argument in the Category class, which should solve this problem. However, trying several options, I cannot migrate my models and run the server again.
My code:
from django.db import models
from django.contrib.auth.models import User
from django.urls import reverse
class Category(models.Model):
cat_name = models.CharField(max_length=300, default="uncategorized")
def get_absolute_url (self):
return reverse("blog")
def __str__(self):
return self.cat_name
class Post(models.Model):
title = models.CharField(max_length=300)
author = models.ForeignKey(User, on_delete = models.CASCADE)
body = models.CharField(max_length=30000)
date = models.DateField(auto_now_add=True)
category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True)
def get_absolute_url (self):
return reverse("post", args = [str(self.id)])
The error:
django.db.utils.IntegrityError: The row in table 'blog_post' with primary key '1' has an invalid foreign key: blog_post.category_id contains a value 'uncategorized' that does not have a corresponding value in blog_category.id.
I have used the category in my forms.py:
class PostForm(forms.ModelForm):
class Meta:
model = models.Post
fields = ["title", "author", "category", "body"]
widgets = {
"title": forms.TextInput(attrs={"class": "form-control"}),
"author": forms.Select(attrs={"class": "form-control"}),
"category": forms.Select(attrs={"class": "form-control"}),
"body": forms.Textarea(attrs={"class": "form-control"}),
}
which is used in my views:
from django.shortcuts import render
from django.views.generic.base import TemplateView
from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView
from . import models
from.forms import PostForm
from django.urls import reverse_lazy
class IndexView(TemplateView):
template_name = "index.html"
class PostListView(ListView):
model = models.Post
template_name = "post_list.html"
#ordering = ["-id"]
class PostDetailView(DetailView):
model = models.Post
template_name = "post_detail.html"
class AddPostView(CreateView):
model = models.Post
form_class = PostForm
template_name = "add_post.html"
#fields = ["title", "author", "body"]
class UpdatePostView(UpdateView):
model = models.Post
form_class = PostForm
template_name = "update_post.html"
#fields = ["title", "body"]
class DeletePostView(DeleteView):
model = models.Post
template_name = "delete_post.html"
success_url = reverse_lazy("blog")

POST and PATCH operations in ArrayModelField using Django DRF

I am using Django 2.2, MongoDb with Djongo. I am facing issues in POST and PATCH API. I am facing three kinds of issues.
When performing a POST operation to create a new entry, API fails with error: Array items must be Model instances.
What is the correct way to refer an instance of Screenplay class in POST API. Is the id of the parent class sufficient?
How to perform a update to a specific field in Scene model including a text field in comments?
Following is the code snippet.
Sample POST API data
{
"title": "intro1",
"screenplay": "49423c83-0078-4de1-901c-f9176b51fd33",
"comments": [
{
"text": "hello world",
"author": "director"
}
]
}
models.py
import uuid
from djongo import models
class Screenplay(models.Model):
id = models.UUIDField(primary_key = True, default = uuid.uuid4,editable = False)
title = models.CharField(max_length=100)
def __str__(self):
return self.title
class Comment(models.Model):
text = models.TextField();
author = models.TextField();
def __str__(self):
return self.author +self.text
class Scene(models.Model):
id = models.UUIDField(primary_key = True, default = uuid.uuid4,editable = False)
title = models.CharField(max_length=100)
screenplay = models.ForeignKey(Screenplay, related_name='scenes', on_delete=models.CASCADE)
comments = models.ArrayModelField(
model_container = Comment,
);
def __str__(self):
return self.title
serializers.py
from rest_framework import serializers
from planning.models import Scene, Comment
class ScreenplaySerializer(serializers.ModelSerializer):
class Meta:
model = Screenplay
fields = ('id', 'title')
class CommentSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Comment
fields = ('text', 'author')
class SceneSerializer(serializers.HyperlinkedModelSerializer):
comments = CommentSerializer();
class Meta:
model = Scene
fields = ('id', 'title', 'comments')
viewsets.py
from planning.models import Screenplay, Scene, Comment
from .serializers import ScreenplaySerializer, SceneSerializer, CommentSerializer
from rest_framework import viewsets
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework import status
from rest_framework import generics
from rest_framework.generics import RetrieveUpdateDestroyAPIView
class ScreenplayViewSet(viewsets.ModelViewSet):
queryset = Screenplay.objects.all()
serializer_class = ScreenplaySerializer
class SceneViewSet(viewsets.ModelViewSet):
queryset = Scene.objects.all()
serializer_class = SceneSerializer
class CommentViewSet(viewsets.ModelViewSet):
queryset = Comment.objects.all()
serializer_class = CommentSerializer
I suggest you read the documentation on Writable nested representations, it will help to dissipate your doubts.

Django update modelform with field constraints

Having the following Model:
class Book(models.Model):
name = models.CharField()
author = models.CharField()
date = models.DateField()
class Meta:
unique_together = ('name', 'author')
class BookSerializerWrite(serializers.ModelSerializer):
class Meta:
model = Book
class BookView(ApiView):
def put(self, request, *args, **kwargs):
serializer = BookSerializerWrite(data=request.data)
if serializer.is_valid():
serializer.save()
The view above does not work as the serializer.is_valid() is False.
The message is:
'The fields name, author must make a unique set'
Which is the constraint of the model.
How do I update the model?
I would rather not override the serializer's validation method.
I also cannot access the validated_data for an update as in
https://www.django-rest-framework.org/api-guide/serializers/#saving-instances
as this is empty due to the fact that the form does not validate.
Is there a builtin solution?
You can achieve it using UpdateAPIview
serializers.py
class BookSerializer(serializers.ModelSerializer):
class Meta:
model = Book
fields = ('name', 'author', 'date')
views.py
from rest_framework.generics import UpdateAPIview
from .serializers import BookSerializer
class BookUpdateView(UpdateAPIView):
serializer_class = BookSerializer
urls.py
from django.urls import path
from . import views
url_patterns = [
path('api/book/<int:pk>/update/', views.BookUpdateView.as_view(), name="book_update"),
]
Now, post your data to above url. It should work.
Reference: https://github.com/encode/django-rest-framework/blob/master/rest_framework/generics.py

add my own class in admin field django-cms

Hi everyone Y create my own app in djando CMS, now I want to add my own class and id's to my field.. y try this, but I don't obtain any successful result.
in my model.py I have this
class Entry(models.Model):
TYPES_CHOICES = (
('none', 'not specified'),
('s', 'Series'),
('mb', 'Multiples Bar'),
('b', 'Bar suggestion'),
)
app_config = AppHookConfigField(HealthConfig)
code = models.CharField(blank=True, default='', max_length=250)
url_suggestion = models.CharField(blank=True, default='', max_length=250, verbose_name="URL for Suggestion" )
health_placeholder = PlaceholderField('health_info')
objects = AppHookConfigManager()
def __unicode__(self):
return self.url
class Meta:
verbose_name_plural = 'entries'
and now in my form.py I have this
from django import forms
from .models import Entry
class EntryForm(forms.ModelForm):
class Meta:
model = Entry
fields = '__all__'
def __init__(self, *args, **kwargs):
super(EntryForm, self).__init__(*args, **kwargs)
self.fields['code'].widget.attrs={
'id': 'my_code',
'class': 'code_class',
}
finally my admin.py is like this
from django.contrib import admin
from cms.admin.placeholderadmin import PlaceholderAdminMixin
from .cms_appconfig import HealthConfig
from .models import Entry
from .forms import EntryForm
from aldryn_apphooks_config.admin import ModelAppHookConfig, BaseAppHookConfig
class EntryAdmin(ModelAppHookConfig, PlaceholderAdminMixin, admin.ModelAdmin):
# pass
fieldsets = (
('General data', {
'fields':('app_config','chart', 'url',('count', 'code', 'start'))
}),
('Suggestion',{
'classes':('collapse', 'suggestion',),
'fields':('url_suggestion',('key1_suggestion_name','key1_suggestion'),('key2_suggestion_name','key2_suggestion'), 'primary_suggestions')
}),
)
list_display =('app_config' ,'url', 'chart');
list_filter = (
'app_config',
)
form = EntryForm
class Media:
js = ('health/js/admin/healthAdmin.js',)
css = {
'all': ('health/css/admin/admin_area.css',)
}
admin.site.register(Entry, EntryAdmin)
any idea is I missing something, after that, I do a migrate of the component again.
Thanks in advance!
You can specify a custom form for admin using the form attribute of ModelAdmin.
So using the example from the docs linked below, that would look like;
from django import forms
from django.contrib import admin
from myapp.models import Person
class PersonForm(forms.ModelForm):
class Meta:
model = Person
exclude = ['name']
class PersonAdmin(admin.ModelAdmin):
exclude = ['age']
form = PersonForm
https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.form
So in your admin.py you'd need something like;
from .forms import EntryForm
class EntryAdmin(admin.ModelAdmin):
form = EntryForm