I am trying to add a user to some events in the calendar (using fullcalendar), but when putting the form to request the data from the user, this form does not send me the data. How can I get the data it is supposed to send?
This is my event_register.html:
<div class="col-xl-6">
<p>Apuntarse como invitado.</p>
<form action="" method="POST">
{% csrf_token %}
<div class="form-group">
<label for="first_name">Nombre:</label>
<!--<input id="first_name" name="first_name" placeholder="Nombre del participante" type="text" required="required" class="form-control">-->
<div class="input-group">
{{form.first_name}}
</div>
</div>
<div class="form-group">
<label for="last_name">Apellidos:</label>
<!--<input id="last_name" name="last_name" placeholder="Apellidos del participante" type="text" required="required" class="form-control">-->
<div class="input-group">
{{form.last_name}}
</div>
</div>
<div class="form-group">
<label for="phone">Teléfono:</label>
<!--<input id="phone" name="phone" placeholder="Teléfono del participante" type="text" required="required" class="form-control">-->
<div class="input-group">
{{form.phone}}
</div>
</div>
<div class="form-group">
<label for="email">Correo electrónico:</label>
<!--<input id="email" name="email" placeholder="Correo electrónico del participante" type="text" required="required" class="form-control">-->
<div class="input-group">
{{form.email}}
</div>
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary btn-block py-2" value="Enviar">
</div>
</form>
</div>
<div class="col-xl-6">
</div>
This is my view.py:
def attend_to(request):
event_form = EventForm()
print('Hola')
if request.method == 'POST':
event_form = EventForm(data=request.POST)
if event_form.is_valid():
Assistant.objects.create(UserManegement=None, Event=request.event_id, frist_name=request.POST["first_name"], last_name=request.POST["last_name"], phone=request.POST["phone"], email=request.POST["email"])
return render(request, "core/home.html")
else:
Assistant.objects.create(UserManegement=request.POST["user"], Event=request.POST["event"])
return render( "core/home.html")
This is my forms.py:
from django import forms
class EventForm(forms.Form):
first_name = forms.CharField(label="first_name", required=True, widget=forms.TextInput(
attrs={'class':'form-control', 'placeholder':'Escribe tu nombre'}
), min_length=3, max_length=100)
last_name = forms.CharField(label="last_name", required=True, widget=forms.TextInput(
attrs={'class':'form-control', 'placeholder':'Apellidos'}
), min_length=3, max_length=100)
phone = forms.CharField(label="phone", required=True, widget=forms.TextInput(
attrs={'class':'form-control', 'placeholder':'Telefono'}
), min_length=9, max_length=9)
email = forms.EmailField(label="Email", required=True, widget=forms.EmailInput(
attrs={'class':'form-control', 'placeholder':'Escribe tu email'}
), min_length=3, max_length=100)
This is my urls.py:
urlpatterns = [
path('', views.attend_to, name='attend_to'),
]
And this is what I receive when clicking on the button:
"POST /event/1/ HTTP/1.1" 200 6249
This is the view that renders the event_register.html view, I have a calendar with fullcalendar and when clicking on an event it shows me that template.
def register_event(request, event_id):
event = get_object_or_404(Event, id=event_id)
return render(request, "events/event_register.html", {'event':event})
Thanks in advance.
Edit 1:
I don't know what the problem is now, but when I click on the event to open the url that contains the form, it doesn't show me the corresponding template. It is as if it did not enter the if request.method == 'POST'. Here I leave the updated code.
The view what renders the template event_register.html:
def register_event(request, event_id):
event_form = EventForm()
event = get_object_or_404(Event, id=event_id)
return render(request, "events/event_register.html", {'event':event,
'form':event_form})
The template what contains the form:
<form action="{% url 'attend_to' %}" method="POST">
{% csrf_token %}
<div class="form-group">
<label for="first_name">Nombre:</label>
<!--<input id="first_name" name="first_name" placeholder="Nombre del participante" type="text" required="required" class="form-control">-->
<div class="input-group">
{{form.frist_name}}
</div>
</div>
urls.py core to load the template:
urlpatterns = [
#Path del core
path('', views.home, name='home'),
path('about/', views.about, name='about'),
path('event/<int:event_id>/', include('events.urls'), name='attend_to'),
]
urls.py for events:
urlpatterns = [
path('', views.attend_to, name='attend_to'),
]
The views.py what contains attend_to, it's show me the print('Hola'):
def attend_to(request, event_id):
event_form = EventForm()
print('Hola')
if request.method == 'POST':
event_form = EventForm(request.POST)
if event_form.is_valid():
event_form.save()
context = {"form":event_form}
Assistant.objects.create(UserManegement=None, Event=request.event_id, frist_name=context.first_name, last_name=context.last_name, phone=context.phone, email=context.email)
#Assistant.objects.create(UserManegement=None, Event=request.event_id, frist_name=request.POST["first_name"], last_name=request.POST["last_name"], phone=request.POST["phone"], email=request.POST["email"])
#return render(request, "core/home.html")
return HttpResponseRedirect('/')
#return render("core/home.html", context)
#else:
# Assistant.objects.create(UserManegement=request.POST["user"], Event=request.POST["event"])
# return render( "core/home.html")
else:
event_form = EventForm()
return render(request, 'core/home.html', {'form': event_form})
The response what shows me the server:
[24/Feb/2021 10:27:05] "GET / HTTP/1.1" 200 9404
Hola
Use Model Form instead of form.Forms
class EventForm(forms.ModelForm):
class Meta:
model = In which You want to save data
fields = "__all__" If you want to select all fields from your model or you can specify the list of fields in a list or tuple
fields = ("field1","Field2","field3")
This form will automatically map all your Model Field to HTML
and just render this form in HTML.In View also you dont need to write so much code
def attend_to(request):
event_form = EventForm()
if request.method == 'POST':
event_form = EventForm(request.POST)
if event_form.is_valid():
event_form.save()
return redirect()#After Form submission use redirect.Never use render as it can create duplicate enteries on refresh.
context = {"form":event_form}#Passing the form in HTML
return render( "core/home.html",context)
HTML
{% csrf_token %}
<div class="form-group">
<label for="first_name">Nombre:</label>
{{form.fieldname}}
<div class="input-group">
{{form.first_name}}
</div>
</div>
<div class="form-group">
<label for="last_name">Apellidos:</label>
<!--<input id="last_name" name="last_name" placeholder="Apellidos del participante" type="text" required="required" class="form-control">-->
<div class="input-group">
{{form.last_name}}
</div>
</div>
<div class="form-group">
<label for="phone">Teléfono:</label>
<!--<input id="phone" name="phone" placeholder="Teléfono del participante" type="text" required="required" class="form-control">-->
<div class="input-group">
{{form.phone}}
</div>
</div>
<div class="form-group">
<label for="email">Correo electrónico:</label>
<!--<input id="email" name="email" placeholder="Correo electrónico del participante" type="text" required="required" class="form-control">-->
<div class="input-group">
{{form.email}}
</div>
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary btn-block py-2" value="Enviar">
</div>
</form>
You can use load_widget_tweaks to style your form instead of writing code in your form
Add the blank form in the register_event view function.
def register_event(request, event_id):
event_form = EventForm()
event = get_object_or_404(Event, id=event_id)
return render(request, "events/event_register.html", {'event':event, 'form': event_form})
This will ensure the form fields are displayed in your event_register.html view that you can then submit.
Then in your form html, change the action attribute to submit the form data to the attend_to view function.
From this
<form action="" method="POST">
to this
<form action="{% url 'attend_to' %}" method="POST">
Related
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>
Basically I have set up a form to create organizations. When I hit the Save button, it simply renders the page again - the POST is not working.
See my code below:
models.py
from django.db import models
from accounts.models import User
from datetime import datetime, date
#// ------------ FUNCTIONS -------------//
# Generate Organisation IDs for each organisation
def org_id_generate():
last_org = Organization.objects.all().order_by('org_id').last()
if not last_org:
return 'ORG_001'
else:
last_org_id = last_org.org_id
number_in_id = int(last_org_id[4:7])
new_number_in_id = number_in_id + 1
new_org_id = 'ORG_' + str(new_number_in_id).zfill(3)
return new_org_id
#// ------------ MODELS -------------//
class Organization(models.Model):
org_id = models.CharField(primary_key=True, max_length=7, default=org_id_generate, editable=False)
organization_code = models.CharField(max_length=20)
company_name = models.CharField(verbose_name="Company Name", max_length=60)
legal_name = models.CharField(verbose_name="Legal Name", max_length=100)
industry_distribution = models.BooleanField(verbose_name="Distribution", default=False)
industry_education = models.BooleanField(verbose_name="Education", default=False)
industry_healthcare = models.BooleanField(verbose_name="Healthcare", default=False)
industry_manufacturing = models.BooleanField(verbose_name="Manufacturing", default=False)
industry_retail = models.BooleanField(verbose_name="Retail", default=False)
industry_services = models.BooleanField(verbose_name="Services", default=False)
business_registration_no = models.CharField(verbose_name="Business Registration Number", max_length=15, blank=True)
vat_registration_no = models.CharField(verbose_name="VAT Registration Number", max_length=15, blank=True)
created_date = models.DateTimeField(default=datetime.now)
created_by = models.ForeignKey(User, on_delete=models.DO_NOTHING, related_name="Created_By", verbose_name="Created By")
effective_start_date = models.DateField(auto_now_add=False)
effective_end_date = models.DateField(auto_now_add=False, blank=True, null=True)
update_date = models.DateTimeField(default=datetime.now)
last_updated_by = models.ForeignKey(User, on_delete=models.DO_NOTHING, related_name="Last_Updated_By", verbose_name="Last Updated By")
def __str__(self):
return self.company_name
forms.py
from django import forms
from organizations.models import Organization
class OrganizationAddForm(forms.ModelForm):
class Meta:
model = Organization
exclude = ['created_date', 'update_date', ]
views.py
from django.shortcuts import get_object_or_404, render, redirect
from organizations.models import Organization
from forms import OrganizationAddForm
from accounts.models import User
from django.contrib.auth.decorators import login_required
#login_required()
def settings(request):
return render(request, 'settings/settings.html')
#login_required()
def organizations_settings(request):
orgs = Organization.objects.all()
context = {
'orgs': orgs,
}
return render(request, 'settings/settings_organizations.html', context)
#login_required
def organization_add(request):
if request.method == 'POST':
user_email = request.user.email
form = OrganizationAddForm(request.POST)
if form.is_valid():
form.organization_code = form.cleaned_data['organization_code']
form.company_name = form.cleaned_data['company_name']
form.legal_name = form.cleaned_data['legal_name']
form.business_registration_no = form.cleaned_data['brn']
form.vat_registration_no = form.cleaned_data['vat']
form.industry_distribution = form.cleaned_data['industry_distribution']
form.industry_education = form.cleaned_data['industry_education']
form.industry_healthcare = form.cleaned_data['industry_healthcare']
form.industry_manufacturing = form.cleaned_data['industry_manufacturing']
form.industry_retail = forms.cleaned_data['industry_retail']
form.industry_services = form.cleaned_data['industry_services']
form.effective_start_date = form.cleaned_data['effective_start_date']
form.effective_end_date = form.cleaned_data['effective_end_date']
form.created_by = form.cleaned_data[user_email]
form.last_updated_by = form.cleaned_data[user_email]
form.save()
return redirect('organizations_settings')
else:
form = OrganizationAddForm()
return render(request, 'settings/add_organization.html', {'form': form})
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.settings, name="settings"),
path('organizations/', views.organizations_settings, name='organizations_settings'),
path('organization_create', views.organization_create, name="organization_create"),
path('organizations/add/', views.organization_add, name="organization_add"),
]
Page Source Code
<!-- Add Organization Form -->
<div class="container form-style">
<i class="fas fa-arrow-left"></i> Back
<div class="form-header">
<h3>Add Organization</h3>
</div>
<form action="{% url 'organization_add' %}" method="POST">
{% csrf_token %}
<div class="container">
<!-- Row 1 -->
<div class="row">
<div class="col-md-4">
<label for="organization_code">Organization Code<span class="star-red">*</span></label>
<input type="text" name="organization_code" class="form-control" required>
</div>
<div class="col-md-4">
<label for="company_name">Organization Name<span class="star-red">*</span></label>
<input type="text" name="company_name" class="form-control" required>
</div>
<div class="col-md-4">
<label for="legal_name">Legal Name<span class="star-red">*</span></label>
<input type="text" name="legal_name" class="form-control" required>
</div>
</div>
<!-- Row 2 -->
<div class="row mt-4">
<!-- <div class="col-md-4">
<label for="industry">Industry<span class="star-red">*</span></label>
<select name="industry" class="selectpicker">
<option value="distribution">Distribution</option>
<option value="education">Education</option>
<option value="healthcare">Healthcare</option>
<option value="manufacturing">Manufacturing</option>
<option value="retail">Retail</option>
<option value="services">Services</option>
</select>
</div> -->
<div class="col-md-6">
<label for="brn">Business Registration No.</label>
<input type="text" name="brn" class="form-control">
</div>
<div class="col-md-6">
<label for="vat">VAT Registration No.</label>
<input type="text" name="vat" class="form-control">
</div>
</div>
<!-- Row 3 -->
<h5 class="mt-4">Industry</h5>
<div class="row">
<div class="col-md-4">
<div class="form-check">
<input type="checkbox" name="industry_distribution" class="form-check-input">
<label for="industry_distribution" class="form-check-label">Distribution</label>
</div>
</div>
<div class="col-md-4">
<div class="form-check">
<input type="checkbox" name="industry_education" class="form-check-input">
<label for="industry_education" class="form-check-label">Education</label>
</div>
</div>
<div class="col-md-4">
<div class="form-check">
<input type="checkbox" name="industry_healthcare" class="form-check-input">
<label for="industry_healthcare" class="form-check-label">Healthcare</label>
</div>
</div>
</div>
<div class="row mt-2">
<div class="col-md-4">
<div class="form-check">
<input type="checkbox" name="industry_manufacturing" class="form-check-input">
<label for="industry_manufacturing" class="form-check-label">Manufacturing</label>
</div>
</div>
<div class="col-md-4">
<div class="form-check">
<input type="checkbox" name="industry_retail" class="form-check-input">
<label for="industry_retail" class="form-check-label">Retail</label>
</div>
</div>
<div class="col-md-4">
<div class="form-check">
<input type="checkbox" name="industry_services" class="form-check-input">
<label for="industry_services" class="form-check-label">Services</label>
</div>
</div>
</div>
<!-- Row 4 -->
<div class="row mt-4">
<div class="col-md-6">
<label for="effective_start_date">Effective Start Date<span class="star-red">*</span></label>
<input type="date" name="effective_start_date" class="form-control" required>
</div>
<div class="col-md-6">
<label for="effective_end_date">Effective End Date:</label>
<input type="date" name="effective_end_date" class="form-control">
</div>
</div>
<!-- Hidden Input - User -->
<input type="hidden" name="user_email" />
<div class="float-right mt-3">
<button type="submit" class="btn btn-custom save">Save and Close</button>
</div>
</div>
</form>
</div>
Any help would be greatly appreciated. If you need any additional info, let me know and I will edit the post.
I did not find any code to show the errors in html.
According to the function in views, if the form is not valid, then it renders the page with the form.
Try to add {{form.errors}} to you the html file to see if it has errors?
I managed to solve it.
views.py
#login_required
def organization_add(request):
if request.method == 'POST':
form = OrganizationAddForm(request.POST)
if form.is_valid():
form.organization_code = form.cleaned_data['organization_code']
form.company_name = form.cleaned_data['company_name']
form.legal_name = form.cleaned_data['legal_name']
form.business_registration_no = form.cleaned_data['business_registration_no']
form.vat_registration_no = form.cleaned_data['vat_registration_no']
form.industry_distribution = form.cleaned_data['industry_distribution']
form.industry_education = form.cleaned_data['industry_education']
form.industry_healthcare = form.cleaned_data['industry_healthcare']
form.industry_manufacturing = form.cleaned_data['industry_manufacturing']
form.industry_retail = form.cleaned_data['industry_retail']
form.industry_services = form.cleaned_data['industry_services']
form.effective_start_date = form.cleaned_data['effective_start_date']
form.effective_end_date = form.cleaned_data['effective_end_date']
org = form.save(commit=False)
org.created_by = request.user
org.last_updated_by = request.user
org.save()
return redirect('organizations_settings')
else:
form = OrganizationAddForm()
return render(request, 'settings/add_organization.html', {'form': form})
The issue was that it was not able to capture the user email for the Created By and Last Updated By fields.
This is resolved by using:
org = form.save(commit=False)
org.created_by = request.user
org.last_updated_by = request.user
Note that the following two posts helped me:
Using request.user with Django ModelForm
Cannot assign "42": "Event.user_id" must be a "User" instance
I wrote in index.html
<div class="heading col-lg-6 col-md-12">
<h2>New account registration</h2>
<form class="form-horizontal" action="regist_save/" method="POST">
<div class="form-group-lg">
<label for="id_username">username</label>
{{ regist_form.username }}
</div>
<div class="form-group-lg">
<label for="id_email">email</label>
{{ regist_form.email }}
</div>
<div class="form-group-lg">
<label for="id_password">password</label>
{{ regist_form.password1 }}
</div>
<div class="form-group-lg">
<label for="id_password">password(conformation)</label>
{{ regist_form.password2 }}
<p class="help-block">{{ regist_form.password2.help_text }}</p>
</div>
<div class="form-group-lg">
<div class="col-xs-offset-2">
<button type="submit" class="btn btn-primary btn-lg">SUBMIT</button>
<input name="next" type="hidden"/>
</div>
</div>
{% csrf_token %}
</form>
</div>
I wanna set minlength&maxlength in template of username&password input tag.If i wrote in html stye,it is
<form class="form-horizontal" action="regist_save/" method="POST">
<div class="form-group-lg">
<label for="id_username">username</label>
<input id="id_username" name="username" type="text" value="" minlength="5" maxlength="12" placeholder="username" class="form-control">
</div>
<div class="form-group-lg">
<label for="id_email">email</label>
{{ regist_form.email }}
</div>
<div class="form-group-lg">
<label for="id_password">password</label>
<input id="id_password1" name="password1" type="password1" value="" minlength="8" maxlength="12" placeholder="password1" class="form-control">
</div>
<div class="form-group-lg">
<label for="id_password">password(conformation)</label>
<input id="id_password2" name="password2" type="password2" value="" minlength="8" maxlength="12" placeholder="password2" class="form-control">
<p class="help-block">{{ regist_form.password2.help_text }}</p>
</div>
<div class="form-group-lg">
<div class="col-xs-offset-2">
<button type="submit" class="btn btn-primary btn-lg">SUBMIT</button>
<input name="next" type="hidden"/>
</div>
</div>
{% csrf_token %}
</form>
in forms.py
class RegisterForm(UserCreationForm):
class Meta:
model = User
fields = ('username', 'email','password1','password1',)
def __init__(self, *args, **kwargs):
super(RegisterForm, self).__init__(*args, **kwargs)
self.fields['username'].widget.attrs['class'] = 'form-control'
self.fields['email'].widget.attrs['class'] = 'form-control'
self.fields['password1'].widget.attrs['class'] = 'form-control'
self.fields['password2'].widget.attrs['class'] = 'form-control'
in views.py
#require_POST
def regist_save(request):
regist_form = RegisterForm(request.POST)
if regist_form.is_valid():
user = regist_form.save(commit=False)
password = regist_form.cleaned_data.get('password')
user.set_password(password)
user.save()
login(request, user)
context = {
'user': request.user,
}
return redirect('detail')
context = {
'regist_form': regist_form,
}
return render(request, 'registration/regist.html', context)
I wanna set username minlength="5" &maxlength="12" and password minlength="8" & maxlength="12".I wanna write it in template,although I searched the way in Google but i cannot find it.I think i can do it by template but do i misunderstand it?Can't i do it in template?
you can set maxlength and minlength by using these attributes with your desired limit and validation will work accordingly
Working example on W3schools
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 ?
I have two forms in a view. One htlm form includes form and formset, other html form includes just single form.
When I am trying to submit singe form (Reminder), I am getting this error:
[u'ManagementForm data is missing or has been tampered with']
View:
form_class = CreateEventForm
second_form_class = modelformset_factory(EventTime, form = EventTimeForm, extra=3, formset=EventTimeFormset)
third_form_class = Reminder
model = Event
template_name = 'eventAdmin.html'
def get_context_data(self, **kwargs):
context = super(EventAdminPage, self).get_context_data(**kwargs)
context['form'] = self.form_class(self.request.POST or None, prefix="form", instance = self.object)
context['formset'] = self.second_form_class(
self.request.POST or None,
prefix="formset",
queryset=context['event_times'])
context['reminder_form'] = Reminder(self.request.POST or None)
return context
def post(self, request, **kwargs):
self.object = self.get_object()
event_times = EventTime.objects.filter(event = self.object).exclude(start_time = None)
if 'update_event_form' in request.POST:
form_class = self.get_form_class()
form = self.form_class(request.POST, prefix="form", instance=self.get_object())
formset = self.second_form_class(request.POST, prefix="formset", queryset=event_times)
if form.is_valid() and formset.is_valid():
event = form.save()
event_times = formset.save()
return HttpResponseRedirect('/event-admin-%s' %self.kwargs['event_id'])
else:
return self.render_to_response(
self.get_context_data(form=form, formset=formset))
if 'reminder_form' in request.POST:
form_class = self.second_form_class
form_name = 'Reminder'
form = form_class(request.POST)
if form.is_valid():
form.save(commit=False)
message = form.cleaned_data.get('text')
return HttpResponseRedirect('/event-admin-%s' %self.kwargs['event_id'])
else:
return self.render_to_response(
self.get_context_data(form=form))
HTML of form that raises error:
<form method='POST' action=''><input type='hidden' name='csrfmiddlewaretoken' value='3uQyEn4m8bHpM7Jy6a8WKQz5A8Uf6RZF' />
<div id="div_id_text" class="form-group"> <label for="id_text" class="control-label requiredField">
Text<span class="asteriskField">*</span> </label> <div class="controls "> <textarea class="textarea form-control" cols="40" id="id_text" maxlength="500" name="text" rows="10">
</textarea> </div> </div>
<input class="btn btn-primary" type="submit" name="reminder_form" value="Send" />
</form>
You need to add this line {{ form.management_form }} after the <form method='POST' action=''>. This is used by Django to manage the forms within the formset.
<form method='POST' action=''>
{{ form.management_form }}
<input type='hidden' name='csrfmiddlewaretoken' value='3uQyEn4m8bHpM7Jy6a8WKQz5A8Uf6RZF' />
<div id="div_id_text" class="form-group">
<label for="id_text" class="control-label requiredField">
Text
<span class="asteriskField">*</span>
</label> <div class="controls ">
<textarea class="textarea form-control" cols="40" id="id_text" maxlength="500" name="text" rows="10">
</textarea>
</div>
</div>
<input class="btn btn-primary" type="submit" name="reminder_form" value="Send" />
</form>