{% for projects in profile.project_set.all %} is not displaying anything - python

I have been learning django through a video course and in the video course the guys has used
{% for projectss in profile.project_set.all %}
{{ projectss.title }}
{% endfor %}
To display List of projects
Here is my Model.py file of project model
class Project(models.Model):
owner = models.ForeignKey(Profile, null=True, blank=True, on_delete=models.SET_NULL)
title = models.CharField(max_length=200)
id = models.UUIDField(default = uuid.uuid4 , primary_key=True, unique=True,
editable=False)
And Here is my Model.py of Users model
class Profile(models.Model):
user = models.OneToOneField(User,on_delete=models.CASCADE)
id = models.UUIDField(default=uuid.uuid4, primary_key=True, editable=False, unique=True)
View.py file
def userProfile(request, pk):
obj = Profile.objects.get(id=pk)
context = {'user': obj}
return render(request, 'users/user_profile.html', context)
The guy in video is doing the same thing its working for him but not me.

Look at the context you are passing to the view:
context = {'user': obj}
Change 'user' to 'profile' and you should be good.
def userProfile(request, pk):
obj = Profile.objects.get(id=pk)
context = {'profile': obj}
return render(request, 'users/user_profile.html', context)

Related

Django- How do I get the content of a model thats related to another?

So i'm creating a to-do app. How do I view the tasks linked to the board? Like I understand that the board needs to be the foreign key to task.
Here is my code so far:
Models.py
class Board(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
admin = models.ForeignKey(User, on_delete=models.CASCADE, related_name="Board")
name = models.CharField(max_length=200)
class Task(models.Model):
board = models.ForeignKey(Board, on_delete=models.CASCADE)
admin = models.ForeignKey(User, on_delete=models.CASCADE)
text = models.CharField(max_length=300)
complete = models.BooleanField(default=False)
assigned_to = models.CharField(max_length=30)
views.py
def board_post_detail(request, board_id):
obj = get_object_or_404(Board, id=board_id)
context = {"object": obj}
return render(request, 'boards/board_post_detail.html', context)
board_post_detail.html
{% block content %}
<h1>{{ object.name}}</h1>
<p>Created by {{object.admin.username }}</p>
{% endblock %}
If you want to find what tasks correspond to a specific instance of the Board class, then you should just make a query filtering by the instance:
obj = get_object_or_404(Board, id=board_id)
Task.objects.filter(board=obj)

Reverse not found with slug field

I am getting error while using get_absolute_url with slug field. Have tried few suggestions which are already exist in stack but didn't worked. Can anyone help me with this please.
Please refer this link for traceback.
models.py
Codes in models.
from django.urls import reverse
class Post(models.Model):
title = models.CharField(max_length=50)
user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1, on_delete=models.CASCADE)
draft = models.BooleanField(default=False)
publish = models.DateTimeField(auto_now=False, auto_now_add=False)
slug = models.SlugField(unique=True)
image = models.ImageField(upload_to=upload_location,
null=True,
blank=True,
width_field="width_field",
height_field="hieght_field")
hieght_field = models.IntegerField(default=0)
width_field = models.IntegerField(default=0)
content = models.TextField()
updates = models.DateTimeField(auto_now=True, auto_now_add=False)
timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
def get_absolute_url(self):
return reverse('post:detail', kwargs={'slug':self.slug})
Views.py
codes in views.
def post_list(request):
queryset_list = Post.objects.active()
if request.user.is_staff or request.user.is_superuser:
queryset_list = Post.objects.all()
query = request.GET.get('q')
if query:
queryset_list = queryset.filter(
Q(title__icontains=query)
).distinct()
context = {
'object_list':queryset_list,
'posts': page,
"page_request_var": page_request_var,
}
return render(request, 'index.html', context)
urls.py
urls mapping.
urlpatterns = [
path('detail/<slug:slug>/', views.detail, name='detail'),
]
html page
code in index.html
{% for obj in object_list %}
<div class="container">
<p class="card-text">{{obj.content|linebreaks|truncatechars:120}}</p>
View
<!-- {{obj.title}} -->
</div>
{% endfor %}
Error was occurring because of commented line in index.html {{obj.title}} after removing this line page is getting loaded perfectly and one more thing 'pk' should be replaced by slug in detail view to work detail page. def detail(request,slug): #slug replaced pk

How to show all foreign key attribute in Django template?

I want to fetch all the foreignkey table's attribute and show it in my HTML template. Here is my code in models, views and in the template:
models.py:
class OrderDashboard(models.Model):
title = models.CharField(max_length=100,default=None)
single_slug = models.SlugField(max_length=100, default=1)
description = models.TextField(max_length=1000)
thumb = models.ImageField()
date = models.DateField()
def __str__(self):
return self.title
class OrderScenario(models.Model):
webshop = models.CharField(max_length=100)
title = models.ForeignKey(OrderDashboard, default=None, on_delete=models.SET_DEFAULT)
order_qty = models.TextField(max_length=10)
order_date = models.DateField()
current_status = models.CharField(max_length=100)
ticket = models.CharField(max_length=200)
remark = models.TextField()
class Meta:
verbose_name_plural = "Scenario"
def __str__(self):
return self.webshop
Views.py:
def single_slug(request, single_slug):
report = OrderDashboard.objects.get(single_slug=single_slug)
return render(request, 'order_dashboard/report.html', {'report': report,
'OrderScenario': OrderScenario.objects.all})
I only want to view all the scenarios added in OrderScenario with respect to Title in OrderDashboard.
You should use backward relationship here; if you are passing the slug through the url, you can use:
views.py:
def single_slug(request, slug): # why you have self as the first argument?
report = OrderDashboard.objects.get(single_slug=slug)
return render(request, 'order_dashboard/report.html', {'report': report}
report.html:
{{ report.title }}
</p>Order Scenarios:</p>
{% for scenario in report.orderscenario_set.all %}
{{ scenario }}
{% endfor %}

One field (ManyToMany) in a Django ModelForm is not saving to database

My app is project management tool where users can add, edit, and view Projects. Projects have titles, summaries, and authors (users). Users have ManyToMany relationships with Projects.
Adding new Projects was working fine until I added an edit project view. I can still create a new Project or edit an existing one, and the new title and summary get saved to the database, but the selected authors do not get saved. Note that I can still go into the shell and add authors to a project manually.
Here are the Project and User models:
class MyUser(AbstractBaseUser):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
bank_id = models.CharField("researcher's four-letter bank id", null=True, max_length=4, unique=True)
#division = models.CharField(max_length=30, blank = True)
department = models.CharField(max_length=3, choices=DEPARTMENTS)
job_title = models.CharField("job title", max_length=30, choices=JOB_TITLES)
citations = models.IntegerField(null=True, blank=True)
institution = models.CharField(max_length=30, choices=DEPARTMENTS, blank=True)
created_on = models.DateTimeField(auto_now_add=True)
updated_on = models.DateTimeField(auto_now=True)
#history = HistoricalRecords()
REQUIRED_FIELDS = ['email']
USERNAME_FIELD = 'username'
class Project(models.Model):
title = models.TextField('Title')
summary = models.TextField('Summary', default=DEFAULT_TEXT)
authors = models.ManyToManyField(MyUser)
internal_status = models.CharField('Internal Status', max_length = 20, choices = INTERNAL_STATUS,
default='wip')
external_status = models.CharField('External Status', max_length = 20, choices = EXTERNAL_STATUS,
blank=True)
mtp_goal = models.CharField(max_length = 50, choices = MTP_GOALS,
blank=True)
topics = ArrayField(models.CharField('Topics', max_length=30), size=4, null=True)
created_on = models.DateTimeField(auto_now_add=True, null=True)
updated_on = models.DateTimeField(auto_now=True, null=True)
history = HistoricalRecords()
views.py
def add_new(request):
if request.method == 'POST':
form = ProjectForm(request.POST)
if form.is_valid():
project = form.save(commit=False)
project.created_on = timezone.now()
project.save()
return redirect('project_profile', pk=project.pk)
else:
form = ProjectForm()
return render(request, 'add_new.html', {'form': form})
def edit_project(request, pk):
project = get_object_or_404(Project, pk=pk)
if request.method == 'POST':
form = ProjectForm(request.POST, instance=project)
if form.is_valid():
project = form.save(commit=False)
project.updated_on = timezone.now()
project.save()
return redirect('project_profile', pk=project.pk)
else:
form = ProjectForm(instance=project)
return render(request, 'edit_project.html', {'form': form})
forms.py:
from django import forms
from .models import Project, MyUser
class ProjectForm(forms.ModelForm):
class Meta:
model = Project
fields = ('title', 'authors', 'summary')
And finally, the add_project.html page (please excuse the horrific html):
<html>
<head>
<title>ResearchTracker</title>
</head>
<body>
<div>
<nav>
About us
Login
Admin
</nav>
</div>
<h1>New project</h1><br>
<form method="POST" class="post-form">{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="save btn btn-default">Save</button>
</form>
Go home
</body>
</html>
Since you use commit=False in save, you need to explicitly call save_m2m to save the many to many fields.
From the documentation:
Calling save_m2m() is only required if you use save(commit=False).
When you use a simple save() on a form, all data – including
many-to-many data – is saved without the need for any additional
method calls. For example:
You would do
project.save()
project.save_m2m()

How do I render ForeignKey fields in my template?

I'm making a comment system for my django app and i've been told it's best to make a seperate model for comment-voting. So i've done that and here's my models.py:
class Comment(models.Model):
user = models.ForeignKey(User, default=1)
destination = models.CharField(default='1', max_length=12, blank=True)
author = models.CharField(max_length=120, blank=True)
comment_id = models.IntegerField(default=1)
parent_id = models.IntegerField(default=0)
comment_text = models.TextField(max_length=350, blank=True)
timestamp = models.DateTimeField(default=timezone.now, blank=True)
def __str__(self):
return self.comment_text
class CommentScore(models.Model):
user = models.ForeignKey(User, default=1)
comment = models.ForeignKey(Comment, related_name='score')
upvotes = models.IntegerField(default=0)
downvotes = models.IntegerField(default=0)
def __str__(self):
return str(self.comment)
Here's my views.py where the comments are created:
def article(request, category, id):
name = resolve(request.path).kwargs['category']
for a, b in CATEGORY_CHOICES:
if b == name:
name = a
instance = get_object_or_404(Post, id=id, category=name)
allauth_login = LoginForm(request.POST or None)
allauth_signup = SignupForm(request.POST or None)
#comments
comment = CommentForm(request.POST or None)
ajax_comment = request.POST.get('text')
comment_length = len(str(ajax_comment))
#database_comment = get_object_or_404(Comments, comment_id=1)
comment_list = Comment.objects.filter(destination=id)
score = CommentScore.objects.filter(comment=comment_list)
if request.is_ajax():
if comment.is_valid():
comment = Comment.objects.create(comment_text=ajax_comment, author=str(request.user), destination=id)
print(comment)
comment.save()
score = CommentScore.objects.create(comment=comment)
score.save()
username = str(request.user)
return JsonResponse({'text': ajax_comment, 'text_length': comment_length, 'username': username})
else:
print(comment.errors)
context = {
'score': score,
'comment_list': comment_list,
'comment': comment,
'instance': instance,
'allauth_login': allauth_login,
'allauth_signup': allauth_signup
}
return render(request, 'article.html', context)
So the comment works fine, but as you can see a couple lines later i'm trying to then create a CommentScore instance to match with the comment. In my template, I've rendered each comment and it's fields (comment_text, author etc), but I want to render the upvotes field associated with that comment. How would I do this?
template
{% for i in comment_list %}
<div class='comment_div'>
<h3>{{ i.author }}</h3>
<p>{{ i.comment_text }}</p><br>
</div>
{% endfor %}
forms.py
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = [
'comment_text',
'id',
'author',
'destination',
]
In your view you have this line:
comment_list = Comment.objects.filter(destination=id)
so if you want to get to CommentScore that associated with Comment, you have to write like this on your view:
score = CommentScore.objects.filter(comment=comment_list)
filter expects multiple variable so you can access to upvotes in your template, like this:
{% for i in score %}
{{i.upvotes}}
{% endfor %}
if you have single score instance, you have to use get parameter:
score = CommentScore.objects.get(comment=comment_list)
then you can you just
{{score.upvotes}}
on your template

Categories