I want to set initial data in my ModelForm for a datefield but it is not working. Below is my code.
def get_date():
return timezone.localtime(timezone.now()).date()
ModelForm:
class TransferPacketForm(forms.ModelForm):
party = forms.ModelChoiceField(
required=True, queryset=Party.objects.all(),
widget=forms.Select(
attrs={
'class': 'form-control'
}
)
)
transferred_on = forms.DateField(
required=True, initial=get_date, input_formats=['%d-%m-%Y'],
validators=[validators.get('min_value')(date(2000, 01, 01))],
widget=forms.DateInput(
format='%d-%m-%Y',
attrs={
'autofocus': 'true', 'class': 'form-control'
}
)
)
transferred_roi = forms.DecimalField(
required=True, max_digits=3, decimal_places=2,
min_value=1.00, max_value=5.00,
widget=forms.TextInput(
attrs={
'class': 'form-control'
}
)
)
transferred_amount = forms.IntegerField(
required=True, min_value=1, widget=forms.TextInput(
attrs={
'class': 'form-control'
}
)
)
class Meta:
model = Packet
fields = (
'transferred_on', 'transferred_amount',
'transferred_remark', 'transferred_roi',
'party'
)
widgets = {
'transferred_remark': forms.Textarea(
attrs={
'class': 'form-control'
}
)
}
View:
class TransferPacketView(LoginRequiredMixin, UpdateView):
model = Packet
form_class = TransferPacketForm
http_method_names = ['get', 'post']
template_name = 'update_templates/transfer_packet.html'
def get_success_url(self):
return reverse(
'girvi:transferred_packet',
kwargs={
'pk': self.get_object()
}
)
def get(self, request, *args, **kwargs):
return super(TransferPacketView, self).get(request, *args, **kwargs)
def form_valid(self, form):
pkt_obj = self.get_object()
pkt_obj.is_transferred = True
pkt_obj.save()
return redirect(
self.get_success_url()
)
Form:
<tr><th><label for="id_transferred_on">Transferred on:</label></th><td><input autofocus="true" class="form-control" id="id_transferred_on" name="transferred_on" type="text" value="15-02-2015" /></td></tr>
<tr><th><label for="id_transferred_amount">Transferred amount:</label></th><td><input class="form-control" id="id_transferred_amount" name="transferred_amount" type="text" /></td></tr>
<tr><th><label for="id_transferred_remark">Transferred remark:</label></th><td><textarea class="form-control" cols="40" id="id_transferred_remark" maxlength="150" name="transferred_remark" rows="10">
</textarea></td></tr>
<tr><th><label for="id_transferred_roi">Transferred roi:</label></th><td><input class="form-control" id="id_transferred_roi" name="transferred_roi" type="text" /></td></tr>
<tr><th><label for="id_party">Party:</label></th><td><select class="form-control" id="id_party" name="party">
<option value="" selected="selected">---------</option>
<option value="2">ram pal</option>
<option value="1">shyam pal</option>
</select></td></tr>
But html form is rendered without any initial data.
Html form field:
<div class="form-group form-group-sm clearfix">
<label class="control-label col-xs-2 col-xs-offset-6" for="id_transferred_on">Dated</label>
<div class="col-xs-4 pull-right">
<div id="datepicker" class="input-group date">
<input id="id_transferred_on" class="form-control" type="text" name="transferred_on" autofocus="true">
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
</div>
Can someone tell me what is wrong??? Why value is not set to initial data.
Template:
<form id="transferPacketForm" class="form form-horizontal width-500 center-block theme-font" role="form" action="." method="post">{% csrf_token %}
<!-- DIV -->
{% if form.errors %}
<div class="alert alert-danger alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
{% for field in form %}
{% if field.errors %}
<span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span>
<span>{{ field.label }}: {{ field.errors|striptags }}</span><br>
{% endif %}
{% endfor %}
{% for error in form.non_field_errors %}
<span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span>
<span>Error: {{ error|striptags }}</span>
{% endfor %}
</div>
{% endif %}
<!-- /DIV -->
<!-- DIV -->
<div class="form-group form-group-sm clearfix">
<label for="id_{{ form.transferred_on.name }}" class="control-label col-xs-2 col-xs-offset-6">Dated</label>
<div class="col-xs-4 pull-right">
<div class="input-group date" id='datepicker'>
{{ form.transferred_on }}
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
</div>
<!-- /DIV -->
<!-- DIV -->
<div class="form-group form-group-sm">
<label for="id_{{ form.party.name }}" class="control-label col-xs-4">{{ form.party.label }}</label>
<div class="col-xs-8">
{{ form.party }}
</div>
</div>
<!-- /DIV -->
<!-- DIV -->
<div class="form-group form-group-sm">
<label for="id_{{ form.transferred_amount.name }}" class="control-label col-xs-4">Amount</label>
<div class="col-xs-8">
{{ form.transferred_amount }}
</div>
</div>
<!-- /DIV -->
<!-- DIV -->
<div class="form-group form-group-sm">
<label for="id_{{ form.transferred_roi.name }}" class="control-label col-xs-4">Interest</label>
<div class="col-xs-8">
{{ form.transferred_roi }}
</div>
</div>
<!-- /DIV -->
<!-- DIV -->
<div class="form-group form-group-sm">
<label for="id_{{ form.transferred_remark.name }}" class="control-label col-xs-4">Remark</label>
<div class="col-xs-8">
{{ form.transferred_remark }}
</div>
</div>
<!-- /DIV -->
<!-- DIV -->
<div class="btn-toolbar" align="middle">
<button type="submit" class="btn btn-primary btn-color btn-bg-color">Submit</button>
<button type="button" class="btn btn-danger btn-color btn-bg-color" onclick="window.close()">Close</button>
</div>
<!-- /DIV -->
</form>
It will only render initial value if you have no model instance passed to the form. Try this:
p = Packet.objects.filter(transferred_on__isnull=True)[0]
# or simply
p = Packet()
f = TransferPacketForm(instance=p)
print(f['transferred_on'])
which will not have initial value for that field, but if you do:
f = TransferPacketForm()
print(f['transferred_on'])
it will. Check it out.
Edit
It doesn't apply when you pass initial dictionary to the form, it will actually check if the model's field is empty and use the value from the dictionary. So workaround for you is not to use field's initial, but forms' initial instead, namely through view's get_initial() it is.
Related
I've a strange bug with my forms.
In a page I must hande 2 separate forms,
the 1st one have no problem at all and I can add the record in DB ,
the 2nd one raise me an error asking to fill a required data of 1st form.
The POST dictionary looks ok
Here the log:
<QueryDict: {'csrfmiddlewaretoken': ['lvt5Ph2SA1xxFK4LMotdHOWk2JuZzYDo0OKWc77rKICYKYmemy3gl0dBphnRNcFb'], 'pk_atto': ['1.1'], 'pk_persona': ['1'], 'capacita': ['11'], 'Aggiungi_persona': ['persona'], 'tipo': ['fondo']}>
<ul class="errorlist"><li>pk_particella<ul class="errorlist"><li>This field is required.</li></ul></li></ul>
the views:
if request.method == 'POST':
if("Aggiungi_particella" in request.POST):
save_atto = AttiPartenzeParticelleForm(request.POST)
else:
save_atto = AttiPartenzePersoneForm(request.POST)
print(request.POST)
print(save_atto.errors)
if save_atto.is_valid():
save_atto.save()
return redirect('/aggiungi_atto_partenza' + '/' + str(save_atto['pk_atto'].value()))
the forms:
class AttiPartenzeParticelleForm(ModelForm):
pk_atto = forms.ModelChoiceField(queryset=Atti.objects.all(),
widget=forms.Select
(attrs={'class': 'form-control'}))
pk_particella = forms.ModelChoiceField(queryset=Particelle.objects.all(),
widget=forms.Select
(attrs={'class': 'form-control'}))
capacita = forms.CharField(max_length=30,
widget=forms.NumberInput
(attrs={'class': 'form-control'}))
tipo = forms.CharField(max_length=30, initial="fondo", widget=forms.TextInput (attrs={'class': 'form-control'}))
class Meta:
model = Acquisizioni_Cessioni_particella
fields = '__all__'
class AttiPartenzePersoneForm(ModelForm):
pk_atto = forms.ModelChoiceField(queryset=Atti.objects.all(),
widget=forms.Select
(attrs={'class': 'form-control'}))
pk_persona = forms.ModelChoiceField(queryset=Persone.objects.all(),
widget=forms.Select
(attrs={'class': 'form-control'}))
capacita = forms.CharField(max_length=30,
widget=forms.NumberInput
(attrs={'class': 'form-control'}))
tipo = forms.CharField(max_length=30, initial="fondo", widget=forms.TextInput (attrs={'class': 'form-control'}))
class Meta:
model = Acquisizioni_Cessioni_particella
fields = '__all__'
and the HTML
<div id="particella" class="content-section d-flex justify-content-center mt-5">
<form action="" method="POST" id="particella_f">
{% csrf_token %}
<fieldset class="form-group">
<div style="visibility:hidden">
{{ form.pk_atto|as_crispy_field }}
</div>
<div class="row">
<div class="col-8">
{{ form.pk_particella|as_crispy_field }}
</div>
<div class="col-2">
{{ form.capacita|as_crispy_field }}
</div>
<div class="col-4 d-flex justify-content-center">
<button form="particella_f" class="btn btn-outline-primary btn-lg mt-5" type="submit" name="Aggiungi_particella" value="particella">
AGGIUNGI PARTICELLA
</button>
</div>
<div style="visibility:hidden">
{{ form.tipo|as_crispy_field }}
</div>
</div>
</fieldset>
</form>
</div>
<div id="persona" class="content-section d-flex justify-content-center mt-5">
<form action="" method="POST" id="persona_f">
{% csrf_token %}
<fieldset class="form-group">
<div style="visibility:hidden">
{{ persona.pk_atto|as_crispy_field }}
</div>
<div class="row">
<div class="col-8">
{{ persona.pk_persona|as_crispy_field }}
</div>
<div class="col-2">
{{ persona.capacita|as_crispy_field }}
</div>
<div class="col-4 d-flex justify-content-center">
<button class="btn btn-outline-primary btn-lg mt-5" form="persona_f" type="submit" name="Aggiungi_persona" value="persona">
AGGIUNGI PERSONA
</button>
</div>
<div style="visibility:hidden">
{{ form.tipo|as_crispy_field }}
</div>
</div>
</fieldset>
</form>
</div>
soneone have any idea?
thx
I am working on a project for a Django web-based application. In this project, there is a section in which I take info from the user through an HTML form. I added a section "image upload " but it gives a MultiValueDictKeyError error when the user does not upload any file. I tried this but not working for me.
This is error section : error image
This is my addpost.html section. It consists of a form through which, I am taking info.
<form action="{% url 'addpost' %}" method='POST' enctype="multipart/form-data" novalidate>
{% include 'includes/messages.html' %}
{% csrf_token %}
{% if user.is_authenticated %}
<input type="hidden" name="user_id" value="{{user.id}}">
{% else %}
<input type="hidden" name="user_id" value="0">
{% endif %}
<div class="row ">
<div class="tex-center">
<div class="row">
<div class="col-md-6 text-left">
<div class="form-group name">
<input type="text" name="author" class="form-control" placeholder="Author"
{% if user.is_authenticated %} value="{{user.first_name}}" {% endif %} readonly>
</div>
</div>
<div class="col-md-6">
<div class="form-group name">
<input type="text" name="title" class="form-control" placeholder="title" required>
</div>
</div>
<div class="col-md-6">
<div class="form-group name">
<input type="text" name="location" class="form-control" placeholder="location" required>
</div>
</div>
<div class="col-md-6">
<div class="form-group name">
<input type="text" name="short_desc" class="form-control"
placeholder="Write short description" required>
</div>
</div>
<div class="col-md-12">
<div class="form-group message">
<textarea class="form-control" name="full_desc"
placeholder="Write full description"></textarea>
</div>
</div>
<input type="file" id="myFile" name="place_photo" required/>
<div class="col-md-12">
<div class="send-btn text-center">
<input type="submit" class="btn btn-outline-success mr-1" value="Send Post">
Cancel
</div>
</div>
</div>
</div>
</div>
</form>
This is the views.py file where I receive POST data
def add_post(request):
if request.method == "POST":
try:
is_private = request.POST['is_private']
except MultiValueDictKeyError:
is_private = False
author = request.POST['author']
title = request.POST['title']
user_id = request.POST.get('user_id')
location = request.POST['location']
short_desc = request.POST['short_desc']
full_desc = request.POST['full_desc']
place_photo = request.FILES['place_photo']
post = Post(author=author, user_id=user_id, title=title, location=location,
short_desc=short_desc,full_desc=full_desc, place_photo=place_photo)
post.save()
messages.success(request,"Your post uploaded successfully")
return render(request,'community/addpost.html')
This is my models.py file
class Post(models.Model):
author = models.CharField(max_length=100, default=' ')
title = models.CharField(max_length=150)
user_id = models.IntegerField(blank=True)
location = models.CharField(max_length=100, default=' ')
short_desc = models.CharField(max_length=255, default='In less than 250 words')
full_desc = models.TextField()
place_photo = models.ImageField(upload_to='photos/%Y/%m/%d/')
added_date = models.DateTimeField(default=datetime.now,blank=True)
Good day, trying to improve my webs skill by building a small web-app that stores contact information. The delete function that allows users to delete contacts of the app shows a success message however the index page does not show the changes in the database.
Checking on an external DBReader (DB Browser) shows no changes made to the database. Based off lurking questions here the return type of request.form.get('affected_field_here') (what i use to get the value of the contact id) returns none. Likewise i tried with request.args / request.values both of which showed the same problem
so can another pair of eyes tell me where i goofed?
Below is the delete function
#app.route('/delete', methods=["GET", "POST"])
def delete():
conn = sqlite3.connect('contacts.db')
db = conn.cursor()
#Get contact_id
contact_id = request.args.get('contact_id')
db.execute("DELETE FROM contacts WHERE id =?", (contact_id,))
conn.commit()
conn.close()
flash('Contacts removed', 'success')
return redirect('/')
index.html code here
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
{% extends "base.html" %}
{% block title%}Landing Page{% endblock %}
{% block body %}
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="jumbotron p-3">
<h1>My Contacts <button type="button" class="btn btn-success float-right" data-toggle="modal"
data-target="#addcontact"> Add Contact</button></h1>
<!--------------------Add Contact Modal placed inside same holder as modalit's for-->
<div id="addcontact" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h3 class="modal-title">Add Contact</h3>
</div>
<div class="modal-body">
<form action="/add" method="POST" autocomplete="off">
<div class="form-group">
<input autofocus class="form-control" autocomplete="off" required type="text" name="fname" placeholder="Enter first name">
</div>
<div class="form-group">
<input class="form-control" autocomplete="off" type="text" required name="lname" placeholder="Enter Surname">
</div>
<div class="form-group">
<input class="form-control" autocomplete="off" type="number" min="1" required name="age" placeholder="Enter Age">
</div>
<div class="form-group">
<input class="form-control" autocomplete="off" type="number" name="contact" required placeholder="Enter Contact Number">
</div>
<div class="form-group">
<input class="form-control" autocomplete="off" type="email" name="email" placeholder="Enter Email address">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Add Contact</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
{% with messages = get_flashed_messages(category_filter=["error"]) %}
{% if messages %}
{% for message in messages %}
<div class="alert alert-danger alert-dismissible">
×
<strong>Message: </strong>{{message}}
</div>
{% endfor %}
{% endif %}
{% endwith %}
{% with messages = get_flashed_messages(category_filter=["success"]) %}
{% if messages %}
{% for message in messages %}
<div class="alert alert-success alert-dismissible">
×
<strong>Success: </strong>{{message}}
</div>
{% endfor %}
{% endif %}
{% endwith %}
<table class="table table-hover">
<thead>
<tr>
<td>ID</td>
<td>First Name</td>
<td>Surname</td>
<td>Age</td>
<td>Contact #</td>
<td>Email</td>
<td>Action</td>
</tr>
</thead>
<tbody>
{% for row in contacts %}
<tr>
<td>{{row['id']}}</td>
<td>{{row['fname']}}</td>
<td>{{row["lname"]}}</td>
<td>{{row['age']}}</td>
<td>{{row['number']}}</td>
<td>{{row['email']}}</td>
<td><button type="button" class="btn btn-primary" data-toggle="modal"
data-target="#editcontact{{row['id']}}">Edit</button>
<form style='display:inline;' action="/delete" method="POST">
<button type="submit" class="btn btn-danger""
onclick="return confirm('Are you sure you want to remove contacts?')">Delete</button></form>
</td>
</tr>
</tbody>
<div class="modal fade" id="editcontact{{row['id']}}" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="staticBackdropLabel">Contact Information</h5>
</div>
<div class="modal-body">
<form action="/edit" method="POST" autocomplete="off">
<div class="form-group">
<input autofocus class="form-control" autocomplete="off" required type="hidden" name="contact_id" value="{{row['id']}}" >
</div>
<div class="form-group">
<input autofocus class="form-control" autocomplete="off" required type="text" name="fname_edit" value="{{row['fname']}}" >
</div>
<div class="form-group">
<input class="form-control" autocomplete="off" type="text" required name="lname_edit" value="{{row["lname"]}}">
</div>
<div class="form-group">
<input class="form-control" autocomplete="off" type="number" min="1" required name="age_edit" value="{{row['age']}}" >
</div>
<div class="form-group">
<input class="form-control" autocomplete="off" type="number" name="contact_edit" required value="{{row['number']}}" >
</div>
<div class="form-group">
<input class="form-control" autocomplete="off" type="email" name="email_edit" value="{{row['email']}}">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Save Contact</button>
</div>
</form>
</div>
</div>
</div>
</div>
{% endfor %}
</table>
</div>
</div>
</div>
{% endblock %}
the rest off appplication.py here incase it may be useful to:
from flask import Flask, render_template, request, flash, redirect, app, url_for, get_flashed_messages
import sqlite3
app = Flask(__name__)
app.secret_key = "this_is_a_secret" #need a key to start app
#app.route('/', methods=["GET", "POST"])
def index():
conn = sqlite3.connect('contacts.db')
db = conn.cursor()
contacts = db.execute("SELECT * FROM contacts")
directory = [] #to store values
for contact in contacts: #loop through query and append
directory.append({
"id": contact[0],
"fname": contact[1],
"lname": contact[2],
"age": contact[3],
"number": contact[4],
"email": contact[5]})
return render_template('index.html', contacts = directory) #load dic into html
#app.route('/add', methods=["POST"])
def add():
conn = sqlite3.connect('contacts.db')
db = conn.cursor()
if request.method == "POST": #general back end error checking
if not request.form.get('fname') or not request.form.get('lname'):
flash('First name and Surname are required fields.', 'error')
return redirect('/')
contact_age = request.form.get('age')
if contact_age.isdigit() == False:
flash ('Invalid age value', 'error')
return redirect('/')
contact_number = request.form.get('contact')
if contact_number.isdigit() == False:
flash ('Invalid contact number', 'error')
return redirect('/')
email = request.form.get('email')
fname = request.form.get('fname')
lname =request.form.get('lname')
db.execute("INSERT INTO contacts (fname, lname, age, number, email) VALUES(?,?,?,?,?)", (fname, lname, contact_age, contact_number, email))
conn.commit()
flash ('Updated your contact list', 'success')
return redirect('/')
#app.route('/edit', methods=["POST"])
def edit():
if request.method == "POST":
conn = sqlite3.connect('contacts.db')
db = conn.cursor()
contact_id = request.form.get('contact_id')
fname_n = request.form.get('fname_edit')
lname_n = request.form.get('lname_edit')
age_n = request.form.get('age_edit')
num_n = request.form.get('contact_edit')
email_n = request.form.get('email_edit')
db.execute("""UPDATE contacts SET fname = ? ,lname = ?,age = ?,number = ?, email = ? WHERE id= ?
""",
(fname_n,lname_n,age_n,num_n,email_n,contact_id ))
conn.commit()
flash('Contacts updated', 'success')
return redirect('/')
#app.route('/delete', methods=["GET", "POST"])
def delete():
conn = sqlite3.connect('contacts.db')
db = conn.cursor()
#Get contact_id
contact_id = request.args.get('contact_id')
db.execute("DELETE FROM contacts WHERE id =?", (contact_id,))
conn.commit()
conn.close()
flash('Contacts removed', 'success')
return redirect('/')
if __name__ == "__main__":
app.run(debug=True)
finally base.html which index.html reference
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<title>{% block title %} {% endblock %} </title>
</head>
<body>
<div class="jumbotron p-3">
<div class="well text-center">
<h1>PRACTICE WEB APPLICATION</h1>
</div>
</div>
{% block body %}
{% endblock %}
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
</html>
EDIT: Figured out answer. answer in post below.
In delete function, i was referencing the wrong id, to solve thus i added a name attribute to the delete button and reference that in the request.form function which allowed the function to work properly and reflect changes.
Hopefully this helps anyone stuck in a similar rut.
I'm trying to update the user profile using the model form by passing the already stored user details with the initial keyword. I don't know what is wrong in my code. When i click the submit button it just reloading the same page instead of updating/saving the details. Please i need some help to fix this issue.
## views.py ##
def personal_details_update(request):
if not request.user.is_authenticated():
return HttpResponseRedirect('/login/')
else:
user = request.user
data = {
'username': user.username,
'email': user.email,
'first_name': user.first_name,
'last_name': user.last_name,
'address': user.address,
'city': user.city,
'state': user.state,
'country': user.country,
'mobile': user.mobile,
}
form = PersonalDetailsForm(request.POST or None, initial=data)
if request.method == 'POST':
if form.is_valid():
user.username = request.POST['username']
user.email = request.POST['email']
user.first_name = request.POST['first_name']
user.last_name = request.POST['last_name']
user.address = request.POST['address']
user.city = request.POST['city']
user.state = request.POST['state']
user.country = request.POST['country']
user.mobile = request.POST['mobile']
user.save()
return HttpResponseRedirect('/personal_details/')
# return HttpResponseRedirect('%s' % (reverse('personal_details')))
context = {
'form': form,
}
return render(request, 'login/personal_details_update.html', context)
def personal_details(request):
if not request.user.is_authenticated():
return HttpResponseRedirect('/login/')
else:
return render(request, 'login/personal_details.html')
## urls.py ##
from django.conf.urls import url
from . import views
app_name = 'login'
urlpatterns = [
url(r'^$', views.home, name='home'),
url(r'^about us/$', views.about_us, name='about_us'),
url(r'^services/$', views.services, name='services'),
url(r'^registration/$', views.registration, name='registration'),
url(r'^login/$', views.login_user, name='login'),
url(r'^admin/$', views.admin_login, name='admin_login'),
url(r'^logout/$', views.logout_user, name='logout'),
url(r'^personal_details/$', views.personal_details, name='personal_details'),
url(r'^personal_details/update/$', views.personal_details_update, name='personal_details_update'),
]
## forms.py ##
from django import forms
from .models import User
from django.contrib.admin.widgets import AdminDateWidget
class UserForm(forms.ModelForm):
date_of_birth = forms.DateField(widget=AdminDateWidget)
password = forms.CharField(widget=forms.PasswordInput)
confirm_password = forms.CharField(widget=forms.PasswordInput)
class Meta:
model = User
fields = ['username', 'email', 'first_name', 'last_name', 'date_of_birth', 'address', 'city', 'state',
'country', 'mobile', 'avatar', 'password', 'confirm_password']
class PersonalDetailsForm(forms.ModelForm):
date_of_birth = forms.DateField(widget=AdminDateWidget)
class Meta:
model = User
fields = ['username', 'email', 'first_name', 'last_name', 'address', 'city', 'state',
'country', 'mobile']
exclude = ['date_of_birth', 'avatar', 'password', 'confirm_password']
## personal_details.html ##
{% extends 'upload/base.html' %}
{% block title %}Cloud | Personal Details{% endblock %}
{% block folders_active %}active{% endblock %}
{% load staticfiles %}
{% block navigation%}
<div class="container-fluid files-container">
<div class="row">
<div class="col-sm-12 col-md-4">
<div class="panel panel-default" style="background: transparent">
<div class="panel-body">
<div class="page-header">
{% if msg %}
<p><strong><font color="#dc143c">{{ msg }}</font></strong></p>
{% endif %}
</div>
<div class="row">
<h4>Personal Details <span class="glyphicon glyphicon-edit"></span></h4><br>
</div>
<form class="form-horizontal" role="form" action="" method="post" enctype="multipart/form-data">
<div class="form-group">
<label class="control-label" for="id_username">
Username:
</label>
{{ user.username }}
</div>
<div class="form-group">
<label class="control-label" for="id_email">
Email:
</label>
{{ user.email }}
</div>
<div class="form-group">
<label class="control-label" for="id_first_name">
First Name:
</label>
{{ user.first_name }}
</div>
<div class="form-group">
<label class="control-label" for="id_last_name">
Last Name:
</label>
{{ user.last_name }}
</div>
<div class="form-group">
<label class="control-label" for="id_date_of_birth">
Date Of Birth:
</label>
{{ user.date_of_birth }}
</div>
<div class="form-group">
<label class="control-label" for="id_address">
Address:
</label>
{{ user.address }}
</div>
<div class="form-group">
<label class="control-label" for="id_city">
City:
</label>
{{ user.city }}
</div>
<div class="form-group">
<label class="control-label" for="id_state">
State:
</label>
{{ user.state }}
</div>
<div class="form-group">
<label class="control-label" for="id_country">
Country:
</label>
{{ user.country }}
</div>
<div class="form-group">
<label class="control-label" for="id_mobile">
Mobile:
</label>
{{ user.mobile }}
</div>
<div class="form-group">
<label class="control-label" for="id_avatar">
Avatar:
</label>
{{ user.avatar }}
</div>
</form>
</div>
</div>
</div>
</div>
</div>
{% endblock %}
## personal_details_update.html ##
{% extends 'upload/base.html' %}
{% block title %}Cloud | Personal Details Update{% endblock %}
{% block folders_active %}active{% endblock %}
{% load staticfiles %}
{% block navigation%}
<div class="container-fluid files-container">
<div class="row">
<div class="col-sm-12 col-md-4">
<div class="panel panel-default" style="background: transparent">
<div class="panel-body">
<div class="page-header">
{% if msg %}
<p><strong><font color="#dc143c">{{ msg }}</font></strong></p>
{% endif %}
</div>
<div class="row">
<h4>Personal Details Update Form</h4><br>
</div>
<form class="form-horizontal" role="form" action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
<div class="form-group">
<label class="control-label" for="id_username">
Username:
</label>
{{ form.username }}
</div>
<div class="form-group">
<label class="control-label" for="id_email">
Email:
</label>
{{ form.email }}
</div>
<div class="form-group">
<label class="control-label" for="id_first_name">
First Name:
</label>
{{ form.first_name }}
</div>
<div class="form-group">
<label class="control-label" for="id_last_name">
Last Name:
</label>
{{ form.last_name }}
</div>
<div class="form-group">
<label class="control-label" for="id_address">
Address:
</label>
{{ form.address }}
</div>
<div class="form-group">
<label class="control-label" for="id_city">
City:
</label>
{{ form.city }}
</div>
<div class="form-group">
<label class="control-label" for="id_state">
State:
</label>
{{ form.state }}
</div>
<div class="form-group">
<label class="control-label" for="id_country">
Country:
</label>
{{ form.country }}
</div>
<div class="form-group">
<label class="control-label" for="id_mobile">
Mobile:
</label>
{{ form.mobile }}
</div>
<div class="form-group">
<div class="col-sm-offset-5">
<button type="submit" class="btn btn-success">Update</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
{% endblock %}
This is the error message i'm getting when i try to update my personal_details form. Please someone help me fix it
I think error is, where you assign the "user" variable.
user = request.user
Instead of this you need to do this ,
user = User.objects.get(username=request.user.username)
In the case of latter, you are referring to the user object, on which you can update or change the data.
While in the former case, django is trying to create a new user which already exists in the database.That's why it gives the error you got. You just have to grab the one from the database and do manipulation on it.
I'm too a novice in django, hope you got what you where looking for.
I am making multiauth. When I submit admin email and password from admin login view I got bellow error
"UnexpectedValueException in Response.php line 444:
The Response content must be a string or object implementing __toString(), "boolean" given."
here is my form
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">Admin Login</div>
<div class="panel-body">
<form class="form-horizontal" role="form" method="POST" action="{{ route('admin.login.submit') }}">
{{ csrf_field() }}
<div class="form-group{{ $errors->has('email') ? ' has-error' : '' }}">
<label for="email" class="col-md-4 control-label">E-Mail Address</label>
<div class="col-md-6">
<input id="email" type="email" class="form-control" name="email" value="{{ old('email') }}" required autofocus>
#if ($errors->has('email'))
<span class="help-block">
<strong>{{ $errors->first('email') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group{{ $errors->has('password') ? ' has-error' : '' }}">
<label for="password" class="col-md-4 control-label">Password</label>
<div class="col-md-6">
<input id="password" type="password" class="form-control" name="password" required>
#if ($errors->has('password'))
<span class="help-block">
<strong>{{ $errors->first('password') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<div class="checkbox">
<label>
<input type="checkbox" name="remember" {{ old('remember') ? 'checked' : '' }}> Remember Me
</label>
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-8 col-md-offset-4">
<button type="submit" class="btn btn-primary">
Login
</button>
<a class="btn btn-link" href="{{ route('password.request') }}">
Forgot Your Password?
</a>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
#endsection
And here is route
Route::prefix('admin')->group(function (){
Route::post('/login', 'Auth\AdminLoginController#login')->name('admin.login.submit');
});
And the controller is here
<?php
namespace App\Http\Controllers\Auth;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class AdminLoginController extends Controller
{
public function __construct()
{
$this->middleware('guest');
}
public function showLoginForm()
{
return view('admin.auth.login');
}
public function login(Request $request)
{
return true;
}
}
What wrong here?
And How can I solve it?
Thanks in advance.
I found that problem. that was in my controller. Exactly in login function. I returened true. Here is the problem. When I return 1 then it worked.