i am reciving a "value error"
because of "ModelForm has no model class specified."
i tried to check the : models.py forms.py and views.py but all looks pretty good for me
views.py :
class CreatePostView(LoginRequiredMixin,CreateView):
login_url='/login/'
redirect_field_name='Myblog/post_detail.html'
form_class = PostForm
model = Post
models.py:
class Post(models.Model):
author = models.ForeignKey('auth.User',on_delete=models.CASCADE)
title = models.CharField(max_length=200)
text = models.TextField()
created_date = models.DateTimeField(default=timezone.now)
published_date = models.DateTimeField(blank=True,null=True)
forms.py:
class PostForm(ModelForm):
class meta:
model = Post
fields = ('author','title','text')
from app.urls.py
url(r'^post/new/$',views.CreatePostView.as_view(),name='post_new'),
Meta is with an uppercase, according to PEP-8 the names of classes all start with an uppercase. In your form, you should write:
# app/forms.py
class PostForm(ModelForm):
class Meta:
model = Post
fields = ('author','title','text')
Since you wrote it as meta, Django indeed did not understand what model you were using.
If you however do not write a form with specific items, you can - like #DanielRoseman says, just define this at the CreateView [Django-doc]:
class CreatePostView(LoginRequiredMixin,CreateView):
login_url='/login/'
redirect_field_name='Myblog/post_detail.html'
model = Post
fields = ('author', 'title', 'text')
Django can construct a form class through the modelform_factory [Django-doc].
Related
l'm new to Django and don't understand what exactly i need to do to update my JSONfield in django model.
models.py:
class Schemas(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=15)
modified = models.DateField()
column_separator = models.CharField(max_length=1)
string_character = models.CharField(max_length=1)
json_data = models.JSONField()
forms.py:
class UpdateSchemaForm(forms.ModelForm):
class Meta:
model = Schemas
fields = ['title', 'column_separator', 'string_character', 'json_data']
views.py:
class UpdateSchema(UpdateView):
model = Schemas
form_class = UpdateSchemaForm
template_name = 'updateschema.html'
success_url = 'home'
I have a form where user can add new fields and fill them with data.
enter image description here
Then these fields save in JSONfield in models.py
I want to allow user to update the JSONfield using UpdateView like making the same forms but filed.
So I'm trying to achieve the general "Like" functionality in a social media website using Django and REST Framework, and a frontend in React.
Using a Post model to save all the posts, and I have a Many-to-Many field for storing the likes and created a through model as follows:
class PostLike(models.Model):
user = models.ForeignKey(AppUser, on_delete=models.CASCADE)
post = models.ForeignKey("Post", on_delete=models.CASCADE)
timestamp = models.DateTimeField(auto_now_add=True)
class Post(models.Model):
user = models.ForeignKey(AppUser, on_delete=models.CASCADE)
caption = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
edited_at = models.DateTimeField(auto_now=True)
likes = models.ManyToManyField(
AppUser, related_name="post_user", blank=True, through=PostLike
)
(AppUser is a custom auth model used)
Similarly, I have created serializers and viewsets for the above models:
class PostSerializer(serializers.ModelSerializer):
class Meta:
model = Post
fields = "__all__"
class PostLikeSerializer(serializers.ModelSerializer):
class Meta:
model = PostLike
fields = "__all__"
class PostViewSet(viewsets.ModelViewSet):
queryset = Post.objects.all()
serializer_class = PostSerializer
class PostLikeViewSet(viewsets.ModelViewSet):
queryset = PostLike.objects.all()
serializer_class = PostLikeSerializer
My question is, how do I "like" or remove an existing "like" from a post using API calls?
One method I know is to just make a POST request to the PostLike endpoint using the user PK and the post PK to create a PostLike instance, but I don't know a way to "remove" a like using the same method.
Please help!
you can use APIView instead of ViewSet like this:
from rest_framework import views
class PostLikeApiView(views.APIView):
serializer = PostLikeSerializer(data=request.data)
if serializer.is_valid():
user = serializer.data['user']
post = serializer.data['post']
post_like_obj = PostLike.objects.filter(user=user, post=post)
if post_like_obj.exists():
post_like_obj.delete()
result = 'unliked'
else:
PostLike.objects.create(user=user, post=post)
result = 'liked'
return Response(
{
'result': result,
},
status=status.HTTP_200_OK
)
else:
return Response(
serializer.errors,
status=status.HTTP_400_BAD_REQUEST
)
models.py
address_choices = (("home":"Home"),("shop", "Shop"))
class Address(models.Model):
address_type = models.CharField(max_length=128, choices=address_choices)
location = models.CharField(max_length=128)
forms.py
class AddressForm(forms.ModelForm):
class Meta:
model = Address
views.py
home_address = AddressForm(prefix="shop")
shop_address = AddressForm(prefix="home")
can i use prefix in serializers just like that i used in forms above
serializers.py
class AddressSerializers(serializers.ModelSerializer):
class Meta:
model = Address
views.py
home_serializer = AddressSerializers(prefix="home")
shop_serializer = AddressSerializers(prefix="shop")
As you have the current model Address it's enough to have one serializer for that. You can specify {'address_type': 'home'} or {'address_type': 'shop'} when using that. If you want to have multiple addresses (bulk creation) you should use a ListSerializer or the many=True parameter if you used it inside other related serializer.
I cant find a way to auto-populate the field owner of my model.I am using the DRF .If i use ForeignKey the user can choose the owner from a drop down box , but there is no point in that.PLZ HELP i cant make it work.The views.py is not include cause i think there is nothing to do with it.
models.py
class Note(models.Model):
title = models.CharField(max_length=200)
body = models.TextField()
cr_date = models.DateTimeField(auto_now_add=True)
owner = models.CharField(max_length=100)
# also tried:
# owner = models.ForeignKey(User, related_name='entries')
class Meta:
ordering = ('-cr_date',)
def __unicode__(self):
return self.title
serializers.py
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('id', "username", 'first_name', 'last_name', )
class NoteSerializer(serializers.ModelSerializer):
owner = request.user.id <--- wrong , but is what a need.
# also tried :
# owner = UserSerializer(required=True)
class Meta:
model = Note
fields = ('title', 'body' )
Django Rest Framework provides a pre_save() method (in generic views & mixins) which you can override.
class NoteSerializer(serializers.ModelSerializer):
owner = serializers.Field(source='owner.username') # Make sure owner is associated with the User model in your models.py
Then something like this in your view class:
def pre_save(self, obj):
obj.owner = self.request.user
REFERENCES
http://www.django-rest-framework.org/tutorial/4-authentication-and-permissions#associating-snippets-with-users
https://github.com/tomchristie/django-rest-framework/issues/409#issuecomment-10428031
I have two Django models:
class Author(models.Model):
user_email = models.CharField(max_length=100, blank=True)
display_name = models.CharField(max_length=250)
class Photo(models.Model):
author = models.ForeignKey(Author)
image = ThumbnailImageField(upload_to='photos')
To get inline photos, I have in admin.py:
class PhotoInline(admin.StackedInline):
model = Author
class AuthorAdmin(admin.ModelAdmin):
list_display = ('display_name','user_email')
inlines = [PhotoInline]
I get an error: Exception at /admin/metainf/author/11/
<class 'metainf.models.Author'> has no ForeignKey to <class 'metainf.models.Author'>
Why?
The inline model should be having a ForeignKey to the parent model. To get Photo as inline in Author your models code is fine. But your admin code should be as follows:
class PhotoInline(admin.StackedInline):
model = Photo
class AuthorAdmin(admin.ModelAdmin):
list_display = ('display_name','user_email')
inlines = [PhotoInline]
Read more info here.
That's because Author doesn't have a foreign key to photo. I think you need to switch the model for the inline like this:
class PhotoInline(admin.StackedInline):
model = Photo
class AuthorAdmin(admin.ModelAdmin):
list_display = ('display_name','user_email')
inlines = [PhotoInline]
Maybe you need to install django-nested-admin library, and later try with NestedStackedInline.
django-nested-admin