Django ModelView's "fields" attribute not working? - python

I'm practicing with Django's Class-Based-View.
While practicing with the generic CreateView, I have trouble understanding why my "fields" attributeis not working... I'm trying to construct a Post Create page using the CreateView, and I want only the "post_title" and "post_content" fields to appear on the post page (In other words, I wan't to omit the "user" and "post_date" field on the form). I'm pretty sure the "fields" attribute is the right place to define this, but for some reason, all 4 fields appear on the Post Form.
Here are my codes:
models.py
class Post(models.Model):
user = models.ForeignKey(User)
post_title = models.CharField(max_length=200)
post_content = models.CharField(max_length=500)
post_date = models.DateTimeField('date posted')
views.py
class PostCreate(CreateView):
template_name = 'app_blog/post_save_form.html'
model = Post
fields = ['post_title', 'post_content']
Any idea why all 4 fields appear..? Thanks :)

You have to do that:
class PostForm(ModelForm):
class Meta:
model = Post
fields = ['post_title', 'post_content']
class PostCreate(CreateView):
template_name = 'app_blog/post_save_form.html'
model = Post
form_class = PostForm

Related

How to use multiple model in froms Django class based view and render fields value in html templates?

I have two model post and HeaderImage. I want use both of model in my html froms. here is my code:
models.py
class Post(models.Model):
title = models.CharField(max_length=300,unique=True,error_messages={'unique':"This title already exists. Please use different title"})
author = models.ForeignKey(User, on_delete=models.CASCADE)
class HeaderImage(models.Model):
header_image = models.ImageField() #I want to merge this model with Post model and want to add image field in my current forms.
froms.py
class BlogPost(forms.ModelForm):
class Meta:
model = Post
fields = ['title','author','body']
views.py
class BlogUpdateView(PermissionRequiredMixin,UpdateView):
raise_exception = True
permission_required = "blog.change_post"
model = Post
template_name = "blog_update_post.html"
form_class = BlogPost
How to get image filed from second model and add it to existing from which using first model?

Save the data of current logged user in django

I am a newbie in django and I have a question about how I can save and show only the data of logged user - since my application is multi-tenant.
my view
class ProjetoCreate(CreateView):
model = Projeto
fields = ['nomeProjeto',
'descricao',
'dtInicio',
'deadline',
'nomeSprint',
'status',
]
def get_queryset(self):
logged_user = self.request.user
return Projeto.objects.filter(User=logged_user)
class ProjetoList(ListView):
paginate_by = 2
model = Projeto
my model
class Projeto(models.Model):
nomeProjeto = models.CharField(max_length=20)
descricao = HTMLField()
dtInicio = models.DateField(auto_now=False, auto_now_add=False)
deadline = models.DateField(auto_now=False, auto_now_add=False)
nomeSprint = models.CharField(max_length=30)
status = models.CharField(max_length=20)
Thank you very much!
Add
user = models.ForeignKey(User, on_delete=models.CASCADE)
to Projecto model. Then, in your view, set project.user = self.request.user before saving your project model.
I think you are doing it completely wrong.
You shouldn't be using get_queryset() at all in CreateView - https://stackoverflow.com/a/24043478/4626254
Here's is what you can try instead.
Add a user field in Project model and apply migrations.
user = models.ForeignKey(User, on_delete=models.CASCADE)
Create a class inheriting Generic APIView instead of CreateView.
Create a POST method like def post(self, request): inside that class and get all the details for creating a Projeto object in the request payload using request.data or request.POST.
Get the logged in user using request.user
Create a Projecto object with all this information as Projeto.objects.create(**your_other_fields, user=request.user)
Next time when filtering the objects, use a filter on user field like user=request.user.

Django Rest Framework - CreateAPIView ForeignKey lookup fields

I am using Django Rest Framework CreateAPIView in order to create a comment. So far everything is OK and here is my code.
Models
class Posts(models.Model):
title = models.CharField(max_length=512, null=True)
slug = models.CharField(max_length=512, null=True)
class Comments(models.Model):
post = models.ForeignKey(Posts, on_delete=models.CASCADE)
content = models.CharField(max_length=5000, null=True)
Serializer
class CommentCreateSerializer(ModelSerializer):
class Meta:
model = Comments
fields = [
'content',
'post'
]
and view
class CommentCreateView(CreateAPIView):
permission_classes = [IsAuthenticated]
queryset = Comments.objects.all()
serializer_class = CommentCreateSerializer
I sent a post request to the create route with post(ID) and content and everything worked. But the problem is I wanna pass post slug instead of post ID.
I am not sure how can I do that. I am familiar with lookup_fields but I am not certain how to apply them for ForeignKey match.
You can use SlugRelatedField in CommentCreateSerializer to use slug instead of pk when you pass the post value on Comment Create request, like this:
class CommentCreateSerializer(ModelSerializer):
post = serializers.SlugRelatedField(
queryset=Posts.objects.all(), slug_field='slug'
)
class Meta:
model = Comments
fields = [
'content',
'post'
]
In the CommentAPIview you need to overwrite the perform create method in to the lookup like so
def perform_create(self):
post_pk = self.kwargs.get("post_pk")
post = get_object_or_404(Post, pk=post_pk)
serializer.save(post=post)

ValueError: Cannot create form field for 'author' yet, because its related model 'settings.AUTH_USER_MODEL' has not been loaded yet

I am trying to set up a basic blog with a custom auth model. I am trying to get a simple form to work but somehow I am not able to make it work. I am not sure what is causing the error. This is a fresh app and a fresh project I am working on.
I tried to reference from the docs but I am not sure what I am doing incorrect. How can i fix this error? Thanks in advance
Docs: https://docs.djangoproject.com/en/1.11/topics/auth/customizing/#changing-to-a-custom-user-model-mid-project
Similar questions: Cannot create form field for 'created_by' yet, because its related model 'users.User' has not been loaded yet
My Current Code
models.py
class User(AbstractUser):
pass
class Post(models.Model):
author = models.ForeignKey('settings.AUTH_USER_MODEL')
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:
from blog.models import User
class PostForm(forms.ModelForm):
image = forms.CharField(
widget=forms.FileInput(attrs={'class': 'form-control'}),required=False)
class Meta():
model = Post
fields = ('author','title', 'text','image')
widgets = {
'title': forms.TextInput(attrs={'class': 'textinputclass'}),
}
views.py
from blog.forms import PostForm, CommentForm
class CreatePostView(LoginRequiredMixin,CreateView):
...
form_class = PostForm
model = Post
def form_valid(self,form):
if self.request.POST:
post = form.save()
return HttpResponseRedirect('/')
settings.py:
AUTH_USER_MODEL = 'blog.User'
admin.py:
from .models import User
from django.contrib.auth.admin import UserAdmin
admin.site.register(User,UserAdmin)
You should use settings.AUTH_USER_MODEL, not the string 'settings.AUTH_USER_MODEL':
class Post(models.Model):
author = models.ForeignKey(settings.AUTH_USER_MODEL)

Want to add a Form field in Admin along with Model fields in django

I want to add 3 fields in my Admin.py page. out of which two fields are from Model.py and one field is from form.py. But somehow when i add these fields to admin.site.register function, an error pops up saying 'userlist' is not recognizable. Below is my code :
Models.py
class About(models.Model):
about_author = models.TextField()
pic = models.FileField(upload_to = '', default = 'static/defaul.jpg')
Form.py
class PostAuthorDetails(forms.ModelForm):
def __init__(self,*args,**kwargs):
super(PostAuthorDetails,self).__init__(*args,**kwargs)
self.fields['userlist'] = forms.ModelChoiceField(queryset=User.objects.all())
class Meta:
model = About
fields = '__all__'
Admin.py
class PostAuthorDetailsAdmin(admin.ModelAdmin):
form = PostAuthorDetails
def get_fieldsets(self,*args,**kwargs):
return((None,{'fields':('about_author','pic','userlist'),}),)
admin.site.register(About,PostAuthorDetailsAdmin)
Please advise whats wrong with the code.
FormFields are class members. You can not declare FormFields during the initialisation of the Form.
class PostAuthorDetails(forms.ModelForm):
userlist = forms.ModelChoiceField(queryset=User.objects.all())
class Meta:
model = About
'__all__'
See the docs about ModelForms: https://docs.djangoproject.com/en/1.10/topics/forms/modelforms/

Categories

Resources