Register data by multiple select django - html

I'm a beginner and I was trying to create a registered data form in the database, all the fields are registered well instead of the multiple select fields.
from.py
class SavePost(forms.ModelForm):
user = forms.IntegerField(help_text = "User Field is required.")
title = forms.CharField(max_length=250,help_text = "Title Field is required.")
description = forms.Textarea()
dep = forms.Textarea()
class Meta:
model= Post
fields = ('user','title','description','file_path', 'file_path2', 'dep')
HTML
<div class="form-group mb-3 ">
<label for="exampleFormControlSelect2"> multiple select</label>
<select multiple class="form-control" id="dep" value={{ post.title }}>
<option>Process</option>
<option>Product</option>
<option>Equipment</option>
</select>
</div>
<div class="form-group mb-3 ">
<label for="title" class="control-label">Title</label>
<input type="text" class="form-control rounded-0" id="title" name="title" value="{{ post.title }}" required>
</div>
<div class="form-group mb-3">
<label for="description" class="control-label">Description</label>
<textarea class="form-control rounded-0" name="description" id="description" rows="5" required>{{ post.description }}</textarea>
thank you in advanced

You need a ChoiceField, write it as follows,
class SavePost(forms.ModelForm):
CHOICES = [('Process', 'Process'), ('Product', 'Product'),
('Equipment', 'Equipment')]
dep = forms.ChoiceField(choices=CHOICES)
user = forms.IntegerField(help_text = "User Field is required.")
title = forms.CharField(max_length=250,help_text = "Title Field is required.")
description = forms.Textarea()
class Meta:
model= Post
fields = ('user','title','description','file_path', 'file_path2', 'dep')
Check out the Django docs
You won't need to build the select in the template. I figure you are calling the for "post" from the view.py. So you will just need to create field in template with {{post.dep}}.

Related

Is there a way to seperate the description for the first image and the second image using django?

so for my website is there is 2 part to uploading an images, one is to upload images for the box and the other is to upload an images of the equipment but when it is uploaded the first image description is together with the second image description. Example shown below.
Picture of what happens when it is uploaded (not I wanted)
picture of what I wanted in my database.
views.py
#login_required()
def ReceptionUnserviceable(request):
descriptionbox = Photo.objects.all()
if request.method == 'POST':
data = request.POST
images = request.FILES.getlist('images')
for image in images:
photo = Photo.objects.create(
descriptionbox=data['descriptionbox'],
image=image,
serialno=data['serialno'],
partno=data['partno'],
reception=data['reception'],
customername=data['customername'],
descriptionequipment=data['descriptionequipment'],
)
return redirect('success')
context = {}
return render(request, 'ReceptionUnserviceable.html', context)
models.py
class Photo(models.Model):
class Meta:
verbose_name = 'Photo'
verbose_name_plural = 'Photos'
image = models.ImageField(null=False, blank=False)
descriptionbox = models.TextField()
serialno = models.TextField()
partno = models.TextField()
reception = models.TextField()
customername = models.TextField()
descriptionequipment = models.TextField()
def __str__(self):
return self.descriptionbox
Receptionunservicable.html
<form method='POST' action="" enctype="multipart/form-data">
{% csrf_token %}
<div>
<label>Description Of The Box</label>
<input required name="descriptionbox" type="text" placeholder="Enter a description" style="width:300px" class="form-control">
</div>
<br>
<div>
<label>Upload Box Photo</label>
<input required name="images" type="file" multiple class="form-control-file">
</div>
<br>
<div>
<label>Part Number</label>
<input required name="partno" type="text" placeholder="Enter part number" style="width:300px" class="form-control">
</div>
<br>
<div>
<label>Serial Number</label>
<input required name="serialno" type="text" placeholder="Enter serial number" style="width:300px" class="form-control">
</div>
<br>
<div>
<label>Reception</label>
<input name="reception" type="text" placeholder="Enter reception number" style="width:300px" class="form-control">
</div>
<br>
<div>
<label>Customer Name</label>
<input required name="customername" type="text" placeholder="Enter customer name" style="width:300px" class="form-control">
</div>
<div>
<label>Description Of The Equipment</label>
<input required name="descriptionequipment" type="text" placeholder="Enter a description" style="width:300px" class="form-control">
</div>
<br>
<div>
<label>Upload Equipment Photo</label>
<input required name="images" type="file" multiple class="form-control-file">
</div>
<br>
<button type='submit' style="width: 100px" class="btn btn-primary">Submit</button>
</form>
How it looks on my website
One way is by naming the images differently so that we know which one is for the box and which one is for the equipment:
Receptionunservicable.html
...
<input required name="image_box" type="file" multiple class="form-control-file">
...
<input required name="image_equipment" type="file" multiple class="form-control-file">
...
Once renamed, we can access them separately and put the appropriate description:
views.py
...
data = request.POST
file_descriptions = [ # This assumes that both images are tagged with <required>
{
"image": request.FILES["image_box"],
"descriptionbox": data['descriptionbox'],
"descriptionequipment": "", # Or better yet make the field <Photo.descriptionequipment> as <null=True> in the model
},
{
"image": request.FILES["image_equipment"],
"descriptionbox": "", # Or better yet make the field <Photo.descriptionbox> as <null=True> in the model
"descriptionequipment": data['descriptionequipment'],
},
]
for file in file_descriptions:
photo = Photo.objects.create(
serialno=data['serialno'],
partno=data['partno'],
reception=data['reception'],
customername=data['customername'],
**file,
)
...

how to show data through input tag

I am working on a Django project .In front-end I want to add user data through input tags but I do not know how to save data through input tags
My models.py file is::
class User(AbstractBaseUser):
full_name = models.CharField(max_length=255, blank=True, null=True)
sur_name = models.CharField(max_length=255, blank=True, null=True)
email = models.EmailField(max_length=255 ,unique=True)
choose_subject = models.CharField(choices=SUBJECT_CHOICES , max_length=100)
staff = models.BooleanField(default=False)
admin = models.BooleanField(default=False)
time_stamp = models.DateTimeField(auto_now_add=True)
father_name = models.CharField(max_length=255)
father_sur_name = models.CharField(max_length=255)
mobile_phone_number = models.IntegerField(blank=True,null=True)
father_email = models.EmailField(max_length=255, unique=True)
fiscal_code = models.CharField(max_length=20)
address = models.CharField(max_length=200 )
A part of my register.html file is:
<div class="card-body">
<h2 class="title">Registration Form</h2>
<form method="POST">{% csrf_token %}
<div class="row row-space">
<div class="col-2">
<div class="input-group">
<label class="label">Full name</label>
<input class="input--style-4" type="text" name="first_name"{{form.full_name}}>
</div>
</div>
<div class="col-2">
<div class="input-group">
<label class="label">Sur name</label>
<input class="input--style-4" type="text" name="last_name"{{form.sur_name}}>
</div>
</div>
</div>
I just want the Django model field to be working in input tags
You must create in the views.py file a method in which the templates and the logic of it, an example can be the following
views.py
#csrf_exempt
def register(request):
if request.method == 'POST':
var1 = request.POST.get('var1')
var2 = request.POST.get('var2')
var3 = request.POST.get('var3')
#Save to the database here
return render_to_response(
'home.html',
{'message': 'Update Success', }
)
else:
#elif request.method == "GET":
obj = table.objects.all()
if obj:
ctx['data'] = obj
return render(request, template_name, ctx)
and in your template add a form tag
<form method="POST">
{ % csrf_token % }
<div class="row row-space">
<div class="col-2">
<div class="input-group">
<label class="label">Full name</label>
<input class="input--style-4" type="text" value={{data.full_name}}>
</div>
</div>
<div class="col-2">
<div class="input-group">
<label class="label">Sur name</label>
<input class="input--style-4" type="text" value={{data.sur_name}}>
</div>
</div>
</div>
<input type="submit" value="OK">
</form>
refer this tutorial

How to sed data from database to html form in Flask for editing

I am trying to send the data from the database to the Html form, but I'm getting an error like this
TypeError: 'ImmutableMultiDict' objects are immutable
this is the flask code for editing the data
#app.route('/edit-project/<string:id>', methods = ['GET', 'POST'])
def edit_project(id):
project = Project.query.get(id)
request.form['title'] = project.title
request.form['link'] = project.link
request.form['description'] = project.description
if request.method == 'POST':
title = request.form['title']
link = request.form['link']
description = request.form['description']
image = request.files['image']
image.save(os.path.join(app.config["IMAGE_UPLOADS"], 'project/'+ project.image))
return render_template('project/edit_project.html')
The Html template 'edit_project.html' is shown below
<div class="container">
<form method="POST" id="project-form" enctype="multipart/form-data">
<div class="form-group">
<input type="text" name="title" class="form-control" id="title" placeholder="Title">
</div>
<div class="form-group">
<input type="text" name="link" class="form-control" id="title" placeholder="Project Link">
</div>
<div class="form-group">
<label for="exampleFormControlTextarea1">Description</label>
<textarea id = project-form name="description" class="form-control" id="description" rows="3"></textarea>
</div>
<div class="input-group" style="width: 30%;">
<div class="input-group-prepend">
<span class="input-group-text" id="inputGroupFileAddon01">Upload</span>
</div>
<div class="custom-file">
<input type="file" name="image" class="custom-file-input" id="inputGroupFile01" aria-describedby="inputGroupFileAddon01">
<label class="custom-file-label" for="inputGroupFile01">Upload image</label>
</div>
</div>
<div class="form-group" style="padding-top: 2rem;">
<button type="submit" class="btn btn-primary">Publish</button>
</div>
</form>
</div>
Is there is any way to display the data in the form without using WTForms or do I've to use WTForms instead?
Thanks in advance.
Can you use jinja templating?
render_template() takes data argument. You can pass the data from your DB to that call and use jinja templates in HTML to render it. Setting the values of your input will do.
For example:
Your data is data = {title:"apple"}
And, return render_template("project/edit_project.html", data=data) will provide you data object in HTML file.
There, you can use jinja like this:
<div class="form-group">
<input type="text" name="title" class="form-control" id="title" placeholder="Title" value={{data.text}}>
</div>
Hope it helps!

some fields aren't being saved in django-models

I am inserting new records in a model using a function-based view, but the problem is that some fields aren't being saved.
I get all fields through request.POST.get(field_name) and assign them to a variable before saving them to the corresponding field of a model.
views.py
import datetime
from django.shortcuts import render, redirect
def CreateExam(request):
if request.method == "POST":
st_exam = exam()
topic = request.POST.get("topic")
auth = request.POST.get("author")
date_now = request.POST.get("date_now")
st_exam.topic = request.POST.get("topic")
st_exam.auth = request.POST.get("author")
st_exam.date = date_now
st_exam.total_grade = request.POST.get("total_grade")
st_exam.semester_id = request.POST.get("semester")
st_exam.exam_id = auth[0:2] + topic[0:2] + date_now
# st_exam.course = request.POST.get("course")
y = datetime.now()
st_exam.semester_id = str(y.year) +'-'+request.POST.get("semester")
st_exam.save()
return redirect('/teacher/')
else:
return render(request, '500.html', {"error": "Ooops Illegal access"})
models.py
from django.db import models
class exam(models.Model):
exam_id = models.CharField(max_length=40,null=True)
date = models.CharField(max_length=40,null=True)
total_grade = models.FloatField(null=True)
author= models.CharField(max_length=40,null=True)
topic = models.CharField(max_length=40,null=True)
course = models.CharField(max_length=40,null=True)
semester_id = models.CharField(max_length=40,null=True)
template.html
<form method="post" action="/teacher/create/exam/">
{% csrf_token %}
<div class="form-group col-md-8">
<label for="topic">Topic</label>
<input type="text" name="topic" class="form-control" id="topic"/>
</div>
<div class="form-group col-md-8">
<label for="grade">Author</label>
<input type="text" name="author" class="form-control" id="author"/>
</div>
<div class="form-group col-md-8">
<label for="date">Date</label>
<input type="date" name="date_now" class="form-control" id="date"/>
</div>
<div class="form-group col-md-8">
<label for="grade">Course</label>
<input type="text" name="course" class="form-control" id="grade"/>
</div>
<div class="form-group col-md-8">
<label for="grade">grade</label>
<input type="number" name="total_grade" class="form-control" id="grade"/>
</div>
<div class="form-group col-md-8">
<label for="cat">Semester </label>
<select name="semester" class="form-control">
<option value="1"> Semester 1</option>
<option value="2"> Semester 2</option>
</select>
</div>
<button type="submit"
class="btn btn-primary m-t-15 waves-effect">Save
</button>
</form>
I expect all fields to be saved but the author field doesn't get saved

How to pass form fields into 'templated' HTML file

I would like to get form data from a pre-built HTML template using a Django form without changing the display.
I know I could use something like:
name = request.POST.get('first_name')
But would like to handle the data using a ModelForm
forms.py
class BioDataForm(forms.ModelForm):
first_name = forms.CharField(max_length=100, label='first_name')
last_name =forms.CharField(max_length=100, label='last_name')
mobile = forms.CharField(max_length=100, label='mobile_number')
email = forms.EmailField(max_length=100, label='personal_email')
gender = forms.CharField(max_length=100, widget=forms.Select(attrs={'class': 'form-control', 'id': 'gender'}))
marital_status = forms.CharField(max_length=100, widget=forms.Select(attrs={'class': 'form-control', 'id': 'marital_status'}))
date_of_birth = forms.DateField(input_formats=['%Y-%m-%d'], widget=forms.SelectDateWidget())
address = forms.CharField(max_length=100)
class Meta:
model = BioData
exclude = ('state',)
fields = ['first_name', 'last_name', 'mobile', 'email',
'gender', 'marital_status', 'date_of_birth', 'address']
Sample HTML
<div class="row form-group">
<div class="col-md-6 col-sm-12 margin-bottom-20-m">
<label for="first_name" class="form-control-label kt-black-text">First Name</label>
<input type="text" class="form-control" id="first_name" name="e_first_name" required>
</div>
<div class="col-md-6 col-sm-12">
<label for="last_name" class="form-control-label kt-black-text">Last Name</label>
<input type="text" class="form-control" id="last_name" name="e_last_name" required>
</div>
</div>
iterate form in template :
<div class="row form-group">
{% for field in form %}
<div class="col-md-6 col-sm-12 margin-bottom-20-m">
<label for="{{ field.id_for_label }}" class="form-control-label kt-black-text">{{ field.label }}</label>
{{ field }}
</div>
{% endfor %}
</div>