Caught UnicodeEncodeError while rendering: 'ascii' codec can't encode characters in position 4-5: ordinal not in range(128) - mysql

Hello I live in Poland so I have to deal with letters like łóźć etc. When I try to add, in admin pannel, text like "Zespół Szkół" I get error like this:
Caught UnicodeEncodeError while rendering: 'ascii' codec can't encode
characters in position 4-5: ordinal not in range(128)
I seen on Stackoverflow page many of similar problem but I don't have any idea how to solve my.
My Databse is MySQL
Unicode collection for my db: utf8_unicode_ci
My models.py
# -*- coding: utf-8 -*-
from django.db import models
import codecs
...
class experience(models.Model):
dateStart = models.DateField()
dateEnd = models.DateField()
company = models.CharField(max_length=50)
position = models.CharField(max_length=50)
description = models.TextField(max_length=255)
def __unicode__(self):
return self.company.decode('utf8')
...
Traceback
Request Method: GET
Request URL: http://vm:8000/admin/mycv/experience/
Django Version: 1.3.1
Python Version: 2.6.6
Installed Applications:
['django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'cv.mycv']
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware')
Template error:
In template /usr/local/lib/python2.6/dist-packages/django/contrib/admin/templates/admin/change_list.html, error at line 97
Caught UnicodeEncodeError while rendering: 'ascii' codec can't encode characters in position 4-5: ordinal not in range(128)
87 : {% endif %}
88 : {% endblock %}
89 :
90 : <form id="changelist-form" action="" method="post"{% if cl.formset.is_multipart %} enctype="multipart/form-data"{% endif %}>{% csrf_token %}
91 : {% if cl.formset %}
92 : <div>{{ cl.formset.management_form }}</div>
93 : {% endif %}
94 :
95 : {% block result_list %}
96 : {% if action_form and actions_on_top and cl.full_result_count %}{% admin_actions %}{% endif %}
97 : {% result_list cl %}
98 : {% if action_form and actions_on_bottom and cl.full_result_count %}{% admin_actions %}{% endif %}
99 : {% endblock %}
100 : {% block pagination %}{% pagination cl %}{% endblock %}
101 : </form>
102 : </div>
103 : </div>
104 : {% endblock %}
105 :
Traceback:
File "/usr/local/lib/python2.6/dist-packages/django/core/handlers/base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/contrib/admin/options.py" in wrapper
307. return self.admin_site.admin_view(view)(*args, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/utils/decorators.py" in _wrapped_view
93. response = view_func(request, *args, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/views/decorators/cache.py" in _wrapped_view_func
79. response = view_func(request, *args, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/contrib/admin/sites.py" in inner
197. return view(request, *args, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/utils/decorators.py" in _wrapper
28. return bound_func(*args, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/utils/decorators.py" in _wrapped_view
93. response = view_func(request, *args, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/utils/decorators.py" in bound_func
24. return func(self, *args2, **kwargs2)
File "/usr/local/lib/python2.6/dist-packages/django/contrib/admin/options.py" in changelist_view
1179. ], context, context_instance=context_instance)
File "/usr/local/lib/python2.6/dist-packages/django/shortcuts/__init__.py" in render_to_response
20. return HttpResponse(loader.render_to_string(*args, **kwargs), **httpresponse_kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/template/loader.py" in render_to_string
188. return t.render(context_instance)
File "/usr/local/lib/python2.6/dist-packages/django/template/base.py" in render
123. return self._render(context)
File "/usr/local/lib/python2.6/dist-packages/django/template/base.py" in _render
117. return self.nodelist.render(context)
File "/usr/local/lib/python2.6/dist-packages/django/template/base.py" in render
744. bits.append(self.render_node(node, context))
File "/usr/local/lib/python2.6/dist-packages/django/template/debug.py" in render_node
73. result = node.render(context)
File "/usr/local/lib/python2.6/dist-packages/django/template/loader_tags.py" in render
127. return compiled_parent._render(context)
File "/usr/local/lib/python2.6/dist-packages/django/template/base.py" in _render
117. return self.nodelist.render(context)
File "/usr/local/lib/python2.6/dist-packages/django/template/base.py" in render
744. bits.append(self.render_node(node, context))
File "/usr/local/lib/python2.6/dist-packages/django/template/debug.py" in render_node
73. result = node.render(context)
File "/usr/local/lib/python2.6/dist-packages/django/template/loader_tags.py" in render
127. return compiled_parent._render(context)
File "/usr/local/lib/python2.6/dist-packages/django/template/base.py" in _render
117. return self.nodelist.render(context)
File "/usr/local/lib/python2.6/dist-packages/django/template/base.py" in render
744. bits.append(self.render_node(node, context))
File "/usr/local/lib/python2.6/dist-packages/django/template/debug.py" in render_node
73. result = node.render(context)
File "/usr/local/lib/python2.6/dist-packages/django/template/loader_tags.py" in render
64. result = block.nodelist.render(context)
File "/usr/local/lib/python2.6/dist-packages/django/template/base.py" in render
744. bits.append(self.render_node(node, context))
File "/usr/local/lib/python2.6/dist-packages/django/template/debug.py" in render_node
73. result = node.render(context)
File "/usr/local/lib/python2.6/dist-packages/django/template/loader_tags.py" in render
64. result = block.nodelist.render(context)
File "/usr/local/lib/python2.6/dist-packages/django/template/base.py" in render
744. bits.append(self.render_node(node, context))
File "/usr/local/lib/python2.6/dist-packages/django/template/debug.py" in render_node
73. result = node.render(context)
File "/usr/local/lib/python2.6/dist-packages/django/template/base.py" in render
921. dict = func(*args)
File "/usr/local/lib/python2.6/dist-packages/django/contrib/admin/templatetags/admin_list.py" in result_list
232. 'results': list(results(cl))}
File "/usr/local/lib/python2.6/dist-packages/django/contrib/admin/templatetags/admin_list.py" in results
217. yield ResultList(None, items_for_result(cl, res, None))
File "/usr/local/lib/python2.6/dist-packages/django/contrib/admin/templatetags/admin_list.py" in __init__
209. super(ResultList, self).__init__(*items)
File "/usr/local/lib/python2.6/dist-packages/django/contrib/admin/templatetags/admin_list.py" in items_for_result
137. f, attr, value = lookup_field(field_name, result, cl.model_admin)
File "/usr/local/lib/python2.6/dist-packages/django/contrib/admin/util.py" in lookup_field
218. value = attr()
File "/usr/local/lib/python2.6/dist-packages/django/db/models/base.py" in __str__
377. return force_unicode(self).encode('utf-8')
File "/usr/local/lib/python2.6/dist-packages/django/utils/encoding.py" in force_unicode
71. s = unicode(s)
File "/home/lechu/apps/cv/../cv/mycv/models.py" in __unicode__
31. return self.company.decode('utf8')
File "/usr/lib/python2.6/encodings/utf_8.py" in decode
16. return codecs.utf_8_decode(input, errors, True)
Exception Type: TemplateSyntaxError at /admin/mycv/experience/
Exception Value: Caught UnicodeEncodeError while rendering: 'ascii' codec can't encode characters in position 4-5: ordinal not in range(128)
104 : {% endblock %}
105 :
Traceback:
File

Your __unicode__ method is unfortunately nonsense.
decode is for converting bytestrings to unicode, but self.company is already unicode. So calling decode('utf-8') on it means that Python has to implicitly encode it to a bytestring first, which it does by the default ascii encoding - which will fail as soon as you have any accented characters.
I don't know what you were trying to do with that method, but __unicode__ methods should always return unicode. Just return self.company is the correct thing to do here.

Related

'NoneType' object has no attribute 'strip' - CS50W Wiki

I'm getting this error while trying to create a search function in Django.
This is where I'm having trouble: If the query does not match the name of an encyclopedia entry, the user should instead be taken to a search results page that displays a list of all encyclopedia entries that have the query as a substring. For example, if the search query were ytho, then Python should appear in the search results.
View:
def search(request):
if request.method == 'POST':
search_title = request.POST['q']
content = converter(search_title)
if search_title is not None:
return render(request, "encyclopedia/entry.html", {
"entry": content,
"entryTitle": search_title
})
else:
entries = util.list_entries()
search_pages = []
for entry in entries:
if search_title in entries:
search_pages.append(entry)
return render(request, "encyclopedia/search.html",{
"entries": search_pages
})
HTML:
<form action="{% url 'search' %}" method="POST">
{% csrf_token %}
<input class="search" type="text" name="q" placeholder="Search Encyclopedia">
</form>
Traceback:
Traceback (most recent call last):
File "C:\Users\anshi\.virtualenvs\storefront-bp3LZ8Cr\lib\site-packages\django\core\handlers\exception.py", line 55, in inner
response = get_response(request)
File "C:\Users\anshi\.virtualenvs\storefront-bp3LZ8Cr\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "D:\Python\Py Projects\CS50 attempt 00\wiki\encyclopedia\views.py", line 70, in search
content = converter(search_title)
File "D:\Python\Py Projects\CS50 attempt 00\wiki\encyclopedia\views.py", line 19, in converter
html = Markdowner.convert(content)
File "C:\Users\anshi\.virtualenvs\storefront-bp3LZ8Cr\lib\site-packages\markdown\core.py", line 248, in convert
if not source.strip():
AttributeError: 'NoneType' object has no attribute 'strip'
[21/Dec/2022 02:09:18] "POST /search/ HTTP/1.1" 500 72472
Traceback shows that the error is during content = converter(search_title).
So either converter has a bug, or search_title = request.POST['q'] is not a valid search_title. (None? Null string? )
Try printing / debugging search_title or investigate in more detail just what is being POSTed by your client.
BTW, please get tracebacks formatted readably after cut/pasting!

Interpret name with nested string

I'm trying to read my conda-forge recipe:
from jinja2 import Environment, BaseLoader
text = """
{% set name = "foo" %}
requires:
- {{ name }}
- {{ compiler('c') }}
"""
rtemplate = Environment(loader=BaseLoader).from_string(text)
data = rtemplate.render(**{"compiler('c')": "foo"})
print(data)
but the (illegal?) field {{ compiler('c') }} throws:
Traceback (most recent call last):
File "/Users/tdegeus/data/prog/src/conda_envfile/t.py", line 14, in <module>
data = rtemplate.render(**{"compiler('cxx')": "foo"})
File "/Users/tdegeus/miniforge3/envs/test/lib/python3.10/site-packages/jinja2/environment.py", line 1301, in render
self.environment.handle_exception()
File "/Users/tdegeus/miniforge3/envs/test/lib/python3.10/site-packages/jinja2/environment.py", line 936, in handle_exception
raise rewrite_traceback_stack(source=source)
File "<template>", line 6, in top-level template code
File "/Users/tdegeus/miniforge3/envs/test/lib/python3.10/site-packages/jinja2/utils.py", line 83, in from_obj
if hasattr(obj, "jinja_pass_arg"):
jinja2.exceptions.UndefinedError: 'compiler' is undefined
Can I solve this with jinja2, or do I need to do pre-processing?

TypeError: Object of type Decimal is not JSON serializable | Django

I am getting quite unusual error. I got pretty confused because of this. When I iterate over the cart items and try to view them it throws a TypeError Object of type Decimal is not JSON serializable. But if i remove the block from my templates then refresh the page and again add the same block to my templates and refresh the page it works. I have added some screenshots. Please have a look and help me out with this
cart.py
class Cart(object):
def __init__(self, request):
"""
Initialize the cart
"""
self.session = request.session
cart = self.session.get(settings.CART_SESSION_ID)
if not cart:
# save an empty cart in the session
cart = self.session[settings.CART_SESSION_ID] = {}
self.cart = cart
def add(self, product, quantity=1, override_quantity=False):
"""
Add a product to the cart or update its quantity
"""
product_id = str(product.id)
if product_id not in self.cart:
self.cart[product_id] = {
'quantity': 0,
'price': str(product.price)
}
if override_quantity:
self.cart[product_id]['quantity'] = quantity
else:
self.cart[product_id]['quantity'] += quantity
self.save()
def __iter__(self):
"""
Iterate over the items in the cart
and get the products from the database
"""
product_ids = self.cart.keys()
# get the product objects and add the o the cart
products = Product.objects.filter(id__in=product_ids)
cart = self.cart.copy()
for product in products:
cart[str(product.id)]['product'] = product
for item in cart.values():
item['price'] = Decimal(item['price'])
item['total_price'] = item['price'] * item['quantity']
yield item
def get_total_price(self):
"""
Calculate the total cost of the items in the cart
"""
return sum(Decimal(item['price']) * item['quantity'] for item in self.cart.values())
orders.py
def order_create(request):
cart = Cart(request)
order = None
address_form = AddressCheckoutForm()
billing_address_id = request.session.get('billing_address_id', None)
shipping_address_id = request.session.get('shipping_address_id', None)
order, created = Order.objects.get_or_create(user=request.user, ordered=False)
if shipping_address_id:
shipping_address = Address.objects.get(id=shipping_address_id)
order.shipping_address = shipping_address
del request.session['shipping_address_id']
if billing_address_id:
billing_address = Address.objects.get(id=billing_address_id)
order.billing_address = billing_address
del request.session['billing_address_id']
if billing_address_id or shipping_address_id:
order.save()
if request.method == 'POST':
for item in cart:
OrderItem.objects.create(
order=order,
product=item['product'],
price=item['price'],
quantity=item['quantity']
)
order.ordered = True
order.save()
cart.clear()
return render(request, 'orders/order/created.html', {'order': order})
return render(request, 'orders/order/create.html', {'cart': cart, 'address_form': address_form, 'object': order})
create.html
<h1>Checkout</h1>
{% if not object.shipping_address %}
<h3>Shipping</h3>
{% url "addresses:checkout_address_create" as checkout_address_create %}
{% include 'address/form.html' with form=address_form next_url=request.build_absolute_uri action_url=checkout_address_create address_type='shipping' %}
{% elif not object.billing_address %}
<h3>Billing</h3>
{% url "addresses:checkout_address_create" as checkout_address_create %}
{% include 'address/form.html' with form=address_form next_url=request.build_absolute_uri action_url=checkout_address_create address_type='billing' %}
{% else %}
{% for item in cart %}
{{ item.quantity }} X {{ item.product.name }}
{{ item.total_price }}
{% endfor %}
<p>Total Price: {{ cart.get_total_price }}</p>
<form action="" method="POST">
{% csrf_token %}
<p><input type="submit" value="Place Order"></p>
</form>
{% endif %}
Traceback
Internal Server Error: /order/create/
Traceback (most recent call last):
File "/home/duke/Monday/truck-giggle/env/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/home/duke/Monday/truck-giggle/env/lib/python3.8/site-packages/django/utils/deprecation.py", line 96, in __call__
response = self.process_response(request, response)
File "/home/duke/Monday/truck-giggle/env/lib/python3.8/site-packages/django/contrib/sessions/middleware.py", line 58, in process_response
request.session.save()
File "/home/duke/Monday/truck-giggle/env/lib/python3.8/site-packages/django/contrib/sessions/backends/db.py", line 83, in save
obj = self.create_model_instance(data)
File "/home/duke/Monday/truck-giggle/env/lib/python3.8/site-packages/django/contrib/sessions/backends/db.py", line 70, in create_model_instance
session_data=self.encode(data),
File "/home/duke/Monday/truck-giggle/env/lib/python3.8/site-packages/django/contrib/sessions/backends/base.py", line 105, in encode
serialized = self.serializer().dumps(session_dict)
File "/home/duke/Monday/truck-giggle/env/lib/python3.8/site-packages/django/core/signing.py", line 87, in dumps
return json.dumps(obj, separators=(',', ':')).encode('latin-1')
File "/usr/lib/python3.8/json/__init__.py", line 234, in dumps
return cls(
File "/usr/lib/python3.8/json/encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/usr/lib/python3.8/json/encoder.py", line 257, in iterencode
return _iterencode(o, 0)
File "/usr/lib/python3.8/json/encoder.py", line 179, in default
raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type Decimal is not JSON serializable
[29/Jul/2020 14:20:17] "GET /order/create/ HTTP/1.1" 500 102125
The error
code block that is raising the error
removing the block
after removing the block and refreshing the page
adding the block again
after adding the block and refreshing the page
As you can see before removing the code block the error is there, after removing it and refreshing the page and adding the code block back to the templates and refreshing the page again seems to work fine. Can you please help me out with this?
The problem here at this line
for product in products:
cart[str(product.id)]['product'] = product
product's instance has a decimal field, the price field, which is not JSON serializable.
So to solve this error, you can add explicitly the product's fields, you want to use in the template, into the session data to loop over.
For instance:
cart[str(product.id)]['product_name'] = product.name
cart[str(product.id)]['product_price'] = float(product.price)
and for the price field, instead of converting it into Decimal, you can use float:
for item in cart.values():
item['price'] = float(item['price'])

I can’t send the desired url to the address bar

I need to do so that I can open the news from the main page. But I ran into a problem, the interpreter throws the error "ValueError: Field 'id' expected a number but got 'news1' (I add the Traceback and code below). I understand that it expects a number, but receives a string, but I can’t figure out how to fix it Who knows, please help
Traceback:
Internal Server Error: /news1/
Traceback (most recent call last):
File "C:\Users\dadi2\Desktop\church\venv\lib\site-packages\django\db\models\fields\__init__.py", line 1772, in get_prep_value
return int(value)
ValueError: invalid literal for int() with base 10: 'news1'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\dadi2\Desktop\church\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Users\dadi2\Desktop\church\venv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\dadi2\Desktop\church\venv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\dadi2\Desktop\church\venv\lib\site-packages\django\views\generic\base.py", line 71, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Users\dadi2\Desktop\church\venv\lib\site-packages\django\views\generic\base.py", line 97, in dispatch
return handler(request, *args, **kwargs)
File "C:\Users\dadi2\Desktop\church\website\views.py", line 18, in get
posts = Blog.objects.get(id=slug)
File "C:\Users\dadi2\Desktop\church\venv\lib\site-packages\django\db\models\manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\dadi2\Desktop\church\venv\lib\site-packages\django\db\models\query.py", line 404, in get
clone = self._chain() if self.query.combinator else self.filter(*args, **kwargs)
File "C:\Users\dadi2\Desktop\church\venv\lib\site-packages\django\db\models\query.py", line 904, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "C:\Users\dadi2\Desktop\church\venv\lib\site-packages\django\db\models\query.py", line 923, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "C:\Users\dadi2\Desktop\church\venv\lib\site-packages\django\db\models\sql\query.py", line 1351, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "C:\Users\dadi2\Desktop\church\venv\lib\site-packages\django\db\models\sql\query.py", line 1378, in _add_q
child_clause, needed_inner = self.build_filter(
File "C:\Users\dadi2\Desktop\church\venv\lib\site-packages\django\db\models\sql\query.py", line 1312, in build_filter
condition = self.build_lookup(lookups, col, value)
File "C:\Users\dadi2\Desktop\church\venv\lib\site-packages\django\db\models\sql\query.py", line 1166, in build_lookup
lookup = lookup_class(lhs, rhs)
File "C:\Users\dadi2\Desktop\church\venv\lib\site-packages\django\db\models\lookups.py", line 22, in __init__
self.rhs = self.get_prep_lookup()
File "C:\Users\dadi2\Desktop\church\venv\lib\site-packages\django\db\models\lookups.py", line 72, in get_prep_lookup
return self.lhs.output_field.get_prep_value(self.rhs)
File "C:\Users\dadi2\Desktop\church\venv\lib\site-packages\django\db\models\fields\__init__.py", line 1774, in get_prep_value
raise e.__class__(
ValueError: Field 'id' expected a number but got 'news1'.
[09/May/2020 14:10:52] "GET /news1/ HTTP/1.1" 500 132319
Not Found: /favicon.ico
[09/May/2020 14:10:53] "GET /favicon.ico HTTP/1.1" 404 2430
Views:
from django.shortcuts import get_object_or_404, render
from django.views.generic.base import View
from .models import Blog, Event
# Create your views here.
class EventView(View):
def get(self, request):
events = Event.objects.all()
posts = Blog.objects.all()
return render(request, "home/home.html", {"events": events, "posts":posts})
class BlogDetailView (View):
def get(self, request, slug):
posts = Blog.objects.get(id=slug)
return render(request, "home/blog-detail.html", {"posts": posts})
Models:
from django.db import models
from datetime import date
from django.urls import reverse
# Create your models here.
class Blog(models.Model):
"""Новости"""
name = models.CharField("Заголовок", max_length=100)
description = models.TextField("Описание")
descriptionTwo = models.TextField("Описание (второй абзац)", blank=True, default="")
blockquote = models.TextField("Цитата", blank=True, default="")
short = models.TextField("Краткое описание", max_length=300)
poster = models.ImageField("Изображение", upload_to="news/")
prewiew = models.ImageField("Превью", upload_to="news/")
dataPost = models.DateField("Дата публикации", default=date.today)
url = models.SlugField(max_length=160, unique=True, blank=True)
draft = models.BooleanField("Черновик", default=False)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse("home_detail", kwargs={"slug": self.url})
class Meta:
verbose_name = "Новости"
verbose_name_plural = "Новости"
class Event(models.Model):
"""События"""
name = models.CharField("Заголовок", max_length=100)
adress = models.TextField("Адрес")
description = models.TextField("Описание")
short = models.TextField("Краткое описание")
phone = models.TextField("Контактный номер телефона")
email = models.EmailField()
image = models.ImageField("Изображение", upload_to="event/")
dataStart = models.DateField("Дата старта", default=date.today)
def __str__(self):
return self.name
class Meta:
verbose_name = "Событие"
verbose_name_plural = "События"
Urls:
from django.urls import path
from . import views
urlpatterns = [
path("", views.EventView.as_view()),
path("<slug:slug>/", views.BlogDetailView.as_view(), name="home_detail")
]
HTML:
<!-- Latest-Blog -->
<section class="latest_blog section-padding">
<div class="container">
<div class="blog">
<div class="section-header text-center">
<h2 class="text-capitalize">Новости церкви</h2>
<p>Здесь вы найдёте самые последние новости из жизни церкви</p>
</div>
<div class="row">
{% if posts %}
{% for posts in posts %}
<article class="col-md-6 col-12">
<div class="blog_wrap">
<div class="blog_img">
<img src="{{ posts.prewiew.url }}" alt="image">
</div>
<div class="blog_info">
<div class="post_date">{{ posts.dataPost}}</div>
<h5>{{ posts.name }}</h5>
<p>{{ posts.short}}</p>
Details <i class="fa fa-caret-right"></i>
</div>
</div>
</article>
{% endfor %}
{% else %}
<p>На данный момент новостей нет</p>
{% endif %}
</div>
</div>
</div>
</section>
<!-- Latest-Blog -->
you have defined the href using the post.url field in the template
<h5>{{ posts.name }}</h5>
so the queryset has to be requested by url slug
class BlogDetailView (View):
def get(self, request, slug):
posts = Blog.objects.get(url=slug)
return render(request, "home/blog-detail.html", {"posts": posts})

Update state of form with button django

Every row of the table has a button with the pk of the element. Using the button should fill the form with the states of the entry.
I think I have a problem with the renderer, as it clears my form but I'm not sure how to fix this. I would like to achieve this without the use of AJAX if possible.
HTML:
<form action="" method="POST">
{% csrf_token %}
<input type="hidden" name="pk" value="{{ post.pk }}">
<input class="btn btn-default btn-danger" name="update" type="submit" value="Ändern"/>
</form>
views.py:
from django.shortcuts import render
from django.utils import timezone
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect
from .forms import NameForm
from .models import Eintrag
#login_required()
def get_name(request):
# if this is a POST request we need to process the form data
if request.method == 'POST' and 'add' in request.POST:
# create a form instance and populate it with data from the request:
form = NameForm(request.POST)
# check whether it's valid:
if form.is_valid():
#Eintrag.objects.filter(Name=request.user).delete()
eintrag = form.save(commit=False)
# process the data in form.cleaned_data as required
# ...
# redirect to a new URL:
eintrag.Name = request.user # Set the user object here
eintrag.pub_date = timezone.now() # Set the user object here
eintrag.save()
return HttpResponseRedirect(request.path) # generate an empty form
if request.method == 'POST' and 'delete' in request.POST:
Eintrag.objects.filter(id=request.POST['pk']).delete()
return HttpResponseRedirect(request.path)
if request.method == 'POST' and 'update' in request.POST:
form = NameForm()
form.fields['Anmeldung'] = Eintrag.objects.get(id=request.POST['pk']).Anmeldung
form.fields['Essen'] = Eintrag.objects.get(id=request.POST['pk']).Essen
form.fields['Email'] = Eintrag.objects.get(id=request.POST['pk']).Email
return HttpResponseRedirect(request.path) # this emptys my form
#posts = Eintrag.objects.filter(Name=request.user)
#return render(request, 'form/name.html', {'form': form, 'posts': posts}) # I get an AttributError with this
# if a GET (or any other method) we'll create a blank form
else:
form = NameForm()
posts = Eintrag.objects.filter(Name=request.user)
return render(request, 'form/name.html', {'form': form, 'posts': posts})
forms.py
from django import forms
from .models import Eintrag
class NameForm(forms.ModelForm):
class Meta:
model = Eintrag
fields = ['Anmeldung', 'Essen','Email']
models.py
from django.db import models
Anmeldung = (
('1', 'Ja'),
('2', 'Nein'),
('3', 'Noch nicht entschieden'),
)
Essen = (
('1', 'Fleisch'),
('2', 'Fisch'),
('3', 'Vegetarisch'),
)
class Eintrag(models.Model):
Name = models.CharField(max_length=200)
Anmeldung = models.CharField(
max_length=2,
choices=Anmeldung)
Essen = models.CharField(
max_length=2,
choices=Essen)
Email = models.EmailField()
pub_date = models.DateTimeField('date published')
With my try to just create posts and render after the POST, I'm getting some error. like this:
Exception Type: AttributeError
Exception Value:
'str' object has no attribute 'get_bound_field'
Thanks for your help.
form.['field'] should set the current state of the form to the selected data, I tried form['field'].initial too.
Full Traceback with:
posts = Eintrag.objects.filter(Name=request.user)
return render(request, 'form/name.html', {'form': form, 'posts': posts})
Template error:
In template C:\Users\basti\Desktop\hochzeit\form\templates\form\name.html, error at line 35
'str' object has no attribute 'get_bound_field'
25 : <div class="row">
26 :
27 :
28 : <div class="col-sm-10">
29 :
30 : <div class='container-fluid'>
31 : <br><br>
32 :
33 : <form action="" method="post">
34 : {% csrf_token %}
35 : {{ form }}
36 : <input type="submit" name="add" value="Update" />
37 : </form>
38 :
39 : {% include "form/post_list.html" %}
40 :
41 : </div>
42 : </div>
43 : </div>
44 :
45 : </body>
Traceback:
File "C:\Python35\lib\site-packages\django\core\handlers\exception.py" in inner
35. response = get_response(request)
File "C:\Python35\lib\site-packages\django\core\handlers\base.py" in _get_response
128. response = self.process_exception_by_middleware(e, request)
File "C:\Python35\lib\site-packages\django\core\handlers\base.py" in _get_response
126. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Python35\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view
21. return view_func(request, *args, **kwargs)
File "C:\Users\basti\Desktop\hochzeit\form\views.py" in get_name
41. return render(request, 'form/name.html', {'form': form, 'posts': posts})
File "C:\Python35\lib\site-packages\django\shortcuts.py" in render
36. content = loader.render_to_string(template_name, context, request, using=using)
File "C:\Python35\lib\site-packages\django\template\loader.py" in render_to_string
62. return template.render(context, request)
File "C:\Python35\lib\site-packages\django\template\backends\django.py" in render
61. return self.template.render(context)
File "C:\Python35\lib\site-packages\django\template\base.py" in render
175. return self._render(context)
File "C:\Python35\lib\site-packages\django\template\base.py" in _render
167. return self.nodelist.render(context)
File "C:\Python35\lib\site-packages\django\template\base.py" in render
943. bit = node.render_annotated(context)
File "C:\Python35\lib\site-packages\django\template\base.py" in render_annotated
910. return self.render(context)
File "C:\Python35\lib\site-packages\django\template\base.py" in render
999. return render_value_in_context(output, context)
File "C:\Python35\lib\site-packages\django\template\base.py" in render_value_in_context
978. value = str(value)
File "C:\Python35\lib\site-packages\django\utils\html.py" in <lambda>
380. klass.__str__ = lambda self: mark_safe(klass_str(self))
File "C:\Python35\lib\site-packages\django\forms\forms.py" in __str__
136. return self.as_table()
File "C:\Python35\lib\site-packages\django\forms\forms.py" in as_table
279. errors_on_separate_row=False)
File "C:\Python35\lib\site-packages\django\forms\forms.py" in _html_output
201. bf = self[name]
File "C:\Python35\lib\site-packages\django\forms\forms.py" in __getitem__
167. self._bound_fields_cache[name] = field.get_bound_field(self, name)
Exception Type: AttributeError at /form/
Exception Value: 'str' object has no attribute 'get_bound_field'
As I said in the comment, that's not how you assign values to a form field. What you've done is to completely replace the field object in the form's dictionary with the value from the model, which isn't at all what you want to do.
With a normal form, you could pass this data in via the initial dict when creating the form instance. But this is a ModelForm, which is specifically designed to take values from models; you should just pass the model instance itself via the instance argument:
eintrag = Eintrag.objects.get(id=request.POST['pk'])
form = NameForm(instance=eintrag)
posts = Eintrag.objects.filter(Name=request.user)
return render(request, 'form/name.html', {'form': form, 'posts': posts})