I am making a django webapp where users can upload profile image. I have also created an EDIT PROFILE page by using the default USERCHANGEFORM. But the problem is, that I cannot update the profile picture from that form. I can delete it but not upload new one? Help needed.
This is my USER CREATION FORM:
class SignUpForm(UserCreationForm):
photo = forms.ImageField(required=False)
bio = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Enter your bio'}))
designation = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Enter your designation'}))
university = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Enter your university'}))
company_name = forms.CharField(widget=forms.TextInput(attrs={'placeholder': "Enter your company's name"}))
grad_year = forms.IntegerField(widget=forms.TextInput(attrs={'placeholder': 'What year did you graduate in?'}))
phone = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Enter your phone number'}))
address = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Enter your present address'}))
city = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Enter your city'}))
company_category = forms.CharField(widget=forms.TextInput(attrs={'placeholder': "Enter your company's category"}))
company_desc = forms.CharField(widget=forms.TextInput(attrs={'placeholder': "Enter your company's description"}))
company_site = forms.CharField()
no_employees = forms.IntegerField(widget=forms.TextInput(attrs={'placeholder': 'Enter no. of employees in your company'}))
technologies = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'What technologies are you interested in?'}))
markets = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'What markets are you interested in?'}))
linkedin = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Enter your Linked In profile'}))
def __init__(self, *args, **kwargs):
super(UserCreationForm, self).__init__(*args, **kwargs)
del self.fields['password2']
for fieldname in ['password1']:
self.fields[fieldname].help_text = None
self.fields['password1'].widget.attrs.update({'placeholder': 'Enter your password'})
self.fields['first_name'].widget.attrs.update({'placeholder': 'Enter your first name'})
self.fields['last_name'].widget.attrs.update({'placeholder': 'Enter your last name'})
self.fields['company_site'].widget.attrs.update({'placeholder': "Enter company's website"})
for field in ['email',
'password1',
'first_name',
'last_name',
'bio',
'designation',
'university',
'company_name',
'grad_year',
'phone',
'photo',
'address',
'city',
'company_category',
'company_desc',
'company_site',
'no_employees',
'technologies',
'markets',
'linkedin']:
self.fields[field].widget.attrs['class'] = "col-lg-4 col-md-12 col-sm-12 col-xs-12 offset-lg-2 ml-6 form-control"
self.fields[field].widget.attrs['style'] = "padding:20px;"
self.fields['photo'].widget.attrs['class'] = "col-lg-8 col-md-12 col-sm-12 col-xs-12 offset-lg-1 "
class Meta:
model = User
widgets = {
"email": forms.fields.TextInput(attrs={'placeholder':'Enter your email'}),
}
fields = ('email',
'password1',
'first_name',
'last_name',
'photo',
'bio',
'designation',
'university',
'company_name',
'grad_year',
'phone',
'address',
'city',
'company_category',
'company_desc',
'company_site',
'no_employees',
'technologies',
'markets',
'linkedin')
This is my USER CHANGE FORM
class EditProfileForm(UserChangeForm):
def __init__(self, *args, **kwargs):
super(UserChangeForm, self).__init__(*args, **kwargs)
for field in [
'first_name',
'last_name',
'bio',
'designation',
'university',
'company_name',
'grad_year',
'phone',
'address',
'city',
'company_category',
'company_desc',
'company_site',
'no_employees',
'technologies',
'markets',
'linkedin']:
self.fields[field].widget.attrs['class'] = "col-lg-8 col-md-12 col-sm-12 col-xs-12 offset-lg-2 ml-6 form-control"
self.fields[field].widget.attrs['style'] = "padding:20px;"
self.fields['photo'].widget.attrs['class'] = "col-lg-8 col-md-12 col-sm-12 col-xs-12 offset-lg-2 ml-6"
self.fields['password'].widget.attrs['class'] = "hidden"
class Meta:
model = User
fields = ('first_name',
'last_name',
"photo",
"bio",
"designation",
"university",
"company_name",
"grad_year",
"phone",
"address",
"city",
"company_category",
"company_desc",
"company_site",
"no_employees",
"technologies",
"markets",
"linkedin"
)```
Basically you are getting the instance but you are not only able to update only the picture.
Try this!
In your EditProfileForm
replace
super(UserChangeForm, self).__init__(*args, **kwargs)
to
super(EditProfileForm, self).__init__(*args, **kwargs)
same in your SignUpForm
replace
super(UserCreationForm, self).__init__(*args, **kwargs)
to
super(SignUpForm, self).__init__(*args, **kwargs)
And you forgot to add photo inside EditProfileForm for field in [...]
{% load static %}
{% block content %}
<!-- Inner Page Banner Area Start Here -->
<div class="inner-page-banner-area" style="background-image: linear-gradient(to bottom,#002147, #fdc800);">
<div class="container">
<div class="pagination-area">
<h1>Edit Profile</h1>
</div>
</div>
</div>
<!-- Inner Page Banner Area End Here -->
<!-- Account Page Start Here -->
<div class="section-space accent-bg">
<div class="container">
<div class="row">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div class="profile-details tab-content">
<div class="tab-pane fade active in" id="Personal">
<h3 class="title-section title-bar-high mb-40">Edit Profile</h3>
<form id='login-form' style='text-align:left;' method="post" enctype="multipart/form-data">
<div class="form-group mt-1">
{% csrf_token %}
{% for field in form %}
<p>
<div class="mb-n5">{% if field.field.required %}{{ field.label_tag}}<span style='color:red;'>*</span>
{% else %}{{ field.label_tag}}
{% endif %}</div>
{% if field.name == 'password' %}
Change Password
{% else %}
{{ field }}
{% endif %}
<br>
{% for error in field.errors %}
<p style="color: red">{{ error }}</p>
{% endfor %}
</p>
</br>
{% endfor %}
</div>
<button class="view-all-primary-btn" type="submit">Save</button>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
{% include 'partials/_footer.html' %}
{% endblock %}
Related
I want to make an input that uploads multiple images. I have been reviewing some tutorials and my experience makes me not understand many things.
I placed a view but in the template, where the input should appear, this appears:
<QuerySet []>
Obviously that should not be there, the input should appear that uploads the images when clicked. Can you see my code? can you give me a hint?
html
<form enctype="multipart/form-data" method="post">
{% csrf_token %}
<div class="col-md-4">
<div class="mb-3">
<label class="form-label">Insurance company</label>
{{ form.compañia_seguros }}
<div class="invalid-feedback">
Please provide a website.
</div>
</div>
</div>
</div>
<div class="row mb-3">
<div class="col-md-4">
<div class="mb-3">
<label>Cliente</label>
{{ form.cliente }}
</div>
</div>
</div>
<div class="tab-pane" id="pictures" role="tabpanel">
<div>
{{ images }}
<label for="file-input" class="btn btn-outline-success">Upload images</label>
<p id="num-of-files">No files chosen</p>
<div id="images"></div>
</div>
</div>
<div class="tab-pane" id="warranty" role="tabpanel">
<div>
{{ garantias }}
<label for="file-inputz" class="btn btn-outline-success">Upload images</label>
<p id="num-of-filez">No files chosen</p>
<div id="imagez"></div>
</div>
<br>
<button class="btn btn-primary mb-3" type="submit" value="Post">Save</button>
</div>
</form>
views.py
def create_carros(request):
if request.method == "POST":
form = CarroForm(request.POST)
images = request.FILES.getlist('fotosCarro')
garantias = request.FILES.getlist('garantia')
for image in images:
Carro.objects.create(fotosCarro=image)
for garantia in garantias:
Carro.objects.create(garantias=garantia)
form = CarroForm(request.POST)
images = FotosCarro.objects.all()
garantias = Garantia.objects.all()
return render(request, 'carros/carros-form-add.html', {'images': images,'garantias': garantias,'form':form})
models.py
class Carro(models.Model):
compañia_seguros=models.CharField(max_length=255, null=True)
cliente= models.ForeignKey(Clientes, on_delete=models.SET_NULL, null=True)
fecha_registros = models.DateTimeField(default=datetime.now, null=True)
def __str__(self):
return f'{self.compañia_seguros}{self.cliente}' \
f'{self.fecha_registros}'
class FotosCarro(models.Model):
carro = models.ForeignKey(Clientes, on_delete=models.SET_NULL, null=True)
fotosCarro=models.ImageField(null=True, upload_to="images/")
class Garantia(models.Model):
carro = models.ForeignKey(Clientes, on_delete=models.SET_NULL, null=True)
garantia=models.ImageField(null=True, upload_to="images/")
forms.py
class CarroForm(forms.ModelForm):
class Meta:
model=Carro
fields = ['compañia_seguros','cliente']
exclude = ['fecha_registros']
widgets = {
'compañia_seguros': forms.TextInput(
attrs={
'class': 'form-control'
}
),
'cliente': forms.Select(
attrs={
'class': 'form-select'
}
),
'fecha_registros': forms.DateInput(
attrs={
'class': 'form-control',
}
),
}
class FotosForm(forms.ModelForm):
model = FotosCarro
widgets = {
'fotosCarro':forms.FileInput(
attrs={
'class': 'type-file',
'multiple': True,
'id': 'file-input',
'onchange':'preview()',
}
),
}
class GarantiaForm(forms.ModelForm):
model = Garantia
widgets = {
'garantia':forms.FileInput(
attrs={
'class': 'type-file',
'multiple': True,
'id': 'file-inputz',
'onchange': 'previewz()',
}
),
}
Now that you have separated out FotosCarro and Garantia as their own models, I assume that Carro can have more than one of each of these. This means your form needs to be a bit more complex. To include "subforms" for related models in the parent form, you can to use inline formsets. This will allow you to upload images for multiple FotosCarros and Grantias for a single Carro.
I am trying to save po_id as a unique key of the "Order table". So I am generating a random number in the Order Form. But the issue is that somehow I can not save the form, even though all the fields are filled up.
models.py
def random_string():
return str(random.randint(10000, 99999))
class Order(models.Model):
po_id = models.CharField(max_length=4, default = random_string)
supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE)
product = models.ForeignKey(Product, on_delete=models.CASCADE)
forms.py
class OrderForm(forms.ModelForm):
class Meta:
model = Order
fields = ['supplier', 'product', 'po_id']
widgets = {
'supplier': forms.Select(attrs={'class': 'form-control', 'id': 'supplier'}),
'product': forms.Select(attrs={'class': 'form-control', 'id': 'product'}),
}
views.py
def create_order(request):
from django import forms
form = OrderForm()
if request.method == 'POST':
forms = OrderForm(request.POST)
if forms.is_valid():
po_id = forms.cleaned_data['po_id']
supplier = forms.cleaned_data['supplier']
product = forms.cleaned_data['product']
order = Order.objects.create(
po_id=po_id,
supplier=supplier,
product=product,
)
return redirect('order-list')
context = {
'form': form
}
return render(request, 'store/addOrder.html', context)
Order.html
<form action="#" method="post" novalidate="novalidate">
{% csrf_token %}
<div class="form-group">
<label for="po_id" class="control-label mb-1">ID</label>
{{ form.po_id }}
</div>
<div class="form-group">
<label for="supplier" class="control-label mb-1">Supplier</label>
{{ form.supplier }}
</div>
<div class="form-group">
<label for="product" class="control-label mb-1">Product</label>
{{ form.product }}
</div>
<div>
<button id="payment-button" type="submit" class="btn btn-lg btn-success btn-block">
<span id="payment-button-amount">Save</span>
</button>
</div>
Can help me with how I can solve the issue?
models.py:
class Venue(models.Model):
author = models.ForeignKey(ProfileUser, on_delete=models.CASCADE)
title = models.CharField(max_length=300)
city = models.ForeignKey(City, on_delete=models.CASCADE)
address = models.CharField(max_length=300)
phone = models.CharField(max_length=20, default='')
email = models.CharField(max_length=100, default='')
site = models.CharField(max_length=100, default='')
facebook = models.CharField(max_length=100, default='')
instagram = models.CharField(max_length=100, default='')
content = models.TextField()
rating = models.DecimalField(default=10.0, max_digits=5, decimal_places=2)
created_date = models.DateTimeField(default=timezone.now)
approved_venue = models.BooleanField(default=False)
admin_seen = models.BooleanField(default=False)
category = models.ForeignKey(Category, on_delete=models.CASCADE)
def __str__(self):
return f"{self.title}"
forms.py
class VenueForm(forms.ModelForm):
class Meta:
model = Venue
fields = [
'title',
'content',
'city',
'address',
'phone',
'email',
'site',
'facebook',
'instagram',
]
def __init__(self, *args, **kwargs):
super(VenueForm, self).__init__(*args, **kwargs)
self.fields['title'].label = "Име"
self.fields['content'].label = 'Описание'
self.fields['city'].label = 'Град'
self.fields['address'].label = 'Адрес'
self.fields['phone'].label = 'Телефон'
self.fields['email'].label = 'E-mail'
self.fields['site'].label = 'Сайт'
html render:
<form method="post" id="dialog_addVenue_part" enctype="multipart/form-data">
{% csrf_token %}
{% for hidden in postForm.hidden_fields %}
{{ hidden }}
{% endfor %}
{% for field in form %}
<div class="fieldWrapper">
<div class="errorcode{{field.html_name}}">
{{ field.errors }}
</div>
{{ field.label_tag }} {{ field }}
{% if field.help_text %}
<p class="help">{{ field.help_text|safe }}</p>
{% endif %}
</div>
{% endfor %}
<div id="map" style="height: 500px;">
</div>
<div class="utf_addVenue_form">
<button type="submit" value="Изпрати">Изпрати</button>
</div>
</form>
Part of HTML with required fields:
<div class="fieldWrapper">
<div class="errorcodesite">
</div>
<label for="id_site">Сайт:</label> <input type="text" name="site" maxlength="100" required="" id="id_site">
</div>
<div class="fieldWrapper">
<div class="errorcodefacebook">
</div>
<label for="id_facebook">Facebook:</label> <input type="text" name="facebook" maxlength="100" required="" id="id_facebook">
</div>
I have not indicated anywhere that form should have "required" to all fields but they comes with it. So, Are Django model forms are required by default and how to set required to false for whole form?
Add blank=True to the fields you don't need to be required.
class Venue(models.Model):
. . .
title = models.CharField(max_length=300, blank=True)
. . .
I want to display only employees which emp_type is 'Doctor'?
** Here is Models.py **
class Employee(models.Model):
name = models.CharField(max_length=50)
emp_type_choices = [
('Nurse', 'Nurse'),
('Doctor', 'Doctor'),
('Other', 'Other'),
]
emp_type = models.CharField(
max_length=6, choices=emp_type_choices, default='Nurse')
def __str__(self):
return self.name
class Ticket(models.Model):
patient = models.CharField(max_length=50)
doctor = models.ForeignKey(Employee, on_delete=models.CASCADE)
def __str__(self):
return self.patient.name
This is my Forms.py
class TicketModelForm(forms.ModelForm):
class Meta:
model = Ticket
fields = ['doctor', 'status']
widgets = {
'doctor': forms.Select(attrs={'class': 'form-control','placeholder': 'Doctor Name'}),
}
This is my Views.py
#login_required
def TicketToGenerateView(request, pk):
ticket = get_object_or_404(Patient, pk=pk)
form = TicketModelForm(request.POST or None)
if form.is_valid():
obj.save()
return redirect('/dashboard/ticket')
context = {
'form': form,
'ticket': ticket,
}
return render(request, 'dashboard/ticket.html', context)
This is my Template
<form action="." method="POST">
{% csrf_token %}.
{% for field in form %}
<div class="form-group">
{{ field }}
{% if field.errors %}
{% for error in field.errors %}
<p class="text-danger">{{ error|escape }}</p>
{% endfor %}
{% endif %}
</div>
{% endfor %}
<div class="form-group float-right">
<button type="submit" class="btn btn-success btn-sm" value=" {{ valueBtn }} "> <span
class="glyphicon glyphicon-plus"></span> </button>
</div>
</form>
In the template, I'm displaying all registered employees as a dropdown list, but I would like to display only employees which their emp_type is 'Doctor'.
Also the Admin site I would like to see the only emp_type which are 'Doctor'.
Thanks
# You have to use filter for your query
emp_doctor = Employee.objects.filter(emp_type='Doctor')
print(emp_doctor)
I had a form with some fields and it was working fine. But when adding new field in the Model django raise an error
when I run the server and click on submit then it shows error for the new field This field is required although I am providing data for this field in the form.
Model.py
class UserInformation(models.Model):
firstName = models.CharField(max_length=128)
lastName = models.CharField(max_length=128)
userName = models.CharField(max_length=128)
institution = models.CharField(choices = [("#xyz.org","XYZ"), ("#abc.edu","ABC")], max_length=128)
userEmail = models.CharField(default="N/A", max_length=128)
phoneNumber = models.CharField(max_length=128)
orchidNumber = models.CharField(max_length=128)
PI = models.CharField(max_length=128)
PIUsername = models.CharField(max_length=128)
PIInstitution = models.CharField(default="N/A",choices = [("#xyz.org","XYZ"), ("#abc.edu","ABC")], max_length=128)
PIEmail = models.CharField(default="N/A", max_length=128)
PIPhoneNumber = models.CharField(max_length=128)
In this model
PIEmail is the field which I have added.
forms.py
class UserInformationForm(ModelForm):
firstName = forms.CharField(max_length=254,
widget=forms.TextInput({
'class': 'form-control',
}))
lastName = forms.CharField(
widget=forms.TextInput({
'class': 'form-control',
}))
userName = forms.CharField(
widget=forms.TextInput({
'class': 'form-control',
}))
institution = forms.ChoiceField( choices = [("#xyz.org","XYZ"), ("#abc.edu","ABC")]
,widget=forms.Select({
'class': 'form-control',
}))
phoneNumber = forms.CharField( required=False,
widget=forms.TextInput({
'class': 'form-control',
}))
orchidNumber = forms.CharField( required=False,
widget=forms.TextInput({
'class': 'form-control',
}))
PI = forms.CharField(
widget=forms.TextInput({
'class': 'form-control',
}))
PIUsername = forms.CharField(
widget=forms.TextInput({
'class': 'form-control',
}))
ctsaPIInstitution = forms.ChoiceField( choices = [("#xyz.org","XYZ"), ("#abc.edu","ABC")]
,widget=forms.Select({
'class': 'form-control',
}))
PIPhoneNumber = forms.CharField(
widget=forms.TextInput({
'class': 'form-control',
}))
userEmail = forms.CharField( required=False,
widget=forms.TextInput({
'class': 'form-control',
}))
PIEmail = forms.CharField( required=False,
widget=forms.TextInput({
'class': 'form-control',
}))
class Meta:
model = UserInformation
exclude = ()
and here is my register.html
<div class="row">
<section id="registerForm">
<div style="font-size:15px; color:red;">
The fields marked with an asterisk (*) are mandatory.
</div><br/>
<form method="post" action=".">{% csrf_token %}
<div class="form-group">
<label for="id_firstName" >First Name (*)</label>
{{ form.firstName }}
</div>
<div class="form-group">
<label for="id_lastName" >Last Name (*)</label>
{{ form.lastName }}
</div>
<div class="form-group">
<label for="id_email">Username (*)</label>
{{ form.userName }}
</div>
<div class="form-group">
<label for="id_intitution">Institution (*)</label>
{{ form.institution }}
</div>
<div class="form-group">
<label for="id_phone" >Contact Number</label>
{{ form.phoneNumber }}
</div>
<div class="form-group">
<label for="id_orcid">Orcid ID (Get Orcid ID)</label>
{{ form.orchidNumber }}
</div>
<div class="form-group">
<label for="id_ctsaPI">Prinicipal Investigator (*)</label>
{{ form.PI }}
</div>
<div class="form-group">
<label for="id_PI">CTSA Prinicipal Investigator Username (*)</label>
{{ form.PIUsername }}
</div>
<div class="form-group">
<label for="id_ctsaPI">Prinicipal Investigator Institute (*)</label>
{{ form.PIInstitution }}
</div>
<div class="form-group">
<label for="id_PIName"> Prinicipal Investigator Phone Number (*)</label>
{{ form.PIPhoneNumber }}
</div>
<div class="form-group">
<label for="id_UserEmail">User Email (*)</label>
{{ form.userEmail }}
</div>
<div class="form-group">
<label for="id_PI">PI Email (*)</label>
{{ form.PIEmail }}
</div>
<div class="form-group" >
<br/>
<input type="submit" value="Submit" class="btn btn-primary" />
</div>
</form>
</section>
view.py
#csrf_protect
def register(request):
if request.method == 'POST':
form = UserInformationForm(request.POST)
if form.is_valid(): //// here it is breaking
form.save()
else:
form = UserInformationForm()
variables = { 'form': form }
return render(request, 'registration/register.html',variables)
I am not sure what is wrong in this code
I'm not sure if this helps but sometimes I find the errors returned look like a bit of a red herring and end up driving me mad for hours on end. I am no expert and from where I am sitting the code for your form looks fine to me which is probably why it was working before. However in your html file you have two labels specified with the same id, the second one just happens to be on the PIEmail field that you have recently added. Coincidence? Maybe! It's a long shot but perhaps change that initially and see if it makes any difference.
Change:
<div class="form-group">
<label for="id_PI">PI Email (*)</label>
{{ form.PIEmail }}
</div>
to:
<div class="form-group">
<label for="id_PIEmail">PI Email (*)</label>
{{ form.PIEmail }}
</div>
Note: The other instance is on the PIUsername field.