I am trying to print the content fields from my database,
Here's my models.py file:
class Post(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
read_time = models.TimeField(null=True, blank=True)
view_count = models.IntegerField(default=0)
Here's my views.py file:-
class PostDetailView(DetailView):
model = Post
def get_object(self):
obj = super().get_object()
obj.view_count += 1
obj.save()
return obj
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
all_texts = {
'texts': context.content
}
print(all_texts[texts])
return context
I am trying to access all the data's from the content field from my database,
But the above way is not working, Is there any way I can access all the data's from the content field, because I have to perform some action on these fields, like calculate the read_time of any content, based on the length of it.
You do not have to override the .get_queryset(…) method [Django-doc] for that, since the object is already passed to the context. You can simply render it in the template with:
{{ object.content }}
In case you really need this in the context, you can implement this as:
class PostDetailView(DetailView):
model = Post
# …
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context.update(
texts=self.object.content
)
return context
In case you need all post objects, you can add these to the context:
class PostDetailView(DetailView):
model = Post
# …
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context.update(
texts=self.object.content,
posts=Post.objects.all()
)
return context
and render these as:
{% for post in posts %}
{{ post.content }}
{% endfor %}
It might be better to work with an F expression [Django-doc] when incrementing the view counter to avoid race conditions:
class PostDetailView(DetailView):
model = Post
def get_object(self):
obj = super().get_object()
views = obj.view_count
obj.view_count = F('view_count') + 1
obj.save()
obj.view_count = views+1
return obj
Just query all objects and loop the queryset to manipulate them according to your needs like so:
def your_view(self, **kwargs):
# Get all table entries of Model Post
queryset = Post.objects.all()
# Loop each object in the queryset
for object in queryset:
# Do some logic
print(object.content)
[...]
return (..., ...)
first import models
from . models import Post
then in your function
data=Post.objects.values('content').all()
Now data have all the values in content field
data=[{'content':first_value},{'content':second_value},..like this...]
Related
I researched how I could pass in a datetime object to my templates, but none of them seems to work. Here is the code for my view:
class LeadListView(LoginRequiredMixin, generic.ListView):
# some other code
today_date = datetime.date.today()
def get_context_data(self, **kwargs):
context = super(LeadListView, self).get_context_data(**kwargs)
context['today_date'] = self.today_date
return context
However, when I try to use the today_date in the template, it doesn't work. I am trying to use the today_date so that I might use it in an if statement to see if today's date is between two other datetime variables. Thanks a lot!
Some additional information on how the django template looks like:
{% if lead.class_start_date <= today_date and lead.class_end_date >= today_date %}
{% endif %}
Here, class_start_date and class_end_date are just part of the Lead model.
This is the full list view:
class LeadListView(LoginRequiredMixin, generic.ListView):
tempalte_name = "leads/lead_list.html"
context_object_name = "leads"
def get_queryset(self):
user = self.request.user
# initial queryset of leads for the entire organisation
if user.is_organisor:
queryset = Lead.objects.filter(
organisation=user.userprofile,
agent__isnull=False
)
else:
queryset = Lead.objects.filter(
organisation=user.agent.organisation,
agent__isnull=False
)
#filter for the agent that is logged in
queryset = queryset.filter(agent__user=user)
return queryset
You do not need to pass this to the context. Django already has a {% now … %} template tag [Django-doc].
You thus can render this with:
{% now 'DATE_FORMAT' %}
If you plan to filter however on the current day, you should filter in the view, since that will filter at the database level, which is more efficient:
from django.utils.timezone import now
class LeadListView(LoginRequiredMixin, generic.ListView):
model = Lead
def get_queryset(self, *args, **kwargs):
today = now().date()
return super().get_queryset(*args, **kwargs).filter(
class_start_date__lte=today,
class_end_date__gte=today
)
I'm trying to display all model objects after a get request in a table using django-tables2. It's currently displaying all and I can't figure out how to filter the queryset based on a model pk in my view:
views.py
class ViewJob(LoginRequiredMixin, SingleTableView):
model = JobResults
table_class = JobResultsTable
template_name = 'app/viewjobresults.html'
paginator_class = LazyPaginator
table_pagination = {"per_page": 30}
def get_context_data(self, **kwargs):
""" ViewJob get_context_data request """
context = super(ViewJob, self).get_context_data(**kwargs)
print("ViewJob >get_context_data()")
context['job_obj'] = Job.objects.get(pk=self.kwargs.get('pk'))
# context['object_list'] = context['object_list'].filter(job_id=context['job_obj'].id)
return context
template - app/viewjobresults.html
{% extends "base.html" %}
{% load render_table from django_tables2 %}
{% render_table table %}
{% endblock %}
tables.py
class JobResultsTable(tables.Table):
job = tables.Column(
accessor='job_id.job_name',
verbose_name='Job')
results = tables.Column(
accessor='results',
verbose_name='Result')
class Meta:
attrs = {"class": "table is-bordered"}
Currently the table rendered is ALL Job objects in a queryset. I have the specific job_obj in my view get_context_data() to filter this, but when i filter context['object_list'] (line hashed out) it still displays the entire list of JobResults. How can I change the queryset given to the table?
You can use the get_table_data() method to modify your queryset.
class ViewJob(LoginRequiredMixin, SingleTableView):
def get_table_data(self):
job_pk = self.request.GET.get('pk')
if job_pk:
return Job.objects.get(pk=job_pk)
else:
return Job.objects.all()
https://django-tables2.readthedocs.io/en/latest/pages/generic-mixins.html
I'm looking for some advice where to go from here. I've been working on making a Form, which dynamically generates its fields.
The form is working and generating everything correctly. However, I am having issues with how to save the actual form data. I'm looking for each field to save as a new item in a model.
The View Class from view.py
class MaintenanceCheckListForm(LoginRequiredMixin, FormView):
login_url = '/accounts/login'
template_name = 'maintenance/checklist.html'
form_class = MaintenanceCheckListForm
success_url = reverse_lazy('m-checklist')
def form_valid(self, form):
form.cleaned_data
for key, values in form:
MaintenanceCheckList.objects.create(
item = key,
is_compliant = values
)
return super().form_valid(form)
The Form from forms.py
class MaintenanceCheckListForm(forms.Form):
def __init__(self, *args, **kwargs):
super(MaintenanceCheckListForm, self).__init__(*args, **kwargs)
items = Maintenance_Item.objects.all()
CHOICES = (
('P','Compliant'),
('F','Non-Compliant'),
)
for item in items:
self.fields[str(item.name)] = forms.ChoiceField(
label=item.name,
choices=CHOICES,
widget=forms.RadioSelect,
initial='F',
)
The Model, from models.py
class MaintenanceCheckList(CommonInfo):
CHOICES = (
('P','Compliant'),
('F','Non-Compliant'),
)
id = models.AutoField(primary_key=True)
item = models.CharField(max_length=100)
is_compliant = models.CharField(max_length=20, choices= CHOICES)
I am having trouble accessing the data from the Form when it POST's. I've done some troubleshooting where I have set the values statically in the '''form_valid''' and it appears to generate the correct amounts of entires in the model. However the trouble begins when I attempt to insert the values from the POST.
I receieve the below error, which I believe it is trying to dump all the keys and values into a single item instead of looping over each key, value and creating the item.
DataError at /maintenance/checklist
value too long for type character varying(100)
Request Method: POST
Request URL: http://t1.localhost:8000/maintenance/checklist
Django Version: 3.1.6
Exception Type: DataError
Exception Value:
value too long for type character varying(100)
I'm fairly new to the world of Django (4 weeks and counting so far, and maybe 12 weeks into python). So any assistance would be amazing!
I believe you have somewhat gone on a tangent. There's a simpler solution of using Model formsets for what you want.
First if you want a custom form make that:
from django import forms
class MaintenanceCheckListComplianceForm(forms.ModelForm):
item = forms.CharField(widget = forms.HiddenInput())
is_compliant = forms.ChoiceField(
choices=MaintenanceCheckList.CHOICES,
widget=forms.RadioSelect,
initial='F',
)
class Meta:
model = MaintenanceCheckList
fields = ('item', 'is_compliant')
Next use it along with modelformset_factory in your views:
from django.forms import modelformset_factory
class MaintenanceCheckListFormView(LoginRequiredMixin, FormView): # Changed view name was a bit misleading
login_url = '/accounts/login'
template_name = 'maintenance/checklist.html'
success_url = reverse_lazy('m-checklist')
def form_valid(self, form):
instances = form.save()
return super().form_valid(form)
def get_form_kwargs(self):
kwargs = super().get_form_kwargs()
kwargs['queryset'] = MaintenanceCheckList.objects.none()
kwargs['initial'] = [{'item': obj['name'], 'is_compliant': 'F'} for obj in Maintenance_Item.objects.all().values('name')]
return kwargs
def get_form(self, form_class=None):
kwargs = self.get_form_kwargs()
extra = len(kwargs['initial'])
form_class = modelformset_factory(MaintenanceCheckList, form=MaintenanceCheckListComplianceForm, extra=extra)
return form_class(**kwargs)
Now in your template:
<form method="post">
{{ form }}
</form>
Or manually render it:
<form method="post">
{{ form.management_form }}
{% for sub_form in form %}
Item: {{ sub_form.item.value }}
{{ sub_form }}
{% endfor %}
</form>
Note: The above usage is a bit weird due to the naming of the formset variable as form by the FormView you should look into improving that a bit.
Note: Looking at the implementation it feels a bit weird to do this. I would advice you to redesign your models a bit. Perhaps a foreign key between your models? It basically feels like you have duplicate data with this implementation.
How can i pass the context data which is coming from a forms.py to my views class which is using generic detailView, i need to pass forms.py to my product detail page.
Here is the code for my view class
class ProductView(generic.DetailView):
model = Product
cart_product_form = CartAddProductForm()
context = {'cart_product_form': cart_product_form}
template_name = 'shopping/product.html'
query_pk_and_slug = True
Please let me know if this is incorrect
Override get_context_data, and add the form to the context before returning it.
class ProductView(generic.DetailView):
model = Product
template_name = 'shopping/product.html'
query_pk_and_slug = True
def get_context_data(self, **kwargs):
context = super(ProductView, self).get_context_data(**kwargs)
cart_product_form = CartAddProductForm()
context['cart_product_form'] = cart_product_form
return context
Given the Django example in making queries:
class Author(models.Model):
name = models.CharField(max_length=50)
...
def __str__(self):
return self.name
class Entry(models.Model):
...
authors = models.ManyToManyField(Author)
I'd like to have an author DetailView which contains a list of entries for that author. What I have so far:
class AuthorDetailView(DetailView):
model = Author
def get_context_data(self, **kwargs):
context = super(AuthorDetailView, self).get_context_data(**kwargs)
context['entries'] = Entry.objects.filter(
authors__name=self.object.name)
return context
and in my template:
{% for entry in entries %}
…
{% endfor %}
I'd also prefer to not filter by name but that specific author since name could be non unique.
You could use reverse relationship
context['entries'] = self.object.entry_set.all()
This gives you all Entry objects of that Author.
EDIT:
And why are you using author__name?
You can filter by the object directly:
context['entries'] = Entry.objects.filter(authors=self.object)