model.py
class Question(models.Model):
user = models.ForeignKey(User)
title = models.CharField(max_length= 200)
description = models.TextField()
location = models.CharField(max_length=150)
tags = TaggableManager()
time = models.DateTimeField(auto_now_add=True)
def __unicode__(self):
return self.title
class Like(models.Model):
user = models.ManyToManyField(User, related_name='likes')
question = models.ForeignKey(Question)
date = models.DateTimeField(auto_now_add=True)
likecount = models.IntegerField(default=0)
urls.py
url(r'^$', ListView.as_view(queryset= Question.objects.all(),
template_name="index.html")),
index.html
{%for question in object_list %}
{%for user_liked in question.like_set.all%}
{% if user.username in user_liked.user.all%} `<!--if current logged in user in Like model user m2m field-->`
<button type="button" class="btn btn-disable" name= {{question.id}}"id="request">Liked </button> <!--disable like button-->
{%else%}
<button type="button" class="btn btn-enable" name= {{question.id}}"id="request">Like </button> <!--enable like button-->
{%endif%}
{%endfor%}
{%endfor%}
Problem is if template tag block doesn't work.
It works, but like_set.all is not list of usernames, but list of users. Therefore check if user.username is in list of users fails. Check if user is in like_set.all.
Related
I am adding a simple review function on my Social platform Django project, where Users can write a review on another user's profile. But after posting the review, it's only showing on the profile page of the user that I'm currently signed in to.
This is my models.py
` class Review(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
reviewmsg = models.TextField(null=True, blank=True)
updated = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now_add=True)
def __str__(self):
return str(self.reviewmsg)`
views.py
` def userProfile(request, pk):
user = User.objects.get(id=pk)
rooms = user.room_set.all()
reviews = user.review_set.all()
if request.method == 'POST':
review = Review.objects.create(
user=request.user,
reviewmsg=request.POST.get('reviewmsg')
)
return redirect('user-profile', pk=user.id)
context = {'user':user, 'rooms':rooms, 'reviews':reviews}
return render(request, 'pages/profile.html', context)`
excerpt from my profile page template
` <div>
{% for review in reviews %}
<div class="comment-sect" style="margin-top: 0.5rem;">
<div class="comment-photo" style="margin: auto;">
<a href="{% url 'user-profile' review.user.id %}">
<div class="profile-photo">
<img src="{{review.user.avatar.url}}">
</div>
</a>
</div>
<div class="comment-info" style="width: 300px;">
<small>#{{review.user}}</small>
<small>{{review.created|timesince}} ago </small>
<p style="margin-bottom:0;">{{review.reviewmsg}}</p>
</div>
</div><!--end of comment-sect-->
{% endfor %}
<div class="comment-form" style="margin-top: 0.5rem; text-align:center;">
<form method="POST" action="">
{% csrf_token %}
<div>Submit a Review
<input type="text" name="reviewmsg" placeholder="What do you think about this User?"/>
</div>
</form>
</div>`
EDITED
As mentioned by #lain Shelvington, I agree that I need to add another ForeignKey to my models. I tried updating the models.py to:
user = models.ForeignKey(User, on_delete=models.CASCADE)
class Review(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
profile = models.ForeignKey(Profile, on_delete=models.SET_NULL, null=True)
reviewmsg = models.TextField(null=True, blank=True)
updated = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now_add=True)
def __str__(self):
return str(self.reviewmsg)
and views.py to:
user = User.objects.get(id=pk)
rooms = user.room_set.all()
reviews = user.review_set.all()
if request.method == 'POST':
review = Review.objects.create(
user=request.user,
profile=user,
reviewmsg=request.POST.get('reviewmsg')
)
return redirect('user-profile', pk=user.id)
context = {'user':user, 'rooms':rooms, 'reviews':reviews}
return render(request, 'pages/profile.html', context)
but ended up with error:
ValueError at /profile/7/
Cannot assign "<User: celeste>": "Review.profile" must be a "Profile" instance
I have created a project with 2 apps:
1.Core for items model to be viewed in home page
2. Score with posts model
The home.html is mainly for listing items by designers, the designers/users might have posts as well so I am trying to show buttons for designers/userswho have posts and hide them if the users don't have posts.
I have added the code but the button for the designers/usersposts is still showing.
App No. 1 CORE
Core Models.py
class Item(models.Model):
designer = models.ForeignKey(
User, on_delete=models.CASCADE)
title = models.CharField(max_length=100)
Core views.py
class HomeView(ListView):
model = Item
paginate_by = 12
template_name = "home.html"
ordering = ['-timestamp']
# context_object_name = 'posts' (I have commented this part as it is from Score Models
when included the home page become 404 error)
Here is the Core URL
urlpatterns = [
path('', HomeView.as_view(), name='home'),
App No.2 Score
Score Models.py:
class Post(models.Model):
designer = models.ForeignKey(User, on_delete=models.CASCADE)
design = models.ImageField(
blank=False, null=True, upload_to=upload_design_to)
Home.html template
{% if post.designer %}
<a href="{% url 'score:user-posts' item.designer.username %}">
<button style="margin-top: 10px;text-transform: none;" button type="button"
class="btn btn-success btn-sm btn-block">
Check my posts</button>
</a>
{% else %}
Show Nothing
{% endif %}
I dont know what might the reason for now working I have used the same logic with other templates but didnt succeed in this trial
You can adjust this solution to your project.
model.py:
class User(models.Model):
user = models.CharField(max_length=50)
def __str__(self):
return str(self.user)
class Item(models.Model):
designer = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=100)
def __str__(self):
return str(self.title)
class Post(models.Model):
designer = models.ForeignKey(User, on_delete=models.CASCADE)
design = models.CharField(max_length=15, blank=False, null=True)
def __str__(self):
return str(self.design)
views.py:
def myview(request):
msg = ''
qs1 = Item.objects.all().values_list('designer')
qs2 = Post.objects.all().values_list('designer')
for result in list(set(qs1) & set(qs2)):
msg += '<a href = "www.google.com"><button style = "margin-top: 10px;text-transform: none;" type = "button" ' \
'class ="btn btn-success btn-sm btn-block" > Check my posts : {0}</button></a><br>'.\
format(User.objects.get(pk=result[0]))
context = {'msg': msg}
return render(request, 'stack/home.html', context)
home.html
<body>
{% autoescape off %}
{{ msg }}
{% endautoescape %}
</body>
This may be a simple answer but after days of searching I cannot seem to figure out the correct way to achieve this.
I have a template where I want to show all the questions that are related to an assessment that has been assigned to a user. I thought that I could use the results from:
ResponseDetails = AssessmentResponse.objects.prefetch_related('assessment').filter(id=response_id)
by looking into the object and grabbing the assessment_id which I could then pass into the next query-set as a filter but I couldn't get that to work.
Problem: Because the view doesn't filter based on the assessment_id found in the AssessmentResponse model, it gives me every question in the AssessmentQuestion model.
An answer would allow me to actually have a good nights sleep trying to figure it out.
Views
def UpdateAssessmentResponse(request, response_id):
ResponseDetails = AssessmentResponse.objects.prefetch_related('assessment').filter(id=response_id)
QuestionList = AssessmentQuestion.objects.all()
ChoiceList = AssessmentQuestionChoice.objects.all()
context = {
"ResponseDetails":ResponseDetails,
"QuestionList":QuestionList,
"ChoiceList": ChoiceList,
#"ID" : ID,
}
return render(request, "assessment/assessment_response_update.html", context)
Template
{% if QuestionList and ResponseDetails%}
{% csrf_token %}
{% for question in QuestionList %}
<p> {{ question.question_text }} </p>
{% for choice in ChoiceList %}
{% if choice.question_id == question.pk %}
<fieldset id="group1">
<div class="custom-control custom-radio custom-control-inline">
<input type="radio" class="custom-control-input" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" />
<label class="custom-control-label" for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label>
</div>
<fieldset id="group1">
{% endif %}
{% endfor %}
{% endfor %}
<div class="card-footer">
<input type="submit" value="Submit" class="btn btn-primary" />
</div>
{% else %}
<p>There are currently no questions for this assessment.</p>
{% endif %}
Models:
class AssessmentForm(models.Model):
name = models.CharField(max_length=400)
description = models.TextField()
created = models.DateTimeField(auto_now_add=True)
is_published = models.BooleanField()
due_date = models.DateField(default=datetime.now, blank=True, null=True)
def __str__(self):
return self.name
class AssessmentResponse(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT)
assessment = models.ForeignKey('AssessmentForm', on_delete=models.CASCADE)
created = models.DateTimeField(auto_now_add=True)
last_update = models.DateTimeField(auto_now=True)
def get_absolute_url(self):
return reverse('assessment_response_detail', args=[str(self.id)])
#def get_assessment_id(self):
# return self.assessment
def __str__(self):
return self.user
class AssessmentQuestionType(models.Model):
type = models.CharField(max_length=30)
def __str__(self):
return self.type
class AssessmentQuestionCategory(models.Model):
name = models.CharField(max_length=200)
assessment = models.ForeignKey('AssessmentForm', on_delete=models.CASCADE)
def __str__(self):
return self.name
class AssessmentQuestionSubCategory(models.Model):
name = models.CharField(max_length=200)
parent_category = models.ForeignKey('AssessmentQuestionCategory', on_delete=models.CASCADE)
def __str__(self):
return self.name
#CHOICES_HELP_TEXT = _(u"""The choices field is only used if the question type if the question type is 'radio', 'select', or 'select multiple' provide a comma-separated list of options for this question .""")
class AssessmentQuestion(models.Model):
question_type = models.ForeignKey('AssessmentQuestionType', on_delete=models.PROTECT)
question_text = models.TextField()
is_required = models.BooleanField()
category = models.ForeignKey('AssessmentQuestionCategory', on_delete=models.PROTECT, blank=True, null=True)
subcategory = models.ForeignKey('AssessmentQuestionSubCategory', on_delete=models.PROTECT, blank=True, null=True)
assessment = models.ForeignKey('AssessmentForm', on_delete=models.CASCADE)
def __str__(self):
return self.question_text
class AssessmentQuestionChoice(models.Model):
question = models.ForeignKey(AssessmentQuestion, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200, blank=True, null=True)
def __str__(self):
return self.choice_text
class AssessmentAnswer(models.Model):
text = models.CharField(max_length=1024)
question = models.ForeignKey('AssessmentQuestion', on_delete=models.CASCADE)
response = models.ForeignKey('AssessmentResponse', on_delete=models.PROTECT)
def __str__(self):
return self.text
Figured it out! Objects.filter is a lazy query so it wasn't actually available to my other query-set to use as a filter. Solved it by using objects.get instead.
I try to make a simple illustration of my question click to view
I have a task to make a quiz.
I try to solve a problem :
Taking items in cycle by "Metrix" model there I get Questions for Quiz
It is no way to get data from "User_metrix" model while using {% for item in metrix_list %} cycle by "Metrix" model.
My models:
from django.db import models
from django.conf import settings
class Metrix(models.Model):
title = models.CharField(max_length=256, verbose_name='Question')
metrix_category = models.ForeignKey(
'category',
related_name='Question_category',
on_delete=models.CASCADE,
verbose_name='Category',
)
is_published = models.BooleanField(default=False)
def __str__(self):
return self.title
class Category(models.Model):
title = models.CharField(max_length=256,
verbose_name='Question_category')
is_published = models.BooleanField(default=False)
def __str__(self):
return self.title
class User_metrix(models.Model):
user = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
related_name="user_metrix",
verbose_name='User')
metrix = models.ForeignKey('Metrix', on_delete=models.CASCADE,
verbose_name='Question')
value = models.DecimalField(max_digits=12, decimal_places=2,
verbose_name='Value')
My view:
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from metrix.models import Metrix, User_metrix
#login_required
def metrix_view(request, pk=None):
metrix_category = {
'pk': 4
}
#Get questions by category
metrix_list = Metrix.objects.filter(is_published=True,
metrix_category__pk=pk)
context = {
'metrix_list': metrix_list
}
return render(request, 'metrix/metrix.html', context)
Template:
I list the questions in template, by cycle "metrix_list"
How to save answers to values and if answers exists return values to template?
<!--cycle for metrix-->
{% for item in metrix_list %}
<div class="row metrix_quiestion_line justify-content-center">
<div class="metrix_quiestion">
<h2>
{{ item }}
</h2>
</div>
<div class="metrix_value">
<input type="number" name="{{ item.id }}" value=" ">
</div>
</div>
{% endfor %}
<!--END cycle -->
I'm new to Django! so could be way wrong :)
I'm building an event app.
I'm trying to add/remove users to a 'host' list in my 'EventProfile' model from 'MyGuest', i basically want a different host list in each 'EventProfile', i'm using a class method.
I can add/delete each object to each specific EventProfile model in the admin but cant seem to do it on my site?
I keep getting this error "get() returned more than one Host -- it returned 2!"
Heres my code please help :)
Models.py
class MyGuest(models.Model):
users = models.ManyToManyField(User)
current_user = models.ForeignKey(User, related_name='add_myguest', null=True)
#classmethod
def make_myguest(cls, current_user, new_myguest):
myguest, created = cls.objects.get_or_create(current_user=current_user)
myguest.users.add(new_myguest)
#classmethod
def lose_myguest(cls, current_user, new_myguest):
myguest, created = cls.objects.get_or_create(current_user=current_user)
myguest.users.remove(new_myguest)
class Host(models.Model):
users = models.ManyToManyField(User)
current_user = models.ForeignKey(User, related_name='add_myguest', null=True)
#classmethod
def make_host(cls, current_user, new_host):
host, created = cls.objects.get_or_create(current_user=current_user)
host.users.add(new_host)
#classmethod
def lose_host(cls, current_user, new_host):
host, created = cls.objects.get_or_create(current_user=current_user)
host.users.remove(new_host)
class EventProfile(models.Model):
event = models.CharField(max_length=100)
greeting = models.CharField(max_length=100)
invitee = models.CharField(max_length=100)
description = models.CharField(max_length=100)
date = models.CharField(max_length=100)
start_time = models.CharField(max_length=100)
finish_time = models.CharField(max_length=100)
venue = models.CharField(max_length=100)
myguest = models.ForeignKey(MyGuest, related_name='add_myguest_profile', null=True)
host = models.ForeignKey(Host, related_name='add_host_profile')
def __str__(self):
return self.event
Views.py
def event_change_hosts(request, operation, pk):
new_host = User.objects.get(pk=pk)
if operation == 'add':
Host.make_host(request.user, new_host)
return redirect('events:event_myguests_profile')
elif operation == 'remove':
Host.lose_host(request.user, new_host)
return redirect('events:event_hosts')
urls.py
url(r'^event_hosts/(?P<pk>\d+)$', views.event_hosts, name= 'event_hosts'),
url(r'^connect_hosts/(?P<operation>.+)/(?P<pk>\d+)/$', views.event_change_hosts, name= 'event_change_hosts'),
template.py
{% for host in hosts %}
<div class="alert alert-info" role="alert">
<a href="{% url 'accounts:profile_with_pk' pk=user.pk %}" type="button"
class="btn btn-primary left"
class="btn btn-default btn-lg active">{{ host.username }}
<a href="{% url 'events:event_change_hosts' operation='remove' pk=user.pk %}">
<button type="button" class="btn btn-danger pull-right btn-s">Remove</button>
</a>
</div>
{% endfor %}