I have a Movie database and a boolean field init. I want to click a button and change that boolean field's value. But I couldn't manage to get Movie pk from the url. I'm getting this error: 'WSGIRequest' object has no attribute 'kwargs'
Here is my views:
#login_required
def one_cikan_button(self, **kwargs):
pk = self.kwargs['pk']
print(pk)
film = Movies.objects.get(pk=pk)
try:
film.featured = False
film.save()
return redirect('/headoffice/onecikanlar/')
except Exception as e:
return redirect('/headoffice/onecikanlar/')
return redirect('/headoffice/onecikanlar/')
My urls:
path('onecikanlar/kaldir/<pk>/', views.one_cikan_button, name="onecikankaldir"),
My template:
<i class="notika-icon notika-trash" style="font-size:14pt; color:black;"></i>
My models:
class Movies(models.Model):
featured = models.BooleanField(default=False)
How can I solve this? Or can I use UpdateView with custom settings?
I just started using session in Django framework. I have create an object cart from Cart model. And when i wan to set cart inside request.session with session['cart'] = cart, I get this error message: TypeError: Object of type Cart is not JSON serializable
This is my Cart model
class Cart(object):
def __init__(self):
self.items = []
def addItem(self, itemCart):
try:
# get index of itemCart if exist
index = self.items.index(itemCart)
# itemCart exist then set its quantity
self.items[index].setQuantity(
self.items[index].quantity + itemCart.quantity)
except ValueError:
# the item does not exits then add to items list
self.items.append(itemCart)
This is my view when i update the session
cart = Cart()
session['cart'] = cart
And When i run the code i get this error:
File "C:\Users\Patrick-PC\AppData\Local\Programs\Python\Python37\lib\json\encoder.py", line 179, in default
raise TypeError(f'Object of type {o.class.name} '
TypeError: Object of type Cart is not JSON serializable.
Please help
If Cart is a model, you'll want to inherit from models.Model. That said, you can try:
from django.core import serializers
session['cart'] = serializers.serialize('json', Cart.objects.all())
Django:1.11.5
Python:3.5.2
Markdown 2.6.9 https://pypi.python.org/pypi/Markdown/
views.py
from django.shortcuts import render
from .models import Post
import markdown
def home(request):
Post_list = Post.objects.all().order_by('-pub_date')
Post.content = markdown.markdown(Post.content)
return render(request, 'home.html',
context={'Post_list':Post_list})
# Create your views here.
models.py
from django.db import models
import django.utils.timezone as timezone
class Category(models.Model):
name = models.CharField(max_length=100)
class Post(models.Model):
title = models.CharField(max_length=256)
content = models.TextField(blank = True, null = True)
pub_date = models.DateTimeField(default=timezone.now)
update_time = models.DateTimeField(auto_now=True)
category = models.ForeignKey(Category)
# Create your models here.
Error message
AttributeError at /
'DeferredAttribute' object has no attribute 'strip'
Request Method: GET
Request URL: http://www.balinzuoqi.com/
Django Version: 1.11.5
Exception Type: AttributeError
Exception Value:
'DeferredAttribute' object has no attribute 'strip'
Exception Location: /usr/local/lib/python3.5/dist-packages/markdown/__init__.py in convert, line 355
Python Executable: /usr/bin/python3
Python Version: 3.5.2
Python Path:
['/data/mysite',
'/usr/local/bin',
'/usr/lib/python35.zip',
'/usr/lib/python3.5',
'/usr/lib/python3.5/plat-i386-linux-gnu',
'/usr/lib/python3.5/lib-dynload',
'/usr/local/lib/python3.5/dist-packages',
'/usr/lib/python3/dist-packages']
Do not know where there is a problem.
Remove Post.content = markdown.markdown (Post.content), show normal!
English is not my native language; please excuse typing errors.
You are reading content from and writing content to the Post class, not an instance of the class. You need to iterate through the list and update each instance:
def home(request):
Post_list = Post.objects.all().order_by('-pub_date')
for post in Post_list:
post.content = markdown.markdown(post.content)
return render(request, 'home.html',
context={'Post_list':Post_list})
Whether that is a recommended way of converting Markdown to HTML to pass to a template is another matter. Its been a few years since I've used Django, but that wasn't how it used to be done. However, that is a different question.
Regardless, you were not actually passing any Markdown text to the Markdown parser as you were not using an instance of the class. With the for loop I added above, the Markdown content for each 'Post' is now being passed to the Markdown parser.
Whenever I try to run, I'm getting the following error described below. Already I researched a solution, but I can not make it work.
Exception Type: ValueError
Exception Value:
ModelForm has no model class specified.
Exception Location: /usr/local/lib/python2.7/dist-packages/django/forms/models.py in init, line 275
Python Executable: /usr/bin/python
Python Version: 2.7.6
Erro Traceback
File "/home/ubuntu/workspace/envelope/views.py" in cad_professor
67. form = ProfessorForm()
File "/usr/local/lib/python2.7/dist-packages/django/forms/models.py" in init
275. raise ValueError('ModelForm has no model class specified.')
views.py
#login_required(login_url='/login/')
def cad_professor(request):
context = {}
if request.method == 'POST':
form = ProfessorForm(request.POST)
if form.is_valid():
form.save()
context['success'] = True
else:
form = ProfessorForm()
context['form'] = form
template_name = 'envelope/cad_professor.html'
return render(request,template_name , context)
forms.py
from django import forms
from .models import Professor
class ProfessorForm(forms.ModelForm):
class meta:
model = Professor
Your meta spelling is wrong. Change to:
class ProfessorForm(forms.ModelForm):
class Meta:
model = Professor
Is this still valid syntax for Django 1.2?
Custom Filter in Django Admin on Django 1.3 or below
I have tried it, but the list_filter option in the admin class is not recognizing my custom filter.
How should the custom filter be added to the list_filter so that it displays?
class MyModelAdmin(admin.ModelAdmin):
...
list_filter = ['is_expired_filter']
Here my 'is_expired_filter' is my newly registered custom filter, which is what the Author says he does like so:
list_filter = ('is_live')
But this is not recognized by Django, and the error I get when I load the admin page is
Exception Type: ImproperlyConfigured
Exception Value: 'PositionAdmin.list_filter[2]' refers to field 'is_expired_filter' that is missing from model 'Position'
Perhaps my mistake is that I am not sure how the original code is used by the Author of that question once he/she implements a custom filter.
Here is the original code:
def is_live(self):
if self.when_to_publish is not None:
if ( self.when_to_publish < datetime.now() ):
return """ <img alt="True" src="/media/img/admin/icon-yes.gif"/> """
else:
return """ <img alt="False" src="/media/img/admin/icon-no.gif"/> """
is_live.allow_tags = True
Now that I have a handle on what I think you want, I'm assuming you have a model that you want to filter by a DateField like:
class Position(models.Model):
expiration_date = models.DateField()
...
which you should now modify to
class Position(models.Model):
expiration_date = models.DateField()
expiration_date.is_expired_filter = True
...
What you want to do is add to your admin.py a new filter class
from django.contrib.admin.filterspecs import FilterSpec, DateFieldFilterSpec
from django.utils.translation import ugettext as _
from datetime import datetime, date
class ExpiredFilterSpec(DateFieldFilterSpec):
"""
Adds filtering by future and previous values in the admin
filter sidebar. Set the is_expired_filter filter in the model field
attribute 'is_expired_filter'.
my_model_field.is_expired_filter = True
"""
def __init__(self, f, request, params, model, model_admin, **kwargs):
super(ExpiredFilterSpec, self).__init__(f, request, params, model,
model_admin, **kwargs)
today = date.today()
self.links = (
(_('All'), {}),
(_('Not Expired'), {'%s__lt' % self.field.name: str(today),
}),
(_('Expired'), {'%s__gte' % self.field.name: str(today),
}))
def title(self):
return "Filter By Expiration Date"
# registering the filter
FilterSpec.filter_specs.insert(0, (lambda f: getattr(f, 'is_expired_filter', False),
ExpiredFilterSpec))
class PositionAdmin(admin.ModelAdmin):
list_filter = ['expiration_date']
Almost copying your link Custom Filter in Django Admin on Django 1.3 or below word for word, I came up with this.
from django.contrib.admin.filterspecs import FilterSpec, ChoicesFilterSpec, DateFieldFilterSpec
from django.utils.encoding import smart_unicode
from django.utils.translation import ugettext as _
from datetime import datetime
class IsExpiredFilterSpec(DateFieldFilterSpec):
"""
Adds filtering by future and previous values in the admin
filter sidebar. Set the is_expired_filter filter in the model field
attribute 'is_expired_filter'.
my_model_field.is_expired_filter = True
"""
def __init__(self, f, request, params, model, model_admin):
super(IsExpiredFilterSpec, self).__init__(f, request, params, model,
model_admin)
# -- You'll need to edit this to make it do what you want. --
# today = datetime.now()
# self.links = (
# (_('Any'), {}),
# (_('Yes'), {'%s__lte' % self.field.name: str(today),
# }),
# (_('No'), {'%s__gte' % self.field.name: str(today),
# }),
#
# )
def title(self):
return "Is Expired"
\# registering the filter
FilterSpec.filter_specs.insert(0, (lambda f: getattr(f, 'is_expired_filter', False),
IsExpiredFilterSpec))
class MyModelAdmin(admin.ModelAdmin):
...
MODEL_FIELD_TO_FILTER.is_expired_filter = True
list_filters = ['MODEL_FIELD_TO_FILTER']
UPDATE: Made a change thanks to jimbob. MODEL_FIELD_TO_FILTER would be the field you want to filter.