Every applicant should enter their data from HTML page and this datas must insert to database. I think I did everything right, but datas are not shown in database. Here are my codes.
models.py:
class Applicant(models.Model):
name = models.CharField(max_length=20)
surname = models.CharField(max_length=30)
phone = models.CharField(max_length=15)
email = models.EmailField(max_length=40)
motivation_letter = models.TextField(max_length=200)
def __str__(self):
return self.name
views.py:
def apply(request):
if request.method == "POST":
if request.POST.get('motivation_letter'):
applicant = Applicant()
applicant.name = request.POST.get('name')
applicant.surname = request.POST.get('surname')
applicant.phone = request.POST.get('phone')
applicant.email = request.POST.get('email')
applicant.motivation_letter = request.POST.get('motivation_letter')
applicant.save()
return render(request, 'index.html')
HTML:
<form method="POST">
{% csrf_token %}
<label>Ad</label><br />
<input type="text" name="name"><br />
<label>Soyad</label><br />
<input type="text" name="surname"><br />
<label>Telefon nömrəsi</label><br />
<input type="number" name="phone"><br />
<label>Elektron poçt</label><br />
<input type="email" name="email"><br />
<label>Something else</label><br />
<textarea class="smth-else-textarea" cols="30" rows="10" name="motivation_letter"></textarea><br />
<input type="submit" value="Göndər" class="apply-button"/>
</form>
You should use model_name.objects.create(xx=something..) to insert data.
def apply(request):
if request.method == "POST":
if request.POST.get('motivation_letter'):
Applicant.objects.create(
name = request.POST.get('name'),
surname = request.POST.get('surname'),
phone = request.POST.get('phone'),
email = request.POST.get('email'),
motivation_letter = request.POST.get('motivation_letter'))
return render(request, 'index.html')
html : (if you don't work , try it : app_name:apply)
<form action="{% url "apply" %}" method='POST' > {% csrf_token %}
<label>Ad</label><br />
<input type="text" name="name"><br />
<label>Soyad</label><br />
<input type="text" name="surname"><br />
<label>Telefon nömrəsi</label><br />
<input type="number" name="phone"><br />
<label>Elektron poçt</label><br />
<input type="email" name="email"><br />
<label>Something else</label><br />
<textarea class="smth-else-textarea" cols="30" rows="10"
name="motivation_letter"></textarea><br />
<input type="submit" value="Göndər" class="apply-button"/>
</form>
urls.py: (not : import your views)
path('apply/', views.apply , name='apply'),
Related
I tried to create a simple Django Chat App. There is no login system.
Whenever a user(e.g. John) tries to create a message, it stores under 'messageroom'
I tried to pass the username 'John' value in the URL but somehow it is not creating a message as expected.
Here is my code
Urls.py :
urlpatterns = [
path('admin/', admin.site.urls),
path('',views.home,name='home'),
path('checkview',views.checkview,name='checkview'),
path('messageroom/<str:room_name>/<str:username>',views.messageroom,name='messageroom'),
]
Models.py
class Room(models.Model):
roomname = models.CharField(max_length=1000)
class Message(models.Model):
messagetext = models.CharField(max_length=10000)
username = models.CharField(max_length=1000)
datetime = models.DateTimeField(default=datetime.now,blank=True)
messageroom = models.CharField(max_length=1000)
Views.py
def home(request):
return render(request,'home.html',{})
def checkview(request):
room_name=request.POST.get('room_name')
username = request.POST.get('username')
Roomexists = Room.objects.filter(roomname=room_name)
if Roomexists.exists():
return redirect('messageroom/'+room_name+'/'+username)
else:
newroom = Room(roomname=room_name)
newroom.save()
return redirect('messageroom/'+room_name+'/'+username)
def messageroom(request,room_name,username):
if request.method == "POST":
messagetext = request.POST.get('message')
newmessage = Message(messagetext=messagetext,messageroom=room_name,username=username)
newmessage.save()
listmessages = Message.objects.filter(messageroom=room_name)
return render(request, 'room.html', {'listmessages':listmessages,'room_name':room_name,'username':username})
Room.html
<form id="post-form2" method="POST" action="messageroom">
{% csrf_token %}
<input type="text" name="message" id="message" width="100px" />
<input type="submit" value="Send">
</form>
I want to create messages under the user which should be there on the URL.
you should pass values in urls in html form like this....
<form id="post-form2" method="POST" action="{% url 'messageroom' room_name username %}">
{% csrf_token %}
<input type="text" name="message" id="message" width="100px" />
<input type="submit" value="Send">
</form>
-------------------------- OR ------------------
<form id="post-form2" method="POST" action="/messageroom/room_name/username/">
{% csrf_token %}
<input type="text" name="message" id="message" width="100px" />
<input type="submit" value="Send">
</form>
I want to save a html form data into django model but it has a foreign key field from another model. How can I save a form which has FK field??
My models:
class Dish(models.Model):
title =models.CharField(max_length=200)
description =models.TextField(blank=True)
price =models.IntegerField()
photo_main= models.ImageField(upload_to="photos/%Y%m%d/")
photo_1= models.ImageField(upload_to="photos/%Y%m%d/", blank= True)
photo_2= models.ImageField(upload_to="photos/%Y%m%d/", blank= True)
def __str__(self):
return self.title
class Order(models.Model):
dishorder= models.ForeignKey(Dish,null=True,on_delete=models.CASCADE)
name = models.CharField(max_length=200,blank=True)
email = models.CharField(max_length=100,blank=True)
phone = models.CharField(max_length=100,blank=True)
quantity =models.IntegerField(blank=True)
def __str__(self):
return self.name
My views:
def order(request):
if request.method == 'POST':
name = request.POST['name']
email = request.POST['email']
phone = request.POST['phone']
quantity = request.POST['quantity']
order= Order(
name=name,
email=email,
phone=phone,
quantity=quantity)
order.save()
messages.success(request, "Your order has been submitted.")
return render(request,"dishes/order.html")
My urls:
urlpatterns = [
path("dish",views.dish,name="dish"),
path("dish/<pk>",views.dishsingle,name="dishsingle"),
path("order",views.order,name="order"),
]
My template dishes/order.html
<form method="POST">
{% csrf_token %}
<div>
<label for="name">Name:</label>
<input type="text" name="name" class="form-control" required>
</div>
<div>
<label for="email">Email:</label>
<input type="email" name="email" class="form-control" required>
</div>
<div>
<label for="phone">Phone:</label>
<input type="number" name="phone" class="form-control" required>
</div>
<div>
<label for="quantity">Quantity:</label>
<input type="number" name="quantity" class="form-control" required>
</div>
<hr>
<input type="submit" value="MAKE AN ORDER">
</form>
While submitting this html form, I would like the foreignkey field dishorder to be saved on the backend as well. When I check the admin page, order is saved but without the name of the dish. How can I resolve this?
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>
I am using #login_decorator('/login/') in every view. Whenever I tried to access other URL it redirects to the login page. The URL turns like this:
http://127.0.0.1:8000/login/?next=/upload_file/
Now, when I enter correct username, password and click Submit, nothing is happening. I am still on the same page with the same URL.
Here's my form.html:
<form action="/login/" method="post">
{% csrf_token %}
Username: <input type="text" name="username" />
Password: <input type="password" name="password" />
<input type="Submit">
Views.py:
def login_upload(request):
try:
if request.method == 'POST':
usern = request.POST['username']
unames = ''.join(usern)
passwo = request.POST['password']
s = ''.join(passwo)
h = hashlib.sha1(s).hexdigest()
db = MySQLdb.connect(user='root', db='galaxy', passwd='devil', host='localhost')
cursor = db.cursor()
cursor.execute("SELECT id, username, password FROM galaxy_user where username=%s and password=%s", (unames, h))
id, compareu, comparep = zip(*cursor.fetchall())
db.close()
return HttpResponseRedirect('/upload_file/')
except ValueError:
return render_to_response('login.html', context_instance=RequestContext(request))
urls.py:
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^upload_file/', 'fileupload.views.upload_file'),
url(r'^sync/', 'fileupload.views.sync'),
url(r'^login_upload/', 'fileupload.views.login_upload'),
url(r'^upload_file_form', 'fileupload.views.upload_file_form' ),
url(r'^book_list', 'fileupload.views.book_list'),
url(r'^backend/', 'fileupload.backend.show_files')
)
You need to put "next" value in your form
<form action="/login/" method="post">
{% csrf_token %}
Username: <input type="text" name="username" />
Password: <input type="password" name="password" />
<input type="hidden" name="next" value="{{ next }}" />
<input type="Submit">
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