Notes should be showed only for the author - django

In my note taking project, I want to do so, that notes should be showed only for the author of the object. I am trying to solve this problem for 3 days. But, I could not solve this. Please Help! Thanks in an advance
view.py
#login_required(login_url='login')
def index(request):
tasks = Task.objects.all()
if request.method=='POST':
form = TaskForm(request.POST)
if form.is_valid():
obj = form.save()
obj.owner = request.user
obj.save()
return redirect('/')
form = TaskForm()
user = request
context = {
'tasks' : tasks,
'form':form,
'obj':obj
}
return render(request, 'list.html',context)
models.py
class Task(models.Model):
title = models.CharField(max_length=200)
completed = models.BooleanField(default=False)
created = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title

Your Task will need a ForeignKey to the user model, to keep track who created the task, so:
from django.conf import settings
class Task(models.Model):
title = models.CharField(max_length=200)
completed = models.BooleanField(default=False)
created = models.DateTimeField(auto_now_add=True)
owner = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE
)
I think in that case it is better to recreate the migration file that creates the table for the Task model.
Now that we have an owner of the Tasks, we can filter with:
#login_required(login_url='login')
def index(request):
tasks = Task.objects.filter(owner=request.user)
if request.method=='POST':
form = TaskForm(request.POST, request.FILES)
if form.is_valid():
form.instance.owner = request.user
obj = form.save()
return redirect('/')
else:
form = TaskForm()
context = {
'tasks' : tasks,
'form': form
}
return render(request, 'list.html', context)

Related

Django modeform choose date

I'm doing a to-do web app and I want user to input deadline and I have DateTimeField for it, but user can write whatever they want, but I want them to choose a legit date.
models:
class Task(models.Model):
title = models.CharField(max_length=50)
completed = models.BooleanField(default=False)
uploaded = models.DateTimeField(auto_now_add=True)
deadline = models.DateTimeField(null=True)
forms:
class TaskForm(forms.ModelForm):
title = forms.CharField(widget= forms.TextInput(attrs={'placeholder':'Add new task...'}))
class Meta:
model = Task
fields = '__all__'
views:
def TaskView(request):
tasklist = Task.objects.all()
tasks = Task.objects.order_by('uploaded')
form = TaskForm()
if request.method == 'POST':
form = TaskForm(request.POST)
if form.is_valid():
form.save()
return redirect('/')
context = {
'tastlist': tasklist,
'tasks': tasks,
'form': form,
}
return render(request, "pages/index.html", context)

Django actual value in choice field form

I have models like this:
class Projects(models.Model):
project = models.CharField(max_length=150, blank=True, null=True)
def __str__(self):
return self.project
class Profile(models.Model):
user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE)
project = models.ForeignKey(Projects, on_delete=models.CASCADE, null=True, blank=True)
def __str__(self):
return self.user.username
I also made a form in which I want to change current Project assigned Profile:
class ProjectForm(ModelForm):
class Meta:
model = Profile
fields = [
'project'
]
My view looks like this:
def change_project(request, user):
user = User.objects.filter(username=user)[:1].get()
profile = Profile.objects.get(user=user)
form = ProjectForm(request.POST, instance=profile)
if request.method == 'POST':
if form.is_valid():
form.save()
context = {'form': form}
return render(request, 'datafiller/change_project.html', context)
I can change the project using this form, but every time I want to do it again the form looks like this
How can I show in the form the current project instead of "------"?
You should not ground the ProjectForm in case you render the form with a GET requuest:
from django.shortcuts import get_object_or_404
def change_project(request, user):
profile = get_object_or_404(Profile, user__username=user)
if request.method == 'POST':
form = ProjectForm(request.POST, instance=profile)
if form.is_valid():
form.save()
else:
form = ProjectForm(instance=profile)
return render(request, 'datafiller/change_project.html', {'form': form})

Django: Create profile page creates everything except Multiple Choice Field in the database

I am using the same form for profile_edit and create_profile functionality. It is updating the multi-choice values in the profile_edit page but does not create in create_profile.
Below is the form code in forms.py
class ProfileForm(ModelForm):
full_name = forms.CharField(required=True)
current_position = forms.CharField(required=True)
about_me = forms.Textarea(attrs={'required':True})
topic_name = forms.ModelMultipleChoiceField(Topic.objects.all())
class Meta:
model = Profile
fields =(
"full_name",
"current_position",
"about_me",
"topic_name",
)
Below is the views.py for profile creation
def create_profile(request, user_id):
if request.method == "POST":
form = ProfileForm(request.POST)
if form.is_valid():
form = form.save(commit=False)
user = get_object_or_404(User, id=user_id)
form.user = user
print(form.topic_name.all()) # Prints empty queryset
form.save()
return redirect("profile_view", user_id=user_id)
else:
context = {"form": form}
return render(request, "profile/create_profile.html", context)
else:
form = ProfileForm()
context = {
"form": form
}
return render(request, "profile/create_profile.html", context)
Below is Model.py
class Topic(models.Model):
topic = models.CharField(max_length=12)
def __str__(self):
return self.topic
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True,)
full_name = models.CharField(max_length=60, null=True)
current_position = models.CharField(max_length=64, null=True)
about_me = models.TextField(max_length=255, null=True)
topic_name = models.ManyToManyField(Topic)
def __str__(self):
return self.full_name
Both create_profile and edit_profile templates are exactly the same.
It saves everything except Multichoice field.
When you do save(commit=False),
you need to use mymodelform.save_m2m() below save(commit=True) on your ModelForm,
because many to many relationships cannot be saved without an ID.
see this docs
so in your views.py
if form.is_valid():
profile = form.save(commit=False)
user = get_object_or_404(User, id=user_id)
profile.user = user
profile.save()
form.save_m2m()
return redirect("profile_view", user_id=user_id)

Django: Can't update database properly

models.py
class Post(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=500, verbose_name='Title')
post = models.TextField(verbose_name='Post')
post_time = models.DateTimeField()
update_time = models.DateTimeField()
exists = models.BooleanField(default=True)
def __str__(self):
return self.title
def save(self, *args, **kwargs):
if not self.id:
self.post_time = timezone.now()
# self.exists = True
self.update_time = timezone.now()
return super(Post, self).save(*args, **kwargs)
class PostEditHistory(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
post = models.ForeignKey(Post, on_delete=models.CASCADE)
title = models.CharField(max_length=500)
body = models.TextField()
edit_time = models.DateTimeField()
views.py
#login_required
def edit_post(request, username, post_id):
other_user = User.objects.get(username=username)
post = Post.objects.get(user=other_user.pk, pk=post_id)
prev_post = post
form = EditPostForm(data=request.POST or None, instance=post)
if form.is_valid():
PostEditHistory.objects.create(
user=request.user,
post=prev_post,
title=prev_post.title,
body=prev_post.post,
edit_time=prev_post.update_time
)
return redirect('single_post', username=username, post_id=post_id)
form.save()
context = {
'form': form
}
return render(request, 'blog_post/edit_post.html', context)
Before saving edited post, I'm trying to save the original post to PostEditHistory model. Every time a post is edited, it performs the same operations. But the code save the edited post to both Post and PostEditHistory model, and the original one gets lost. Help me to solve the problem.
Thanks in advance.
You are leaving of your function before use form.save()
return redirect('single_post', username=username, post_id=post_id)
form.save()
Change the position
form.save()
return redirect('single_post', username=username, post_id=post_id)
Suggestion: You should remove logic from views and handle it only in your models using functions...
Obs.: Dont use straight .objects.get() because if this do not exist will break your page and throw error, use filter to get the values without breaking and check it
class PostHistory(models.Model):
...
#staticmethod
def add_history(user, prev_post):
PostEditHistory.objects.create(
user=user,
post=prev_post,
title=prev_post.title,
body=prev_post.post,
edit_time=prev_post.update_time
)
#login_required
def edit_post(request, username, post_id):
...
post = Post.objects.filter(user=other_user.pk, pk=post_id).first()
prev_post = post if post else None
if form.is_valid():
PostEditHistory.add_history(request.user, prev_post)
form.save()
return redirect('single_post', username=username, post_id=post_id)

ValueError at /new_topic/ Cannot assign "<SimpleLazyObject: <django......>": "Topic.owner" must be a "User" instance

*Any time i insert data the above error occurred! *
# my views
def new_topic(request):
"""Add a new topic."""
if request.method != 'POST':
# No data submitted; create a blank form.
form = TopicForm()
else:
# POST data submitted; process data.
form = TopicForm(request.POST or None, request.FILES or None)
if form.is_valid():
new_topic = form.save(commit=False)
new_topic.owner = request.user #this where i think, i'm messing up!
new_topic.save()
return HttpResponseRedirect(reverse('learning_logs:topics'))
context = {'form': form}
return render(request, 'learning_logs/new_topic.html', context)
*model representing each Topic *
from django.contrib.auth.models import User
def upload_location(instance, filename):
return "%s/%s" %(instance.id, filename)
class Topic(models.Model):
"""A topic the user is learning about"""
text = models.CharField(max_length=200)
date_added = models.DateTimeField(auto_now_add=True)
image = models.ImageField()
height_field = models.IntegerField(default=0)
width_field = models.IntegerField(default=0)
owner = models.ForeignKey(User)
def __str__(self):
"""Return a string representation of the model."""
return self.text
Any help please!
Setting new_topic.owner = request.user should be fine if the user is logged in. However if the user is not logged in, then trying to assign an anonymous user would cause problems.
You can prevent this by using the login_required decorator, so that only logged-in users can access the view.
#login_required
def new_topic(request):
...