display data of form 1 on form 2 django SessionWizardView - python

Django SessionWizardView: User fills in form 1 and then, some of the values of the fields in form one are needed to calculate a number. This number must then be displayed on form 2. I don't know how I can grab the data of form 1 and use it to make a calculation and then display it on form 2.
models.py
class CapsProd(models.Model):
production = models.OneToOneField(Productions, on_delete=models.CASCADE, primary_key=True)
amount_of_caps = models.IntegerField()
conc_per_cap = models.FloatField()
conc_per_tab = models.FloatField()
amount_of_weighed_tabs = models.IntegerField()
mass_all_tabs = models.FloatField()
required_mass_powder = models.FloatField()
weighed_mass_powder = models.FloatField()
caps_size = models.FloatField(choices=CHOICES,)
forms.py
class CapsProdForm1(forms.ModelForm):
class Meta:
model = CapsProd
fields = [
'production',
'amount_of_caps',
'conc_per_cap',
'conc_per_tab',
]
class CapsProdForm2(forms.ModelForm):
class Meta:
model = CapsProd
fields = [
'amount_of_weighed_tabs',
'mass_all_tabs',
'required_mass_powder',
'weighed_mass_powder',
'caps_size',
]
urls.py
app_name = 'caps_prod'
urlpatterns = [
path('', views.CapsProdWizardView.as_view([CapsProdForm1, CapsProdForm2]), name="add_new"),
]
views.py
class CapsProdWizardView(SessionWizardView):
template_name = "caps_prod/prod_form.html"
html
{% extends "base.html" %}
{% load django_bootstrap5 %}
{% block body_block %}
<h1>
Step {{ wizard.steps.step1 }} of {{ wizard.steps.count }}
</h1>
<form class="custom-form" method="post">
{% csrf_token %}
<!-- {% bootstrap_form form %} -->
{{ wizard.management_form }}
{% if wizard.form.forms %}
{{wizard.form.management_form }}
{% for form in wizard.form.forms %}
{% bootstrap_form form %}
{% endfor %}
{% else %}
{% bootstrap_form wizard.form %}
{% endif %}
{% if wizard.steps.prev %}
<button type="submit" class="btn btn-primary" value="{{ wizard.steps.first }}">First step</button>
<button type="submit" class="btn btn-primary" value="{{ wizard.steps.prev }}">Previous step</button>
{% endif %}
<input type="submit" value="Submit">
</form>
{% endblock %}
Thanks!

Related

Using fields from a aggregated QuerySet in a django template

So I got a QuerySet result from an aggregate function to display in a low-spec eBay clone of mine. But my problem is displaying certain fields in the Django template as I want, for example, I want to display the highest bidder's username and bid. When I call the whole object itself like so {{winner}}, then it displays. But when I try to access its fields like so {{winner.user_id.username}}, I get no output although the QuerySet does execute.
When I try to get a field like so (winner.user_id.username):
When I only call winner:
models.py
from django.contrib.auth.models import AbstractUser
from django.db import models
CATEGORIES = [
('Appliances', 'Appliances'),
('Tech', 'Tech'),
('Gaming', 'Gaming'),
('Fashion', 'Fashion'),
('Sports and Fitness','Sports and Fitness'),
('Other','Other'),
("Hygiene and Medicine","Hygiene and Medicine"),
("Stationery","Stationery"),
('Decor', 'Decor'),
('Furniture','Furniture'),
('Cars and Mechanical Things','Cars and Mechanical Things'),
("Tools","Tools")
]
# Create models here
class User(AbstractUser):
pass
class Auction_Listing(models.Model):
user_id = models.IntegerField(default=1)
list_title = models.CharField(max_length=64)
desc = models.TextField(max_length=600)
img_url = models.URLField(max_length=200, null=True, blank=True)
start_bid = models.IntegerField()
category = models.CharField(choices=CATEGORIES, max_length=35, null=True, blank=True)
active = models.BooleanField(default=True)
def __str__(self):
return f"ID:{self.id}, {self.list_title}: {self.desc}, {self.start_bid} posted by user:{self.user_id} in Category:{self.category}, url:{self.img_url}"
class Bids(models.Model):
user_id = models.ForeignKey('User', on_delete=models.CASCADE)
auctions = models.ForeignKey('Auction_Listing', on_delete=models.CASCADE, default=1,related_name='bidauc')
bid = models.IntegerField()
def __str__(self):
return f"ID:{self.id}, Bid {self.bid} posted by user:{self.user_id} on auction {self.auctions}"
class Auction_Comments(models.Model):
user_id = models.ForeignKey('User', on_delete=models.CASCADE)
comment = models.TextField(max_length=324, default='N/A')
auctions = models.ForeignKey('Auction_Listing', on_delete=models.CASCADE, default=1,related_name='comauc')
def __str__(self):
return f"ID:{self.id}, Comment: {self.comment} posted by user:{self.user_id} on auction {self.auctions}"
class Watchlist(models.Model):
user_id = models.ForeignKey('User', on_delete=models.CASCADE)
auctions = models.ForeignKey('Auction_Listing', on_delete=models.CASCADE, default=1, related_name='watchauc')
def __str__(self):
return f"ID:{self.id}, user:{self.user_id} on auction {self.auctions}"
views.py
def render_listing(request, title):
if request.method == "POST":
form = BidForm(request.POST)
bid = int(request.POST['new_bid'])
listing = Auction_Listing.objects.get(list_title=title)
comments = Auction_Comments.objects.filter(auctions=listing)
if bid <= listing.start_bid:
error = True
else:
error = False
listing.start_bid = bid
listing.save()
new_bid = Bids(user_id=request.user, auctions=listing, bid=bid)
new_bid.save()
return render(request, 'auctions/listing.html', {
"listing": listing,
"form": form,
"comments": comments,
"error": error,
"comform": CommentForm()
})
else:
form = BidForm()
comform = CommentForm()
listing = Auction_Listing.objects.get(list_title=title)
comments = Auction_Comments.objects.filter(auctions=listing)
high_bid = Bids.objects.filter(auctions=listing).aggregate(maximum=Max("bid"))
winner = Bids.objects.filter(auctions=listing, bid=high_bid['maximum'])
print(winner)
return render(request, 'auctions/listing.html', {
"listing": listing,
"form": form,
"comments": comments,
"error": False,
"comform": comform,
"winner": winner
})
template's code:
{% extends "auctions/layout.html" %}
{% load static %}
{% block title %} Listing: {{listing.list_title}} {% endblock %}
{% block body %}
{% if listing.active %}
<h2>{{ listing.list_title }}</h2>
<div class='listing'>
{% if listing.img_url == "" or listing.img_url == None %}
<a href='#'><img src="{% static 'auctions/img404.png' %}" class='img-fluid'></a>
{% else %}
<a href='#'><img src="{{ listing.img_url }}" class="img-fluid" alt='image of {{ listing.list_title }}'></a>
{% endif %}
<p>
{{ listing.desc }}
</p>
<p>
Current Bid: ${{ listing.start_bid }}
</p>
<p>Category: {{ listing.category }}</p>
<p></p>
{% if user.is_authenticated %}
<div class="bid">
<a href='{% url "watch" listing.list_title %}' class='btn btn-primary'>Add to/Remove from Watchlist</a>
{% if listing.user_id == user.id %}
<a href='{% url "close" listing.list_title %}' class='btn btn-primary'>Close Auction</a>
{% endif %}
</div>
<div class="bid">
<h3>Bid:</h3>
<form method="POST" action='{% url "renlist" listing.list_title %}'>
{% csrf_token %}
{{form}}
<button type="submit" class='btn btn-primary'>Make New Bid</button>
{% if error %}
Please enter a bid higher than the current bid.
{% endif %}
</form>
</div>
{% else %}
<p><a href='{% url "register" %}' class='register'>Register</a> to bid on this item and gain access to other features</p>
{% endif %}
</div>
<div class="listing">
<h3>Comments:</h3>
{% if user.is_authenticated %}
<div id='comform'>
<h4>Post a Comment</h4>
<form method="POST" action="{% url 'commentadd' %}">
{% csrf_token %}
{{comform}}
<button type="submit" class="btn btn-primary">Post Comment</a>
</form>
</div>
{% endif %}
<p>
{% for comment in comments %}
<div class="comment">
<h4>{{comment.user_id.username}} posted:</h4>
<p>{{comment.comment}}</p>
</div>
{% empty %}
<h4>No comments as of yet</h4>
{% endfor %}
</p>
</div>
{% else %}
<h2>This auction has been closed</h2>
<div>
<a href='{% url "watch" listing.list_title %}' class='btn btn-primary'>Add to/Remove from Watchlist</a>
</div>
<p>{{winner.user_id.username}}</p>
{% endif %}
{% endblock %}
Thanks in advance for the help!
Kind Regards
PrimeBeat
This will give a QuerySet. You can see in your second image.
A QuerySet represents a collection of objects from your database.
winner = Bids.objects.filter(auctions=listing, bid=high_bid['maximum'])
You need to iterate over that QuerySet, get whatever data you want and show it in your template.
{% for win in winner %}
<p>{{ win.user_id.username }}</p>
{% endfor %}

Django autocomplete light: no input field

I've installed "Django autocomplete light" and now following this tutorial: http://django-autocomplete-light.readthedocs.io/en/master/tutorial.html
Here is my code so far:
setting.py
INSTALLED_APPS = [
'dal',
'dal_select2',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.gis',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'accounts',
'directory',
'geopy',
]
models.py
class Company(models.Model):
CATEGORY_CHOICES = (
('P', 'Parrucchiere'),
('Ce', 'Centro estetico'),
)
self_key = models.ForeignKey('self', null=True, blank=True, related_name='related_self_key_models')
city = models.ForeignKey(City, on_delete=models.CASCADE)
name = models.CharField(max_length=200)
address = models.CharField(max_length=255)
telephone = models.CharField(max_length=200)
category = models.CharField(max_length=1, choices=CATEGORY_CHOICES, null=True)
email = models.CharField(max_length=255, null=True, blank=True)
vat = models.CharField(max_length=200, null=True, blank=True)
location = gis_models.PointField(u"longitude/latitude", geography=True, blank=True, null=True)
gis = gis_models.GeoManager()
objects = models.Manager()
slug = AutoSlugField(populate_from='name', null=True)
def __str__(self):
return self.name
views.py
class CompanyAutocomplete(autocomplete.Select2QuerySetView):
def get_queryset(self):
# Don't forget to filter out results depending on the visitor !
if not self.request.user.is_authenticated():
return Company.objects.none()
qs = Company.objects.all()
if self.q:
qs = qs.filter(name__istartswith=self.q)
return qs
forms.py
class AddCompanyForm(forms.ModelForm):
vat = forms.CharField(required=True)
class Meta:
model = Company
fields = ('name','city','address','telephone','email','vat','self_key')
widgets = {
'self_key': autocomplete.ModelSelect2(url='company-autocomplete')
}
def clean_vat(self):
vat = self.cleaned_data['vat']
if Company.objects.filter(vat__iexact=vat).count() > 1:
raise ValidationError("L'attività digitata esiste già...")
return vat
urls.py
url(
r'^company-autocomplete/$',
autocomplete.Select2QuerySetView.as_view(model=Company),
name='company-autocomplete'
),
html
{% extends 'base.html' %}
{% load static %}
{% block title %}
<title>Aggiungi azienda | ebrand directory</title>
{% endblock title %}
{% block upper_content %}
<br style="line-height:25px"/>
<div class="google-card-full" style="width:auto; height:auto; text-align:center;">
<br style="line-height:25px"/>
<h1 class='title'><img style="width:auto; height:auto;" src='{% static "images/new_company.png" %}'> Aggiungi azienda</h1>
<hr/>
<br/>
<form method="post">
{% csrf_token %}
<table class='form-group' style="width:25%; margin:auto;">
{% for field in form.visible_fields %}
<tr>
<th style='text-align:left'>{{ field.label|capfirst }}:</th>
{% if forloop.first %}
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
{% endif %}
{{ field.errors.as_ul }}
<td style='text-align:right'>{{ field }}</td>
</tr>
{% endfor %}
</table>
<br/>
<button class="btn btn-raised btn-primary" type="submit"
style="background-color:#1A88B9;">Aggiungi</button>
</form>
<p style="height:5px"/>
<p><b>ATTENZIONE</b>: ebrand<sup>©</sup> si riserva di verificare l'autenticità dei dati<br/>
prima dell'inserimento dell'azienda all'interno del database.</p>
<p style="height:5px"/>
</div>
<h2 style='margin:0px 0px 15px 25px;'>Oppure...</h2>
<div class="google-card-full" style="width:auto; height:auto; text-align:center;">
<br style="line-height:25px"/>
<h1 class='title'><img style="width:auto; height:auto;" src='{% static "images/new_company.png" %}'> Reclama azienda esistente</h1>
<hr/>
<br/>
<form method="post">
{% csrf_token %}
<table class='form-group' style="width:25%; margin:auto;">
{% for field in form.visible_fields %}
<tr>
<th style='text-align:left'>{{ field.label|capfirst }}:</th>
{% if forloop.first %}
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
{% endif %}
{{ field.errors.as_ul }}
<td style='text-align:right'>{{ field }}</td>
</tr>
{% endfor %}
</table>
<br/>
<button class="btn btn-raised btn-primary" type="submit"
style="background-color:#1A88B9;">Aggiungi</button>
</form>
<p style="height:5px"/>
</div>
{% endblock %}
{% block middle_content %} {% endblock %}
{% block content %} {% endblock %}
{% block bottom_content %} {% endblock %}
The problem: 'self_key' field is not populated and also I cannot type (is not an input).
I have already looked at this question without result: Django autocomplete light: field not populated

Django survey with forms

I am building a survey tool and I'm wondering how would I continue with this or if my current solution is even the proper way to do it.
Admin of the page may add or remove questions from questionnaires, so if I have understood it, I can't use ModelForms to handle the form data?
A form may consist of 5 multichoice questions and 2 free text questions or any other amount of different types of questions so there isn't any fixed type of questionnaire
How do I then save the values of the form as I do not have a model to use?
Is this even possible to achieve without using a model for the form?
Thank you for any input in advance.
views.py
from django.shortcuts import render
from .models import Questionnaire, Question, Answer
def index(request):
all_questionnaires = Questionnaire.objects.all()
all_questions = Question.objects.all()
return render(request, 'questions/index.html', locals())
def questionnaire_detail(request, questionnaire_id):
questionnaire = Questionnaire.objects.get(id=questionnaire_id)
questions = Question.objects.filter(questionnaire=questionnaire)
return render(request, 'questions/questionnaire.html',
{'questionnaire': questionnaire, 'questions': questions})
def calculate(request):
if request.method == 'POST':
pass
models.py
from django.db import models
MC = 'MC'
CN = 'CN'
TX = 'TX'
CATEGORY = (
(MC, 'Multichoice'),
(CN, 'Choose N'),
(TX, 'Text'),
)
VALYK = '1'
VALKA = '2'
VALKO = '3'
VALNE = '4'
VALVI = '5'
MULTICHOICE = (
(VALYK, 'Least'),
(VALKA, 'Less than average'),
(VALKO, 'Average'),
(VALNE, 'More than average'),
(VALVI, 'Most'),
)
class Questionnaire(models.Model):
questionnaire_name = models.CharField(max_length=100,
verbose_name="Questionnaire",
null=False,
default=None,
blank=False)
def __str__(self):
return self.questionnaire_name
class Question(models.Model):
questionnaire = models.ManyToManyField(Questionnaire)
question_text = models.CharField(max_length=200,
verbose_name="Questionnaire name",
null=True,
default=None,
blank=True)
question_category = models.CharField(max_length=2,
verbose_name="Question category",
null=False,
choices=CATEGORY,
default=None,
blank=False)
def __str__(self):
return self.question_text
class Answer(models.Model):
question = models.ForeignKey(Question)
class MultiChoiceAnswer(Answer):
answer = models.IntegerField(choices=MULTICHOICE)
def __str__(self):
return self.answer
questionnaire.html
{% extends "questions/base.html" %}
{% block title_html %}
Questionnaire
{% endblock %}
{% block h1 %}
Questionnaire
{% endblock %}
{% block content %}
{% if questions|length > 0 %}
<form action="{% url "questions:calculate" %}" method="post">
{% csrf_token %}
{% for question in questions %}
{{ question.question_text }}<br>
{% if question.question_category == "MC" %}
<input type="radio" name="{{ question.id }}" value="1"> 1<br>
<input type="radio" name="{{ question.id }}" value="2"> 2<br>
<input type="radio" name="{{ question.id }}" value="3"> 3<br>
<input type="radio" name="{{ question.id }}" value="4"> 4<br>
<input type="radio" name="{{ question.id }}" value="5"> 5<br>
{% elif question.question_category == "CN" %}
<input type="checkbox" name="{{ question.id }}" value="a">a<br>
<input type="checkbox" name="{{ question.id }}" value="b">b<br>
{% elif question.question_category == "TX" %}
<textarea rows="4" cols="50" name="{{ question.id }}">Test</textarea><br>
{% endif %}
{% endfor %}
<input type="submit" value="Send" />
</form>
{% else %}
<span>No questions</span>
{% endif %}
{% endblock %}
This is the solution I ended up with. Edited it a bit to be more generic.
In the view there is checking if the form was loaded or submitted. If it was submitted, then check the validity of all of the forms. As there are multiple forms they are then made as formsets.
View
def answerpage(request, questionnaire_pk):
AnswerFormSet = formset_factory(AnswerForm, extra=0)
questions = Question.objects.filter(questionnaire=questionnaire_pk)
qname = Questionnaire.objects.get(id=questionnaire_pk)
if request.method == 'POST':
answer_formset = AnswerFormSet(request.POST)
if answer_formset.is_valid():
for answer_form in answer_formset:
if answer_form.is_valid():
instance = answer_form.save(commit=False)
instance.fieldValue = answer_form.cleaned_data.get('fieldValue')
instance.save()
return redirect('main:calcs')
else:
return redirect('main:home')
else:
quest_id = request.session.get('questionnaire_key', defaultValue)
question_data = [{'question': question,
'questionnaire_key': quest_id} for question in questions]
answer_formset = AnswerFormSet(initial=question_data)
combined = zip(questions, answer_formset)
context = {
'combined': combined,
'answer_formset': answer_formset,
'qname': qname,
}
return render(request, 'main/questionnaire.html', context)
The form is a modelform with the default widgets overwritten.
Form
class AnswerForm(forms.ModelForm):
class Meta:
model = QuestionAnswer
exclude = ['']
widgets = {
'field1': RadioSelect(choices=CHOICES, attrs={'required': 'True'}),
'field2': HiddenInput,
}
Webpage renders the values from the view in to a table. Management_form is needed to handle the formset values correctly.
Webpage
{% extends "main/base.html" %}
{% load static %}
{% block content %}
<link rel="stylesheet" href="{% static 'css/survey.css' %}">
<h1>{{ qname.questionnaire_text }}</h1>
<h2>{{ qname.description }}</h2>
<form method="post">{% csrf_token %}
{{ answer_formset.management_form }}
<table>
{% for question, form in combined %}
<tr><td style="width:65%">{{ question }}{{ question.question_type }}</td><td style="width:35%">{{ form.business_id }}{{ form.question }}{{ form.questionnaire_key }}{{ form.answer_text }}</td></tr>
{% endfor %}
</table>
<div class="buttonHolder">
<input type="submit" value="Save" id="next_button"/>
</div>
</form>
{% endblock %}

Custom Django Form Not Displaying - Using Wagtail

Wagtail Blog Site - Comment Model Form Issues
I'm creating a blog site, using Wagtail, and I've run in to a snag. I've added a Comment Model to my page, which I can add comments through the admin section and they display on the correct posts, but the comment form I've created is not displaying for some reason. Here's my relevant code. Any tips on where I went wrong would be greatly appreciated.
blog/models.py
class BlogPage(Page):
date = models.DateField("Post date")
intro = models.CharField(max_length=250)
body = RichTextField(blank=True)
#tag manager
tags = ClusterTaggableManager(through=BlogPageTag, blank=True)
#get feature image
def main_image(self):
gallery_item = self.gallery_images.first()
if gallery_item:
return gallery_item.image
else:
return None
search_fields = Page.search_fields + [
index.SearchField('intro'),
index.SearchField('body'),
]
content_panels = Page.content_panels + [
MultiFieldPanel([
FieldPanel('date'),
FieldPanel('tags'),
], heading="Blog information"),
FieldPanel('intro'),
FieldPanel('body'),
InlinePanel('gallery_images', label="Gallery images"),
]
def serve(self, request):
# Get current page
post = self
# Get comment form
form = CommentForm(request.POST or None)
# Check for valid form
if form.is_valid():
comment = form.save(commit=False)
comment.post = post
comment.save()
return redirect(request.path)
return render_to_response(self,
{
'post': post,
'form': form,
},
context_instance=RequestContext(request))
class Comment(models.Model):
post = models.ForeignKey(BlogPage, related_name='comments')
author = models.CharField(max_length=250)
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 __unicode__(self):
return self.text
def __str__(self):
return self.text
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ('author', 'text',)
blog_page.html
{% extends "base.html" %}
{% load wagtailcore_tags wagtailimages_tags %}
{% block body_class %}template-blogpage{% endblock %}
{% block content %}
<div class="section">
<div class="container">
<h1 class="title">{{ page.title }}</h1>
<p class="meta subtitle">{{ page.date }}</p>
{% with page.main_image as main_image %}
{% if main_image %}{% image main_image fill-500x300 %}{% endif %}
{% endwith %}
<p>{{ main_image.caption }}</p>
<div class="hero-body subtitle">{{ page.intro }}</div>
<div class="content">
{{ page.body|richtext }}
{% if page.tags.all.count %}
<div class="tags">
<h3>Tags</h3>
{% for tag in page.tags.all %}
<span class="tag is-primary is-medium is-link"><a style="color: white" href="{% slugurl 'tags' %}?tag={{ tag }}">{{ tag }}</a></span>
{% endfor %}
</div>
{% endif %}
<p>Return to blog archive</p>
<hr>
<br>
<form action="" method="POST">
{% csrf_token %}
<table>
{{ form.as_table }}
</table>
<input class="control button is-primary" type='submit' name='submit' value='Add Comment'>
</form>
<br>
<hr>
<div class="section">
{% if page.comments.all.count %}
<h2 class='subtitle'>Comments</h2>
<div class="comments">
{% for comment in page.comments.all %}
{% if comment.approved_comment %}
<div class="comment">
<h5 class="date">{{ comment.created_date }}</h5>
<strong><h3 class="title is-3">{{ comment.author }}</h3></strong>
<h4 class="subtitle is-5">{{ comment.text|linebreaks }}</h4>
<br>
<hr>
</div>
{% endif %}
{% empty %}
<br>
<p>No comments yet...</p>
{% endfor %}
</div>
{% endif %}
</div>
</div>
</div>
</div>
{% endblock %}
Now I'm getting an error saying:
File "/home/kenneth/development/web/sites/mysite/dynamicsalesops/blog/models.py", line 88, in serve
context_instance=RequestContext(request))
TypeError: render_to_response() got an unexpected keyword argument 'context_instance'
Your view_post function is never used. In Wagtail, rendering pages as HTML is handled by a serve method on the page model itself, not by a separate view function: http://docs.wagtail.io/en/v1.9/reference/pages/theory.html#anatomy-of-a-wagtail-request

Bad for-loop in django with Groups model, ManyToMany field

I want to display 1 button in the for-loop, but i get as many buttons as many i have created groups. So.. when i created 3 groups where i'm one of the members, i got 3 buttons under every group i have. The problem is with this first loop in my code, but i don't know how to solve this.
Problem is in loop:
{% for z in mem %}
When i create any memberships it's like:
m = Membership.objects.create(person="damian", group="name_group", leader=True) / or False
Thanks for any help!
groups.html:
{% for g in gr %}
<div class="jumbotron">
<div class="jumbo2">
<form method="POST" class="post-form"> {% csrf_token %}
<p id="name"><b>Group's name:</b> {{g.name}}</p><br>
{% for member in g.members.all %}
<p><b>Member:</b> {{member.name}} </p>
{% endfor %}
<br>
<span class="desc2">Group's description:</span>
<p id="desc">{{g.description}}</p><br>
{% for z in mem %}
{% if z.leader == False %}
<button style="float: right" type="submit" name = "leave" value = "{{g.name}}" class="save btn btn-default">Leave</button>
{% elif z.leader == True %}
<button style="float: right" type="submit" name = "delete" value = "{{g.name}}" class="save btn btn-default">Delete</button>
{% endif %}
{% endfor %}
</form>
<br><br>
<p>
{% if messages %}
{% for message in messages %}
<p>{{ message }}</p>
{% endfor %}
{% endif %}
</p>
</div>
</div>
{% endfor %}
views.py:
cvs = Cv.objects.all()
cv = Cv.objects.filter(author = request.user)
per = Person.objects.all()
gr = Group.objects.filter(members__name=request.user)
perr = Person.objects.filter(name=request.user)
mem = Membership.objects.filter(group = gr, person = perr)
form = GroupForm()
context = {
'gr': gr,
'per':per,
'mem':mem,
'form': form,
'cvs':cvs,
'cv':cv,
}
return render(request, 'groups.html', context)
models.py:
class Person(models.Model):
name = models.CharField(max_length=128)
def __str__(self): # __unicode__ on Python 2
return self.name
class Group(models.Model):
name = models.CharField(max_length=128)
members = models.ManyToManyField(Person, through='Membership')
description = models.TextField(max_length=350)
def __str__(self): # __unicode__ on Python 2
return self.name
class Membership(models.Model):
person = models.ForeignKey(Person)
leader = models.BooleanField(default=False)
group = models.ForeignKey(Group)
Ok, i replace my groups and used only membership objects. Here's my working code:
{% for z in mem %}
<div class="jumbotron">
<div class="jumbo2">
<form method="POST" class="post-form"> {% csrf_token %}
<p id="name"><b>Group's name:</b> {{z.group}}</p><br>
{% for member in z.group.members.all %}
<p><b>Member:</b> {{member.name}} </p>
{% endfor %}
<br>
<span class="desc2">Group's description:</span>
<p id="desc">{{z.group.description}}</p><br>
{% if z.leader == False %}
<button style="float: right" type="submit" name = "leave" value = "{{z.group}}" class="save btn btn-default">Leave</button>
{% elif z.leader == True %}
<button style="float: right" type="submit" name = "delete" value = "{{z.group}}" class="save btn btn-default">Delete</button>
{% endif %}
</form>
<br><br>
<p>
</p>
</div>
</div>
{% endfor %}

Categories

Resources