Display the data of User role in Django Template - python

I have a django model with User roles. I want to be able to get the first_name, last_name and other details of a user role displayed other a template when another user role or the same user role is logged in.
This is my models
class User(AbstractUser):
is_customer = models.BooleanField(default=False)
is_employee = models.BooleanField(default=False)
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
#username = models.CharField(unique = False , max_length=100)
#email = models.CharField(unique = True , max_length=100 )
nin = models.IntegerField(unique = False , null=True)
avatar = models.ImageField(null= True, default="avatar.svg")
is_landlord = models.BooleanField(default=False)
objects = UserManager()
REQUIRED_FIELDS= []
class Landlord(models.Model):
user = models.OneToOneField(User,related_name="prop_owner", null= True, on_delete=models.CASCADE)
bio = models.TextField(null=True)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS= []
objects = UserManager()
def __str__(self):
return str(self.user)
This is my views
def propertySingle(
request,
pk,
is_landlord,
):
user = User.objects.get(is_landlord=is_landlord)
property = Property.objects.get(id=pk)
properties = Property.objects.all()
images = Image.objects.filter(property=property)
context = {
"property": property,
"properties": properties,
"images": images,
'user':user,
}
return render(request, "base/page-listing-single.html", context)
Template
<div class="sl_creator">
<h4 class="mb25">Property Owned By:</h4>
<div class="media">
<img class="mr-3" style="width: 90px; height:90px;" src="{{request.user.avatar.url}}" alt="avatar">
<div class="media-body">
<h5 class="mt-0 mb0">{{user.last_name}} {{request.user.first_name}}</h5>
<a class="text-thm" href="#">View other Listings by {{property.landlord.last_name}} {{property.user.is_landlord.first_name}}

You can do all this in the template if all you are testing for if the current user is a landlord, because you can always refer to the request.user User instance to see who is accessing the page.
<h4 class="mb25">Property Owned By:</h4>
{% if request.user.is_landlord %}
...#show landlord details
{% else %}
This information only available to landlords
However, you have a problem in your view. You are using get (returns one record) to get all the users who have is_landlord = True (which will be many). This will give you an error. Also, you may get confused about which user you are referring to in your template as there ius already a rquest user in your tempalte by default. Try something like this
def propertySingle(
request,
pk,
):
# get the property and all info about the landlord
#now in the template we can access property.landlord with no extra db calls
property = Property.objects.get(id=pk).select_related('landlord')
properties = Property.objects.all()
images = Image.objects.filter(property=property)
context = {
"property": property,
"properties": properties,
"images": images,
}
return render(request, "base/page-listing-single.html", context)
Now in your template you can do the following
Template
<div class="sl_creator">
<h4 class="mb25">Property Owned By:</h4>
{% if request.user == property.landlord %}
<!-- the user is THE landlord for this property -->
You: {{request. user.last_name}}, {{request.user.first_name}}
{% endif %}
{% if request.user.is_landlord %}
<!-- the user is A landlord, but not necessarily for this property -->
<div class="media">
<img class="mr-3" style="width: 90px; height:90px;" src="{{property.landlord.avatar.url}}" alt="avatar">
<div class="media-body">
<a class="text-thm" href="#">View other Listings by {{property.landlord.last_name}} {{property.landlord.first_name}}
</div>
</div>
{% else %}
<div class="media-body">
This information only available to landlords
</div>
{%end if %}

Related

Why is my send interest request not appearing? It's like the variables I defined are not working

ValueError at /HomeFeed/slug-1/detail/
The QuerySet value for an exact lookup must be limited to one result using slicing.
interest_list = InterestList.objects.get(interestuser=account)
There are multiple errors in my code and this error is only one of them...
In my project, people get to post blog posts, and people that read the blog post and like it can send an "interest request" maybe to comment more about the blog post and the maker of the blog post can accept or reject that interest request. Its basically something like a friend request, except the request you are sending are your "thoughts" in a form. I am trying to tilt my code while building my relationship system to fit into this "submit interest system".
I have 4 models in total, one for the posts, one is my user account model, one is the interest list and the second one is the interestrequest.
There are 4 major functions, accept the request, decline the request (if you are the blog post maker) and send and unsend the request (if you are the interested user)
I find it difficult to link interest to blog post to account model such that the interest is sent to that particular blog post.
There are 5 things to note if you want to understand my code
is_myself = True means you are looking at your own post
is_others = True means you are looking at the accepted request's member's post (aka your interest has been accepted)
is_others = False can mean 3 things
Other people has sent a request to your post
you have sent a request to other people's post
no one has sent anything (which will be the default likely)
models.py
class InterestList(models.Model):
interestuser = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="interestuser")
interests = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, related_name="interests")
def __str__(self):
return self.interestuser.username
def add_interest(self, account):
if not account in self.interests.all():
self.interests.add(account)
self.save()
def remove_interest(self, account):
if account in self.interests.all():
self.interests.remove(account)
class InterestRequest(models.Model):
interestsender = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="interestsender")
interestreceiver = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="interestreceiver")
is_active = models.BooleanField(blank=False, null=False, default=True)
timestamp = models.DateTimeField(auto_now_add=True)
my_name = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
my_thoughts = models.TextField(max_length=5000, null=False, blank=False)
def __str__(self):
return self.interestsender.username
def accept(self):
receiver_interest_list = InterestList.objects.get(user=self.interestreceiver)
if receiver_interest_list:
receiver_interest_list.add_interest(self.interestsender)
sender_interest_list = InterestList.objects.get(user=self.interestsender)
if sender_interest_list:
sender_interest_list.add_interest(self.interestreceiver)
self.is_active = False
self.save()
def decline(self):
self.is_active = False
self.save()
def cancel(self):
self.is_active = False
self.save()
class BlogPost(models.Model):
chief_title = models.CharField(max_length=50, null=False, blank=False)
body = models.TextField(max_length=5000, null=False, blank=False)
likes = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='blog_posts', blank=True)
slug = models.SlugField(blank=True, unique=True)
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
class Account(AbstractBaseUser):
email = models.EmailField(verbose_name="email", max_length=60, unique=True)
username = models.CharField(max_length=30, unique=True)
views.py
def detail_blog_view(request, slug):
context = {}
#need to import a package get_object_or_404. return object or throw 404
blog_post = get_object_or_404(BlogPost, slug=slug)
total_likes = blog_post.total_likes()
liked = False
if blog_post.likes.filter(id=request.user.id).exists():
liked = True
context['liked'] = liked
context['blog_post'] = blog_post
context['total_likes'] = total_likes
account = Account.objects.all()
context['account'] = account
try:
interest_list = InterestList.objects.get(interestuser=account)
except InterestList.DoesNotExist:
interest_list = InterestList(interestuser=account)
interest_list.save()
interests = interest_list.interests.all()
context['interests'] = interests
is_myself = True
is_others = False
request_sent = InterestRequestStatus.NO_REQUEST_SENT.value
interest_requests = None
user = request.user
if user.is_authenticated and blog_post.author != user:
is_myself = False
if interests.filter(pk=user.id):
is_others = True
else:
is_others = False
#CASE 1: THEY HAVE SENT A REQUEST TO YOU
if get_interest_request_or_false(sender=account, receiver=user) != False:
request_sent = InterestRequestStatus.THEM_SENT_TO_YOU.value
context['pending_interest_request_id'] = get_interest_request_or_false(sender=account, receiver=user).id #or you can use pk instead of id
#CASE 2: REQUEST SENT FROM YOU TO THEM
if get_interest_request_or_false(sender=account, receiver=user) != False:
request_sent = InterestRequestStatus.YOU_SENT_TO_THEM.value
#CASE 3: NTH HAS BEEN SENT
else:
request_sent = InterestRequestStatus.NO_REQUEST_SENT.value
elif not user.is_authenticated:
is_myself = False
#when you are looking at your own post
else:
try:
interest_requests = InterestRequest.objects.filter(receiver=user, is_active=True)
except:
pass
context['is_myself'] = is_myself
context['is_others'] = is_others
context['request_sent'] = request_sent
context['interest_requests'] = interest_requests
context['BASE_URL'] = settings.BASE_URL
return render(request, 'HomeFeed/detail_blog.html', context)
utils.py
from HomeFeed.models import InterestRequest
def get_interest_request_or_false(interestsender, interestreceiver):
try:
return InterestRequest.objects.get(interestsender=interestsender, interestreceiver=interestreceiver, is_active=True)
except InterestRequest.DoesNotExist:
return False
interest_request.py
from enum import Enum
class InterestRequestStatus(Enum):
NO_REQUEST_SENT = -1 #no request sent in that blog post to you or to them. this is the constant, how it should normally look like for most posts
THEM_SENT_TO_YOU = 0
YOU_SENT_TO_THEM = 1
template html
{% if request.user.is_authenticated %}
<div class="d-flex flex-column mb-4" >
<!-- THEM to YOU -->
{% if request_sent == 0 %}
<div class="card m-2 p-4" >
<div class="d-flex flex-row align-items-center">
<span class="friend-text align-items-center mr-2">Accept Member Request</span>
<span id="id_cancel_{{id}}" class="decline-friend-request material-icons p-1" onclick='triggerDeclineFriendRequest("{{pending_friend_request_id}}")'>cancel</span>
<span id="id_confirm_{{id}}" class="confirm-friend-request material-icons p-1" onclick='triggerAcceptFriendRequest("{{pending_friend_request_id}}")'>check</span>
</div>
</div>
{% endif %}
<div class="card m-2 px-4 pb-4">
<!-- Cancel Friend Request / Send Friend Request / Remove Friend -->
{% if is_others == False and is_myself == False %}
<!-- You sent them a request -->
{% if request_sent == 1 %}
<div class="d-flex flex-column align-items-center pt-4">
<button class="btn btn-danger" id="id_cancel_friend_request_btn">
Cancel Interest Request
</button>
</div>
{% endif %}
<!-- No requests have been sent -->
{% if request_sent == -1 %}
<div class="d-flex flex-column align-items-center pt-4">
<button class="btn btn-primary" id="id_send_friend_request_btn">
Send Interest Request
</button>
</div>
{% endif %}
{% endif %}
{% if is_others %}
<div class="dropdown pt-4 m-auto">
<button class="btn btn-secondary dropdown-toggle friends-btn" type="button" id="id_friends_toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Accepted Members
</button>
<div class="dropdown-content" aria-labelledby="id_friends_toggle">
<a class="dropdown-item" href="#" onclick="removeFriend('{{id}}', onFriendRemoved)">Remove Member</a>
</div>
</div>
{% endif %}
{% endif %}
urls.py
path('<slug>/detail/', detail_blog_view, name= "detail"),
THE PROBLEM
This error you described in the beginning is appearing because you are tryng to query a model using a queryset. In your views.py in your detail_blog_view you have a line that says:
account = Account.objects.all()
Here the value of the account variable is a queryset of ALL the available accounts, then you are trying to query your database using this queryset with a get method here:
interest_list = InterestList.objects.get(interestuser=account)
Since your interestuser field is a one2one relationship it can only accept a **single **object in the query while you are passing a queryset.
THE SOLUTION
All you have to do is instead of using account = Account.objects.all() write a query that would make the account variable store a single object value, for example:
account = request.user # if you are logged in and trying to get your own account
Pass a variable pk (of the user you want to get the list for) to the url path like this:
urlpatterns = [
path('detail_blog_view/<int:pk>/', views.detail_blog_view, name="detail_blog_view"),
]
then where you create links to your detail_blog_view pages write it something like this:
{{ user.username }} # here i'm passing a known user.pk from the context of the view that stores this template.
and in the end in your view query your account with the pk passed in the url like this:
account = Account.objects.get(pk=pk)

Why do I get either NoReverseMatch or FieldError

I am working on a project, and want to create a report on a film. (That it doesn´t exist) At the moment I only get error when I try to go to either film// or film//report. Can anybody help me?
When I try film//: NoReverseMatch; Reverse for 'film-report' with no arguments not found. 1 pattern(s) tried: ['film/(?P[0-9]+)/report$']
And film//report gives: FieldError; Unknown field(s) (reported) specified for Report
models.py
class Report(models.Model):
title = models.CharField(default="", max_length=100)
comment = models.TextField(default="")
reporter = models.ForeignKey(User, on_delete=models.CASCADE, related_name="Reporter")
# receiver = models.ForeignKey(
# User, on_delete=models.CASCADE, related_name="Receiver"
# )
reports = models.ForeignKey(Film, on_delete=models.CASCADE)
def __str__(self): # pragma: no cover
return f"{self.reporter.username} reports {self.reports.title}"
urls.py
urlpatterns = [
path("", views.films_view, name="board-home"),
path("film/add", FilmAddView.as_view(), name="film-add"),
path("film/<int:pk>/", FilmDetailView.as_view(), name="film-detail"),
path("film/<int:pk>/report", FilmReport.as_view(), name="film-report")
]
views.py
class FilmReport(LoginRequiredMixin, UpdateView):
model = Report
fields = ["title", "reported"]
# def __str__(self):
# return self.title
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
This should be the page where I can click on "Report", and then be redirected to a report page.
film_detail.html
{% extends "board/base.html" %}
{% block content %}
<article class="media content-section">
<img class="rounded-circle film-img" src="/media/{{object.poster}}">
<!-- Mulighet for å ha en "add review"-knapp på siden der hvor filmene vises. -->
<i class="material-icons right">rate_review</i>add review
<i class="material-icons right">report</i>report
<!-- <a onclick="myFunction()" class="waves-effect waves-light red darken-4 btn"><i class="material-icons right">report</i>report</a>
<script>
function myFunction() {
var txt;
if (confirm("Are you sure you want to report this film?")) {
$("#inline2").fadeIn(300);
$(".overlay-fixed").fadeIn(300);
$(".fancybox-opened").fadeIn(300);
return false;
} else {}
}
</script> -->
<div class="media-body">
<h2 class="film-title">{{ object.title }}</h2>
<p class="film-plot">{{ object.plot }}</p>
</div>
</article>
{% endblock content %}
In your class FilmReport you can just take the fileds from your model Report.
The field "reported" does not exist. You should take "reporter" or "reports".
You can just try the urls you have specified, either film nor film/report are valid urls. You need to have at least one Film object in your database to get access to the url
film/1/report.

django, does not display the avatar in the comments

I extended standart django user model by one-to-one field. Made news block, and added comments there. In comments i cant display user avatar from UserProfile model, cause dont understand how correctly ask database for it D;. Here my code:
main/models.py
from django.db import models
from django.utils import timezone
from django.contrib import auth
from django.contrib.auth.forms import User
from django.shortcuts import render, redirect
from profiles.models import UserProfile
# Create your models here.
class News(models.Model):
news_title = models.CharField(max_length=250)
news_body = models.TextField(max_length=2000, blank=True)
author = models.ForeignKey('auth.User', on_delete=models.CASCADE)
image = models.FileField()
published_date = models.DateTimeField(blank=True, null=True)
def publish(self, request):
self.published_date = timezone.now()
self.save()
return redirect('index')
def __str__(self):
return self.news_title
class Comment(models.Model):
news = models.ForeignKey('main.News', related_name='comments',
on_delete=models.CASCADE)
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
profiles/models.py
class UserProfile(models.Model):
JEW_CHOICE = (
('Да', 'Да'),
('Нет', 'Нет'),
)
MF_CHOICE = (
('М', 'М'),
('Ж', 'Ж')
)
user = models.OneToOneField(User, on_delete=models.CASCADE)
country = models.CharField(max_length=100, default='', blank=True)
city = models.CharField(max_length=100, default='', blank=True)
description = models.CharField(max_length=500, default='', blank=True)
website = models.URLField(default='', blank=True)
avatar = models.ImageField(default='', blank=True)
gender = models.CharField(max_length=100, choices = MF_CHOICE, default = 'М', blank=True)
jew = models.CharField(max_length=100, choices = JEW_CHOICE, default = 'Да', blank=True)
def __str__(self):
return self.user.username
#receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
UserProfile.objects.get_or_create(user=instance)
#receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
instance.userprofile.save()
#property
def avatar_url(self):
if self.avatar and hasattr(self.avatar, 'url'):
return self.avatar.url
main/views.py (meme_detail is the view, where should be comments with user info)
def meme_detail(request, pk):
news = get_object_or_404(News, pk=pk)
if request.method == "POST":
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save(commit=False)
comment.author = request.user
comment.news = news
comment.save()
return redirect('main:meme_detail', pk=news.pk)
else:
form = CommentForm()
return render(request, 'main/meme_detail.html', {'news': news, 'form': form,})
meme_detail.html (news template with comments)
{% extends 'main/base.html' %}
{% block body %}
<h2>{{news.news_title}}</h2>
<img src='{{news.image.url}}' name='image' width='500px;'><br>
{{news.news_body}} <br><br>
<div class="row">
<div class="col">
<b>{{news.author}}</b>
</div>
<div class="col">
<i>{{news.published_date}}</i>
</div>
</div>
<div class="underline"></div>
<h3>Комментарии:</h3><br>
{% for comment in news.comments.all %}
<div class="row">
<div class="col-"><img src="{{ userprofile.avatar.url }}" alt="user-avatar" width="100px" height="100px"></div>
<div class="col">{{ comment.text }}</div>
</div>
<div class="row">
<div class="col"><strong>{{ comment.author }}</strong></div>
<div class="col">{{ comment.created_date}}</div>
</div>
<div class="underline"></div>
<br>
{% empty %}
<p>Пока ещё нет комментариев :(</p>
{% endfor %}
{% if request.user.is_authenticated %}
<div class="row">
<form method="POST">
{% csrf_token %}
{{form.text}}<br><br>
<a class="btn btn-success" href="{% url 'main:meme_detail' pk=news.pk %}"><button class='btn btn-success'>Добавить коммент! </button></a>
</form>
</div>
{% else %}
<i>Вы не можете писать комментарии, необходимо зарегистрироваться!</i>
{% endif %}
{% endblock %}
So, in this template, where "userprofile.avatar.url" should be object reference on User avatar. I tryed a lot of things, but it always the same:not displaying
You should do:
<img src="{{ comment.author.userprofile.avatar.url }}" alt="user-avatar" width="100px" height="100px">
Your comment has a foreign key to User (author), and User has a one to one field to UserProfile, which is the one that has the avatar attribute.
Also another tip:
You shouldn't really reduce the image in CSS (width: 100px; height: 100px;), but instead use a tool that allows you to create thumbnails of images. I use sorl-thumbnail and can't recommend it enough.
The reason is that if every user uploads a 1000x1000 image, you are downloading those big images that you don't really need, hence your site will be slower.
Maybe you should try accesing the User object in the template, not the Userprofile.
<img src="{{ user.userprofile.avatar.url }}" ...

Django save only first form of formset

I've looked through every similar question (and tried them), but still couldn't find answer.
I have two models:
class Project(models.Model):
author = models.ForeignKey(settings.AUTH_USER_MODEL, default=1)
name = models.CharField(max_length=120, verbose_name = "Название проекта")
url = models.URLField(max_length=120, unique=True, verbose_name = "Полный адрес сайта")
robots_length = models.CharField(max_length=5, default=0)
updated = models.DateTimeField(auto_now=True, auto_now_add=False)
timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
def __unicode__(self):
return self.name
def __str__(self):
return self.name
def get_absolute_url(self):
from django.urls import reverse
return reverse('projects:detail', args=[str(self.id)])
class ProjectPage(models.Model):
page_project = models.ForeignKey(Project, on_delete=models.CASCADE)
page_url = models.URLField(verbose_name = "Адрес страницы")
page_title = models.CharField(max_length=300, blank=True, verbose_name = "meta-title",default="")
page_description = models.CharField(max_length=300, blank=True, verbose_name = "meta-description",default="")
page_h1 = models.CharField(max_length=300, blank=True, verbose_name = "Заголовок h1",default="")
def __unicode__(self):
return self.page_url
def __str__(self):
return self.page_url
For each model there is a form:
class ProjectFormUpdate(forms.ModelForm):
class Meta:
model = Project
fields = [
"name",
"url",
]
widgets = {
'name': forms.TextInput(attrs={'placeholder': 'Произвольное название'}),
}
class ProjectPageForm(forms.ModelForm):
class Meta:
model = ProjectPage
fields = [
'page_project',
'page_url',
'page_title',
'page_description',
'page_h1',
]
widgets = {
'page_project': forms.HiddenInput()
}
In views.py I have:
def projects_update(request, proj=None):
instance = get_object_or_404(Project, id=proj)
form = ProjectFormUpdate(request.POST or None, instance=instance)
formset_f = modelformset_factory(ProjectPage, form=ProjectPageForm, extra=3)
formset = formset_f(queryset=ProjectPage.objects.filter(page_project__id=proj), initial =[{'page_project': proj}])
if request.method == 'POST':
formset = formset_f(request.POST)
for formset_form in formset:
if formset_form.is_valid() and formset_form.has_changed():
formset_form.save()
if form.is_valid():
form.save()
context = {
'title': "Редактируем проект - "+instance.name,
'form': form,
'formset': formset,
'instance': instance,
}
return render(request, "projects_update.html", context)
And, finaly, html
<form method="POST" action="" class="create-form">
{{ formset.management_form }}
{% csrf_token %}
<div class="row">
<div class="col-lg-6 offset-lg-3 col-md-10 offset-md-1 col-xs-10 offset-xs-1 form-bg">
<h2>Общие данные</h2>
{{ form|crispy}}
<input type="submit" class="btn btn-success" value="Обновить проект" />
</div>
</div>
{% for formset_form in formset %}
<div class="row form-container">
<div class="col-lg-6 offset-lg-3 col-md-10 offset-md-1 col-xs-10 offset-xs-1 form-bg">
<h3>Страница {{forloop.counter}}</h3>
{{ formset_form|crispy}}
</div>
</div>
{% endfor %}
</form>
What I am trying to achieve is: when user enters a page, he gets a form with project name and project URL already filled in. So, he can correct them.
Below, I want to show a filled in form for every page allready created for this project and several empty forms for creating new.
What happens is all initial data is displayed correctly, but when I fill several empty forms - only first empty form is saved each time.
Here is how it was solved:
Included errors properly.
Saw that second to last form lack required field (hiddenInput)
Made changes in view so it looks like:
formset_f = modelformset_factory(ProjectPage, form=ProjectPageForm, extra=3)
formset = formset_f(queryset=ProjectPage.objects.filter(page_project__id=proj), initial =[{'page_project': proj}, {'page_project': proj}, {'page_project': proj}])
Initial values now match number of extra forms - every form got it's own foreign key.
Probably there is a better solution, but the the problem is found and solved for me!
My problem was that when I tried to render every form of the formset manually I added an unneded <form></form> html element
wrong:
{ form.management_form }}
{% for form in formset %}
<form class="form-class">
{{form.name}}
</form>
right:
{ form.management_form }}
{% for form in formset %}
<div class="form-class">
{{form.name}}
</div>
After that change my forms were recognized correctly.

Most effective way to create Attending Event option button [Django/Python]?

Trying to implement an "Attending" button. It's simple (or so I thought). A user with a profile clicks "Attending", and a checkmark appears. Can't quite get this to work on the Django/Python side of things. ie: Put that user who clicked 'Attending' into the attendee(list) within the Event.
Template:
{% if is_attending %}
<button class="btn" disabled="disabled">
<i class="icon-ok-sign"></i> Attending
</button>
{% else %}
<form class="left" method="POST" action="/profile/event/{{ event.id }}/">
{% csrf_token %}
<input type="hidden" name="profile_id" value="user" />
<button class="btn">
Attending
</button>
</form>
{% endif %}
Models:
class Event(models.Model):
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
owner = models.ForeignKey(User, null=True, blank=True, on_delete=models.SET_NULL)
name = models.CharField(max_length=200)
location = models.CharField(max_length=200)
start_date = models.DateTimeField(auto_now=False, auto_now_add=False)
end_date = models.DateTimeField(auto_now=False, auto_now_add=False)
about = models.TextField(null=True, blank=True)
attendees = models.ManyToManyField(Profile, null=True, blank=True)
View:
#login_required
def attending_event(request, event_id):
event = get_object_or_404(Event, id=event_id)
if request.method == 'POST':
try:
id = request.POST.get('profile_id')
attendee = Profile.objects.get(id=id)
relationship = Event.objects.create(attendees__user=attendee)
is_attending = True
except:
pass
return HttpResponseRedirect('/profile/event/' + event_id + '/')
else:
if not Event.objects.filter(attendees__user=request.user).exists():
is_attending = False
data = {
'is_attending': is_attending
}
return render_to_response('profiles/event.html', data, context_instance=RequestContext(request))
Maybe there's something I'm missing and can't see what it is I'm doing wrong. But if anyone could offer some insight/advice about how to go about completing this; I'd really appreciate it.
Just giving you hint, change it according to your needs
Template:
{% if is_attending %}
<button class="btn"> # this code will executes when is_attending is True
<i class="icon-ok-sign"></i> Attending
</button>
{% else %}
<form class="left" method="POST" action="/profile/event/{{ event.id }}/"> # Always user reverse urls instead of Hard coded
{% csrf_token %}
<input type="hidden" name="profile_id" value="{{profile.id}}" />
<button class="btn">
Attending
</button>
</form>
{% endif %}
View:
#login_required
def event_profile(request, event_id)
event = get_object_or_404(Event, id=event_id)
if request.method == 'POST':
try:
id = request.POST.get('profile_id')
attendee = Profile.objects.get(id=id)
relationship = Event.objects.create(attendees__user=attendee, .... ) # set other variable you want
is_attending = True
else:
# check in your event either your profile user is already attending or not? and set is_attending variable according to it
data = {
'is_attending': is_attending,
....
}
return render_to_response('my_template.html',
data,
context_instance=RequestContext(request))

Categories