Biểu mẫu Alter Django
Aug 19 2020
Tôi có thể điều chỉnh mã của mình như thế nào để người dùng không thể chọn người dùng khác cho bài đăng mới. Tôi muốn làm cho nó để người dùng đã đăng nhập được tự động thêm vào với tư cách là tác giả.
Tôi đã thử đặt phần trường trong views.py thành chỉ trường nội dung, tuy nhiên nó không hoạt động
models.py
class post(models.Model):
author = models.ForeignKey(User, on_delete=models.CASCADE)
content = models.CharField(max_length=140)
views.py
class CreatePostView(CreateView):
model = post
fields = '__all__'
template_name = 'users/create.html'
Myform.html
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Login">
</form>
Trả lời
1 bkrop Aug 18 2020 at 23:50
class CreatePostView(CreateView):
model = post
template_name = 'users/create.html'
fields = ['content']
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
MukheemMohammed Aug 18 2020 at 23:51
Bạn có thể chèn giá trị người dùng theo cách thủ công bằng cách sử dụng request.user.username(hoặc) Hãy xem phần này . Câu trả lời của người hỏi nằm ở dưới cùng.
AbhishekBera Aug 19 2020 at 00:37
Có 3 điều bạn cần làm:
- Bảo vệ trang để những người dùng ẩn danh không thể truy cập trang đó, Sử dụng
LoginRequiredMixin - Xóa người dùng khỏi các trường
- Nhập người dùng hiện tại vào biểu mẫu đã gửi sau khi biểu mẫu được đăng, sử dụng
form_validphương pháp
from django.views.generic.edit import CreateView
from django.contrib.auth.mixins import LoginRequiredMixin
class CreatePostView(LoginRequiredMixin, CreateView):
model = Post
fields = ["content"]
template_name = "create.html"
def form_valid(self, form):
form.instance.user = self.request.user
return super().form_valid(form)