I'm making site for applications. And have two models: Applications and Guests and they have manytomany connection, because application can have 2 or more guests and 1 guest may be in many applications.
For making applications i use formset_factory with delete option. The problem is - I can't find any good examples with code for manytomanyfield and formset and I can't bound them in template. I can't display the table at all. Here's the code.
p.s. don't pay attention to cyrillic symbols
models
class Guests(models.Model):
unique_number_guest = models.IntegerField(unique=True, primary_key=True, verbose_name='№')
organisation = models.CharField(max_length=100, verbose_name='Организация', null=True)
full_name = models.CharField(max_length=100, verbose_name='ФИО')
position = models.CharField(max_length=100, verbose_name='Должность', blank=True, null=True)
chosen = models.BooleanField(default=False, verbose_name='Выбран')
class Applications(models.Model):
ntc_cabins = (
('2-5', '2-5'),
('2-10', '2-10'),
('2-12', '2-12'),
)
ntc_blocks = (
('ЦОК', 'ЦОК'),
('БМЗ', 'БМЗ')
)
unique_number_app = models.IntegerField(unique=False, null=True)
visit_date = models.DateField(default=date.today()+timedelta(days=1), verbose_name='Дата:')
visit_time = models.TimeField(default='12:00', verbose_name='Время:')
cabin = models.CharField(max_length=5, verbose_name='Кабинет:', choices=ntc_cabins, default='2-12')
block = models.CharField(max_length=10, verbose_name='Корпус:', choices=ntc_blocks, default='ЦОК')
author = models.CharField(max_length=100, verbose_name='Автор:')
guests = models.ManyToManyField(Guests)
views
def ApplicationFormation(request):
form = ApplicationsForm(request.POST)
form.guest_instanses = GuestsFormSet(request.POST)
if request.method == "POST":
if form.is_valid():
applications = Applications()
applications.cabin = form.cleaned_data['cabin']
applications.save()
for person in form.guests_visited:
guest = Guests()
guest.full_name = person['full_name']
guest.organisation = person['organisation']
guest.position = person['position']
guest.save()
applications.guests.add(guest)
return HttpResponse('good job')
print(form.errors)
else:
formset = GuestsFormSet()
print('FORMSET:', formset)
return render(request, 'myprofile/applications_form.html', {'form': form, 'fomset': formset})
forms
class GuestsForm(ModelForm):
organisation = forms.CharField()
full_name = forms.CharField()
position = forms.CharField()
class Meta:
model = Guests
exclude = ('unique_number_guest', 'chosen',)
GuestsFormSet = formset_factory(GuestsForm, extra=1, can_delete=True)
class ApplicationsForm(ModelForm):
visit_date = forms.DateField()
visit_time = forms.TimeField()
cabin = forms.CharField()
block = forms.CharField()
guests = GuestsFormSet()
class Meta:
model = Applications
exclude = ('unique_number_app', 'author', 'guests', 'ntc_cabin')
and template
{% extends "base.html" %}
{% load static %}
{% block title %}{% endblock %}
{% block content %}
<h2>Заявка на пропуск</h2>
<hr>
<div class="col-md-4">
<form action="" method="post" class="">
{% csrf_token %}
{{ form.as_p }}
<h3>Гости</h3>
<table id="table-guests">
{{ formset.management_form }}
{% for form in formset %}
{% if forloop.first %}
<thead>
<tr>
{% for field in form.visible_fields %}
<th>{{ field.label|capfirst }}</th>
{% endfor %}
</tr>
</thead>
{% endif %}
<tr class="{% cycle row1 row2 %} formset_row">
{% for field in form.visible_fields %}
<td>
{# Include the hidden fields in the form #}
{% if forloop.first %}
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
{% endif %}
{{ field.errors.as_ul }}
{{ field }}
</td>
{% endfor %}
</tr>
{% endfor %}
</table>
<input type="submit" value="Сохранить и сформировать заявку"/> Назад
</form>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="{% static 'formset/jquery.formset.js' %}"></script>
<script type="text/javascript">
$('.formset_row').formset({
addText: 'добавить',
deleteText: 'удалить',
prefix: 'Guests'
});
</script>
Related
views.py.
#login_required
def friends_profile(request):
f_profiles = Profile.objects.get(user=request.user)
return render(request, 'mains/friends_profile.html', {'f_profiles':f_profiles} )
urls.py
path('friends_profile/', views.friends_profile, name='friends_profile'),
template = friends_profile.html
{% extends "mains/base.html" %}
{% block content %}
{% for friends in f_profiles %}
{{ friends.full_name }}
{% empty %}
<li>NO DATA</li>
{% endfor %}
{% endblock content %}
models.py
class Profile(models.Model):
user = models.OneToOneField(User,
on_delete=models.CASCADE,default='',unique=True)
full_name = models.CharField(max_length=100,default='')
friends = models.ManyToManyField(User, related_name='friends',blank=True)
email = models.EmailField(max_length=60,default='')
date_added = models.DateTimeField(auto_now_add=True)
def get_friends(self):
return self.friends.all()
def get_friends_no(self):
return self.friends.all().count()
def __str__(self):
return f'{self.user.username}'
STATUS_CHOICES = (
('send', 'send'),
('accepted','accepted'),
)
class Relationship(models.Model):
sender = models.ForeignKey(Profile, on_delete=models.CASCADE,
related_name='sender')
receiver = models.ForeignKey(Profile, on_delete=models.CASCADE,
related_name='receiver')
status = models.CharField(max_length=8, choices=STATUS_CHOICES)
def __str__(self):
return f"{self.sender}-{self.receiver}-{self.status}"
'Profile' object is not iterable. This is raising when i open this template( friends_profiles.html ). Please... Help me in this ERROR. What am i missing in this ?
I will really appreciate your HELP.
You are only passing a single object f_profiles in the context to the template, but are trying to iterate over an iterable by doing {% for friends in f_profiles %}.
f_profiles = Profile.objects.get(user=request.user) this will only give you one object which is the profile of the request.user. You are not getting friends of the user with this line of code.
Also, it maybe better to use
f_profiles = get_object_or_404(Profile, user=request.user)
Try to replace this code in the templates:
{% for friends in f_profiles %}
{{ friends.full_name }}
with
{% for friend in f_profiles.friends.all %}
{{ friend.full_name}}
or
{% for friend in f_profiles.get_friends %}
{{ friend.full_name }}
So i'm creating a to-do app. How do I get the html view to show the tasks? I tried to show the name of the tasks but it's blank. So far, it only shows the board name and the user who created it.
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)
taskobj= Task.objects.filter(board=obj)
context = {"object": obj, "tasks": taskobj}
return render(request, 'boards/board_post_detail.html', context)
board_post_detail.html
{% block content %}
<h1>{{ object.name}}</h1>
<p> {{tasks.text}}<p>
<p>Created by {{object.admin.username }}</p>
{% endblock %}
I realise that I needed to use a for loop to iterate throught the tasks.
{% block content %}
<h1>{{ object.name}}</h>
<ul>
{% for task in tasks %}
<li>{{ task.text }} is assigned to {{ task.assigned_to }}</li>
{% endfor %}
</ul>
<p>Created by {{object.admin.username }}</p>
{% endblock %}
On the admin site, I create ConclusionName and RetrospectiveField. I need the fields baseText and comments to appear on the site under the word Application 2 'Retrospective'
Conclusion (app)
models.py
class ConclusionName(models.Model):
name = models.CharField(max_length=250)
def __unicode__(self):
return self.name
class RetrospectiveField(models.Model):
user = models.ForeignKey(User)
conclusionName = models.ForeignKey(ConclusionName)
baseText = models.TextField(max_length=255)
comments = models.TextField(max_length=255)
project = models.ForeignKey(Project)
forms.py
class RetrospectiveFieldForm(forms.Form):
project = forms.ModelChoiceField(queryset=Project.objects.all(), label=u'Project')
conclusionName = forms.ModelChoiceField(queryset=ConclusionName.objects.all(), label=u'ConclusionName')
baseText = forms.TextField(max_length=255, label=u'BaseText')
comments = forms.TextField(max_length=255, label=u'Comments')
class Meta:
model = RetrospectiveField
fields = ('project', 'conclusionName', 'baseText', 'comments',)
views.py
def add_form_retrospective_field(request):
if request.method == 'POST':
form = RetrospectiveFieldForm(request.POST)
if form.is_valid():
retro = RetrospectiveField()
retro.user = User.objects.get(username=request.user)
retro.project = form.cleaned_data.get('project')
retro.conclusionName = form.cleaned_data.get('conclusionName')
retro.baseText = form.cleaned_data.get('baseText')
retro.comments = form.cleaned_data.get('comments')
retro.save()
return redirect('/')
else:
form = RetrospectiveForm()
return render(request, 'completeness/forms_retrospective_field.html', {'form': form})
def showRetrospectiveField(request, slug):
projects = Project.objects.filter(id=slug)
retrospectiveFields = RetrospectiveField.objects.get(project=projects)
return render(request, 'completeness/view_retrospectiveField.html', {'retrospectiveFields': retrospectiveFields})
conclusion/example.html
{% extends 'completeness/base.html' %}
{% load staticfiles %}
{% load i18n %}
{% block title %}{% trans 'Network' %}{% endblock %}
{% block head %}
<meta charset="UTF-8">
<title>Conclusion</title>
<script data-require="jquery#*" data-semver="3.0.0" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.js"></script>
<link href="style.css" rel="stylesheet" />
<script src="script.js"></script>
{% block js %}
{{ form.media }}
{% endblock %}
{% endblock head %}
{% block content %}
<div class="parent">
<div class="block">
<h3>Application 2 "Retrospective"</h3>
{% for retro in retrospectiveField %}
<p>{{ retro.baseText }}</p>
<p>{{ retro.comments }}</p>
{% endfor %}
</div>
</div>
{% endblock content %}
You are returning retrospectiveFields in your showRetrospectiveField view, but you're using retrospectiveField in your for loop of conclusion/example.html
I am trying to implement a search feature with pagination.
I have successfully either managed to get the search to work or the pagination to work. But I cannot figure out how to get both of them working together at the same time.
Here is the .html, by switching object_list to filter.qs in the .html, I can switch between either searching correctly or pagination correctly.
Can someone help me fix the code so that I can have both working together ?
{% extends 'base.html' %}
{% load widget_tweaks %}
{% load my_tags %}
{% block head %}
<title> Overview</title>
{% endblock %}
{% block content %}
<form method="get">
<div class="jumbotron">
<h4 style="margin-top: 0">Filter</h4>
<div class="row">
<div class="form-group col-sm-4 col-md-3">
{{ filter.form.name.label_tag }}
{% render_field filter.form.name class="form-control" %}
</div>
<div class="form-group col-sm-4 col-md-3">
{{ filter.form.city_location.label_tag }}
{% render_field filter.form.city_location class="form-control" %}
</div>
</div>
<button type="submit" class="btn btn-primary">
<span class="glyphicon glyphicon-search"></span> Search
</button>
</div>
</form>
<table class="table table-bordered">
<thead>
<tr>
<th>Name</th>
<th>City Location</th>
</tr>
</thead>
<tbody>
{% for object in object_list %}
<tr>
<td>{{ object.name }}</td>
<td>{{ object.city_location }}</td>
</tr>
{% empty %}
<tr>
<td colspan="5">No data</td>
</tr>
{% endfor %}
</tbody>
</table>
<br>
<br>
<div id="footer">
<div class="container text-center">
<p class="text-muted credit" style="color:#fff">
{% if is_paginated %}
{% if page_obj.has_previous %}
First
{% if page_obj.previous_page_number != 1 %}
Previous
{% endif %}
{% endif %}
Page {{ page_obj.number }} of {{ paginator.num_pages }}
{% if page_obj.has_next %}
{% if page_obj.next_page_number != paginator.num_pages %}
Next
{% endif %}
Last
{% endif %}
<p>Objects {{ page_obj.start_index }}—{{ page_obj.end_index }}</p>
{% endif %}
</div>
</div>
{% endblock %}
Here is my models
from django.db import models
# Create your models here.
class lab(models.Model):
name = models.CharField(max_length=255)
city_location = models.CharField(max_length=255)
def __str__(self):
return self.Lab_name
Here is my views.py
class labListView(LoginRequiredMixin, ListView):
context_object_name = "Lab_folders"
model = lab
template_name = "researcher_view_app/Lab_overview.html"
paginate_by = 20
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['filter'] = labOverviewFilter(self.request.GET, queryset=self.get_queryset())
return context
Here is my filters.py
import django_filters
class labOverviewFilter(django_filters.FilterSet):
Lab_name = django_filters.CharFilter(lookup_expr='icontains')
Lab_city_location = django_filters.CharFilter(lookup_expr='icontains')
And the part which I have no idea about, that I do not know how to modify but works is: my tempatetag
app_name/templatetags/my_tags.py
from django import template
register = template.Library()
#register.simple_tag(takes_context=True)
def param_replace(context, **kwargs):
"""
Return encoded URL parameters that are the same as the current
request's parameters, only with the specified GET parameters added or changed.
It also removes any empty parameters to keep things neat,
so you can remove a parm by setting it to ``""``.
For example, if you're on the page ``/things/?with_frosting=true&page=5``,
then
Page 3
would expand to
Page 3
Based on
https://stackoverflow.com/questions/22734695/next-and-before-links-for-a-django-paginated-query/22735278#22735278
"""
d = context['request'].GET.copy()
for k, v in kwargs.items():
d[k] = v
for k in [k for k, v in d.items() if not v]:
del d[k]
return d.urlencode()
You can apply filter in get_queryset method. Like this
class labListView(ListView):
context_object_name = "Lab_folders"
model = lab
template_name = "researcher_view_app/Lab_overview.html"
paginate_by = 20
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['filter'] = labOverviewFilter(self.request.GET, queryset=self.get_queryset())
return context
def get_queryset(self):
qs = super().get_queryset()
word = labOverviewFilter(self.request.GET, queryset=qs)
return word.qs
pagination logic works after getting queryset. So provide filtered queryset to paginator.
I want to get image form Image model for my Product model and show it cart template
This is my Code:
ecommerce/models.py
class Product(models.Model):
name = models.CharField(max_length=200)
content = models.TextField()
excerpt = models.TextField()
price = models.DecimalField(max_digits=6, decimal_places=2)
status = models.IntegerField(default=0)
date = models.DateTimeField(auto_now_add=True)
quantity = models.PositiveIntegerField()
author = models.PositiveIntegerField()
featured_image = models.CharField(max_length=300)
available = models.BooleanField(default=True)
def __str__(self):
return self.name
class Image(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE)
image = models.ImageField()
cart/views.py
#require_POST
def cart_add(request, product_id):
cart = Cart(request)
product = get_object_or_404(Product, pk=product_id)
form = CartAddProductForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
cart.add(product=product,
quantity=cd['quantity'],
update_quantity=cd['update'])
return redirect('cart:cart_detail')
def cart_detail(request):
cart = Cart(request)
for item in cart:
item['update_quantity_form'] = CartAddProductForm(initial={'quantity': item['quantity'],
'update': True})
return render(request, 'cart_detail.html', {'cart': cart})
cart/templates/cart.html
<tbody>
{% for item in cart %}
{% with product=item.product %}
<tr>
<td>
{% for product in products %}
<img src="{{ product.first_image.src }}" alt="" width="auto" height="340"/>
{% endfor %}
</td>
<td>{{ product.name }}</td>
.
.
.
</tr>
{% endwith %}
{% endfor %}
</tbody>
i have read this link
but it is no use to me, please help me, I am newby to this
Thank you
You should use reverse lookup image_set. To get first image do product.image_set.first.image.url:
<img src="{{ product.image_set.first.image.url }}" alt="" width="auto" height="340"/>
to get all images iterate over image_set:
{% for image in product.image_set.all %}
<img src="{{ image.src }}" alt="" width="auto" height="340"/>
{% endfor %}
Note you should remove this part:
{% for product in products %}
{% endfor %}
since you dont pass products variable into template context.