CreateView Model Objects to a template - django

So I am trying to pass a list of objects into my template. I want my profile.html to reflect the information in the model. I found some documentation on ListView but nothing on CreateView.
The only thing that is passing through to the template is {{ user.username }}. Any suggestions would be greatly appreciated.
profile.html
{% extends 'base.html' %}
{% block title %}User Profile{% endblock %}
{% block content %}
{% if user.is_authenticated %}
<p>User: {{ user.username }} logged in.</p>
<p>homepage</p>
<p>logout</p>
{% else %}
login |
signup
{% endif %}
{% endblock %}
models.py
class Volunteer(CustomUser):
user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, primary_key=True)
about_me = models.TextField(default='')
class Meta:
db_table = "volunteer"
forms.py
class VolunteerSignUpForm(UserCreationForm):
class Meta(UserCreationForm.Meta):
model = Volunteer
fields = ("username", "email", "first_name", "last_name",)
#transaction.atomic
def save(self):
user = super(VolunteerSignUpForm, self).save(commit=False)
user.is_volunteer = True
user.save()
return user
views.py
class VolunteerSignUp(CreateView):
form_class = VolunteerSignUpForm
success_url = reverse_lazy('login')
template_name = 'volunteer_signup.html'
#added code from answer
def get_context_data(self, **kwargs):
context = super(VolunteerSignUp, self).get_context_data(**kwargs)
context['profile_list'] = Volunteer.objects.all()
return context
profile.html Here are some things iv tried to get the info across that didn't work.
<ul>
{% for volunteer in object_list %}
<li>{{ volunteer.about_me }}</li>
{% endfor %}
</ul>
<ul>
{% for volunteer in profile_list %}
<li>{{ volunteer.about_me }}</li>
{% endfor %}
</ul>
{% if profile_list %}
{% else %}
<p>There is no info.</p>
{% endif %}

You can use get_context_data() method in your class.
class VolunteerSignUp(CreateView):
form_class = VolunteerSignUpForm
success_url = reverse_lazy('login')
template_name = 'volunteer_signup.html'
def get_context_data(self, **kwargs):
data = super(VolunteerSignUp, self).get_context_data(**kwargs)
data['profile_list'] = 'your queryset goes here'
return data

Related

how to implement search that can access complete database in Django

My views.py
class SearchView(TemplateView):
template_name = 'search.html'
def get(self, request, *args, **kwargs):
q = request.GET.get('q', '')
self.results = Item.objects.filter(title__icontains=q)
return super().get(request, *args, **kwargs)
def get_context_data(self, **kwargs):
return super().get_context_data(results=self.results, **kwargs)
My urls.py
url(r'^search/$', SearchView.as_view(), name='search')
My search.html
{% extends 'base.html' %} {% load static %} {% block content %}
<body>
<h1>Search Result</h1>
<ul>
{% for item in q %}
<li>
{{ q.title }}, {{ q.price }}
</li>
{% endfor %}
</ul>
</body>
{% endblock%}}
My nav.html
<form method="GET" action="{% url 'core:search' %}">
This is the code that i used but due to some missing or error in this above code i can't get any data if i make any search in my website, Can some one please tell me what is the mistake i have done.
Thank you.
My Models.py
class Item(models.Model):
title = models.CharField(max_length=50)
category = models.ForeignKey(Category, on_delete=models.CASCADE)
model_no = models.CharField(max_length=100)
try this:
def get_context_data(self, *, object_list=None, **kwargs):
context = super().get_context_data(**kwargs)
context['results'] = self.results
return context
in html
{% extends 'base.html' %}
{% load static %}
{% block content %}
<body>
<h1>Search Result</h1>
<ul>
{% for item in results %}
<li>
{{ item.title }}, {{ item.price }}
</li>
{% endfor %}
</ul>
</body>
{% endblock%}}

Django: form not displaying in browser

The form doesn't display in the browser. The navbar and submit button show up but no form in between. The problem must be straightforward but I haven't been able to find the issue. Thank you for your help.
views.py
def ProductCreateView(request):
if request.method == 'POST':
form = ProductForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('set_app/product_list.html'))
else:
product_form = ProductForm()
return render(request, 'set_app/product_form.html', {'product_form':product_form})
forms.py
class ProductForm(forms.Form):
class Meta():
model = models.Product
fields = ('code', 'barcode', 'name', 'description', 'brand', 'status')
product_form.html
{% extends "set_app/basic_app_base.html" %}
{% block body_block %}
<h1>
{% if not form.instance.pk %}
Create Product
{% else %}
Update Product
{% endif %}
</h1>
<form method="post">
{% csrf_token %}
{{ product_form.as_p }}
<input type="submit" class="btn btn-primary" value="Submit">
</form>
{% endblock %}
Found the issue:
in forms.py
instead of
class ProductForm(forms.Form):
it should be
class ProductForm(forms.ModelForm):

Reverse Query Through Django Template File

models.py file
class Company(models.Model):
name = models.CharField(max_length=30)
def __str__(self):
return self.name
class Contact(models.Model):
first_name = models.CharField(max_length=20)
last_name = models.CharField(max_length=20)
company = models.ForeignKey(Company, on_delete=models.CASCADE)
def __str__(self):
return self.first_name
views.py file
class company_detail(DetailView):
def get(self, request, *args, **kwargs):
company = get_object_or_404(Company, pk=kwargs['pk'])
context = {'company': company}
return render(request, 'crm/company_detail.html', context)
company_detail.html file
{% extends 'base.html' %}
{% block content %}
<div id="container">
<ul>
<li>{{company.name}}</li>
</ul>
{% for company in object_list %}
{{ company.name }}
{% for Contact in company.contact_set.all %}
{{Contact.first_name}}
{% empty %}
<!-- no entries -->
{% endfor %}
{% endfor %}
</div>
{% endblock content %}
I'm trying to get the Contacts who are under that company to show up on the company_detail.html page. How do I reverse query it properly to show all Contacts under that company?
Thanks in advance
There is no object_list in your DetailView's context, only the object. You need to remove the for loop over object_list in the template
{% for contact in company.contact_set.all %}
{{ contact.first_name }}
{% empty %}
<!-- no entries -->
{% endfor %}

A List inside a list in django templates

How do you render a list of user who have a list of their own objects related with foreign-key in Models. When I render in html it brings all list of all users in all users,
EDIT
Sorry for late reply, I rarely get time to get to my computer,
I have three models, Profile, Resume and Skills with the two related to Profile through foreign key...
VIEWS.PY
class ResumeList(ListView):
model = User_Profile
context_object_name = 'profile'
template_name = 'resume/list.html'
paginate_by = 6
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['resume'] = Resume.objects.all()
context['skill_list'] = Skill.objects.all()
return context
LIST.HTML
{% extends "base.html" %}
{% load static %}
{% block content %}
{% for obj in profile %}
{{ obj.first_name }}
{{ obj.last_name }}
{% for obj in resume %}
{{ obj.resume }}
{% endfor %}
{% for obj in skill_list %}
{{ obj.name }}
{% endfor %}
{% endfor %}
{% endblock %}
The Resume and Skill model loops are inside the profile loop but it displays all skills for all profiles...
When I change the get_context_data() to filter it brings error...
Thanks in advance...

django forms comments not visible

i can add comments in db and see its in admin panel but dont see added comments in posts (view_post.html).
i dont understand reason for this
models:
class Comment(models.Model):
name = models.CharField('Имя:', max_length=100)
create_date = models.DateField(blank=True, null=True)
text = models.TextField()
def __str__(self):
return '%s' % self.name
forms:
class CommentForm(ModelForm):
class Meta:
model = Comment
fields = ['name', 'create_date', 'text']
views:
def view_post(request, slug):
post_detail = get_object_or_404(Article, slug=slug)
form = CommentForm(request.POST or None)
if form.is_valid():
comment = form.save(commit=False)
comment.post_detail = post_detail
comment.save()
return redirect(request.path)
return render_to_response('view_post.html', {
'post_detail': post_detail, 'form': form },
context_instance=RequestContext(request))
post template:
{% extends 'base.html' %}
{% block head_title %}{{ post_detail.title }}{% endblock %}
{% block title %}{{ post_detail.title }}{% endblock %}
{% block content %}
{{ post_detail.body }}
{% if post_detail.comment_set.all %}
{% for comment in post_detail.comment_set.all %}
{{ comment.name }}
{{ comment.text }}
{% endfor %}
{% endif %}
<form action="" method="POST">
{% csrf_token %}
<table>
{{ form.as_table }}
</table>
<input type="submit" name="submit" value="Submit" />
</form>
{% endblock %}
You set comment.post_detail to the current Article when saving, but there you don't actually seem to have a post_detail ForeignKey. In fact you don't seem to have any relationship between Comment and Article at all, or between Comment and anything.