How can I reinsert a row using SQLAlchemy? - python

To add the item with the given description I use: db.session.add(new_item). To delete the item: db.session.query(Item).filter_by(item_id=new_id).delete(). To update some parts of the item: db.session.query(Item).filter_by(item_id=new_id).update({"status":"1 "}).
What should I use if I want to edit the item completely, that is, reinsert the data for the same item?
here is the code for the form:
<form class="form" action="{{ url_for('new_item') }}" method="post" role="form" enctype=multipart/form-data>
{{ form.csrf_token }}
<table>
<tr>
<td>
<div class="form-group">
<label for="item_name">item name:</label>
<input name="name" type="text" class="form-control" id="item_name">
</div>
</td>
<td>
<div class="form-group">
<label for="item_price">item price</label>
<input name="price" type="number" class="form-control" id="item_price">
</div>
</td>
<td>
<div class="form-group">
<label for="photo">Download the photo</label>
<input type="file" name="file">
<p class="help-block">Download</p>
</div>
</td>
</tr>
<tr>
<td>
<div class="form-group">
<label for="item_category">Category:</label>
<select name="category" class="form-control" id="item_category">
<option>LEGO</option>
<option>Игры_и_игрушки</option>
<option>Малыш</option>
<option>Школа_и_канцтовары</option>
<option>Творчество_и_развитие</option>
</select>
</div>
</td>
</tr>
</table>
<div class="form-group">
<label for="item_description">Description of the item:</label>
<textarea name="description" class="form-control" id="item_description" rows="3"></textarea>
</div>
<button type="submit" class="btn btn-default">Save</button>
</form>
Here is the route for the form. There are others as well, to update the items and to delete it, but i guess this should be enough
#app.route('/admin_items', methods=['GET', 'POST'])
def admin_items():
form = AddItemForm(request.form)
available = db.session.query(Item).filter_by(status='1').order_by(Item.name.asc())
not_available = db.session.query(Item).filter_by(status='0').order_by(Item.name.asc())
return render_template('admin_items.html',
available_items=available,
not_available_items=not_available,
form=form)
#app.route('/add_item', methods=['GET', 'POST'])
#login_required
def new_item():
error = None
form = AddItemForm(request.form)
if request.method == 'POST':
file = request.files['file']
if file and allowed_file(file.filename) and form.name.data != "" and form.description.data != "":
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOADED_ITEMS_DEST'], filename))
new_item = Item(
filename,
form.name.data,
form.description.data,
form.price.data,
form.age.data,
form.particles.data,
form.category.data,
'1',
)
db.session.add(new_item)
db.session.commit()
return redirect(url_for('admin_items'))
else:
return render_template('admin_items.html', form=form, error=error)
if request.method == 'GET':
return redirect(url_for('admin_items'))

You can specify more elements to the update clause .update({"status":"1", "colour":"red"}) or you can grab the object from the database and just change it as required:
item = db.session.query(Item).get(1) # grab the item with PK #1.
item.status = '1'
item.colour = 'red'
db.session.commit() # commit your changes to the database.

Related

I'm not getting any option to select product list in order form

I'm not getting any option to select product list in order formenter image description hereModels.py
from django.db import models
from re import I
from django.utils import timezone
from django.dispatch import receiver
from more_itertools import quantify
from django.db.models import Sum
# Create your models here.
CHOICES = (
("1", "Available"),
("2", "Not Available")
)
class Brand(models.Model):
name = models.CharField(max_length=255)
status = models.CharField(max_length=10, choices=CHOICES)
def __str__(self):
return self.name
class Category(models.Model):
name = models.CharField(max_length=255)
status = models.CharField(max_length=10, choices=CHOICES)
def __str__(self):
return self.name
class Product(models.Model):
brand = models.ForeignKey(Brand, on_delete=models.CASCADE)
category = models.ForeignKey(Category, on_delete=models.CASCADE)
name = models.CharField(max_length=255)
code = models.CharField(max_length=10)
#image = models.ImageField(upload_to="media/product/images/")
quantity = models.IntegerField()
rate = models.FloatField(max_length=100)
status = models.CharField(max_length=10, choices=CHOICES)
def __str__(self):
return self.name
class Order(models.Model):
date = models.DateTimeField(auto_now_add=True)
sub_total = models.FloatField(max_length=100)
vat = models.FloatField(max_length=100)
total_amount = models.FloatField(max_length=100)
discount = models.FloatField(max_length=100)
grand_total = models.FloatField(max_length=100)
paid = models.FloatField(max_length=100)
due = models.FloatField(max_length=100)
payment_type = models.CharField(max_length=100)
payment_status = models.IntegerField()
status = models.IntegerField()
class OrderItem(models.Model):
order_id = models.ForeignKey(Order, on_delete=models.CASCADE)
product_id = models.ForeignKey(Product, on_delete=models.CASCADE)
quantity = models.IntegerField()
rate = models.FloatField(max_length=100)
total = models.FloatField(max_length=100)
status = models.IntegerField()
views.py
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.models import User
from django.template.loader import render_to_string
from django.views.decorators.csrf import csrf_exempt
import json
from .models import Brand, Category, Product, Order, OrderItem
# Create your views here.
#login_required(login_url="/account/signin/")
def index(request):
return render(request, "index.html", {})
def signup(request):
if request.method == "POST":
if request.POST.get("pwd1") == request.POST.get("pwd2"):
print(request.POST.get("pwd1"))
user = User.objects.create(
username=request.POST.get("username")
)
user.set_password(request.POST.get("pwd1"))
user.save()
return redirect("/account/signin/")
else:
return redirect("/account/signup/")
return render(request, "signup.html", {})
def signin(request):
if request.method == "POST":
pass
user = authenticate(request, username=request.POST.get("username"), password=request.POST.get("password"))
if user:
login(request, user)
return redirect("/dashboard/")
else:
messages.error(request, "Username or password error!")
return redirect("/account/signin/")
return render(request, "login.html", {})
def logout_view(request):
logout(request)
return redirect("/account/signin/")
#login_required(login_url="/account/signin/")
def dashboard(request):
return render(request, "dashboard.html", {})
#csrf_exempt
#login_required(login_url="/account/signin/")
def products(request):
return render(request, "product.html", {})
#login_required(login_url="/account/signin/")
def categories(request):
return render(request, "categories.html", {})
def categories_list(request):
categories_lists = Category.objects.all()
html = render_to_string('modules/tables_categories.html', {"categories": categories_lists})
return JsonResponse({"message": "Ok", "html": html})
#csrf_exempt
def create_product(request):
data = dict()
if request.method == "GET":
categories_lists = Category.objects.all()
brands_lists = Brand.objects.all()
data['html'] = render_to_string('modules/add_product.html', {"categories": categories_lists, "brands": brands_lists})
else:
print(request.FILES)
Product.objects.create(
name=request.POST["name"],
brand=Brand.objects.get(id=request.POST["brand"]),
category=Category.objects.get(id=request.POST["category"]),
code=request.POST["code"],
quantity=request.POST["quantity"],
rate=request.POST["rate"],
status=request.POST["status"],
)
products_lists = Product.objects.all()
data['html'] = render_to_string('modules/tables_products.html', {"products": products_lists})
return JsonResponse(data)
#csrf_exempt
def products_list(request):
products_lists = Product.objects.all()
html = render_to_string('modules/tables_products.html', {"products": products_lists})
return JsonResponse({"message": "Ok", "html": html})
#login_required(login_url="/account/signin/")
def orders(request):
return render(request, "orders.html", {})
#login_required(login_url="/account/signin/")
def report(request):
return render(request, "report.html", {})
#csrf_exempt
def create_brand(request):
data = dict()
brand_name = request.POST.get("brandName")
brand_status = request.POST.get("brandStatus")
Brand.objects.create(name=brand_name, status=brand_status)
brands_list = Brand.objects.all()
data['html'] = render_to_string('modules/tables.html', {"brands": brands_list})
return JsonResponse(data)
#csrf_exempt
def create_categories(request):
data = dict()
category_name = request.POST.get("categoryName")
category_status = request.POST.get("categoryStatus")
Category.objects.create(name=category_name, status=category_status)
categories_lists = Category.objects.all()
data['html'] = render_to_string('modules/tables_categories.html', {"categories": categories_lists})
return JsonResponse(data)
#csrf_exempt
def remove_categories(request, id):
data = dict()
category = Category.objects.get(id=id)
category.delete()
categories_lists = Brand.objects.all()
data['html'] = render_to_string('modules/tables_categories.html', {"categories": categories_lists})
return JsonResponse(data)
#csrf_exempt
def edit_brand(request, id):
data = dict()
brand_name = Brand.objects.get(id=id)
if request.method == "GET":
data['html'] = render_to_string('modules/edit.html', {"brand": brand_name})
else:
brand_name.name = request.POST["brandName"]
brand_name.status = request.POST["brandStatus"]
brand_name.save()
brands_list = Brand.objects.all()
data['html'] = render_to_string('modules/tables.html', {"brands": brands_list})
return JsonResponse(data)
#csrf_exempt
def remove_brand(request, id):
data = dict()
brand = Brand.objects.get(id=id)
brand.delete()
brands_list = Brand.objects.all()
data['html'] = render_to_string('modules/tables.html', {"brands": brands_list})
return JsonResponse(data)
#login_required(login_url="/account/signin/")
def brand_list(request):
brands_list = Brand.objects.all()
html = render_to_string('modules/tables.html', {"brands": brands_list})
return JsonResponse({"message": "Ok", "html": html})
#csrf_exempt
#login_required(login_url="/account/signin/")
def brands(request):
return render(request, "brand.html", {})
#csrf_exempt
#login_required
def invoices(request):
invoice = Order.objects.all()
return render(request, 'report.html', {})
#login_required
def delete_invoice(request):
resp = {'status':'failed', 'msg':''}
if request.method == 'POST':
try:
invoice = Order.objects.get(id = request.POST['id'])
invoice.delete()
messages.success(request, 'Invoice has been deleted successfully')
resp['status'] = 'success'
except Exception as err:
resp['msg'] = 'Invoice has failed to delete'
print(err)
else:
resp['msg'] = 'Invoice has failed to delete'
return HttpResponse(json.dumps(resp), content_type="application/json")
order.html
If I select the product in this order form, the product list should appear. But the list does not appear.
{% extends 'modules/base.html' %}
{% load static %}
{% block content %}
<div class="container">
<div class="row vertical">
<div class="col-sm-12">
<div class="breadcrumb">
<p>Home / Orders </p>
</div>
<div class="card card-outline-secondary">
<div class="card-header">
<h3 class="mb-0 text-center">Manage Orders</h3>
</div>
<div class="card-block">
<form class="form form-horizontal" method="post" action="" id="createOrderForm">
<div class="form-group">
<label for="orderDate" class="col-sm-2 control-label">Order Date</label>
<div class="col-sm-12">
<input type="text" class="form-control" id="orderDate" name="orderDate"
autocomplete="off"/>
</div>
</div> <!--/form-group-->
<div class="form-group">
<label for="clientName" class="col-sm-2 control-label">Client Name</label>
<div class="col-sm-12">
<input type="text" class="form-control" id="clientName" name="clientName"
placeholder="Client Name" autocomplete="off"/>
</div>
</div> <!--/form-group-->
<div class="form-group">
<label for="clientContact" class="col-sm-2 control-label">Client Contact</label>
<div class="col-sm-12">
<input type="text" class="form-control" id="clientContact" name="clientContact"
placeholder="Contact Number" autocomplete="off"/>
</div>
</div>
<table class="table" id="productTable">
<thead>
<tr>
<th width="30%">Product</th>
<th width>Rate</th>
<th width="15%">Quantity</th>
<th width="20%">Total</th>
<th></th>
</tr>
</thead>
<tbody>
<tr id="" class="">
<td>
<div class="form-group">
<select class="form-control" name="productName[]"
id="productName<?php echo $x; ?>"
onchange="">
<option value="">SELECT</option>
</select>
</div>
</td>
<td>
<input type="text" name="rate[]" id="rate<?php echo $x; ?>"
autocomplete="off"
disabled="true" class="form-control"/>
<input type="hidden" name="rateValue[]" id="rateValue<?php echo $x; ?>"
autocomplete="off" class="form-control"/>
</td>
<td>
<div class="form-group">
<input type="number" name="quantity[]" id="quantity<?php echo $x; ?>"
onkeyup="" autocomplete="off"
class="form-control" min="1"/>
</div>
</td>
<td>
<input type="text" name="total[]" id="total<?php echo $x; ?>"
autocomplete="off"
class="form-control" disabled="true"/>
<input type="hidden" name="totalValue[]" id="totalValue<?php echo $x; ?>"
autocomplete="off" class="form-control"/>
</td>
<td>
<button class="btn btn-default removeProductRowBtn" type="button"
id="removeProductRowBtn" onclick="">
<i class="fa fa-trash" aria-hidden="true"></i></button>
</td>
</tr>
</tbody>
</table>
<div class="container">
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label for="subTotal" class="col-sm-6 control-label">Sub Amount</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="subTotal" name="subTotal"
disabled="true"/>
<input type="hidden" class="form-control" id="subTotalValue"
name="subTotalValue"/>
</div>
</div> <!--/form-group-->
<div class="form-group">
<label for="vat" class="col-sm-6 control-label">VAT 13%</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="vat" name="vat"
disabled="true"/>
<input type="hidden" class="form-control" id="vatValue"
name="vatValue"/>
</div>
</div> <!--/form-group-->
<div class="form-group">
<label for="totalAmount" class="col-sm-6 control-label">Total Amount</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="totalAmount"
name="totalAmount" disabled="true"/>
<input type="hidden" class="form-control" id="totalAmountValue"
name="totalAmountValue"/>
</div>
</div> <!--/form-group-->
<div class="form-group">
<label for="discount" class="col-sm-6 control-label">Discount</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="discount" name="discount"
onkeyup="discountFunc()" autocomplete="off"/>
</div>
</div> <!--/form-group-->
<div class="form-group">
<label for="grandTotal" class="col-sm-6 control-label">Grand Total</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="grandTotal"
name="grandTotal" disabled="true"/>
<input type="hidden" class="form-control" id="grandTotalValue"
name="grandTotalValue"/>
</div>
</div> <!--/form-group-->
</div>
<div class="col-sm-6">
<div class="form-group">
<label for="paid" class="col-sm-6 control-label">Paid Amount</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="paid" name="paid"
autocomplete="off" onkeyup="paidAmount()"/>
</div>
</div> <!--/form-group-->
<div class="form-group">
<label for="due" class="col-sm-6 control-label">Due Amount</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="due" name="due"
disabled="true"/>
<input type="hidden" class="form-control" id="dueValue"
name="dueValue"/>
</div>
</div> <!--/form-group-->
<div class="form-group">
<label for="clientContact" class="col-sm-6 control-label">Payment
Type</label>
<div class="col-sm-9">
<select class="form-control" name="paymentType" id="paymentType">
<option value="">SELECT</option>
<option value="1">Cheque</option>
<option value="2">Cash</option>
<option value="3">Credit Card</option>
</select>
</div>
</div> <!--/form-group-->
<div class="form-group">
<label for="clientContact" class="col-sm-6 control-label">Payment
Status</label>
<div class="col-sm-9">
<select class="form-control" name="paymentStatus" id="paymentStatus">
<option value="">SELECT</option>
<option value="1">Full Payment</option>
<option value="2">Advance Payment</option>
<option value="3">No Payment</option>
</select>
</div>
</div>
<div class="form-group submitButtonFooter" style="margin-top: 50px">
<div class="col-sm-offset-2 col-sm-10">
<button type="button" class="btn btn-default" onclick="addRow()"
id="addRowBtn" data-loading-text="Loading..."><i
class="glyphicon glyphicon-plus-sign"></i> Add Row
</button>
<button type="submit" id="createOrderBtn" data-loading-text="Loading..."
class="btn btn-success"><i
class="glyphicon glyphicon-ok-sign"></i> Save Changes
</button>
<button type="reset" class="btn btn-default" onclick="resetOrderForm()">
<i class="glyphicon glyphicon-erase"></i> Reset
</button>
</div>
</div>
</div>
</div>
</div>
</form>
</div>
<!--/card-block-->
</div>
</div>
</div>
</div>
{% endblock %}
{% block script %}
<script src="{% static 'js/order.js' %}"></script>
{% endblock %}
Not getting your quetion perfectly But you will get Idea By below code:
<select id="" class="" name="">
{% for i in Product %}
<option value="{{ i.name }}">
{{i.name }}
</option>
{% endfor %}
</select>
Basically you need to use jinja html and loop with the data/model(here Product) which is given from view.py(function) and then you can access each column of model(here name).
To do this you should create a serialiser and pass that as part of the context to the frontend and loop through that.
visit this link to see how t make a serializer docs
After you have created your serializer and lets say you named it ProductSerializer, you then add the below line to the place that passes data to that order page screen in the frontend. The below line serializes your raw queryset and passes it to your frontend to be consumable.
products = Product.objects.all()
products = ProductSerializer(cart, many=True)
context = {"products": products}
Then in your frontend you can access this and loop through like so:
<select id="" class="" name="">
{% for product in products %}
<option value="{{ product.name }}">
{{product.name }}
</option>
{% endfor %}
</select>

How to have single view for multiple HTML forms - Django

This is my view.So I want to keep 2 different HTML forms in same view ,But I am unable to do so beacuse whenever I add 1 form , I get the error of other on being none.
def home(request):
name = None
if request.method == 'POST':
name = request.POST.get('name')
choices = request.POST.get('choices')
subtest = request.POST.get('subtest')
reference = request.POST.get('reference')
unit = request.POST.get('unit')
test = Test()
test.name = name
test.save()
subtest = Subtest()
subtest.test = Test.objects.get(name=choices)
subtest.name = subtest
subtest.unit = unit
subtest.reference_value = reference
subtest.save()
# print(name)
return redirect('home')
return render(request,'main.html',{})
I have got 2 different forms . I didn't use django forms because I wanted to try something new.
MY FIRST FORM
<form method="POST">
{% csrf_token %}
<div class="icon-holder">
<i data-modal-target="test-popup" class="icon-cross"></i>
</div>
<div class="input-group">
<input type="text" name="name" placeholder="Test name" />
</div>
<div class="button-group">
<button type="submit">Submit</button>
</div>
</form>
MY SECOND FORM
<form method="POST">
{% csrf_token %}
<div class="icon-holder">
<i data-modal-target="menu-test-popup" class="icon-cross"></i>
</div>
<div class="input-group">
<label for="test-select">Test Name:</label>
<select name="choices" id="test-select">
{% for test in test %}
<option value="{{test.name}}" name='choices'>{{test.name|title}}</option>
{% endfor %}
</select>
</div>
<div class="input-group">
<input type="text" name="subtest" placeholder="SubTest name" />
</div>
<div class="input-group">
<input type="text" name="reference" placeholder="Reference rate" />
</div>
<div class="input-group">
<input type="text" name="unit" placeholder="Unit" />
</div>
<div class="button-group">
<button type="submit">Submit</button>
</div>
</form>
first form
<form method="POST">
...
<input name="form_type" value="first-form" type="hidden">
</form>
second form
<form method="POST">
...
<input name="form_type" value="second-form" type="hidden">
</form>
view function
def view(request):
if method == "POST":
form_type = request.POST.get('form_type')
if form_type == "first-form":
# first form's process
elif form_type == "second-form":
#second form's process
You have two forms here, when you submit the second form, only the fields from the second form gets submitted.
so from this line
name = request.POST.get('name')
name will become None. But I believe your Test model does not take any None value for name field( the reason for you " IntegrityError at / NOT NULL constraint failed: lab_test.name ").
To overcome this, first check if there is any value for 'name' then proceed with creating the test instance
if name:
test = Test()
test.name = name
test.save()
Similarly check if the other fields are present for the second form before creating and saving the instance.

Django Ajax get request - load model instance into a form

I have a table in a HTML template that displays all instances of a django model. on each row of the template I have an edit button that looks up the primary key of each instance, and by clicking that button I want all the fields in the model instance to be populated in a modal by using ajax. After that I want to be able to edit the data and use ajax to send the edited data back to the database.
I have been searching all over the web and found this post that is exactly what I need, but I still can't get it to work. Any help would be greatly appreciated.
jQuery code
var modalDiv = $("#modal-div");
$(".open-modal").on("click", function() {
console.log("button clicked");
var url = $(this).attr('data-url').replace('/', '');
console.log("url:",url); // this returns my customer number but is not used in the code below
$.ajax({
url: $(this).attr("data-url"),
type: 'get',
success: function(data) {
console.log("success");
modalDiv.html(data);
$("#myEdit").modal(); //#myEdit is the ID of the modal
},
error : function() {
console.log("Error: this did not work"); // provide a bit more info about the error to the console
}
});
});
a tag in form
<a class="btn open-modal" data-url="{% url 'dashboard:customer_update' kunde.kundenr %}">Edit</a>
Needless to say, I keep receiving the error console.log message.
Below is the complete codebase.
Model:
class Kunde(models.Model):
avd = [('610','610'), ('615', '615'), ('620', '620'), ('625', '625'), '630', '630'), ('635', '635'),('640', '640'),('645', '645'), ('650', '650'), ('655', '655')]
avdeling = models.CharField(max_length=3, choices=avd)
selskap = models.CharField(max_length=50, unique=True)
kundenr = models.CharField('Kundenummer', max_length=15, unique=True, primary_key=True)
gatenavn = models.CharField(max_length=50,)
postnr = models.CharField('Postnummer', max_length=4)
poststed = models.CharField(max_length=30)
kommune = models.CharField(max_length=30)
timestamp = models.DateField(auto_now_add=True)
updated = models.DateField(auto_now=True)
def get_absolute_url(self):
return reverse("dashboard:index")
def __str__(self):
return self.selskap
class Meta:
ordering = ['selskap']
Urls
app_name = "dashboard"
urlpatterns = [
path('', views.dashboard, name='index'),
path('', views.customer_list, name='customer_list'),
url(r'^(?P<kundenummer>[0-9]+)$', views.customer_update, name='customer_update'),
]
Views:
main view to display the table
def dashboard(request):
template = 'dashboard/index.html'
if request.user.groups.filter(name__in=['Vest']).exists():
queryset = Kunde.objects.filter(Q(avdeling='630') | Q(avdeling='635')).all()
elif request.user.groups.filter(name__in=['Nord']).exists():
queryset = Kunde.objects.filter(Q(avdeling='610') | Q(avdeling='615') | Q(avdeling='620')).all()
elif request.user.groups.filter(name__in=['Øst']).exists():
queryset = Kunde.objects.filter(Q(avdeling='660') | Q(avdeling='655') | Q(avdeling='650')).all()
elif request.user.groups.filter(name__in=['Sør']).exists():
queryset = Kunde.objects.filter(Q(avdeling='640') | Q(avdeling='645')).all()
elif request.user.groups.filter(name__in=['Nord-Vest']).exists():
queryset = Kunde.objects.filter(Q(avdeling='625')).all()
else:
queryset = Kunde.objects.all()
context = {
"object_list": queryset,
}
return render(request, template, context)
view to display the modal with
def customer_update(request, kundenr=None):
template = 'dashboard/index.html'
instance = get_object_or_404(Kunde, kundenr=kundenr)
context={
'selskap': instance.selskap,
'instance': instance,
}
return render(request, template, context)
HTML table
<div class"container-table" style="overflow-x:auto;">
<table class="display table table-bordered table-condensed" id="table_kundeliste">
<thead class="thead-inverse">
<tr>
<th>Avdeling</th>
<th>Selskap</th>
<th>Kundenr.</th>
<th>Poststed</th>
<th>Kommune</th>
<th>Rediger</th>
</tr>
</thead>
<tbody>
{% for kunde in object_list %}
<tr>
<td> {{ kunde.avdeling }} </td>
<td> {{ kunde.selskap }} </td>
<td> {{ kunde.kundenr }} </td>
<td> {{ kunde.poststed }} </td>
<td> {{ kunde.kommune }} </td>
<td>
<a class="btn open-modal" data-url="{% url 'dashboard:customer_update' kunde.kundenr %}">Edit</a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
this part include modal in html
<div id="modal-div" class="modal-div">
{% include 'dashboard/customer-modal.html' %}
</div>
this is the modal template itself
<div class="modal fade" id="myEdit" role="dialog">
<div class="modal-dialog">
<form class="well contact-form" method="post" action="{% url dashboard:'customer_update'}">
{% csrf_token %}
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<label for="avdeling">Avdeling:</label>
<input type="text" class="form-control" required="" name="avdeling" value="{{ instance.avdeling }}" id="avdeling">
<label for="selskap">Selskap:</label>
<input type="text" class="form-control" required="" name="selskap" value="{{ instance.selskap }}" id="selskap">
<label for="kundenummer">Kundenummer:</label>
<input type="text" class="form-control" required="" name="kundenummer" value="{{ instance.kundenr }}" id="kundenummer">
<label for="gatenavn">Gatenavn:</label>
<input type="text" class="form-control" required="" name="gatenavn" value="{{ instance.gatenavn }}" id="gatenavn">
<label for="postnummer">Postnummer:</label>
<input type="text" class="form-control" required="" value="{{ instance.postnr }}" name="postnummer" id="postnummer" >
<label for="poststed">Poststed:</label>
<input type="text" class="form-control" required="" value="{{ instance.poststed }}" name="poststed" id="poststed" >
<label for="kommune">Kommune:</label>
<input type="text" class="form-control" required="" value="{{ instance.kommune }}" name="kommune" id="kommune" >
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-default">Valider</button>
<button value="" type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</form>

Error of Django's forms instance

my files in project is:
djangoTry
--views.py
--forms.py
--others not included in this question files
When I click submit in my form I call this method from views.py:
from .forms import NameForm
def kontakt(request):
if request.method == 'POST':
form = NameForm(request.POST)
form.test("test")
if form.is_valid():
first_name = form.cleaned_data['first_name']
last_name = form.cleaned_data['last_name']
phone_number = form.cleaned_data['phone_number']
email = form.cleaned_data['email']
details = form.cleaned_data['details']
return HttpResponseRedirect('/')
else:
form = NameForm()
return render(request, 'index.html', {'form':form})
NameForm is class from forms.py file:
from django import forms
class NameForm(forms.Form):
first_name = forms.CharField(label='first_name', max_length=100)
last_name = forms.CharField(label='last_name', max_length=100)
phone_number = forms.CharField(label='phone_number', max_length=100)
email = forms.CharField(label='email', max_length=100)
details = forms.CharField(label='details', max_length=100)
def test(self, message):
print("i'm in test and message is: %s " , (message))
print(self.first_name)
def is_valid(self):
print("jest valid")
return True
form.html
<form class="col s12" action="{% url 'kontakt' %}" method="post">
{% csrf_token %}
{{ form }}
<div class="row">
<div class="input-field col s6">
<input
id="first_name"
type="text"
value="hehe">
<!-- value="{{ form.first_name }}"> -->
<label for="first_name">First name</label>
</div>
<div class="input-field col s6">
<input
id="last_name"
type="text"
autocomplete="off"
value="hehe">
<!-- value="{{ form.last_name }}" > -->
<label for="last_name">Last name</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<input id="phone_number" type="number" autocomplete="off"
value="123456789">
<label for="phone_number">Phone number</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<input id="email" type="email" autocomplete="off" value="rafald121#gmail.com" >
<label for="email">Email</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<input id="details" type="text" autocomplete="off" value="qweqweqeq">
<label for="details">Details</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<a class="waves-effect waves-light btn">
<input id="submit" type="submit" >
<i class="material-icons right">send</i>
</a>
<!-- <input id="submit" type="submit" > -->
<label for="details">Details</label>
</div>
</div>
</form>
but everytime I get error:
AttributeError: 'NameForm' object has no attribute 'first_name'
but NameForm has "first_name" atribute
NameForm's method "test" work properly everytime but any of NameForm's variable can't be called.
Does anybody have idea what's going on ?

django forms, not valid

so no matter what I seem to do I can't get a valid form from just a integer field.
Controller:
def upload_image(request):
if request.method == "POST":
form = AddFloorplan(request.POST, request.FILES)
print request.POST.get('floornumber')
if form.is_valid():
print 'valid'
else:
print(form.errors)
return redirect("/wayfinder/editor/")
Form:
class AddFloorplan(forms.Form):
floor_number = forms.IntegerField(required=True)
Template:
<form action="/wayfinder/addfloorplan/" method="POST" enctype="multipart/form-data"> {% csrf_token %}
<div class="input-field col s12">
<input id="floornumber" autofocus name="floornumber" placeholder="Floor Number" type="text" required>
</div>
<div class="col s12">
<p>
<button class="btn waves-effect waves-light z-depth-0" type="submit" name="action">
<span>Upload</span>
</button>
</p>
</div>
</form>
had no luck passing the values
The name of your form field, floor_number
floor_number = forms.IntegerField(required=True)
does not match the name of your form input, floornumber
<input id="floornumber" autofocus name="floornumber" placeholder="Floor Number" type="text" required>
You need to use the same name in both places.

Categories