Form with bootstrap - python

I'm trying to make the create form look better but it just doesn't work. It shows fine but when I try to submit it doesn't do anything. I've already tried with different forms of one field, I think I can't make it work because this has file fields and foreign keys, etc.
Why it doesn't work?
forms.py
class Lcreate(forms.ModelForm):
class Meta:
model = Auction
fields = ('name', 'img', 'description', 'category', 'starting_bid')
widgets = {
'description' : forms.Textarea(attrs={
'rows': '5',
'cols': '90',
'maxlength': '500',
}),
'name' : forms.Textarea(attrs={
'rows': '1',
'cols': '100',
'maxlength': '30',
}),
}
views.py
#login_required(login_url="login")
def create(request):
if request.method == "POST":
form = Lcreate(request.POST or None, request.FILES or None)
if form.is_valid():
user = request.user
starting_bid = form.cleaned_data["starting_bid"]
description = form.cleaned_data["description"]
name = form.cleaned_data["name"]
img = form.cleaned_data["img"]
category = form.cleaned_data["category"]
listing = Auction(user=user, starting_bid=starting_bid, description=description, name=name, img=img, category=category)
listing.save()
return redirect('index')
else:
form = Lcreate()
return render(request, "auctions/create.html", {
"form": Lcreate,
"categories": Category.objects.all()
})
html
<div class="space"></div>
<div class="create-form">
<h1>Create Listing</h1>
<form method="POST" enctype="multipart/form-data">
{%csrf_token%}
<div class="form-group">
<label for="name">Title</label>
<input autofocus class="form-control" id="name" type="text" name="name" placeholder="Title">
<div class="space"></div>
<label for="img">Image</label>
<input type="file" id="img" name="img" class="form-control-file">
<div class="space"></div>
<label for="description">Description</label>
<textarea class="form-control" name="description" id="description" rows="3" placeholder="description"></textarea>
<div class="space"></div>
<label for="category">Category</label>
<select class="form-control" id="category" name="category">
{% for category in categories %}
<option name="category">{{category.category_list}}</option>
{%endfor%}
</select>
<div class="space"></div>
<label for="starting_bid">Bid</label>
<input class="form-control" type="number" name="starting_bid" placeholder="Starting Bid">
</div>
<button type="submit" class="btn btn-primary">Post Auction</button>
</form>
</div>

It should be like this
views.py:
def create(request):
infos=listing.objects.all()
form = listingForm(request.POST, request.FILES)
if form.is_valid():
listing.objects.create(**form.cleaned_data)
return render(request, "auctions/index.html", {'infos':infos})
else:
return render(request, 'auctions/create.html', {'form': form})
HTML
<h2>Create Listings</h2>
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}{% load widget_tweaks %}
<div class="form-group row">
<label for="{{ form.id_name}}" class="col-sm-2 col-form-label">Title</label>
<div class="col-sm-10">
{{ form.name|add_class:"form-control" }}
</div>
</div>
<div class="form-group row">
<label for="{{ form.id_description}}" class="col-sm-2 col-form-label">Description</label>
<div class="col-sm-10">
{{ form.description |add_class:"form-control" }}
</div>
</div>
<div class="form-group row">
<label for="{{ form.id_starting_bid}}" class="col-sm-2 col-form-label">Starting Bid</label>
<div class="col-sm-10">
{{ form.id_starting_bid|add_class:"form-control" }}
</div>
</div>
<div class="form-group row">
<label for="{{ form.id_img }}" class="col-sm-2 col-form-label">Image</label>
<div class="col-sm-10">
{{ form.img |add_class:"form-control" }}
</div>
</div>
<div class="form-group row">
<label for="{{ form.id_category }}" class="col-sm-2 col-form-label">Category</label>
<div class="col-sm-10">
{{ form.category|add_class:"form-control" }}
</div>
</div>
<div class="form-group row">
<div class="col-sm-10">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</form>

Related

NOT NULL constraint failed: posts_subscribe.firstname

I am trying to retrieve data from a form using the Post method and store it in the database. However, when I click on the submit button,I keep on getting the following error:
NOT NULL constraint failed: posts_subscribe.firstname
Here is my views.py:
def subscribe(request):
if request.method == 'POST':
firstname=request.POST.get('firstname')
secondname=request.POST.get('secondname')
email=request.POST.get('email')
phonenumber=request.POST.get('phonenumber')
en= Subscribe(firstname=firstname, secondname=secondname, email = email, phonenumber = phonenumber)
en.save()
return redirect('/')
return render(request, 'subscribe.html')
My models.py:
class Subscribe(models.Model):
firstname = models.CharField(max_length=30, blank = True)
secondname = models.CharField(max_length=30, blank = True)
email = models.CharField(max_length=30)
phonenumber = models.IntegerField()
Here is my template:
{% extends 'index.html' %}
{% block subscribe %}
<div class="card mx-5">
<h1 class="mx-5 mt-3"> Subscribe</h1>
<form method="POST" enctype="multipart/form-data" action="subscribe">
{% csrf_token %}
<div class="mb-3 mx-5">
<label for="firstname" class="form-label ">First Name</label>
<input type="text" class="form-control form-control-lg" id="firstname" placeholder="firstname">
</div>
<div class="mb-3 mx-5">
<label for="secondname" class="form-label">Second Name (Optional)</label>
<input type="text" class="form-control form-control-lg" id="secondname" placeholder="secondname">
</div>
<div class="mb-3 mx-5">
<label for="email" class="form-label">Email</label>
<input type="email" class="form-control form-control-lg" id="email" placeholder="example#example.com">
</div>
<div class="mb-3 mx-5">
<label for="phonenumber" class="form-label">Phonenumber</label>
<input type="number" class="form-control form-control-lg" id="phonenumber" placeholder="0712345678">
</div>
<div class="mb-3 mx-5">
<button type="submit" class="btn-primary"> Subscribe</button>
</div>
</form>
</div>
{% endblock %}
And my url patterns:
urlpatterns= [
path('', views.index, name='index'),
path('subscribe', views.subscribe, name ='subscribe'),
path('allposts', views.allposts, name='allposts'),
path('political', views.political, name='political'),
path('religion', views.religion, name='religion'),
path('trending', views.trending, name='treniding'),
path('<str:pk>', views.post, name='post'),
]
You should add a name="…" attribute [mdn] to the <input> elements, so:
<input type="text" name="firstname" class="form-control form-control-lg" id="firstname" placeholder="firstname">
…
<input type="text" name="secondname" class="form-control form-control-lg" id="secondname" placeholder="secondname">
…
<input type="email" name="email" class="form-control form-control-lg" id="email" placeholder="example#example.com">
…
<input type="number" name="phonenumber" class="form-control form-control-lg" id="phonenumber" placeholder="0712345678">

Nothing returned when editing profile page

Trying to edit a profile using a form I have that should allow a user to edit her first name, last name and email. Problem is when I try editing the form nothing happens. Still trying to learn Django so could be something I am missing/not getting right.
Here is my form;
<form id="edit-mentor-profile" class="form-horizontal" method="post" >
{% csrf_token %}
<div class="form-group">
<label for="photo" class="col-sm-2 control-label">Avatar</label>
<div class="col-md-6">
<div class="media v-middle">
<div class="media-left">
<div class="icon-block width-100 bg-grey-100">
<i class="fa fa-photo text-light"></i>
</div>
</div>
<div class="media-body">
</i>
</div>
</div>
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-md-2 control-label">Full Name</label>
<div class="col-md-8">
<div class="row">
<div class="col-md-6">
<div class="form-control-material">
<input type="text" class="form-control" id="edit-mentor-profile-first_name" placeholder= {{ user.first_name }}>
<label for="edit-mentor-profile-first_name"></label>
</div>
</div>
<div class="col-md-6">
<div class="form-control-material">
<input type="text" class="form-control" id="edit-mentor-profile-last_name" placeholder={{ user.last_name }}>
<label for="edit-mentor-profile-last_name"></label>
</div>
</div>
</div>
</div>
</div>
<div class="form-group">
<label for="email" class="col-md-2 control-label">Email</label>
<div class="col-md-6">
<div class="form-control-material">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-envelope"></i></span>
<input type="email" class="form-control" id="edit-mentor-profile-email" placeholder={{ user.email }}>
<label for="edit-mentor-profile-email"></label>
</div>
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-6">
<div class="checkbox checkbox-success">
<input id="checkbox3" type="checkbox" checked="">
<label for="checkbox3">Subscribe to our Newsletter</label>
</div>
</div>
</div>
<div class="form-group margin-none">
<div class="col-md-offset-2 col-md-10">
<button type="submit" class="btn btn-primary paper-shadow relative" data-z="0.5" data-hover-z="1" data-animated>Save Changes</button>
</div>
</div>
</form>
this is what I have on forms.py
class TeacherSignUpForm(UserCreationForm):
email = forms.EmailField(max_length=100)
first_name = forms.CharField(max_length=100)
last_name = forms.CharField(max_length=100)
linkedin = forms.URLField(max_length=200)
class Meta(UserCreationForm.Meta):
model = User
fields = ('email', 'username', 'first_name', 'last_name')
def save(self, commit=True):
self.instance.is_teacher = True
user = super(UserCreationForm, self).save(commit=False)
user.email = self.cleaned_data['email']
user.first_name = self.cleaned_data['first_name']
user.last_name = self.cleaned_data['last_name']
user.save()
mentor = Mentor.objects.create(
user=user,
linkedin=self.cleaned_data['linkedin']
)
return user
forms.py
# edit mentor profile
class MentorProfileForm(forms.Form):
first_name = forms.CharField(widget=forms.TextInput(attrs={'type': 'text', 'id': 'edit-mentor-profile-first_name',
'class': 'form-control'}))
last_name = forms.CharField(widget=forms.TextInput(attrs={'type': 'text', 'id': 'edit-mentor-profile-last_name',
'class': 'form-control'}))
email = forms.EmailField(widget=forms.EmailInput(attrs={'type': 'email', 'id': 'edit-mentor-profile-email',
'class': 'form-control'}))
and teachers.py(views.py)
class TeacherSignUpView(CreateView):
model = User
form_class = TeacherSignUpForm
template_name = 'registration/signup_form.html'
def get_context_data(self, **kwargs):
kwargs['user_type'] = 'teacher'
return super().get_context_data(**kwargs)
def form_valid(self, form):
user = form.save()
# user.set_password(form.cl)
login(self.request, user)
return redirect('teachers:app-instructor-dashboard')
#edit mentor profile
def edit_user(request):
user = request.user
form = MentorProfileForm(initial={'first_name':user.first_name,'last_name':user.last_name,'email':user.email})
if request.method == 'POST':
if form.is_valid():
user.first_name = request.POST['first_name']
user.last_name = request.POST['last_name']
user.email = request.POST['email']
# user.password = request.POST['password']
user.save()
return HttpResponseRedirect('%s'%(reverse('profile')))
context = {
"form":form
}
return render(request, 'classroom/teachers/app-instructor-profile.html', context)
UPDATE
Based on the answer provided I made the following changes
html form:
<form id="edit-mentor-profile" class="form-horizontal" method="post" >
{% csrf_token %}
<div class="form-group">
<label for="photo" class="col-sm-2 control-label">Avatar</label>
<div class="col-md-6">
<div class="media v-middle">
<div class="media-left">
<div class="icon-block width-100 bg-grey-100">
<i class="fa fa-photo text-light"></i>
</div>
</div>
<div class="media-body">
</i>
</div>
</div>
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-md-2 control-label">Full Name</label>
<div class="col-md-8">
<div class="row">
<div class="col-md-6">
<div class="form-control-material">
{{ form.first_name }}
<label for="edit-mentor-profile-first_name"></label>
</div>
</div>
<div class="col-md-6">
<div class="form-control-material">
{{ form.last_name }}
<label for="edit-mentor-profile-last_name"></label>
</div>
</div>
</div>
</div>
</div>
<div class="form-group">
<label for="email" class="col-md-2 control-label">Email</label>
<div class="col-md-6">
<div class="form-control-material">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-envelope"></i></span>
{{ form.email }}
<label for="edit-mentor-profile-email"></label>
</div>
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-6">
<div class="checkbox checkbox-success">
<input id="checkbox3" type="checkbox" checked="">
<label for="checkbox3">Subscribe to our Newsletter</label>
</div>
</div>
</div>
<div class="form-group margin-none">
<div class="col-md-offset-2 col-md-10">
<button type="submit" class="btn btn-primary paper-shadow relative" data-z="0.5" data-hover-z="1" data-animated>Save Changes</button>
</div>
</div>
</form>
and forms.py
class MentorProfileForm(forms.Form):
class Meta:
widgets = {
'first_name': forms.TextInput(attrs={'class':'form-control'}),
'last_name': forms.TextInput(attrs={'class':'form-control'}),
'email': forms.EmailInput(attrs={'class':'form-control'})
}
With these changes I cannot interact with the form. I cannot click the textboxes available.
Here is a sample of what i am seeing
You should render the inputs using the form field elements themselves
Instead of this
<input type="text" class="form-control" id="edit-mentor-profile-first_name" placeholder= {{ user.first_name }}>
Use this
{{ form.first_name }}
If you need to add the class to the input then in your model form add the class attribute to the field's widget
class Meta:
widgets = {
'first_name': forms.TextInput(attrs={'class': 'form-control'})
}

Saving edited data via formsets

I am trying to edit multiple rows of data in a model via formsets. In my rendered form, I use javascript to delete (hide and assign DELETE) rows, and then save changes with post.
My view:
def procedure_template_modification_alt(request, cliniclabel, template_id):
msg = ''
clinicobj = Clinic.objects.get(label=cliniclabel)
template_id = int(template_id)
template= ProcedureTemplate.objects.get(templid = template_id)
formset = ProcedureModificationFormset(queryset=SectionHeading.objects.filter(template = template))
if request.method == 'POST':
print(request.POST.get)
# Create a formset instance with POST data.
formset = ProcedureModificationFormset(request.POST)
if formset.is_valid():
print("Form is valid")
instances = formset.save(commit=False)
print(f'instances:{instances}')
for instance in instances:
print(f'Instance: {instance}')
instance.template = template
instance.save()
msg = "Changes saved successfully."
print("Deleted forms:")
for form in formset.deleted_forms:
print(form.cleaned_data)
else:
print("Form is invalid")
print(formset.errors)
msg = "Your changes could not be saved as the data you entered is invalid!"
template= ProcedureTemplate.objects.get(templid = template_id)
headings = SectionHeading.objects.filter(template = template)
return render(request, 'procedures/create_procedure_formset_alt.html',
{
'template': template,
'formset': formset,
'headings': headings,
'msg': msg,
'rnd_num': randomnumber(),
})
My models:
class ProcedureTemplate(models.Model):
templid = models.AutoField(primary_key=True, unique=True)
title = models.CharField(max_length=200)
description = models.CharField(max_length=5000, default='', blank=True)
clinic = models.ForeignKey(Clinic, on_delete=models.CASCADE)
def __str__(self):
return f'{self.description}'
class SectionHeading(models.Model):
procid = models.AutoField(primary_key=True, unique=True)
name = models.CharField(max_length=200)
default = models.CharField(max_length=1000)
sortorder = models.IntegerField(default=1000)
fieldtype_choice = (
('heading1', 'Heading1'),
('heading2', 'Heading2'),
)
fieldtype = models.CharField(
choices=fieldtype_choice, max_length=100, default='heading1')
template = models.ForeignKey(ProcedureTemplate, on_delete=models.CASCADE, null=False)
def __str__(self):
return f'{self.name} [{self.procid}]'
My forms:
class ProcedureCrMetaForm(ModelForm):
class Meta:
model = SectionHeading
fields = [
'name',
'default',
'sortorder',
'fieldtype',
'procid'
]
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['name'].widget.attrs.update({'class': 'form-control'})
self.fields['default'].widget.attrs.update({'class': 'form-control'})
self.fields['sortorder'].widget.attrs.update({'class': 'form-control'})
self.fields['fieldtype'].widget.attrs.update({'class': 'form-control'})
ProcedureCreationFormset = formset_factory(ProcedureCrMetaForm, extra=3)
ProcedureModificationFormset = modelformset_factory(SectionHeading, ProcedureCrMetaForm,
fields=('name', 'default', 'sortorder','fieldtype', 'procid'),
can_delete=True,
extra=0
# widgets={"name": Textarea()}
)
The template:
{% block content %} {% load widget_tweaks %}
<div class="container">
{% if user.is_authenticated %}
<div class="row my-1">
<div class="col-sm-2">Name</div>
<div class="col-sm-22">
<input type="text" name="procedurename" class="form-control" placeholder="Enter name of procedure (E.g. DNE)"
value="{{ template.title }}" />
</div>
</div>
<div class="row my-1">
<div class="col-sm-2">Description</div>
<div class="col-sm-22">
<input type="text" name="proceduredesc" class="form-control" placeholder="Enter description of procedure (E.g. Diagnostic Nasal Endoscopy)"
value="{{ template.description }}" />
</div>
</div>
<form action="" method="post" enctype="multipart/form-data">
{% csrf_token %} {{ formset.management_form }}
<div class="row mt-3">
<div class="col-sm-1">Select</div>
<div class="col-sm-6">Heading</div>
<div class="col-sm-8">Default (Normal description)</div>
<div class="col-sm-2">Sort Order</div>
<div class="col-sm-4">Type</div>
<div class="col-sm-2">Action</div>
</div>
{% for form in formset %}
<div class="row procrow" id="row{{ forloop.counter0 }}">
<div class="" style="display: none;">{{ form.procid }}</div>
<div class="col-sm-6">
{{ form.name }}
</div>
<div class="col-sm-8">
<div class="input-group">
{{ form.default }}
</div>
</div>
<div class="col-sm-2">
<div class="input-group">
{{ form.sortorder }}
</div>
</div>
<div class="col-sm-4">
<div class="input-group">
{{ form.fieldtype }}
</div>
</div>
<div class="col-sm-2">
<div class="input-group">
<div class="input-group-append">
<button id="add{{ forloop.counter0 }}" class="btn btn-success add-row">+</button>
</div>
<div class="input-group-append">
<button id="del{{ forloop.counter0 }}" class="btn btn-danger del-row">-</button>
</div>
</div>
</div>
</div>
{% endfor %} {% endif %}
<div class="row my-3">
<div class="col-sm-8"></div>
<div class="col-sm-8">
<div class="input-group">
<div class="input-group-append mx-1">
<button id="save_report" type="submit" class="btn btn-success"><i class="fal fa-shield-check"></i>
Save Report Format</button>
</div>
<div class="input-group-append mx-1">
<button id="save_report" type="button" class="btn btn-danger"><i class="fal fa-times-hexagon"></i>
Cancel</button>
</div>
</div>
</div>
<div class="col-sm-8"></div>
</div>
<div>
{% for dict in formset.errors %} {% for error in dict.values %} {{ error }} {% endfor %} {% endfor %}
</div>
</form>
</div>
{% endblock %}
My data is displayed as below (Screenshot). I make changes with javascript when the delete button is pressed, so that the html becomes like this:
<div class="row procrow" id="row2" style="display: none;">
<div class="" style="display: none;"><input type="hidden" name="form-2-procid" value="25" id="id_form-2-procid"></div>
<div class="col-sm-6">
<input type="text" name="form-2-name" value="a" maxlength="200" class="form-control" id="id_form-2-name">
</div>
<div class="col-sm-8">
<div class="input-group">
<input type="text" name="form-2-default" value="v" maxlength="1000" class="form-control" id="id_form-2-default">
</div>
</div>
<div class="col-sm-2">
<div class="input-group">
<input type="number" name="form-2-sortorder" value="1000" class="form-control" id="id_form-2-sortorder">
</div>
</div>
<div class="col-sm-4">
<div class="input-group">
<select name="form-2-fieldtype" class="form-control" id="id_form-2-fieldtype">
<option value="heading1" selected="">Heading1</option>
<option value="heading2">Heading2</option>
</select>
</div>
</div>
<div class="col-sm-2">
<div class="input-group">
<div class="input-group-append">
<button id="add2" class="btn btn-success add-row">+</button>
</div>
<div class="input-group-append">
<button id="del2" class="btn btn-danger del-row">-</button>
</div>
</div>
</div>
<input type="checkbox" name="form-2-DELETE" id="id_form-2-DELETE" checked=""></div>
On submitting the data, I get the following output, and data does not reflect the deletion I did. It displays the same thing again. There are no errors. But my edited data is not being saved.
Output:
<bound method MultiValueDict.get of <QueryDict: {'csrfmiddlewaretoken': ['ka3avICLigV6TaMBK5a8zeVJlizhtsKW5OTDBLlYorKd7Iji9zRxCX2vvjBv6xKu'], 'form-TOTAL_FORMS': ['3'], 'form-INITIAL_FORMS': ['3'], 'form-MIN_NUM_FORMS': ['0'], 'form-MAX_NUM_FORMS': ['1000'], 'form-0-procid': ['23'], 'form-0-name': ['External ear canal'], 'form-0-default': ['Bilateral external ear canals appear normal. No discharge.'], 'form-0-sortorder': ['100'], 'form-0-fieldtype': ['heading1'], 'form-1-procid': ['24'], 'form-1-name': ['Tympanic membrane'], 'form-1-default': ['Tympanic membrane appears normal. Mobility not assessed.'], 'form-1-sortorder': ['500'], 'form-1-fieldtype': ['heading1'], 'form-2-procid': ['25'], 'form-2-name': ['a'], 'form-2-default': ['v'], 'form-2-sortorder': ['1000'], 'form-2-fieldtype': ['heading1'], 'form-2-DELETE': ['on']}>>
Form is valid
instances:[]
Deleted forms:
{'name': 'a', 'default': 'v', 'sortorder': 1000, 'fieldtype': 'heading1', 'procid': <SectionHeading: a [25]>, 'DELETE': True}
You actually need to delete the instances: Loop through the formsets' deleted_objects property after you called saved(commit=False) and delete them.

MultiSelect field in Django 2 is not working

I'm working on a project using Python(3.7) and Django(2) in which I need to create a multi-select field inside one of my form.
Here's what I have tried:
from models.py:
class ExperimentModel(models.Model):
user = models.ForeignKey(User, related_name='experiments',
on_delete=models.CASCADE)
name = models.CharField(max_length=255)
start_date = models.DateField()
change_date = models.DateField()
end_date = models.DateField()
assets = models.CharField(max_length=450, choices=choices)
goals = models.CharField(max_length=255, blank=True)
comments = models.TextField(max_length=1000)
created_at = models.DateTimeField(auto_now=True)
From forms.py:
class ExperimentForm(forms.ModelForm):
choices = (
('CO2 SCRUBBER', 'CO2 SCRUBBER'),
('CORN OIL', 'CORN OIL'),
('DRYERS', 'DRYERS'),
('ENVIRONMENTAL', 'ENVIRONMENTAL'),
('UTILITIES', 'UTILITIES'),
('LAB', 'LAB'),
('SIEVES', 'SIEVES'),
('GRAINS & MILLING', 'GRAINS & MILLING'),
('SEPARATION', 'SEPARATION'),
('AIR & GAS', 'AIR & GAS'),
('COOK', 'COOK'),
('EVAPORATION', 'EVAPORATION'),
('WATER', 'WATER'),
('STORAGE', 'STORAGE'),
('BOILER', 'BOILER'),
('FERMENTATION', 'FERMENTATION'),
('DISTILLATION', 'DISTILLATION'),
('BUILDING AND FACILITIES', 'BUILDING AND FACILITIES'),
('CHEMICAL', 'CHEMICAL'),
)
assets = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple,
choices=choices)
class Meta:
model = ExperimentModel
fields = ('user', 'name', 'start_date', 'change_date', 'end_date', 'assets',
'goals', 'comments')
From template.html:
<form method="POST" action="{% url 'new-experiment' %}">
{% if form.errors %}
{% for field in form %}
{% for error in field.errors %}
<div class="alert alert-danger">
<strong>{{ error|escape }}</strong>
</div>
{% endfor %}
{% endfor %}
{% for error in form.non_field_errors %}
<div class="alert alert-danger">
<strong>{{ error|escape }}</strong>
</div>
{% endfor %}
{% endif %}
{% csrf_token %}
<h2> Create new Experiment:</h2>
{# {{ form|crispy }}#}
<div class="form-group">
<input type="text" name="name" id="name" class="form-control input-lg"
placeholder="experiment name" tabindex="3" required>
</div>
<div class="form-group">
<label for="start_date"> Start Date </label>
<input type="date" name="start_date" id="start_date" class="form-control input-lg"
placeholder="start_date" tabindex="4" required>
</div>
<div class="form-group">
<label for="change_date"> Change Date </label>
<input type="date" name="change_date" id="change_date" class="form-control input-lg"
placeholder="change date" tabindex="4" required>
</div>
<div class="form-group">
<label for="end_date"> End Date </label>
<input type="date" name="end_date" id="end_date" class="form-control input-lg"
placeholder="end date" tabindex="4" required>
</div>
<div class="form-group">
<label for="assets"> Assets </label>
{# <input type="text" name="assets" id="assets" class="form-control input-lg"#}
{# placeholder="Assets" tabindex="3" required>#}
<select name="assets" class="form-control" id="assets" multiple>
<option value="CO2 SCRUBBER">CO2 SCRUBBER</option>
<option value="CORN OIL">CORN OIL</option>
<option value="DRYERS">DRYERS</option>
<option value="ENVIRONMENTAL">ENVIRONMENTAL</option>
<option value="UTILITIES">UTILITIES</option>
<option value="LAB">LAB</option>
<option value="SIEVES">SIEVES</option>
<option value="GRAINS & MILLING">GRAINS & MILLING</option>
<option value="SEPARATION">SEPARATION</option>
<option value="AIR & GAS">AIR & GAS</option>
<option value="COOK">COOK</option>
<option value="EVAPORATION">EVAPORATION</option>
<option value="WATER">WATER</option>
<option value="STORAGE">STORAGE</option>
<option value="BOILER">BOILER</option>
<option value="FERMENTATION">FERMENTATION</option>
<option value="BUILDING AND FACILITIES">BUILDING AND FACILITIES</option>
<option value="CHEMICAL">CHEMICAL</option>
</select>
</div>
<div class="form-group">
<label for="assets"> Goals </label>
<input type="text" name="goals" id="goals" class="form-control input-lg"
placeholder="Goals" tabindex="3" required>
</div>
<div class="form-group">
<label for="comments"> Comments </label>
<textarea name="comments" id="comments" class="form-control input-lg"
rows="5" required>
</textarea>
</div>
<hr class="colorgraph">
<div class="row">
<div class="col-md-12 float-right">
<input type="submit" value="Create" class="btn btn-primary btn-block btn-lg float-right"
tabindex="7" style="background-color: #7386D5; color: white">
</div>
{# <div class="col-xs-12 col-md-6"><a href="{% url 'register' %}"#}
{# class="btn btn-success btn-block btn-lg">Create New Account</a>#}
{# </div>#}
</div>
</form>
And here's the views.py:
def post(self, request, *args, **kwargs):
if request.method == 'POST':
post_data = request.POST.copy()
post_data.update({'user': request.user.pk})
form = ExperimentForm(post_data)
print('req submitted')
if form.is_valid():
print('form valid')
form.save(commit=False)
form.user = request.user
form.save()
return HttpResponseRedirect(reverse_lazy('all-experiments'))
else:
return HttpResponseRedirect(reverse_lazy('new-experiment'))
When I select the only one option from multiple assets, the experiment has been created but when select multiple options the request failed, what's can wrong here?
How can I achieve the multi-select functionality for assets for experiment Model?
Also, no error is displaying in the template, even though I have printed the errors in the template, but doesn't any error is displaying on the template.
Thanks in advance!

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 ?

Categories