Error during template rendering using extra_context django - python

Hello I'm using extra_context in views and in the HTML I'm passing it, but it seems that I am doing it wrong because I get this error:
ProgrammingError at /informacion-tiendas/add
column InformacionTiendas_informaciontiendas.nombre does not exist
LINE 1: ...ECT "InformacionTiendas_informaciontiendas"."id", "Informaci...
And when commenting the extra_context line in views, the HTML page is already seen without errors, obviously the context does not pass and the inputs do not appear, but at least there are no errors
Does anyone know why?
views.py
class InformacionTiendasAdd(CreateView):
model=InformacionTiendas
form_class=InformacionTiendasForm
template_name='InformacionTiendas/informacion-tiendas-agregar.html'
success_url=reverse_lazy('InformacionTiendas:list_tiendas')
extra_context={'tiendas': InformacionTiendas.objects.all()}
models.py
class InformacionTiendas(models.Model):
nombre=models.CharField(max_length=255)
registro_desde=models.DateTimeField(default=datetime.now )
tax_id=models.IntegerField()
def __str__(self):
return f'{self.nombre} {self.registro_desde} {self.tax_id}'
informacion-agregar-tiendas.html
<form class="needs-validation" novalidate>
{% for tienda in tiendas %}
<div class="row mb-3">
<div class="col-md-12">
<div>
<label class="form-label" for="validationCustom01">Name</label>
{{ tienda.nombre }}
<div class="invalid-feedback">
Please provide the workshop name.
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="mb-3">
<label class="form-label" for="validationCustom06">Registration</label>
{{ tienda.registro_desde }}
Please provide workshop`s registration number.
</div>
</div>
</div>
<div class="col-md-6">
<div class="mb-3">
<label class="form-label" for="validationCustom07">TAX ID</label>
{{ tienda.tax_id }}
<div class="invalid-feedback">
Please provide workshop`s registration number.
</div>
</div>
</div>
</div>
{% endfor %}
</form>

Based on the new information from your edit, it looks like you haven’t migrated the database.
Try running this in your shell:
python manage.py makemigrations
python manage.py migrate

Related

Modifying django-allauth error messages on a signup form

I'm currently building a website that makes use of django-allauth and I've come across a problem regarding error messages while using a custom User model.
My custom User model is called CustomUser, I've noticed that when django-allauth handles errors regarding the username, it uses the name of the user model as the starting word to the error message's sentence. Example image is linked below.
Image of the error message
How can I change this error message? I'd like to stay away from overriding any django-allauth views if possible, though I'd be happy with any solution!
This is my Django form code that makes use of django-crispy-forms:
<form class="signup" id="signup_form" method="post" action="{% url 'account_signup' %}">
{% csrf_token %}
<div class="row">
<div class="col-12 col-lg-7">
{{ form.email|attr:"autofocus"|as_crispy_field }}
</div>
<div class="col-12 col-lg-5">
{{ form.username|as_crispy_field }}
</div>
<div class="col-6 col-lg-4">
{{ form.first_name|as_crispy_field }}
</div>
<div class="col-6 col-lg-4">
{{ form.last_name|as_crispy_field }}
</div>
<div class="col-12 col-lg-4">
{{ form.birthday|as_crispy_field }}
</div>
<div class="col-12 col-sm-6">
{{ form.password1|as_crispy_field }}
</div>
<div class="col-12 col-sm-6">
{{ form.password2|as_crispy_field }}
</div>
<div class="col-12 text-center">
{{ form.captcha|as_crispy_field }}
{% for error in form.captcha.errors %}
{% if error %}
<style>
#div_id_captcha {
margin-bottom: 0px !important;
}
</style>
<span class="invalid-feedback d-block mb-3">
<strong>
You must complete the captcha to register
</strong>
</span>
{% endif %}
{% endfor %}
</div>
</div>
{% if redirect_field_value %}
<input type="hidden" name="{{ redirect_field_name }}" value="{{ redirect_field_value }}" />
{% endif %}
<button type="submit" class="btn btn-primary btn-light mb-3">Register <i class="fa fa-user-plus fa-fw"></i></button>
<p>Already have an account?<br /><small>Login here</small></p>
</form>

Can not save form with CreateView (Django, Python)

I am trying to save data that fill out with form to database but it doesn't work as well. when i click on Submit button nothing change, the webpage just refresh!
These are my codes.
Views.py
class HotelAdCreate(AuthorsAccessMixin,CreateView):
model = HotelBookingAd
form_class = HotelBookingAdForm
template_name = "account/article-create-update.html"
def form_valid(self,form):
form.save()
return super(HotelAdCreate).form_valid(form)
Forms.py
class HotelBookingAdForm(forms.ModelForm):
class Meta:
model = HotelBookingAd
fields = '__all__'
def clean_sales_price(self):
sales_price = self.cleaned_data["sales_price"]
purchase_price = self.cleaned_data["purchase_price"]
if sales_price > purchase_price:
raise forms.ValidationError("error.")
print("error")
return sales_price
Edit :
i just added template file codes to debaug clearly.
Template File
{% extends 'account/base.html' %}
{% load crispy_forms_tags %}
{% block title %}{% endblock %}
{% block title-meta %} آگهی{% endblock %}
{% block main %}
<div class="col-md-12">
<div class="card card-primary">
<div class="card-header">
<h3 class="card-title- mb-0">ایجاد آگهی </h3>
</div>
<div class="card-body">
<form method="post" enctype="multipart/form-data">{% csrf_token %}
<div class="row">
<div class="col-6">
{{form.title|as_crispy_field}}
</div>
<div class="col-6">
{{form.hotel_name|as_crispy_field}}
</div>
<div class="col-12">
{{form.sale_reason|as_crispy_field}}
</div>
<div class="col-6">
{{form.check_in_date|as_crispy_field}}
</div>
<div class="col-6">
{{form.check_out_date|as_crispy_field}}
</div>
<div class="col-6">
{{form.purchase_price|as_crispy_field}}
</div>
<div class="col-6">
{{form.sales_price|as_crispy_field}}
</div>
<div class="col-6">
{{form.city_name|as_crispy_field}}
</div>
<div class="col-6">
{{form.room_type|as_crispy_field}}
</div>
<div class="col-6">
{{form.confirm|as_crispy_field}}
</div>
{% if user.is_superuser %}
<div class="col-6">
{{form.slug_generator|as_crispy_field}}
</div>
{% endif %}
</div>
<button class="btn btn-success">ارسال مقاله</button>
{% if user.is_superuser and request.resolver_match.kwargs.pk %}
<a class="btn btn-danger "href="{% url 'account:hotelad-delete' request.resolver_match.kwargs.pk %}">
حذف مقاله
</a>
<a target="_blank" class="btn btn-dark "href="{% url 'primary:preview' request.resolver_match.kwargs.pk %}">
پیش نمایش
</a>
{% endif %}
</form>
</div>
</div>
</div>
{% endblock %}
I've tried different options, but I don't have enough skills to handle this problem.
Can anyone help me?
UPDATE (FIXED)
I found problem by my self, here it is :
As you see in forms.py, i am using __all__ for fields but in template i am not using all the fields, so form will not be valid.
To fix the bug completely i just added Exclude option and added the fields that i didn't use in template. finally everything works fine :)

i'm having trouble with my django code while i deleting the data from the table form on click of the delete button

But it will showing an error which is (TypeError at /deletecase deletecase() missing 1 required positional argument: 'pk') please help me out this
Here is the url link of the page:
```path("deletecase",views.deletecase,name="deletecase")```
THE VIEW FILE FUNCTION:
```
def policcasesdetails(request):
cases=Case.objects.all()
return render(request,'policeside/policcasesdetails.html',{'cases':cases})
def deletecase(request,pk):
obj=Case.objects.get(id=pk)
obj.delete()
return HttpResponse("Data is Deleted")
```
AND THE FORM IS:-
<div class="container">
<div class="content-middle">
<div class="col-md-12 sed-in">
<h3>Cases Details</h3>
{% for i in cases %}
<div class="col-md-4 sed-top">
<div class="top-sed">
<!-- <img src="{{ i.image.url }}" class="img-responsive" alt=""> -->
<!-- <label><span>{{ i.oname }}</span></label> -->
</div>
<h4>
Case Number- <a>{{i.casenumber}}</a>
</h4>
<p>Case Name- {{i.casename}}</p>
<p>Case Result- {{ i.caseresult }}</p>
<p>Case Conclusion- {{ i.casecoclusion }}</p>
<p><a href="{% url 'deletecase' i.id %}">
<button type="submit" value="delete" class="btn btn-
danger">Delete</button>
</p>
</div>
{% endfor %}
<div class="clearfix"> </div>
</div>
<div class="clearfix"> </div>
</div>
</div>
In your URL, pk is missing.
path("deletecase/<id>/",views.deletecase,name="deletecase")
This should solve your issue

How to modify css class using jinja2 macro

Hi guys i'm learning flask and have a problem. I'm trying to modify a input form control class based on validation.
In the jinja2 template i have the following (i'm using render_field) have imported the macro:
{% from 'includes/_formhelpers.html' import render_field %}
<div class="form-group">
<div class="input-group input-group-alternative mb-3">
<div class="input-group-prepend">
<span class="input-group-text"><i class="ni ni-hat-3"></i></span>
</div>
{{ render_field(form.username, placeholder="Username",class="form-control") }}
</div>
</div>
And then in the macro file i have the following content:
{% macro render_field(field) %}
{{ field(**kwargs)|safe }}
{% if field.errors %}
{% for error in field.errors %}
<input class="form-control is-invalid">
<div class="invalid-feedback">
{{ error }}
</div>
{% endfor %}
{% endif %}
{% endmacro %}
The problem is that the macro in rendering another input box
Generated HTML:
<div class="form-group">
<div class="input-group input-group-alternative mb-3">
<div class="input-group-prepend">
<span class="input-group-text"><i class="ni ni-hat-3"></i></span>
</div>
<input class="form-control" id="username" name="username" placeholder="Username" required="" type="text" value="pandazulweb">
<input class="form-control is-invalid">
<div class="invalid-feedback">
Username already in use.
</div>
</div>
I think it's something related to kwargs and how i'm passing the class to the template but i'm a noob with jinja2
Unless I’m missing something, it looks like the second field is due to the ‘<input class=“form-control is-invalid”>’ which you’re including in the error condition of your macro.
EDIT: In order to pass the class to a form field, you need to use ‘class_=“is-invalid”‘, not ‘class=‘. So just use that and remove the second input from your error case.
EDIT 2: I think I see what the problem is. You need to put the first call to field() inside the macro’s error block, in the else block. So only if there is no error will it create the field with kwargs, etc.

How to access form data in Flask_WTF Form before the form is submitted?

I am creating a form to find other group members, where all members belongs to departments. Some department, but not all, departments have an internal id that can be used to identify each member. Each department also has a different term for this internal member id. Department A calls it "personal identifier," department B calls it "unique id," etc. In the database departments table, the member_id_term field stores what the department calls the internal member id. In the members table in the database, the internal_id stores the member's internal_id if they belong to a department with the internal_id system.
On the first page of the form, the user selects the department, and on the second page of the form, if the user has selected a department that uses internal member ids, they are asked to put the internal member id.
My strategy was to create a variable in views.py called member_id_term and set it to 0 if there is no form.dept.data, but to set member_id_term to form.dept.data.member_id_term when form.dept.data exists. Then, in input_find_member.html, I would conditionally display the input field for internal_id if member_id_term exists.
Problem: I don't have access to form.dept.data until I submit the form. How can I access this value before submitting the form?
Here is the code I currently have. It throws an error on member_id_term = 0 if not form.dept.data else form.dept.data.member_id_term and says that form.dept.data is none.
forms.py
class FindMemberForm(Form):
name = StringField(
'name', default='', validators=[Regexp('\w*'), Length(max=50),
Optional()]
)
internal_id = StringField('internal_id', default='', validators=[Regexp('\w*'), Length(max=55)])
dept = QuerySelectField('dept', validators=[DataRequired()],
query_factory=dept_choices, get_label='name')
views.py
#main.route('/find', methods=['GET', 'POST'])
def get_officer():
form = FindMemberForm()
member_id_term = 0 if not form.dept.data else form.dept.data.member_id_term
if form.validate_on_submit():
return redirect(url_for('main.get_gallery'), code=307)
return render_template('input_find_member.html', form=form)
{% extends "base.html" %}
{% block content %}
and here is input_find_member.html
<div role="main">
<div class="hero-section no-sub">
<div class="hero">Find a Member </div>
</div>
</div>
<div class="container" role="main">
<form action="{{ url_for('main.get_member') }}" method="post" class="form">
{{ form.hidden_tag() }}
<div class="row form-group">
<div class="col-xs-12">
<ul class="nav nav-pills nav-justified thumbnail setup-panel">
<li class="active"><a href="#step-1">
<h4 class="list-group-item-heading">Step 1</h4>
<p class="list-group-item-text">Department Information</p>
</a></li>
<li class="disabled"><a href="#step-2">
<h4 class="list-group-item-heading">Step 2</h4>
<p class="list-group-item-text">Member Info </p>
</a></li>
</ul>
</div>
</div>
<div class="row setup-content" id="step-1">
<div class="col-xs-12">
<div class="col-md-12 well text-center">
<h2><small>Select Department</small></h2>
<div class="input-group input-group-lg col-md-4 col-md-offset-4">
{{ form.dept(class="form-control") }}
</div>
{% for error in form.dept.errors %}
<p>
<span style="color: red;">[{{ error }}]</span>
</p>
{% endfor %}
<br>
<button id="activate-step-2" class="btn btn-primary btn-lg">Next Step</button>
</div>
</div>
</div>
<div class="row setup-content" id="step-2">
<div class="col-xs-12">
<div class="col-md-12 well text-center">
<h2><small>Do you know the member's name?</small></h2>
<div class="input-group input-group-lg col-md-4 col-md-offset-4">
{{ form.name(class="form-control") }}
{% for error in form.name.errors %}
<p><span style="color: red;">[{{ error }}]</span></p>
{% endfor %}
</div>
{% if member_id_term %}
<h2><small>Do you know the member's {{ member_id_term }}?*</small></h2>
<div class="input-group input-group-lg col-md-4 col-md-offset-4">
{{ form.internal_id(class="form-control") }}
{% for error in form.internal_id.errors %}
<p><span style="color: red;">[{{ error }}]</span></p>
{% endfor %}
</div>
{% endif %}
<br>
<button id="activate-step-3" class="btn btn-primary btn-lg">Next Step</button>
</div>
</div>
</div>
</form>
</div>
I've already read these pages
Flask WTForms: how do I get a form value back into Python?
Get data from WTForms form
populate WTForms select field using value selected from previous field
Thanks for reading!

Categories

Resources