I have a Comment Form for my django project, which has a two columns: Author, Text.
I would like to make a author to be the currently looged user and be not able to edit that value. Is there a way to do it?
Here are my codes
forms.py
class CommentForm(forms.ModelForm):
author = forms.CharField(label = "名前", max_length=10,
widget=forms.TextInput(attrs={'style': 'position: relative;left: 0px;'}))
class Meta:
model = Comment
fields = ('author', 'text',)
views.py
def add_comment_to_post(request, pk):
post = get_object_or_404(Post, pk=pk)
if request.method == "POST":
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save(commit=False)
comment.post = post
comment.save()
return redirect('Post-detail', pk=post.pk)
else:
form = CommentForm()
return render(request, 'blog/add_comment_to_post.html', {'form': form})
models.py
class Comment(models.Model):
post = models.ForeignKey('blog.Post', on_delete=models.CASCADE, related_name='comments')
author = models.CharField(max_length=200)
text = models.TextField()
created_date = models.DateTimeField(default=timezone.now)
approved_comment = models.BooleanField(default=False)
def approve(self):
self.approved_comment = True
self.save()
def __str__(self):
return self.text
Related
Comments are saving to DB but not linking to Post, unless I manually go to Admin page and link.
MODELS.PY
class Post(models.Model):
title = models.CharField(max_length=50)
description = models.CharField(max_length=50)
info = models.TextField(max_length=2000)
slug = models.SlugField(null=True, unique=True, max_length=300)
created = models.DateField(null=True, auto_now_add=True)
approved = models.BooleanField(default=False, blank=True)
id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False)
class Comment(models.Model):
post = models.ForeignKey(Post, related_name="comments", on_delete=models.CASCADE, null=True)
name = models.CharField(max_length=50, verbose_name="Name")
comment = models.TextField(max_length=500, verbose_name="Comment")
created = models.DateField(null=True, auto_now_add=True)
approved = models.BooleanField(default=False, blank=True)
id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False)
FORMS.PY
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ['name','comment']
VIEWS.PY
def create_comment(request, slug):
form = CommentForm()
post = Post.objects.get(slug=slug)
if request.method == "POST":
form = CommentForm(request.POST)
comment = form.save()
comment.post = post
comment.save()
messages.success(request, 'Your comment was successfully submitted!')
return render(request, 'post.html', {'post': post, 'form':form})
return render(request, 'post.html', {'post': post, 'form':form})
From Admin page I can add comment and manually link to post, but from frontend form, comment is created and saved to DB but not linked to any post. Any idea what I'm doing incorrectly?
Where does this review object instance come from, woudn't it be the comment object?
Also, check if the the form is valid:
def create_comment(request, slug):
form = CommentForm()
post = Post.objects.get(slug=slug)
if request.method == "POST":
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save()
comment.post = post
comment.save()
messages.success(request, 'Your comment was successfully submitted!')
return render(request, 'post.html', {'post': post, 'form':form})
return render(request, 'post.html', {'post': post, 'form':form})
I am currently trying to create a form where users get to fill in their details after creating an account. The idea is that every user, after registration, gets redirected to this form page to fill it out. To achieve this, i'm using foreign keys.However it doesn't save to database.
models.py
class User(AbstractUser):
pass
def __str__(self):
return self.username
class Detail(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, null=False, default="")
first_name = models.CharField(max_length=200, default="")
last_name = models.CharField(max_length=255, default="")
class Meta:
verbose_name_plural = "Detail"
def __str__(self):
return self.first_name+ " "+self.last_name
forms.py
class Details(forms.ModelForm):
class Meta:
model = Detail
fields = "__all__"
widgets={
"user": forms.TextInput()
}
views.py
def details(request):
if request.method =="POST":
form = Details(request.POST)
if form.is_valid():
detail = form.save(commit=False)
detail.user = request.user
detail.first_name = detail.first_name.lower()
detail.last_name = detail.last_name.lower()
detail.save()
return redirect("admin:index")
else:
form = Details(initial={"user":request.user.username})
return render(request, "details.html", {"form":form})
You need to exclue user field from ModelForm like this
form.py
class Details(forms.ModelForm):
class Meta:
model = Detail
fields = "__all__"
exclude =["user"]
views.py
def details(request):
if request.method =="POST":
form = Details(request.POST)
if form.is_valid():
detail = form.save(commit=False)
detail.user = request.user
detail.first_name = detail.first_name.lower()
detail.last_name = detail.last_name.lower()
detail.save()
return redirect("admin:index")
else:
form = Details()
return render(request, "details.html", {"form":form})
My English is not good.. Hope you understand that..
I(beginner) use django and python, and I try to upload multiple files.
finally i find working code but It is difficult to apply to the original code
What am I doing wrong?
(form.py, model.py is same each other)
working ex code(views.py)
def a(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
files = request.FILES.getlist("files")
if form.is_valid():
for f in files:
file_instance = Upload(file_upload=f)
file_instance.save()
return render(request, 'single_pages/about_me.html', {'form':form,})
# return HttpResponse(" File uploaded! ")
else:
form = UploadFileForm()
return render(request, 'single_pages/about_me.html', {'form': form})
my Spaghetti code(views.py)
def a(request, pk):
if request.method == 'POST':
comment_form = CommentForm(request.POST, request.FILES)
files = request.FILES.getlist('files')
if comment_form.is_valid():
comment = comment_form.save(commit=False)
comment.post = post
comment.author = request.user
comment.save()
for f in files:
file_instance = Comment(file_upload=f)
file_instance.save()
return redirect(comment.get_absolute_url())
else:
return redirect(post.get_absolute_url())
forms.py
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = {'content', 'file_upload', 'head_image'}
files = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True}))
models.py
class Comment(models.Model):
post = models.ForeignKey(Post, on_delete=models.CASCADE)
author = models.ForeignKey(User, on_delete=models.CASCADE)
content = models.TextField()
head_image = models.ImageField(upload_to='blog/images/%Y/%m/%d/', blank=True)
file_upload = models.FileField(upload_to='blog/files/%Y/%m/%d/', blank=True)
created_at = models.DateTimeField(auto_now_add=True)
modified_at = models.DateTimeField(auto_now=True)
def __str__(self):
return f'{self.author}::{self.content}'
def get_absolute_url(self):
return f'{self.post.get_absolute_url()}#comment-{self.pk}'
def get_file_name(self):
return os.path.basename(self.file_upload.name)
def get_file_ext(self):
return self.get_file_name().split('.')[-1]
What should I do..
thank you very much
here user i want user and userprofile. useing exclude. when i add userprofile error 'WSGIRequest' object has no attribute 'userprofile'
modelform
class ProductForm(forms.ModelForm):
class Meta:
model = Product
fields = ('categories', 'title', 'description', 'image', 'price')
exclude = ('user','userprofile')
view
#login_required
def productpost(request):
form = ProductForm()
if request.method == "POST":
form = ProductForm(request.POST, request.FILES)
if form.is_valid():
form = form.save(commit=False)
form.user = request.user
form.userprofile = request.userprofile
form.save()
return success(request)
else:
print("The Form Is Invalid")
return render(request, 'product/postproduct.html', {'form': form})
Model
class Product(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
userprofileinfo = models.ForeignKey(UserProfileInfo, on_delete=models.CASCADE)
categories = models.ForeignKey(Categories, on_delete=models.CASCADE)
title = models.CharField(max_length=255)
description = models.TextField()
image = models.FileField()
price = models.IntegerField()
pub_date = models.DateTimeField('date published', auto_now_add=True)
def __str__(self):
return self.title
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
i create simple page where i can add article (title, text and category). When i do it on 'site administration everything is ok', but when i add it on page i can't choose category.
http://i.stack.imgur.com/4Nxzb.jpg
I choose category, for example like on this screen but my article do not have this category after i save it (article is uncategorized).
I created forms.py file and i done it like this:
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ('title', 'text', 'categories')
How must i change 'categories' here to make it usable?
models.py:
from django.db import models
from django.utils import timezone
class Category(models.Model):
name = models.CharField('Nazwa Kategorii', max_length=100)
slug = models.SlugField('Odnośnik', max_length=100)
icon = models.ImageField('Ikonka Kategorii', upload_to='icons',
blank=True)
class Meta:
verbose_name = "Kategoria"
verbose_name_plural = "Kategorie"
def __unicode__(self):
return self.name
class Post(models.Model):
author = models.CharField(max_length=25, blank=True, null=True)
title = models.CharField(max_length=200)
slug = models.SlugField('Odnośnik', max_length=255)
text = models.TextField()
published_date = models.DateTimeField(
default=timezone.now)
categories = models.ManyToManyField(Category, verbose_name='Kategorie')
def publish(self):
self.published_date = timezone.now()
self.save()
def __unicode__(self):
return self.title
And from views.py my view
def post_new(request):
if request.method == "POST":
form = PostForm(request.POST)
if form.is_valid():
post = form.save(commit=False)
post.author = request.user
post.save()
return redirect('blog.views.post_detail', pk=post.pk)
else:
form = PostForm()
return render(request, 'blog/post_edit.html', {'form': form})
When you save a form using commit=False you should call the save_m2m() method of the form:
post = form.save(commit=False)
post.author = request.user
post.save()
form.save_m2m()
Another, more elegant, solution is to pass the instance with preset field to the form's constructor. Is this case you don't need to use the commit=False argument:
form = PostForm(request.POST, instance=Post(author=request.user))
if form.is_valid():
post = form.save()
return redirect('blog.views.post_detail', pk=post.pk)