I am making a personal training website and am having trouble getting the profile pic to upload
my form looks like this:
<form class="form-horizontal" action="updateProfile" method="post" enctype= "multipart/form-data">
{% csrf_token %}
<div class="form-group">
<label class="control-label col-sm-2" for="gym">Main Gym</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="gym" placeholder="Enter gym name" name="gym" id="gym">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="last name">Qualifications</label>
<div class="col-sm-10">
<textarea name="qualifications" rows="10" cols="130" name="qualifications" id="qualifications"></textarea>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="last name">About Me</label>
<div class="col-sm-10">
<textarea name="aboutme" rows="10" cols="130" id="aboutme"></textarea>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="servicedetails">Service Details</label>
<div class="col-sm-10">
<textarea name="servicedetails" rows="10" cols="130" id="servicedetails"></textarea>
</div>
<div class="form-group">
<label for="avatar">Choose a profile picture:</label>
<div class="form-group">
<input type="file"
id="avatar" name="avatar"
accept="image/png, image/jpeg">
</div>
</div>
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default">Submit</button>
</div>
</div>
</form>
models.py:
class trainerabout(models.Model):
userID = models.IntegerField()
gym = models.TextField(max_length=30)
qualifications = models.TextField()
aboutme = models.TextField()
servicedetails = models.TextField()
profilepic = models.ImageField(upload_to='images/')
added this to urls.py
urlpatterns = urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
views.py:
def updateProfile(request):
if request.method == 'POST':
gym = request.POST['gym']
qualifications = request.POST['qualifications']
aboutme = request.POST['aboutme']
servicedetails = request.POST['servicedetails']
avatar = request.POST['avatar']
trainer = trainerabout(gym=gym, qualifications=qualifications, aboutme=aboutme, servicedetails=servicedetails, profilepic=avatar, userID=request.user.id)
trainer.save()
return render(request, 'updateProfile.html')
added this to settings.py
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
when I enter in stuff on my form it saves the url of the image to the database no problem but the image doesn't get saved into the media folder. I was under the impression that it created a media folder for you but it didn't. I then created a media folder and still nothing. What am I doing wrong here?
You should be using request.FILES, not request.POST to access uploaded files. Please, see Django docs for more. And, it is convention that model names are Capitalized at each containing word, like TrainerAbout, not trainerabout.
Related
I wanna create a appointment system but its not working now. I'dont have a error actually i just have a error and it's coming from views.py (messages.warning(request,"ERROR!")). When i opened the page its coming anyway i just wanna send my informations.
models.py: I created models but im not sure for policlinic and doctor because it doesn't seems like charfield text. It's a option field in HTML.
class Randevu(models.Model):
STATUS = (
('New', 'Yeni'),
('True', 'Evet'),
('False', 'Hayır'),
)
policlinic=models.ForeignKey(Policlinic,on_delete=models.CASCADE)
user=models.ForeignKey(User,on_delete=models.CASCADE)
doctor=models.ForeignKey(Doctors,on_delete=models.CASCADE)
phone = models.CharField(max_length=15)
email = models.CharField(max_length=50)
date=models.DateField(null=True)
time=models.TimeField(null=True)
payment= models.CharField(max_length=50)
insurance= models.CharField(max_length=50)
note=models.TextField(max_length=200)
status = models.CharField(max_length=10, choices=STATUS,default='New')
ip=models.CharField(max_length=20,blank=True)
create_at = models.DateTimeField(auto_now_add=True)
update_at = models.DateTimeField(auto_now=True)
def str(self):
return self.user.username
class AppointmentForm(ModelForm):
class Meta:
model=Randevu
fields=['phone','email','date','time','payment','insurance','note']
views.py:
def randevu(request):
setting=Setting.objects.get(pk=1)
policlinic=Policlinic.objects.all()
doctor=Doctors.objects.all()
context={'setting':setting ,'doctor':doctor,'policlinic':policlinic}
if request.method=='POST':
form=AppointmentForm(request.POST)
if form.is_valid():
current_user=request.user
data=Randevu()
data.user_id=current_user.id
data.phone=form.cleaned_data['phone']
data.email=form.cleaned_data['email']
data.date=form.cleaned_data['date']
data.time=form.cleaned_data['time']
data.payment=form.cleaned_data['payment']
data.insurance=form.cleaned_data['insurance']
data.note=form.cleaned_data['note']
data.ip=request.META.get('REMOTE_ADDR')
data.save()
messages.success(request,"DONE! :)")
return render(request,'randevu.html',context)
messages.warning(request,"ERROR!")
return render(request,'randevu.html',context)
urls.py
urlpatterns = [
path('randevu',views.randevu,name='randevu') ]
randevu.html
<!-- MAKE AN APPOINTMENT -->
<section id="appointment" data-stellar-background-ratio="3">
<div class="container">
<div class="row">
<div class="col-md-6 col-sm-6">
<img src="{% static 'images/appointment-image.jpg' %}" class="img-responsive" alt="">
</div>
<div class="col-md-6 col-sm-6">
<!-- CONTACT FORM HERE -->
<form id="appointment-form" role="form" action="{% url 'randevu' %}" method="post">
<!-- SECTION TITLE -->
<div class="section-title wow fadeInUp" data-wow-delay="0.4s">
<h2>Randevu Alın</h2>
{%if messages%}
{%for message in messages%}
<div class="alert alert-{{message.tags}}"role="alert">
{{message}}
</div>
{%endfor%}
{%endif%}
</div>
{% csrf_token %}
<div class="wow fadeInUp" data-wow-delay="0.8s">
<div class="col-md-6 col-sm-6">
<label for="email">E-mail</label>
<input type="email" class="form-control" id="email" name="email" placeholder="Your Email">
</div>
<div class="col-md-6 col-sm-6">
<label for="telephone">Telefon Numaranız</label>
<input type="tel" class="form-control" id="phone" name="phone" placeholder="Phone">
</div>
<div class="col-md-6 col-sm-6">
<label for="date">Tarih</label>
<input type="date" name="date" id="date" value="" class="form-control">
</div>
<div class="col-md-6 col-sm-6">
<label for="time">Zaman</label>
<input type="time" name="time" id="time" value="" class="form-control">
</div>
<div class="col-md-6 col-sm-6">
<label for="select">Poliklinik Seçiniz</label>
<select name="policlinic" class="form-control" id="policlinic">
{% for rs in policlinic %}
<option>{{rs.title}}</option>
{%endfor%}
</select>
</div>
<div class="col-md-6 col-sm-6">
<label for="select">Doktor Seçiniz</label>
<select name="doctor" class="form-control" id="doctor">
{% for rs in doctor %}
<option>{{rs.name}}</option>
{%endfor%}
</select>
</div>
<div class="col-md-6 col-sm-6">
<label for="select">Ödeme Yöntemi</label>
<select name="payment" class="form-control" id="payment">
<option>Nakit</option>
<option>Banka Kartı</option>
<option>Kredi Kartı</option>
<option>Diğer</option>
</select>
</div>
<div class="col-md-6 col-sm-6">
<label for="select">Sigorta</label>
<select name="insurance" class="form-control" id="insurance">
<option>SGK</option>
<option>AXA Sağlık Sigortası</option>
<option>Anadolu Sağlık Sigortası</option>
<option>Allianz Sağlık Sigortası</option>
<option>Akbank Sağlık Sigortası</option>
<option>Tamamlayıcı Türkiye Sağlık Sigortası</option>
<option>Diğer (Belirtiniz)</option>
</select>
</div>
<div class="col-md-12 col-sm-12">
<label for="Message">Belirtmek istediğiniz herhangi bir durum</label>
<textarea class="form-control" rows="5" id="note" name="note" placeholder="Notunuz"></textarea>
{%if user.id is not None%}
<button type="submit" class="form-control" id="cf-submit" name="submit">Submit Button</button>
{%else%}
Randevu oluşturmak için login olunuz!
{% endif %}
</div>
</div>
</form>
</div>
</div>
</div>
</section>
It's my appointment page:
enter image description here
Because get method is used to render the page
and in views.py you dont write
if request.method=='GET':
As a result, the error message is executed while there is no error
add this :
if request.method=='GET':
I have a html file that I wanna use this template to render my form and save it to my database
How to do this?
HTML code:
<div class="container-contact100">
<div class="wrap-contact100">
<form class="contact100-form validate-form" enctype="multipart/form-data" method="POST">
{% csrf_token %}
<span class="contact100-form-title">
Add Item!
</span>
<div class="wrap-input100 validate-input" data-validate="Name is required">
<span class="label-input100">Title</span>
<input class="input100" type="text" name="name" placeholder="Enter food name">
<span class="focus-input100"></span>
</div>
<div class="wrap-input100 validate-input">
<span class="label-input100">Price</span>
<input class="input100" type="number" name="price" placeholder="Enter food price">
<span class="focus-input100"></span>
</div>
<div class="wrap-input100 validate-input" data-validate = "Message is required">
<span class="label-input100">Description</span>
<textarea class="input100" name="message" placeholder="Your description here..."></textarea>
<span class="focus-input100"></span>
</div>
<div class="wrap-input100 validate-input" data-validate="Image is required">
<input type="file" class="custom-file-input" id="customFile" name="filename">
<label class="custom-file-label" for="customFile">Choose file</label>
<span class="focus-input100"></span>
</div>
<div class="container-contact100-form-btn">
<div class="wrap-contact100-form-btn">
<div class="contact100-form-bgbtn"></div>
<button class="contact100-form-btn" type="submit">
<span>
Add
<i class="fa fa-long-arrow-right m-l-7" aria-hidden="true"></i>
</span>
</button>
</div>
</div>
</form>
</div>
</div>
<div id="dropDownSelect1"></div>
and here is my forms.py :
from django import forms
from .models import Product
class AddItemForm(forms.ModelForm):
class Meta:
model = Product
fields = '__all__'
even you can access my project from this link via github:
https://github.com/imanashoorii/FoodMenu.git
You have to set the name attributes in your form in your html according to field names of your Porudct model like this (using data from your GitHub link):
add_product.html
<form method="post" enctype="multipart/form-data"> # here define enctype attribute so your form can accept images
{% csrf_token %}
<input type="text" name="title">
<input type="text" name="description">
<input type="number" name="price">
<input type="file" name="image">
<button type="submit">Submit</button>
</form>
Or instead of manually defining each field you can just pass a {{ form.as_p }} to your html to render each field inside a <p> tag like this:
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Submit</button>
</form>
Then here is how you would save it in a view:
views.py
def add_product(request):
if request.method == 'POST':
form = AddItemForm(request.POST, request.FILES) # request.FILES is so your form can save images
if form.is_valid()
form.save()
return redirect('home') # redirect to a valid page
else:
form = AddItemForm()
return render(request, 'add_product.html', {'form': form})
I have fixed my problem by changing views.py to this and fix it :
if form.is_valid():
title = request.POST.get('title')
description = request.POST.get('description')
price = request.POST.get('price')
image = request.POST.get('image')
form.save()
return redirect("food:home")
actually i am trying to sumbit the details from my contact from to them of my django app but i am facing same error with all the
varriable i am am able to get the details from my html page and can
print it in my vs code cmd but when i try to save it in my model i
face same error for all variable so please can anyone help me with it
html code:
<form method="POST" action="">
{% csrf_token %}
<div class="container">
<div class="form-row">
<div class="col">
<label for="inputEmail1">E-mail</label>
<input type="text" class="form-control" name="emails" id="emails" placeholder="Enter your E-mail">
</div>
<div class="col">
<label for="inputEmail2">Phone-Number</label>
<input type="text" class="form-control" name="phones" id="phones" placeholder="Enter your phone number">
</div>
</div>
<div class="form-row">
<div class="col">
<label for="inputEmail1">Age</label>
<input type="text" class="form-control" name="ages" id="ages" placeholder="Enter your age">
</div>
<div class="col">
<label for="inputEmail2">Height</label>
<input type="text" class="form-control" name="height" id="height" placeholder="Enter your height">
</div>
</div>
<div class="form-row">
<div class="col">
<label for="inputEmail4">Weight</label>
<input type="text" class="form-control" name="weight" id="weight" placeholder="Enter your weight">
</div>
<div class="col">
<label for="inputEmail3">Food Habit</label>
<input type="text" class="form-control" name="habit" id="habit" placeholder="Are you veg/non-veg/vegan">
</div>
</div>
<br>
<div class="form-group">
<label for="exampleFormControlTextarea1">Enter other important detail\'s</label>
<textarea class="form-control" placeholder="Enter your message here....."
id="messagess"
name="messagess"
rows="5"></textarea>
</div>
<button type="submit" class="btn btn-danger">Submit</button>
</div>
</form>
my model that i have used:
class ninja(models.Model):
ninjaemail= models.CharField(max_length=50)
phones = models.CharField(max_length=50)
ages = models.CharField(max_length=50)
height = models.CharField(max_length=50)
weight = models.CharField(max_length=50)
habit = models.CharField(max_length=100)
message = models.CharField(max_length=800)
my views.py where i am facing issue
def ninja(request):
if request.method=='POST':
emails = request.POST['emails']
phones = request.POST['phones']
ages = request.POST['ages']
height = request.POST['height']
weight = request.POST['weight']
habit = request.POST['habit']
messagess = request.POST['messagess']
ninj=ninja(ninjaemail=emails,phones=phones,ages=ages,height=height,weight=weight,habit=habit,messages=messagess)
ninj.save()
Your ninja model has a property message but when you create your ninja instance you try to set the property messagess.
So change the line
ninj=ninja(ninjaemail=emails,phones=phones,ages=ages,height=height,weight=weight,habit=habit,messagess=messagess)
to
ninj = ninja(ninjaemail=emails,
phones=phones,
ages=ages,
height=height,
weight=weight,
habit=habit,
message=messagess
)
That the Error also occures for every other variable could be caused by your naming. You try to create a ninja object by calling ninja(ninjaemail= ....) inside a ninja method. So it probably doesn't call the Object but the method.
Change your naming like this:
class ninja(models.Model):
...
to
class Ninja(models.Model):
...
and
def ninja(request):
...
to
def create_ninja(request):
...
applyonline.html(I have given file fields for adhaarcopy and idcopy)
<body ng-app="">
{% extends "pmmvyapp/base.html" %}
{% load crispy_forms_tags %}
{% load static %}
{% block content%}
<div class="col-md-8">
<form method="post" action="/personal_detail/">
{% csrf_token %}
<div class="form-group">
<div class=" mb-4">
<h6><u>(*Mandatory Fields)Please Fill up the details below </u></h6>
</div>
<legend class="border-bottom mb-4" ,align="center">1.Beneficiary Details</legend>
<label for="formGropuNameInput">Does Beneficiary have an Adhaar Card?*</label>
<input type="radio" name="showHideExample" ng-model="showHideTest" value="true">Yes
<input type="radio" name="showHideExample" ng-model="showHideTest" value="false">No
<!--logic for yes-->
<div ng-if="showHideTest=='true'">
<div class="form-group">
<label for="formGropuNameInput">Name of Beneficiary(as in Aadhar Card)*</label>
<input name="beneficiary_adhaar_name" class="form-control" id="formGroupNameInput" placeholder="Enter name of Beneficiary as in Aadhar Card" required>
</div>
<div class="custom-file">
<input type="file" class="custom-file-input" id="customFile" name="adhaaarcopy">
<label class="custom-file-label" for="customFile">Choose file</label>
</div>
</div>
<!--logic for no-->
<div ng-if="showHideTest=='false'">
<div class="form-group">
<div class="form-group">
<label for="adhaar_eid">Aadhaar Enrollment ID(EID):</label>
<input name="adhaar_eid" id="identityno" class="form-control" required>
</div>
<div class="form-group">
<label for="formGropuNameInput">Name of Beneficiary(as in Identity Card)* </label>
<input name="beneficiary_id_name" class="form-control" id="formGroupNameInput" placeholder="Enter your name" required>
</div>
<div class="form-group">
<label for="idno">Identity Number(Enclose Copy of Identity Card)*:</label>
<input name="idno" id="identityno" class="form-control" required>
</div>
<div class="custom-file">
<input type="file" class="custom-file-input" name="idcopy" id="customFile">
<label class="custom-file-label" for="customFile">Choose file</label>
</div>
</div>
</div>
<button type="submit" class="btn btn-primary" style="margin-bottom:10px ">Submit</button>
</form>
</div>
{% endblock %}
</body>
this is my views.py i've used POST.get
#login_required
def personal_detail(request):
# ShowHideExample = request.POST.get('showHideExample',False)
beneficiary_adhaar_name=request.POST.get('beneficiary_adhaar_name')
adhaarno=request.POST.get('adhaarno')
adhaarcopy=request.POST.get('adhaarcopy')
idcard=request.POST.get('idcard')
adhaar_eid=request.POST.get('adhaar_eid')
beneficiary_id_name=request.POST.get('beneficiary_id_name')
idno=request.POST.get('idno')
idcopy=request.POST.get('idcopy')
apply_online = Personal_Detail(beneficiary_adhaar_name=beneficiary_adhaar_name,adhaarno=adhaarno,adhaarcopy=adhaarcopy,
idcard=idcard,adhaar_eid=adhaar_eid,beneficiary_id_name=beneficiary_id_name,idno=idno,idcopy=idcopy)
apply_online.save()
return render(request,'users/applyonline.html')
this is my models.py where i have created FileField for both
class Personal_Detail(models.Model):
beneficiary_adhaar_name=models.TextField(blank=True, null=True)
adhaarno=models.IntegerField(blank=True, null=True)
adhaarcopy = models.FileField(upload_to='adhaar/')
idcard=models.TextField(blank=True, null=True)
adhaar_eid=models.IntegerField(blank=True,null=True)
beneficiary_id_name=models.TextField(blank=True, null=True)
idno=models.IntegerField(blank=True, null=True)
idcopy=models.FileField(upload_to='identitycard/')
def __str__(self):
return self.beneficiary_adhaar_name or self.beneficiary_id_name
settings.py I have given the media root and provided the media url
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR,'media')
MEDIA_URL ='/media/'
CRISPY_TEMPLATE_PACK='bootstrap4'
Like I want to know how can I upload the images like what should be my next steps.
You should get the file after submitted the form as below...
idcopy = request.FILES['idcopy']
adhaaarcopy = request.FILES['adhaaarcopy']
insted of...
idcopy=request.POST.get('idcopy')
adhaaarcopy=request.POST.get('adhaaarcopy')
And so on for other fields...
After that you can save and get it in appropriate location in media.
I'm learning django now, and i'm facing a problem, I create a form to submite data in my database, but the problem is when i click on submit button, postgres isn't receiving data, I cant understand the problem.
This is my contact form
This is my database
This is my html code
<form action="." method='post' class="p-5 bg-white">
<h2 class="h4 text-black mb-5">Contact Form</h2>
{% csrf_token %}
<div class="row form-group">
<div class="col-md-6 mb-3 mb-md-0">
<label class="text-black" for="fname">First Name</label>
<input type="text" id="fname" class="form-control rounded-0">
</div>
<div class="col-md-6">
<label class="text-black" for="lname">Last Name</label>
<input type="text" id="lname" class="form-control rounded-0">
</div>
</div>
<div class="row form-group">
<div class="col-md-12">
<label class="text-black" for="email">Email</label>
<input type="email" id="email" class="form-control rounded-0">
</div>
</div>
<div class="row form-group">
<div class="col-md-12">
<label class="text-black" for="subject">Subject</label>
<input type="subject" id="subject" class="form-control rounded-0">
</div>
</div>
<div class="row form-group">
<div class="col-md-12">
<label class="text-black" for="message">Message</label>
<textarea name="message" id="message" cols="30" rows="7" class="form-control rounded-0" placeholder="Leave your message here..."></textarea>
</div>
</div>
<div class="row form-group">
<div class="col-md-12">
<input type="submit" value="Send Message" class="btn btn-primary mr-2 mb-2">
</div>
</div>
</form>
This is my models.py
from django.db import models
class Form(models.Model):
fname=models.CharField(max_length=300)
lname=models.CharField(max_length=300)
email=models.EmailField()
subject=models.CharField(max_length=300)
message=models.TextField()
This is my views.py
from django.shortcuts import render
from .models import Form
def test(request):
if request.method == 'POST':
request.POST.get('fname')
request.POST.get('lname')
request.POST.get('email')
request.POST.get('subject')
request.POST.get('message')
post=Form()
post.fname= request.POST.get('fname')
post.lname= request.POST.get('lname')
post.email= request.POST.get('email')
post.subject= request.POST.get('subject')
post.message= request.POST.get('message')
post.save()
else:
return render(request,'test.html')
1st. In the form action="." is not necessary as if action is empty it will be sent to the current view itself.
2nd. I suggest using Model Forms which are a lot easier.
Let's say the model name is M1.
models.py
from django.db import models
class M1(models.Model):
fname = models.CharField(max_length=300)
lname = models.CharField(max_length=300)
email = models.EmailField()
subject = models.CharField(max_length=300)
message = models.TextField()
forms.py
from django import forms
M1Form(forms.modelForm):
class Meta:
model = M1
views.py
from django.shortcuts import render
from .models import M1
from .forms import M1Form
def test(request):
if request.method == "POST":
form = M1Form(request.POST)
if form.is_valid():
form.save()
else:
return render(request, "test.html")
else:
return render(request, "test.html")
3rd. If you look at the Templates:
<input type="email" id="email" class="form-control rounded-0">
it does not have an attribute "name" in it. If you want email in request.POST It should be written like
<input type="email" id="email" name="email" class="form-control rounded-0">
Please keep in mind that the name should be the same as the model name (Since we are not overwitting the Form).
For more Documentation:
https://docs.djangoproject.com/en/3.0/topics/forms/modelforms/