I have a 'ProjectRecord' model with several filefields:
class ProjectRecord(models.Model):
prjname = models.CharField(max_length=200, unique=True)
agencyID = models.CharField(max_length=30, unique=True, blank=True, null=True)
client = models.CharField(max_length=50, choices=CLIENT_CHOICES)
...
upload_template1 = models.FileField(max_length=100, upload_to="media/%Y%m%d", blank=True, null=True)
upload_template2 = models.FileField(max_length=100, upload_to="media/%Y%m%d", blank=True, null=True)
upload_template3 = models.FileField(max_length=100, upload_to="media/%Y%m%d", blank=True, null=True)
my upload handler is very basic:
def handle_uploaded_file(file):
destination = open('tmp.pdf', 'wb+')
for chunk in file.chunks():
destination.write(chunk)
destination.close()
and my view function is as follows:
def edit_project(request, agencyID):
if request.method == 'POST':
a=ProjectRecord.objects.get(agencyID=agencyID)
form = RecordForm(request.POST, request.FILES, instance=a)
if form.is_valid():
handle_uploaded_file(request.FILES['upload_template1', 'upload_template2', 'upload_template3' ])
form.save()
return HttpResponseRedirect('login.html')
else:
a=ProjectRecord.objects.get(agencyID=agencyID)
form = RecordForm(instance=a)
return render_to_response('portalproduction/production.html', {'form': form})
the existing code works only so long as I have a single file request:
handle_uploaded_file(request.FILES['upload_template1'])
as soon as I add multiple file requests (like the former view function), I get key errors.
Is what I'm trying to accomplish possible, and can someone help me with the view function?
this is a condesed version of the generated source
<div id="formshell" class="clearfix">
<form action="." method="POST" enctype="multipart/form-data">
<div id="" class="component_stage clearfix">
<div class="component_wrapper edit cw1">
<table>
<tr><td><input id="id_sellnumber1" type="text" name="sellnumber1" value="01" maxlength="30" /></td><td><input id="id_format1" type="text" name="format1" value="Inline Brochure" maxlength="64" /></td></tr>
<tr><td colspan="2"><input id="id_componentname1" type="text" name="componentname1" value="PA-to-SC_Redhead Brochure" maxlength="200" /></td></tr>
<tr><td colspan="2"><input type="file" name="upload_template1" id="id_upload_template1" /></td></tr>
</table>
</div>
<div class="component_wrapper edit cw2">
<table>
<tr><td><input id="id_sellnumber2" type="text" name="sellnumber2" value="02" maxlength="30" /></td><td><input id="id_format2" type="text" name="format2" value="OE" maxlength="64" /></td></tr>
<tr><td colspan="2"><input id="id_componentname2" type="text" name="componentname2" value="PA-to-SC_RedheadOE" maxlength="200" /></td></tr>
<tr><td colspan="2"><input type="file" name="upload_template2" id="id_upload_template2" /></td></tr>
</table>
</div>
<div class="component_wrapper edit cw3" style="margin-right:0;">
<table>
<tr><td><input id="id_sellnumber3" type="text" name="sellnumber3" maxlength="30" /></td><td><input id="id_format3" type="text" name="format3" maxlength="64" /></td></tr>
<tr><td colspan="2"><input id="id_componentname3" type="text" name="componentname3" maxlength="200" /></td></tr>
<tr><td colspan="2"><input type="file" name="upload_template3" id="id_upload_template3" /></td></tr>
</table>
</div>
<div id=""><input type='file' name='file' id='file'/><input type="submit" value="save record" /></div>
</form>
request.FILES simply has no key: ('upload_template1', 'upload_template2', 'upload_template3')
It's request.FILES['upload_template1'], request.FILES['upload_template2'], request.FILES['upload_template3']
handle_uploaded_file(request.FILES['upload_template1'])
handle_uploaded_file(request.FILES['upload_template2'])
#... so on.
This would illustrate your problem:
dic = {'key1':'value1', 'key2': 'value2'}
print dic['key1', 'key2']
# KeyError
dic['key1', 'key2'] = 'value3'
print dic['key1', 'key2']
# out: value3
Related
When I submitting the form in django it is giving error ''TypeError at /user expected string or bytes-like object''.
This is my staff models
class staff(models.Model):
id = models.AutoField
name = models.CharField(max_length=250)
role = models.CharField(max_length=250)
salary = models.CharField(max_length=250)
address = models.CharField(max_length=250)
number = models.CharField(max_length=250)
date = models.DateField()
This is my user views.
def user(request):
if request.method == "POST" :
name = request.POST['name']
role = request.POST['role']
salary = request.POST['salary']
address = request.POST['address']
number = request.POST['number']
date = DateTimeField()
ins = staff(name=name, role=role, salary=salary, address=address, date=date, number=number)
ins.save()
staffs = staff.objects.all()
return render(request, "salary/user.html", {'staff': staffs})
and this is form of template user.html
<form class="forms-sample" action="/user" method="post">
{% csrf_token %}
<div class="form-group row">
<label for="exampleInputUsername2" class="col-sm-3 col-form-label">Name:</label>
<div class="col-sm-9">
<input type="text" name="name" id="name" class="form-control" id="exampleInputUsername2" placeholder="Username">
</div>
</div>
<div class="form-group row">
<label for="exampleInputUsername2" class="col-sm-3 col-form-label">Role:</label>
<div class="col-sm-9">
<input type="text" name="role" id="role" class="form-control" id="exampleInputUsername2" placeholder="Role">
</div>
</div>
<div class="form-group row">
<label for="exampleInputUsername2" class="col-sm-3 col-form-label">Salary:</label>
<div class="col-sm-9">
<input type="text" name="salary" id="salary" class="form-control" id="exampleInputUsername2" placeholder="Salary">
</div>
</div>
<div class="form-group row">
<label for="exampleInputUsername2" class="col-sm-3 col-form-label">Address:</label>
<div class="col-sm-9">
<input type="text" name="address" id="address" class="form-control" id="exampleInputUsername2" placeholder="Address">
</div>
</div>
<div class="form-group row">
<label for="exampleInputUsername2" class="col-sm-3 col-form-label">Mobile no.:</label>
<div class="col-sm-9">
<input type="text" name="number" id="number" class="form-control" id="exampleInputUsername2" placeholder="Mobile no.">
</div>
</div>
<button type="submit" class="btn btn-primary mr-2">Submit</button>
<button class="btn btn-dark">Cancel</button>
</form>
I am new in django and i not know what the problem is.
Thanks for helping in advance.
It makes no sense to pass a reference to the AutoField model field in your model, you should construct a field, so:
class staff(models.Model):
id = models.AutoField()
# ⋮
as for the date field, you can work with auto_now_add=True [Django-doc] to automatically fill in the current day:
class staff(models.Model):
# ⋮
date = models.DateField(auto_now_add=True)
then this can be omitted while constructing a staff object:
def user(request):
if request.method == "POST" :
name = request.POST['name']
role = request.POST['role']
salary = request.POST['salary']
address = request.POST['address']
number = request.POST['number']
# no date=… ↓
ins = staff.objects.create(name=name, role=role, salary=salary, address=address, number=number)
ins.save()
staffs = staff.objects.all()
return render(request, "salary/user.html", {'staff': staffs})
It might however be better to work with Django forms to validate, clean and fill in data from a POST request.
Note: In case of a successful POST request, you should make a redirect
[Django-doc]
to implement the Post/Redirect/Get pattern [wiki].
This avoids that you make the same POST request when the user refreshes the
browser.
Note: Models in Django are written in PascalCase, not snake_case,
so you might want to rename the model from staff to Staff.
My django cabin form is not submitting. I have applied foreign key and slug in my cabin's model and after that my form stopped getting submitted. whenever I enter all the fields and hit submit button,the form page is getting reloaded and no data is getting submitted.Most Importantly it is not showing any error so that I can fix it.I have tried and searched a lot about it and tried different things but still it didn't work. I am stuck to it. Please help!!
class Centre(models.Model):
name= models.CharField(max_length=50, blank=False, unique=True)
address = models.CharField(max_length =250)
phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$',
message="Phone number must be entered in the format: '+999999999'. Up to 10 digits allowed.")
contact = models.CharField(max_length=100, blank=False)
phone = models.CharField(validators=[phone_regex], max_length=10, blank=True) # validators should be a list
slug = models.SlugField(unique=False)
def save(self, *args, **kwargs):
self.slug = slugify(self.name)
super(Centre, self).save(*args, **kwargs)
class Cabin(models.Model):
random_string = str(random.randint(100000, 999999))
centre_name = models.ForeignKey(Centre, on_delete=models.CASCADE,blank=True,null=True)
code = models.CharField(max_length=6, blank=False, unique=True, default=random_string)
total_seats = models.IntegerField(blank='False')
category=models.CharField(max_length=100, default=False)
booked_date=models.DateField(blank='False')
released_date=models.DateField(blank='False')
price=models.IntegerField(blank=False, default=None)
slug = models.SlugField(unique=False,default=None)
def save(self, *args, **kwargs):
self.slug = slugify(self.category)
super(Cabin, self).save(*args, **kwargs)
In views.py file
class CabinCreateView(CreateView):
fields = '__all__'
model = Cabin
success_url = reverse_lazy("NewApp:logindex")
def form_valid(self, form):
self.object = form.save(commit=False)
self.object.cabin = Cabin.objects.filter(slug=self.kwargs['slug'])[0]
self.object.save()
return HttpResponseRedirect(self.get_success_url())
In my cabin template,
<div class="row">
<div class="col-md-6">
<form method="POST">
{% csrf_token %}
{{ form.non_field_errors }}
<div class="col col-md-12">
<div class="fieldWrapper" >
{{ form.centre_name.errors }}
<div class="form-group col col-md-3">
<label>Centre Name</label>
{{form.centre_name}}
</div>
<div class="form-group col col-md-3" style="float:right; margin-top=-80px;width=200%">
<label for="{{form.code.id_for_label}" style="margin-left:200px;width:200%;white-space:nowrap;">Code</label>
<input type="text" placeholder="Code" value="{{form.code.value}}" name="code" maxlength="6" id="id_code" style="width:500px; margin-left:200px;">
</div>
</div>
<div class="col col-md-12">
<div class="form-group col col-md-3" style="float:right; margin-top=-80px;">
<label for="{{form.total_seats.id_for_label}" style="margin-left:200px;width:200px;white-space:nowrap;">seats</label>
<input type="text" placeholder="seats" name="total_seats" id="id_total_seats" style="width:500px; margin-left:200px;">
</div>
<div class="fieldWrapper" >
{{ form.category.errors }}
<div class="form-group col col-md-3" >
<label for="{{form.category.id_for_label}" style="margin-top:-40px">Category</label>
<input type="text" name="category" maxlength="100" id="id_category" placeholder="Category" style="width:500px";>
</div></div></div>
<div class="col col-md-12">
<div class="fieldWrapper" >
{{ form.released_date.errors }}
<div class="form-group col col-md-3" style="float:right; margin-top=-80px;">
<label for="{{form.released_date.id_for_label}" style="margin-left:200px;width:200px;white-space:nowrap;">released date</label>
<input type="text" placeholder="%yyyy-mm-dd" name="released_date" id="id_released_date" style="width:500px; margin-left:200px;">
</div>
</div>
<div class="fieldWrapper" >
{{ form.booked_date.errors }}
<div class="form-group col col-md-3" >
<label for="{{form.booked_date.id_for_label}" style="margin-top:-40px">booked date</label>
<input type="text" name="booked_date" id="id_booked_date" placeholder="%yyyy-mm-dd" style="width:500px";>
</div>
</div>
</div>
<div class="col col-md-12">
<div class="form-group col col-md-3" >
<label for="{{form.price.id_for_label}" style="margin-top:-40px">price</label>
<input type="text" name="price" maxlength="10" id="id_price" placeholder="in rupees" style="width:500px";>
</div>
</div>
<div class="form-group col col-md-3" >
<input type="submit" onclick="comparedate()" value="Save" class="btn btn-primary" style=" height:30px;width:80px;padding-bottom:2em;"/>
</div></div>
</form>
</div></div></div></div></div></div></div></div></div></div>
It looks like your problem is in your views.py file. You are telling the view that it should build a form including __all__ of the fields on the model, but in your template you don't include the slug field. Since you have overridden the save method on the Cabin model to populate the slug field, I guess you don't want that displayed in the template.
You have two options for fixing this. You could add a hidden field to the template containing the slug field. Or, what I think is a better option, you can change the fields attribute on your view to exclude the slug field.
class CabinCreateView(CreateView):
fields = ('centre_name', 'code', 'total_seats', 'category', 'booked_date', 'released_date', 'price',)
model = Cabin
success_url = reverse_lazy("NewApp:logindex")
P.S. This isn't a problem you are asking about, but I couldn't help noticing that you have what looks like multiple broken variables in your template. You might want to check if your label for="" attributes are working as expected.
I have a booking system in which i enter dates and timeslots available to book.
the form gets the timeslots from the date and converts it to the user timezone time.
i want the client to select a date and an available timeslot before continuing the form but even with required it doesnt work.
i have a model for timeslots and one for event, date+timeslot
then a form to make client select available date+timeslot, with a html to find timeslot available for each day
html
<option value="">{% if time_slots %}Available Slots{% else %}No Slot Available{% endif %}</option>
{% for time_set in time_slots %}
<option value="{{ time_set.pk }}">{{ time_set.start }} - {{ time_set.end }}</option>
{% endfor %}
models
class TimeSlots(models.Model):
start = models.TimeField(null=True, blank=True)
end = models.TimeField(null=True, blank=True)
class Meta:
ordering = ['start']
def __str__(self):
return '%s - %s' % (self.start.strftime("%I:%M %p"), self.end.strftime("%I:%M %p"))
class Event(models.Model):
event_date = models.DateField()
start = models.ForeignKey(TimeSlots, on_delete=models.CASCADE, verbose_name='Slot Time', null=True)
available = models.BooleanField(default=True)
class Meta:
verbose_name = u'Event'
verbose_name_plural = u'Event'
def __str__(self):
return str(self.event_date)
def get_absolute_url(self):
url = reverse('admin:%s_%s_change' % (self._meta.app_label, self._meta.model_name), args=[self.pk])
return u'%s' % (url, str(self.start))
form
class PatientForm(forms.ModelForm):
class Meta:
model = Patient
fields = ('patient_name', 'patient_country','phone_number', 'email', 'event_date','start', 'timestamp', 'datestamp')
widgets = {
'event_date': DateInput(),
'patient_country': CountrySelectWidget(),
}
def __init__(self, *args, **kwargs):
super(PatientForm, self).__init__(*args, **kwargs)
self.fields['start'].queryset = TimeSlots.objects.none()
if 'event_date' in self.data:
try:
event_id = self.data.get('event_date')
# event = Event.objects.get(pk=event_id)
self.fields['start'].queryset = TimeSlots.objects.filter(event__event_date=event_id, event__available=True)
except (ValueError, TypeError):
pass # invalid input from the client; ignore and fallback to empty City queryset
elif self.instance.pk:
self.fields['start'].queryset = self.instance.timeslot_set
views
class PatientCreate(CreateView):#was CreateView
form_class = PatientForm
template_name = 'appointment/index.html'
def get_context_data(self, **kwargs): # new
context = super(PatientCreate, self).get_context_data(**kwargs)
context['key'] = settings.STRIPE_PUBLISHABLE_KEY
return context
def load_time_slots(request):
event_date = request.GET.get('event_date')
client_timezone = request.GET.get('timezone')
client_timezone = pytz.timezone(client_timezone)
event_date, original_date = get_original_event_date_by_timezone(client_timezone, event_date)
time_slots = TimeSlots.objects.filter(event__event_date= event_date, event__available=True)
final_time_slots = []
for time_slot in time_slots:
start_time = time_slot.start
original_start_date_time = original_date.replace(hour=start_time.hour, minute=start_time.minute,
second=start_time.second,
tzinfo=original_time_zone)
timezone_start_date_time = original_start_date_time.astimezone(client_timezone)
end_time = time_slot.end
original_end_date_time = original_date.replace(hour=end_time.hour, minute=end_time.minute,
second=end_time.second,
tzinfo=original_time_zone)
timezone_end_date_time = original_end_date_time.astimezone(client_timezone)
final_time_slots.append({'pk': time_slot.pk, 'start': timezone_start_date_time.time,
'end': timezone_end_date_time.time})
return render(request, 'appointment/dropdown_list_options.html', {'time_slots': final_time_slots})
def get_original_event_date_by_timezone(client_timezone, event_date):
client_date = datetime.datetime.strptime(event_date, '%Y-%m-%d')
client_date = client_date.replace(tzinfo=client_timezone)
original_date = client_date.astimezone(original_time_zone)
original_date = original_date.replace(hour=0, minute=0, second=0, microsecond=0)
event_date = original_date.strftime('%Y-%m-%d')
return event_date, original_date
def create_event(request, start_time, day_date):
time_slot = TimeSlots.objects.get(start=start_time)
Event.objects.create(event_date=day_date, start=time_slot)
return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
form page html
<div class="container" style="margin-top:50px;margin-bottom:50px;">
<div class="stepwizard col-md-offset-3">
<div class="stepwizard-row setup-panel">
<div class="stepwizard-step">
1
<p>Date & Time</p>
</div>
<div class="stepwizard-step">
2
<p>Information</p>
</div>
<div class="stepwizard-step">
3
<p>Calling Method</p>
</div>
<div class="stepwizard-step">
4
<p>Payment Method</p>
</div>
</div>
</div>
<form role="form" action="{% url 'charge' %}" method="POST" id="patientForm" data-times-url="{% url 'ajax_load_time_slots' %}">
<div class="row setup-content" id="step-1">
<div class="col-xs-6 col-md-offset-3">
<div class="col-md-12">
<h3> Appointments date and time</h3>
<div class="form-group">
<label class="control-label" for="id_event_date">Event Date:</label>
<input class="form-control" type="date" name="event_date" id="id_event_date" required="required" />
</div>
<div class="form-group">
<label class="control-label" for="id_start">{% trans "Time:"%}</label>
<p><select required="required" class="form-control" name="start" style="display:inline;" id="id_start">
<option value="">---------</option></select></p><input type="hidden" name="timezone">
<script>$("#patientForm input[name='timezone']").val(Intl.DateTimeFormat().resolvedOptions().timeZone);</script>
</select></p>
</div>
<button class="btn btn-primary nextBtn btn-lg pull-right" type="button">Next</button>
</div>
</div>
</div>
<div class="row setup-content" id="step-2">
<div class="col-xs-6 col-md-offset-3">
<div class="col-md-12">
<h3> Step 2</h3>
<div class="form-group">
<label for="id_patient_fname" class="control-label">First Name:</label>
<input name="patient_name" id="id_patient_name" required="required" maxlength="100" type="text" class="form-control" placeholder="Enter First Name" />
</div>
<div class="form-group">
<label class="control-label">Last Name:</label>
<input required="required" maxlength="100" type="text" class="form-control" placeholder="Enter Last Name" />
</div>
<div class="form-group">
<label for="id_phone_number" class="control-label">Phone Number:</label>
<input name="phone_number" id="id_phone_number" required="required" maxlength="100" type="text" class="form-control" placeholder="Enter Phone Number" />
</div>
<div class="form-group">
<label for="id_emal" class="control-label">Email:</label>
<input name="email" id="id_email" maxlength="100" type="text" required="required" class="form-control" placeholder="Enter Email" />
</div>
<div class="form-group">
<label class="control-label">City</label>
<textarea required="required" class="form-control" placeholder="Enter your address"></textarea>
</div>
<button class="btn btn-primary nextBtn btn-lg pull-right" type="button">Next</button>
</div>
</div>
</div>
<div class="row setup-content" id="step-3">
<div class="col-xs-6 col-md-offset-3">
<div class="col-md-12">
<div class="form-group">
<label class="control-label">Choose The Way You Want to Receive The Video Call:</label>
<label class="radio-inline"><input class="form-control" type="radio" name="optradio" checked>Skype</label>
<label class="radio-inline"><input class="form-control" type="radio" name="optradio">Whatsapp</label>
</div>
<button class="btn btn-primary nextBtn btn-lg pull-right" type="button">Next</button>
</div>
</div>
</div>
<div class="row setup-content" id="step-4">
<div class="col-xs-6 col-md-offset-3">
<div class="col-md-12">
<script src="https://checkout.stripe.com/checkout.js" class="stripe-button" data-key="pk_test_KPSQTmUOl1DLP2eMc7zlvcnS"
data-description="Buying a 30mn Skype Session" data-amount="3000" data-locale="auto"></script>
</div>
</div>
</div>
</form>
</div>
in the html of the form page, i add required to select but it doesnt work
i need client to select lets say 29/01/2019, then if there is availability choose a timeslote lets say 5.30pm-6.00pm, and then only the next arrow will appear
With CreateView it's a little bit tricky when you want to initialize your ModelForm data. So, instead of doing initialization under your ModelForm, do it under the CreateView class like this example:
Your form:
class PatientForm(forms.ModelForm):
class Meta:
model = Patient
fields = ('patient_name', 'patient_country','phone_number', 'email', 'event_date','start', 'timestamp', 'datestamp')
widgets = {
'event_date': DateInput(),
'patient_country': CountrySelectWidget(),
}
Your view:
class PatientCreate(CreateView):
form_class = PatientForm
template_name = 'appointment/index.html'
initial = {}
def get_initial(self):
base_initial = super().get_initial() # it's a simple dict
# initialize your form's data here
# Your logic ...
return base_initial
# The rest of your logic
...
And, in order to know why you need to do this. CreateView inherits from FormMixin which has initial and get_initial() thus will initialize your form's data instead of doing it under your form.
See this links for more details: CreateView MRO and FormMixin
I want to store data from template that is not in same directory as views.
My form is located in mysite/style.html <-data inserted in this form, I want to pass them in models from another app called "services".
/mysite/ is my root directory.
<form name = "form" action="{% url 'services.views.add_style' %}" method = "POST" class="form-inline">{% csrf_token %}
<div class="col-sm-6 form-group">
<input class="form-control" id="style" name="name" placeholder="style" type="style" required>
</div>
<div class="col-sm-6 form-group">
<input class="form-control" id="color" name="color" placeholder="color" type="color" required>
</div>
<input class="form-control" id="positions" name="positions" placeholder="positions" type="positions" required>
<input class="form-control" id="font_size" name="font_size" placeholder="font_size" type="font_size" required>
<input class="form-control" id="background" name="background" placeholder="background" type="background" required>
<input class="form-control" id="font" name="font" placeholder="font" type="font" required>
<button class="btn btn-default pull-right" type="submit">Send</button>
</form>
than I have separated app called "services"
Here is views.py
def add_style(request):
if request.method == "POST":
style = request.POST.get('style')
color = request.POST.get('color')
positions = request.POST.get('positions')
font_size = request.POST.get('font_size')
background = request.POST.get('background')
font = request.POST.get('font')
Model = style(style=style, color=color, positions=positions, font_size=font_size, background=background, font=font)
Model.save()
return redirect('/')
and models.py
class style(CMSPlugin):
style = models.CharField(max_length=30)
color=RGBColorField(max_length=30)
positions = models.CharField(max_length=30)
font_size = models.CharField(max_length=30)
background = models.CharField(max_length=100)
font = models.CharField(max_length=100)
def __str__(self):
return self.style
Traceback shows error in this line
Model = style(style=style, positions=positions, font_size=font_size, background=background, font=font)
The problem is in the HTML form you are using :
In this line :
<input class="form-control" id="style" name="name" placeholder="style" type="style" required>
The name attribute of is defined as name but in your views.py,you are using :
style = request.POST.get('style')
So the correct HTML form should be :
<form name = "form" action="{% url 'services.views.add_style' %}" method = "POST" class="form-inline">{% csrf_token %}
<div class="col-sm-6 form-group">
<input class="form-control" id="style" name="style" placeholder="style" type="style" required>
</div>
<div class="col-sm-6 form-group">
<input class="form-control" id="color" name="color" placeholder="color" type="color" required>
</div>
<input class="form-control" id="positions" name="positions" placeholder="positions" type="positions" required>
<input class="form-control" id="font_size" name="font_size" placeholder="font_size" type="font_size" required>
<input class="form-control" id="background" name="background" placeholder="background" type="background" required>
<input class="form-control" id="font" name="font" placeholder="font" type="font" required>
<button class="btn btn-default pull-right" type="submit">Send</button>
</form>
You have a class named style and also a local variable named style that overrides that name.
class style(CMSPlugin):
...
style = request.POST.get('style') # this is None, and also overrides your class
...
Model = style(style=style, color=color,) # you are trying to call None()
If you followed the convention on naming classes with title case, you would have avoided this bug.
class Style(CMSPlugin): # Title case
...
style = request.POST.get('style') # No shadowing of other variable
...
model = Style(style=style, color=color,)
Currently I have a form, but somehow no matter how I register, I always fail. My implementation doesn't show what's wrong. Can someone figure out what's might happened?
Also, how can I add error messages next to each input box?
Below are my codes
{% block content%}
<div class="container">
<form class="form-signin" method="post" action="/sign_in/" role="form">
{% csrf_token %}
<h2 class="form-signin-heading">Please sign in</h2>
{% if error%} Your registration has not been successful. {%endif%}
<input type="username" class="form-control" name="username" placeholder="Username" required>
<input type="password" class="form-control" name="password" placeholder="Password" required>
<input type="password" class="form-control" name="password2" placeholder="Password" required>
<input type="username" class="form-control" name="name" placeholder="Name" required>
<input type="username" class="form-control" name="address" placeholder="Address" required>
<input type="username" class="form-control" name="Phone" placeholder="Phone Number" required>
<input type="email" class="form-control" name="emailAddress" placeholder="Email" required>
<input type="sinOrStNo" class="form-control" name="sinOrStNo" placeholder="Username" required>
<select class="form-control" name="type">
<option value="ST">Student</option>
<option value="FA">Faculty</option>
<option value="SF">Staff</option>
</select>
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
</form>
</div> <!-- /container -->
{% endblock %}
my views.py
error = False;
if request.method == 'POST':
borrower = BorrowerForm(request.POST)
if borrower.is_valid():
username = borrower.cleaned_data['username']
password = borrower.cleaned_data['password']
type = borrower.cleaned_data['type']
name = borrower.cleaned_data['name']
address = borrower.cleaned_data['address']
phone = borrower.cleaned_data['phone']
emailAddress = borrower.cleaned_data['emailAddress']
sinOrStNo = borrower.cleaned_data['sinOrStNo']
expiryDate = borrower.cleaned_data['expiryDate']
# add borrower accounts
user = User.objects.create_user(username, None, password)
user.set_password(password)
user.save()
user_type = UserProfile(username=username,type=0)
user_type.save()
# add borrower table
borrower_user = Borrower(username = username, password=password,name= name, address=address, phone=phone,emailAddress=emailAddress,sinOrStNo=sinOrStNo, expiryDate=expiryDate, type=type)
borrower_user.save()
else:
error = True;
else:
borrower = BorrowerForm()
return render(request, 'books/clerk/add_borrower.html', {'logged_in':logged_in, 'username':username, 'type':type, 'error':error, 'borrower':borrower})
My forms.py
class BorrowerForm(forms.Form):
username = forms.CharField(max_length=30)
password = forms.CharField(widget=forms.PasswordInput())
password2 = forms.CharField(widget=forms.PasswordInput())
name = forms.CharField(max_length=30)
address = forms.CharField(max_length=30)
phone = forms.CharField(max_length=30)
emailAddress = forms.CharField(widget=forms.EmailInput())
sinOrStNo = forms.CharField(max_length=10)
expiryDate = forms.DateField()
type = forms.CharField(max_length=3)
def clean_username(self):
existing = User.objects.filter(username__iexact=self.cleaned_data['username'])
if existing.exists():
raise forms.ValidationError(("A user with that username already exists."))
else:
return self.cleaned_data['username']
def clean(self):
if 'password' in self.cleaned_data and 'password2' in self.cleaned_data:
if self.cleaned_data['password'] != self.cleaned_data['password2']:
raise forms.ValidationError(("The two password fields didn't match."))
return self.cleaned_data
hm you use form and write all htmls in the html file why???
why don't you use
views.py
if request.method=='POST':
borrower = BorrowerForm(request.POST)
if borrower.is_valid():
......
return HttpResponseRedirect(<success url>)
else:
#here error messages it passed along with the form
return render(request, 'books/clerk/add_borrower.html',
{'borrower':borrower})
borrower = BorrowerForm()
return render(request, 'books/clerk/add_borrower.html',
{'logged_in':logged_in, 'username':username, 'type':type,
'error':error, 'borrower':borrower})
and use it the templates. that is what the purpose of forms.py. like :
<form class="form-signin" method="post" action="/sign_in/" role="form">
{% csrf_token %}
{{borrower.as_table}}
</form>