django show me "django.db.models.query_utils.DeferredAttribute object at" - python

I'm trying to get values from an object of my DB on a form in html to edit it but when I call the current "value" from the attribute I get this:
Form
HTML
<form enctype="multipart/form-data" method="post">
{% csrf_token %}
{% for campo in formulario %}
<div class="mb-3">
<label for="" class="form-label">{{ campo.label }}:</label>
{% if campo.field.widget.input_type == 'file' and campo.value %}
<br/>
<img src="{{MEDIA_URL}}/imagenes/{{campo.value}}" width="100"srcset="">
{% endif %}
<input
type="{{ campo.field.widget.input_type}}"
class="form-control"
name="{{ campo.name }}"
id=""
aria-describedby="helpId"
placeholder="{{campo.label}}"
value="{{campo.value | default:''}}"
/>
</div>
<div class="col-12 help-text"> {{campo.errors}}</div>
{% endfor %}
<input name="" id="" class="btn btn-success" type="submit" value="Enviar informacion">
</form>
Views
Models

I found the problem... I instantiate the class instead of the object

Related

Form errors are displayed at the wrong place

I am working on my Blog website and in the registration template I should insert the username and email and password so I can register but if i have an error it should give me what is it BUT every error I have it goes to the bottom of the template, not under the field I want.
P.S.: I am using Django framework!!
template.html:
<h1>Register</h1>
<form action="" method="post">
{% csrf_token %}
<div class="form-floating mb-3">
<input type="text" class="form-control" id="floatingInput" placeholder="name#example.com" name="username">
<label for="floatingInput">Username</label>
</div>
<div class="form-floating mb-3">
<input type="email" class="form-control" id="floatingInput" placeholder="name#example.com" name="email">
<label for="floatingInput">Email</label>
</div>
<div class="form-floating">
<input type="password" class="form-control" id="floatingPassword" placeholder="Password" name="password1">
<label for="floatingPassword">Password</label>
</div>
<div class="form-floating">
<input type="password" class="form-control mt-3" id="floatingPassword" placeholder="Password" name="password2">
<label for="floatingPassword">Re-Type Password</label>
</div>
{% if forms.errors %}
{% for field in forms %}
{% for error in field.errors %}
<h5 style="color: red;">{{ error|escape }}</h5>
{% endfor %}
{% endfor %}
{% for error in forms.non_field_errors %}
<h5 style="color: red;">{{ error|escape }}</h5>
{% endfor %}
{% endif %} <br>
<button type="submit">Register</button>
</form>
</div>
if anything needs to be added other then the template please tell me in the comment!!
Thanks in advance!! <3
You render the field errors at the bottom as well, hence the error. In order to render the errors of a specific field, you should iterate over the errors of that field, so:
<div class="form-floating mb-3">
{% for error in forms.username.errors %}
<h5 style="color: red;">{{ error|escape }}</h5>
{% endfor %}
<input type="text" class="form-control" id="floatingInput" placeholder="name#example.com" name="username">
<label for="floatingInput">Username</label>
</div>
and this for all fields of course.

MultiValueDictKeyError in Django Project

View.py
if req.method == 'POST':
df = DocumentForm.objects.filter(document_id=id)
logging.info('LOG: I am here')
if df.exists():
for d in df:
description = req.POST['{}'.format(d.description, False)]
displayName = req.POST['{}'.format(d.displayName, False)]
df.update(displayName=displayName, description=description)
return redirect('/adboard/upd')
HTML File
<form class="needs-validation" action="{{id}}" method="POST" enctype="multipart/form-data" novalidate>
{% csrf_token %}
<div class="row mt-3 mb-3"></div>
{% if messages %}
<div class="alert alert-danger" role="alert">
{% for message in messages %}
{{ message }}
{% endfor %}
</div>
{% endif %}
{% for df in data %}
<div class="form-group">
<small class="text-muted bold-label m-lower">{{{df.field}}}</small>
<label for="validationCustom01">{{df.displayName}}</label>
<input type="text" class="form-control" id="validationCustom01" name="{{df.displayName}}" value="{{df.displayName}}" placeholder="Enter Display Name">
<label for="validationCustom01">{{df.description}}</label>
<input type="text" class="form-control" id="validationCustom01" name="{{df.description}}" value="{{df.description}}" placeholder="Enter description">
<div class="invalid-feedback">
Please enter required fileds.
</div>
<!-- <div class="valid-feedback">
Looks good!
</div> -->
</div>
{% endfor %}
<button type="submit" class="btn btn-primary btn-red btn-block">SAVE</button>
</form>
What I am trying to achieve is.
Pass a variable form to the user to fill
And I get the result.
I can't tell what the input id/name would be because it's a variable.
But I am finding it difficult getting the value from the view.py file.
change
req.POST['{}'.format(d.description, False)]
to
req.POST.get('{}'.format(d.description, False))

Get the dropdown data and update the data in Django

Dear all of the Django developer community, I am facing this below issue:
I try to update a db table data which has one field and one drop down field. But I only get basic field data and not drop down list data.
I request expert help me. How can I fix this issue?
Advanced Thanks For All
views.py
def update_brands(request, id):
brand = Brand.objects.get(id=id)
form = AddBrandForms(request.POST, instance=brand)
if form.is_valid():
form.save()
return redirect('/parts/brands')
return render(request, 'parts/edit_brands.html', {'brand': brand })
edit_brands.html
{% extends 'parts/base.html' %}
{% block content %}
<form method="post" action="/parts/update_brands/{{brand.id}}/" class="post-form">
{% csrf_token %}
<div class="form-group row">
<label class="col-sm-2 col-form-label">Country Name:</label>
<div class="col-sm-4">
<input type="text" name="country" value="{{ brand.brand_name }}"/>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Country Name:</label>
<div class="col-sm-4">
<select id="cars" name="cars">
{% for db in dbf.all %}
<option value="{{ db.db}}">{{ db.db}}</option>
{% endfor %}
</select>
</div>
</div>
<button type="submit" class="btn btn-success">Submit</button>
</form>
{% endblock %}
try this
{% extends 'parts/base.html' %}
{% block content %}
<form method="post" action="/parts/update_brands/{{brand.id}}/" class="post-form">
{% csrf_token %}
<div class="form-group row">
<label class="col-sm-2 col-form-label">Country Name:</label>
<div class="col-sm-4">
<input type="text" name="country" value="{{ brand.brand_name }}"/>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Country Name:</label>
<div class="col-sm-4">
<select id="cars" name="cars">
{% for car in brand.all %}
<option value="{{ car }}">{{ car }}</option>
{% endfor %}
</select>
</div>
</div>
<button type="submit" class="btn btn-success">Submit</button>
</form>
{% endblock %}

Add Bootstrap to Inbulit Login View Django

I am using the default view for logging the users.So I have not made any modelForm for it.So I am not able to provide any bootstrap class to the input fields i.e username and password. So my login form is looking ugly.Is there anyway. I want to add bootstrap class form-control to the input fields username and password.
Following is my HTML and URL snippets. All functions and classes used have their modules imported.
urls.py
url(r'^login/$', login, {'template_name': 'app/login.html'}),
login.html
<form class="form-signin" method="post"><span class="reauth-email"> </span>
{% csrf_token %}
<!--{{form.as_p}}-->
{% for field in form %}
<div class="fieldWrapper">
{{ field.errors }}
{{ field.label_tag }} {{ field }}
{% if field.help_text %}
<p class="help">{{ field.help_text|safe }}</p>
{% endif %}
</div>
{% endfor %}
<!--<input class="form-control" type="email" required="" placeholder="Email address" autofocus="" id="inputEmail">-->
<!--<input class="form-control" type="password" required="" placeholder="Password" id="inputPassword">-->
<div class="checkbox">
<div class="checkbox">
<label><input type="checkbox">Remember me</label>
</div>
</div>
<button class="btn btn-primary btn-block btn-lg btn-signin" type="submit">Sign in</button>
</form>
change your login template to this
you can modify it
<div class="center-block" id="login" style="width: 40%;">
<form class="form-horizontal form" name="LoginForm" method="post">
{% csrf_token %}
{% if next %}
<input type="hidden" name="next" value="{{ next }}" />
{% endif %}
<div class="control-group">
<label class="control-label" for="username">Username</label>
<div class="controls">
<input class="form-control" type="text" id="username" name="username" placeholder="Username">
</div>
</div>
<div class="control-group">
<label class="control-label" for="password">Password</label>
<div class="controls">
<input class="form-control" type="password" name="password" id="password" placeholder="Password">
</div>
</div><br>
<div class="control-group">
<div class="controls">
<button type="submit" class="btn btn-success">Login</button> or sign up
</div>
</div>
</form>
</div>
If you want to add a CSS-class, you can write a custom template filter
First, read how to make a custom template filter
https://docs.djangoproject.com/en/1.11/howto/custom-template-tags/#writing-custom-template-filters
You'll have write here
my_app/
__init__.py
models.py
templatetags/
__init__.py
my_app_extra_filters.py # <-----------------
views.py
smth like this
my_app_extra_filters.py
from django import template
register = template.Library()
#register.filter
def add_class(modelform_input, css_class):
return modelform_input.as_widget(attrs={'class': css_class})
*if you want to know about as_widget() method, used above:
https://docs.djangoproject.com/en/1.11/ref/forms/api/#django.forms.BoundField.as_widget
then use it in the template
{% load my_app_extra_filters %}
...
{{ field.errors }}
{{ field.label_tag }}
{{ field|add_class:'bootstrap_class_name' }}
all you need is add this codes to your loginform in form.py
class AuthenticationForm(AuthenticationForm):
.
.
.
def __init__(self, *args, **kwargs):
super(UserCreationForm, self).__init__(*args, **kwargs)
for fieldname in ['username', 'password1', 'password2',]:
self.fields[fieldname].widget.attrs = {'class':'form-control'}

django form template designer friendly

I am doing the django project right now. I love the principle of DRY. I have a form which can be applied to all other pages which needs it. I mean a generic form based from django docs. But in the form, there can be select type, file upload, checkbox, radio etc which I dont like the design of native html. I want to leverage the design of material with some customization. How can I do it? Below is my form and my form has checkbox, file upload and multiple select which I need to customize. In a nutshell, my question is how do I make my generic form designer friendly?
For now I am handling my form template as follow
<form class="form" role="form" action="" method="post">
{% csrf_token %}
<div class="form-group label-floating">
<label class="control-label" for="{{ form.company.id_for_label}}">Company</label>
<select class="form-control" name="{{ form.company.name }}" id="{{ form.company.id_for_label}}">
<option value=""></option>
{% for id, name in form.company.field.choices %}
<option value="{{ id }}" class="option">{{ name }}</option>
{% endfor %}
</select>
</div>
<div class="form-group label-floating">
<label class="control-label" for="{{ form.name.id_for_label}}">Job Title</label>
<input type="text" id="{{ form.name.id_for_label }}" name="{{ form.name.name }}" class="form-control">
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group label-floating">
<label class="control-label" for="{{ form.description.id_for_label}}">{{ form.description.label }}</label>
<div class="markdownx">
{{ form.description|add_css:'form-control' }}
</div>
</div>
</div>
</div>
<div class="form-group label-floating">
<label class="control-label" for="{{ form.category.id_for_label}}">{{ form.category.label }}</label>
<select class="form-control" name="{{ form.category.name }}" id="{{ form.category.id_for_label}}">
<option value=""></option>
{% for id, name in form.category.field.choices %}
<option value="{{ id }}">{{ name }}</option>
{% endfor %}
</select>
</div>
<div class="form-group label-floating">
<label class="control-label" for="{{ form.city.id_for_label}}">{{ form.city.label }}</label>
<input type="text" id="{{ form.city.id_for_label }}" name="{{ form.city.name }}" class="form-control">
</div>
<div class="form-group label-floating">
<label class="control-label" for="{{ form.address.id_for_label}}">{{ form.address.label }}</label>
<input type="text" id="{{ form.address.id_for_label }}" name="{{ form.address.name }}" class="form-control">
</div>
</form>
This way the code to show the form becomes so huge and its only 1 form. Its not good to write such huge code for the app with more than 8 10 forms.
The better way is
{% load add_css %}
<div class="row">
<div class="col-lg-12">
<div class="text-center m-t-lg">
<form class="form-horizontal" role="form" action="" method="post" enctype='multipart/form-data'>
{% csrf_token %}
{% for field in form %}
{% if field.errors %}
<div class="form-group has-error">
<label class="col-sm-2 control-label" for="id_{{ field.name }}">{{ field.label }}</label>
<div class="col-sm-10">
{{ field|add_css:'form-control' }}
<span class="help-block">
{% for error in field.errors %}{{ error }}{% endfor %}
</span>
</div>
</div>
{% else %}
<div class="form-group">
<label class="col-sm-2 control-label" for="id_{{ field.name }}">{{ field.label }}</label>
<div class="col-sm-10">
{{ field|add_css:'form-control' }}
{% if field.help_text %}
<p class="help-block"><small>{{ field.help_text }}</small></p>
{% endif %}
</div>
</div>
{% endif %}
{% endfor %}
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
</div>
</div>
</div>
But here is one difficulty I am facing. I can't check if its a file upload field or multiple select field etc so I can design them accordingly. Because sometime, I need to handle many divs to show it properly.
Is there any way to make the form template more flexible for the designer?
You can use the arg widget in your field definition, and create some custom widget template. So you define them once, and you just have to care about printing field in your template. Here doc on widget et custom widget

Categories