Error of Django's forms instance - python

my files in project is:
djangoTry
--views.py
--forms.py
--others not included in this question files
When I click submit in my form I call this method from views.py:
from .forms import NameForm
def kontakt(request):
if request.method == 'POST':
form = NameForm(request.POST)
form.test("test")
if form.is_valid():
first_name = form.cleaned_data['first_name']
last_name = form.cleaned_data['last_name']
phone_number = form.cleaned_data['phone_number']
email = form.cleaned_data['email']
details = form.cleaned_data['details']
return HttpResponseRedirect('/')
else:
form = NameForm()
return render(request, 'index.html', {'form':form})
NameForm is class from forms.py file:
from django import forms
class NameForm(forms.Form):
first_name = forms.CharField(label='first_name', max_length=100)
last_name = forms.CharField(label='last_name', max_length=100)
phone_number = forms.CharField(label='phone_number', max_length=100)
email = forms.CharField(label='email', max_length=100)
details = forms.CharField(label='details', max_length=100)
def test(self, message):
print("i'm in test and message is: %s " , (message))
print(self.first_name)
def is_valid(self):
print("jest valid")
return True
form.html
<form class="col s12" action="{% url 'kontakt' %}" method="post">
{% csrf_token %}
{{ form }}
<div class="row">
<div class="input-field col s6">
<input
id="first_name"
type="text"
value="hehe">
<!-- value="{{ form.first_name }}"> -->
<label for="first_name">First name</label>
</div>
<div class="input-field col s6">
<input
id="last_name"
type="text"
autocomplete="off"
value="hehe">
<!-- value="{{ form.last_name }}" > -->
<label for="last_name">Last name</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<input id="phone_number" type="number" autocomplete="off"
value="123456789">
<label for="phone_number">Phone number</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<input id="email" type="email" autocomplete="off" value="rafald121#gmail.com" >
<label for="email">Email</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<input id="details" type="text" autocomplete="off" value="qweqweqeq">
<label for="details">Details</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<a class="waves-effect waves-light btn">
<input id="submit" type="submit" >
<i class="material-icons right">send</i>
</a>
<!-- <input id="submit" type="submit" > -->
<label for="details">Details</label>
</div>
</div>
</form>
but everytime I get error:
AttributeError: 'NameForm' object has no attribute 'first_name'
but NameForm has "first_name" atribute
NameForm's method "test" work properly everytime but any of NameForm's variable can't be called.
Does anybody have idea what's going on ?

Related

NOT NULL constraint failed: posts_subscribe.firstname

I am trying to retrieve data from a form using the Post method and store it in the database. However, when I click on the submit button,I keep on getting the following error:
NOT NULL constraint failed: posts_subscribe.firstname
Here is my views.py:
def subscribe(request):
if request.method == 'POST':
firstname=request.POST.get('firstname')
secondname=request.POST.get('secondname')
email=request.POST.get('email')
phonenumber=request.POST.get('phonenumber')
en= Subscribe(firstname=firstname, secondname=secondname, email = email, phonenumber = phonenumber)
en.save()
return redirect('/')
return render(request, 'subscribe.html')
My models.py:
class Subscribe(models.Model):
firstname = models.CharField(max_length=30, blank = True)
secondname = models.CharField(max_length=30, blank = True)
email = models.CharField(max_length=30)
phonenumber = models.IntegerField()
Here is my template:
{% extends 'index.html' %}
{% block subscribe %}
<div class="card mx-5">
<h1 class="mx-5 mt-3"> Subscribe</h1>
<form method="POST" enctype="multipart/form-data" action="subscribe">
{% csrf_token %}
<div class="mb-3 mx-5">
<label for="firstname" class="form-label ">First Name</label>
<input type="text" class="form-control form-control-lg" id="firstname" placeholder="firstname">
</div>
<div class="mb-3 mx-5">
<label for="secondname" class="form-label">Second Name (Optional)</label>
<input type="text" class="form-control form-control-lg" id="secondname" placeholder="secondname">
</div>
<div class="mb-3 mx-5">
<label for="email" class="form-label">Email</label>
<input type="email" class="form-control form-control-lg" id="email" placeholder="example#example.com">
</div>
<div class="mb-3 mx-5">
<label for="phonenumber" class="form-label">Phonenumber</label>
<input type="number" class="form-control form-control-lg" id="phonenumber" placeholder="0712345678">
</div>
<div class="mb-3 mx-5">
<button type="submit" class="btn-primary"> Subscribe</button>
</div>
</form>
</div>
{% endblock %}
And my url patterns:
urlpatterns= [
path('', views.index, name='index'),
path('subscribe', views.subscribe, name ='subscribe'),
path('allposts', views.allposts, name='allposts'),
path('political', views.political, name='political'),
path('religion', views.religion, name='religion'),
path('trending', views.trending, name='treniding'),
path('<str:pk>', views.post, name='post'),
]
You should add a name="…" attribute [mdn] to the <input> elements, so:
<input type="text" name="firstname" class="form-control form-control-lg" id="firstname" placeholder="firstname">
…
<input type="text" name="secondname" class="form-control form-control-lg" id="secondname" placeholder="secondname">
…
<input type="email" name="email" class="form-control form-control-lg" id="email" placeholder="example#example.com">
…
<input type="number" name="phonenumber" class="form-control form-control-lg" id="phonenumber" placeholder="0712345678">

Cannot assign "'1'": "staff.staff_type" must be a "staff_type" instance. Django Error in OneToOne field

I am working on a small django-python project which has two models "staff_type" and "staff". In the staff_type model, only designation and date fields are populated. And in the staff model, there is OneToOneField relation of staff_type. Means whenever a user want to add staff first he/she will have to add staff_type and then in the staff module, user will choose the staff type (designation) from a select menu in which all the staff_type are shown respectively.
Now, whenever a user select any designation (staff_type) and fill the entire form, I want to store the selected staff_type id in the staff model/table.
Note: I have tried this from django admin, and it works perfectly but I want to do the same work in my own designed templates.
Modles.py
class staff_type(models.Model):
designation = models.CharField(max_length=50)
salary = models.IntegerField()
datetime = models.DateTimeField()
entrydatetime = models.DateTimeField( auto_now=False, auto_now_add=False)
class staff(models.Model):
staff_type = models.OneToOneField(staff_type, on_delete=models.CASCADE)
firstname = models.CharField(max_length=50)
lastname = models.CharField(max_length=50)
fathername = models.CharField(max_length=50)
city = models.CharField(max_length=50)
country = models.CharField(max_length=50)
state = models.CharField(max_length=50)
zip = models.IntegerField(blank=True)
address = models.CharField(max_length=100)
contact =models.CharField(max_length=20)
cnic = models.CharField(max_length=14)
photo = models.ImageField()
cv = models.ImageField()
otherfiles = models.ImageField()
views.py
def add_staff_type(request):
if request.method == 'POST':
designation = request.POST.get('designation')
salary = request.POST.get('salary')
datetime = request.POST.get('datetime')
add_staff_type = staff_type.objects.create(designation=designation, salary=salary, datetime=datetime, entrydatetime = dt.now())
add_staff_type.save()
messages.info(request, "Staff type has been Added.")
return redirect('add_staff_type')
else:
#fetching records from the database table
display_staff_type = staff_type.objects.all()
return render(request, 'staff/staff_type.html',{'display_staff_type':display_staff_type})
#this view is for fetching the designation column and displaying in the select tag
#and rendering add_staff html form
def add_staff(request):
staff = staff_type.objects.all()
return render(request, 'staff/add_staff.html', {'staff':staff})
#this view is for adding the staff
def add_staff_view(request):
if request.method == 'POST':
staff_type = request.POST.get('stafftype')
firstname = request.POST.get('firstname')
lastname = request.POST.get('lastname')
fathername = request.POST.get('fathername')
city = request.POST.get('city')
country = request.POST.get('country')
state = request.POST.get('state')
zipcode = request.POST.get('zip')
contact = request.POST.get('contact')
cnic = request.POST.get('cnic')
address = request.POST.get('address')
photo = request.FILES.get('photo')
cv = request.FILES.get('cv')
otherfiles = request.FILES.get('photo')
add_staff = staff.objects.create(firstname=firstname, lastname=lastname, fathername=fathername, city=city,country=country, state=state, contact=contact, cnic=cnic, zip=zipcode, address=address, photo=photo, cv=cv, otherfiles=otherfiles, staff_type=staff_type)
add_staff.save()
messages.info(request, "Staff has been Added.")
return redirect('add_staff')
else:
return render(request, 'staff/add_staff.html')
urls.py
urlpatterns = [
path("", views.index, name="index"),
path("staff/add_staff_type", views.add_staff_type, name="add_staff_type"),
path("staff/add_staff", views.add_staff, name="add_staff"),
path("staff/add_staff_view", views.add_staff_view, name="add_staff_view"),
]
add_staff.html
<form class="needs-validation" action="add_staff_view" method="POST" enctype="multipart/form-data" novalidate>
{% csrf_token %}
<div class="card-body">
<div class="form-row">
<div class="col-md-3 mb-3">
<label for="validationCustom01">Staff Type</label>
<select class="form-control" id="validationCustom01" name="stafftype">
{% for staff in staff %}
<option name="stafftype" value="{{ staff.id }}" required>{{staff.designation}}</option>
{% endfor %}
</select>
<div class="valid-feedback">
Looks good!
</div>
</div>
<div class="col-md-3 mb-3">
<label for="validationCustom02">First name</label>
<input type="text" class="form-control" id="validationCustom02" placeholder="First name" name="firstname" required>
<div class="valid-feedback">
Looks good!
</div>
</div>
<div class="col-md-3 mb-3">
<label for="validationCustom03">Last name</label>
<input type="text" class="form-control" id="validationCustom03" placeholder="Last name" name="lastname" required>
<div class="valid-feedback">
Looks good!
</div>
</div>
<div class="col-md-3 mb-3">
<label for="validationCustom04">Father Name</label>
<input type="text" class="form-control" id="validationCustom04" placeholder="Father Name" name="fathername" required>
<div class="valid-feedback">
Looks good!
</div>
</div>
</div>
<div class="form-row">
<div class="col-md-3 mb-3">
<label for="validationCustom05">City</label>
<input type="text" class="form-control" id="validationCustom05" placeholder="City" name="city" required>
<div class="invalid-feedback">
Please provide a valid city.
</div>
</div>
<div class="col-md-3 mb-3">
<label for="validationCustom06">Country</label>
<input type="text" class="form-control" id="validationCustom06" value="Pakistan" name="country" required>
<div class="invalid-feedback">
Please provide a valid country.
</div>
</div>
<div class="col-md-3 mb-3">
<label for="validationCustom07">State</label>
<input type="text" class="form-control" id="validationCustom07" placeholder="State" name="state" >
</div>
<div class="col-md-3 mb-3">
<label for="validationCustom08">Zip</label>
<input type="number" class="form-control" id="validationCustom08" value="0000" name="zip">
</div>
</div>
<div class="form-row">
<div class="col-md-3 mb-3">
<label for="validationCustom09">Contact</label>
<input type="text" class="form-control" id="validationCustom09" placeholder="Phone Number" name="contact" required>
<div class="invalid-feedback">
Please provide a valid country.
</div>
</div>
<div class="col-md-3 mb-3">
<label for="validationCustom10">CNIC</label>
<input type="number" class="form-control" id="validationCustom10" placeholder="xxxxx-xxxxxxx-x" name="cnic" required>
<div class="invalid-feedback">
Please provide a valid country.
</div>
</div>
<div class="col-md-6 mb-3">
<label for="address">Address</label>
<input type="text" class="form-control" id="address" placeholder="Current Address" name="address">
</div>
</div>
<div class="form-row">
<div class="file col-md-4 mb-3">
<label class="file-label" for="customFile01">Photo</label>
<input type="file" class="form-control" id="customFile01" name="photo"/>
</div>
<div class="file col-md-4 mb-3">
<label class="file-label" for="customFile02">CV</label>
<input type="file" class="form-control" id="customFile02" name="cv"/>
</div>
<div class="file col-md-4 mb-3">
<label class="file-label" for="customFile03">Other Files/Photos</label>
<input type="file" class="form-control" id="customFile03" name="otherfiles"/>
</div>
</div>
<div classs="form-row">
<button class="btn btn-primary" type="submit">Add Staff</button>
</div>
</div>
</div>
</form>
I tried my best at the above code but it gives me the error.
Error
Exception Value:
Cannot assign "'1'": "staff.staff_type" must be a "staff_type" instance.
staff_type in staff model must be staff_type model instance so first get model instance
s_type = staff_type.objects.get(id=request.POST.get('stafftype'))
staff.objects.create(...,staff_type=s_type)
Or you can also assign fk directly like this.
staff.objects.create(staff_type_id=request.POST.get('stafftype'))
And please try to follow PEP8 standards for writing python codes.
Note: It's better using django forms and Also you can use built-in generic class-based views which will make your things easier.
The problem is that you are sending number to Staff model into the field "staff_type". You either need to cast it to staff_type, or put an instance there

Nothing returned when editing profile page

Trying to edit a profile using a form I have that should allow a user to edit her first name, last name and email. Problem is when I try editing the form nothing happens. Still trying to learn Django so could be something I am missing/not getting right.
Here is my form;
<form id="edit-mentor-profile" class="form-horizontal" method="post" >
{% csrf_token %}
<div class="form-group">
<label for="photo" class="col-sm-2 control-label">Avatar</label>
<div class="col-md-6">
<div class="media v-middle">
<div class="media-left">
<div class="icon-block width-100 bg-grey-100">
<i class="fa fa-photo text-light"></i>
</div>
</div>
<div class="media-body">
</i>
</div>
</div>
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-md-2 control-label">Full Name</label>
<div class="col-md-8">
<div class="row">
<div class="col-md-6">
<div class="form-control-material">
<input type="text" class="form-control" id="edit-mentor-profile-first_name" placeholder= {{ user.first_name }}>
<label for="edit-mentor-profile-first_name"></label>
</div>
</div>
<div class="col-md-6">
<div class="form-control-material">
<input type="text" class="form-control" id="edit-mentor-profile-last_name" placeholder={{ user.last_name }}>
<label for="edit-mentor-profile-last_name"></label>
</div>
</div>
</div>
</div>
</div>
<div class="form-group">
<label for="email" class="col-md-2 control-label">Email</label>
<div class="col-md-6">
<div class="form-control-material">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-envelope"></i></span>
<input type="email" class="form-control" id="edit-mentor-profile-email" placeholder={{ user.email }}>
<label for="edit-mentor-profile-email"></label>
</div>
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-6">
<div class="checkbox checkbox-success">
<input id="checkbox3" type="checkbox" checked="">
<label for="checkbox3">Subscribe to our Newsletter</label>
</div>
</div>
</div>
<div class="form-group margin-none">
<div class="col-md-offset-2 col-md-10">
<button type="submit" class="btn btn-primary paper-shadow relative" data-z="0.5" data-hover-z="1" data-animated>Save Changes</button>
</div>
</div>
</form>
this is what I have on forms.py
class TeacherSignUpForm(UserCreationForm):
email = forms.EmailField(max_length=100)
first_name = forms.CharField(max_length=100)
last_name = forms.CharField(max_length=100)
linkedin = forms.URLField(max_length=200)
class Meta(UserCreationForm.Meta):
model = User
fields = ('email', 'username', 'first_name', 'last_name')
def save(self, commit=True):
self.instance.is_teacher = True
user = super(UserCreationForm, self).save(commit=False)
user.email = self.cleaned_data['email']
user.first_name = self.cleaned_data['first_name']
user.last_name = self.cleaned_data['last_name']
user.save()
mentor = Mentor.objects.create(
user=user,
linkedin=self.cleaned_data['linkedin']
)
return user
forms.py
# edit mentor profile
class MentorProfileForm(forms.Form):
first_name = forms.CharField(widget=forms.TextInput(attrs={'type': 'text', 'id': 'edit-mentor-profile-first_name',
'class': 'form-control'}))
last_name = forms.CharField(widget=forms.TextInput(attrs={'type': 'text', 'id': 'edit-mentor-profile-last_name',
'class': 'form-control'}))
email = forms.EmailField(widget=forms.EmailInput(attrs={'type': 'email', 'id': 'edit-mentor-profile-email',
'class': 'form-control'}))
and teachers.py(views.py)
class TeacherSignUpView(CreateView):
model = User
form_class = TeacherSignUpForm
template_name = 'registration/signup_form.html'
def get_context_data(self, **kwargs):
kwargs['user_type'] = 'teacher'
return super().get_context_data(**kwargs)
def form_valid(self, form):
user = form.save()
# user.set_password(form.cl)
login(self.request, user)
return redirect('teachers:app-instructor-dashboard')
#edit mentor profile
def edit_user(request):
user = request.user
form = MentorProfileForm(initial={'first_name':user.first_name,'last_name':user.last_name,'email':user.email})
if request.method == 'POST':
if form.is_valid():
user.first_name = request.POST['first_name']
user.last_name = request.POST['last_name']
user.email = request.POST['email']
# user.password = request.POST['password']
user.save()
return HttpResponseRedirect('%s'%(reverse('profile')))
context = {
"form":form
}
return render(request, 'classroom/teachers/app-instructor-profile.html', context)
UPDATE
Based on the answer provided I made the following changes
html form:
<form id="edit-mentor-profile" class="form-horizontal" method="post" >
{% csrf_token %}
<div class="form-group">
<label for="photo" class="col-sm-2 control-label">Avatar</label>
<div class="col-md-6">
<div class="media v-middle">
<div class="media-left">
<div class="icon-block width-100 bg-grey-100">
<i class="fa fa-photo text-light"></i>
</div>
</div>
<div class="media-body">
</i>
</div>
</div>
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-md-2 control-label">Full Name</label>
<div class="col-md-8">
<div class="row">
<div class="col-md-6">
<div class="form-control-material">
{{ form.first_name }}
<label for="edit-mentor-profile-first_name"></label>
</div>
</div>
<div class="col-md-6">
<div class="form-control-material">
{{ form.last_name }}
<label for="edit-mentor-profile-last_name"></label>
</div>
</div>
</div>
</div>
</div>
<div class="form-group">
<label for="email" class="col-md-2 control-label">Email</label>
<div class="col-md-6">
<div class="form-control-material">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-envelope"></i></span>
{{ form.email }}
<label for="edit-mentor-profile-email"></label>
</div>
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-6">
<div class="checkbox checkbox-success">
<input id="checkbox3" type="checkbox" checked="">
<label for="checkbox3">Subscribe to our Newsletter</label>
</div>
</div>
</div>
<div class="form-group margin-none">
<div class="col-md-offset-2 col-md-10">
<button type="submit" class="btn btn-primary paper-shadow relative" data-z="0.5" data-hover-z="1" data-animated>Save Changes</button>
</div>
</div>
</form>
and forms.py
class MentorProfileForm(forms.Form):
class Meta:
widgets = {
'first_name': forms.TextInput(attrs={'class':'form-control'}),
'last_name': forms.TextInput(attrs={'class':'form-control'}),
'email': forms.EmailInput(attrs={'class':'form-control'})
}
With these changes I cannot interact with the form. I cannot click the textboxes available.
Here is a sample of what i am seeing
You should render the inputs using the form field elements themselves
Instead of this
<input type="text" class="form-control" id="edit-mentor-profile-first_name" placeholder= {{ user.first_name }}>
Use this
{{ form.first_name }}
If you need to add the class to the input then in your model form add the class attribute to the field's widget
class Meta:
widgets = {
'first_name': forms.TextInput(attrs={'class': 'form-control'})
}

Update in django

I am new to django and I want to make an update view but I can't succeed.
I have this page that shows information about a user, and when I press the 'Update My Profile' button I want to update or save(i.e if I change 'Laszlo' with 'Lucy' I want to update it and if I write in the 'nickname' input: 'NICKNAME' I want to save that infomartion into de dababase so next time when I access this page to show me all the information about the user)
My models: 'UserProfile'(which is the 'User') and 'User_Details'(they are in 1-1 relationship)
class UserProfile(AbstractUser):
pass
class User_Details(models.Model):
user = models.OneToOneField(UserProfile, on_delete=models.CASCADE)
first_name = models.CharField(max_length=50, blank = True)
last_name = models.CharField(max_length=50, blank=True)
gender = models.CharField(max_length=6, blank=True, default='')
image = models.ImageField(upload_to='avatar_image', blank=True, null=True)
public_info=models.CharField(max_length=100, blank=False, default='')
nickname=models.CharField(max_length=100,blank=True,default="")
website=models.CharField(max_length=100,blank=True,default="")
My view to show the information:
class ShowProfile(APIView):
renderer_classes = [TemplateHTMLRenderer]
template_name = 'profile.html'
def get(self, request, pk, format=None):
details = UserProfile.objects.get(id=pk)
serializer = UserProfileSerializer(details)
pprint.pprint(json.loads(JSONRenderer().render(serializer.data)))
return Response({'seri':serializer.data})
Serializers:
class UserDetailsSerializer(serializers.ModelSerializer):
class Meta:
model = User_Details
fields = (
'first_name',
'last_name',
'gender',
'public_info',
'nickname',
'website'
)
class UserProfileSerializer(serializers.ModelSerializer):
user_details = UserDetailsSerializer()
lookup_field = 'username'
class Meta:
model = UserProfile
fields = ('id', 'user_details')
Template:
{% extends 'base2.html' %}
{% load rest_framework %}
{% block content %}
<div class="container">
<div class="row">
<div class="col-md-3 ">
<div class="list-group ">
Profile
My Posts
</div>
</div>
<div class="col-md-9">
<div class="card">
<div class="card-body">
<div class="row">
<div class="col-md-12">
<h4>Your Profile</h4>
<hr>
</div>
</div>
<div class="row">
<div class="col-md-12">
<form>
<div class="form-group row">
<label for="username" class="col-4 col-form-label">User Name*</label>
<div class="col-8">
<input id="username" name="username" placeholder="" class="form-control here" required="required" type="text">
</div>
</div>
<div class="form-group row">
<label for="name" class="col-4 col-form-label">First Name</label>
<div class="col-8">
<input id="name" name="first_name" placeholder= {{ seri.user_details.first_name }} class="form-control here" type="text">
</div>
</div>
<div class="form-group row">
<label for="lastname" class="col-4 col-form-label">Last Name</label>
<div class="col-8">
<input id="lastname" name="last_name" placeholder={{ seri.user_details.last_name}} class="form-control here" type="text">
</div>
</div>
<div class="form-group row">
<label for="text" class="col-4 col-form-label">Nick Name*</label>
<div class="col-8">
<input id="text" name="nickname" placeholder="{{ seri.user_details.nickname}}" class="form-control here" required="required" type="text">
</div>
</div>
<div class="form-group row">
<label for="website" class="col-4 col-form-label">Website</label>
<div class="col-8">
<input id="website" name="website" placeholder="{{seri.user_details.website}} " class="form-control here" type="text">
</div>
</div>
<div class="form-group row">
<label for="publicinfo" class="col-4 col-form-label">Public Info</label>
<div class="col-8">
<textarea id="publicinfo" name="public_info" cols="40" rows="4" class="form-control" placeholder='{{seri.user_details.public_info}}'></textarea>
</div>
</div>
<div class="form-group row">
<div class="offset-4 col-8">
<button name="submit" type="submit" class="btn btn-primary">Update My Profile</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
{% endblock %}
I tried to make this(into the 'ShowProfile' view) :
def put(self, request,pk):
serializer = ProfileUpdateSerializer()
post = request.POST.copy()
serializer.update(validated_data=dict(post))
return HttpResponseRedirect('/account/login.html')
Serializer
class ProfileUpdateSerializer(serializers.HyperlinkedModelSerializer):
first_name = serializers.CharField(source='User_Details.first_name')
last_name = serializers.CharField(source='User_Details.last_name')
gender = serializers.CharField(source='User_Details.gender')
public_info = serializers.CharField(source='User_Details.public_info')
# image=serializers.ImageField(source='User_Details.image')
nickname = serializers.CharField(source='User_Details.nickname')
website = serializers.CharField(source='User_Details.website')
class Meta:
model = User_Details
fields = ('first_name', 'last_name', 'gender', 'public_info', 'nickname', 'website')
def update(self, validated_data, uid):
user = UserProfile.objects.get(id=uid)
firstname = validated_data.pop('user_details.firstname')[0]
lastname = validated_data.pop('user_details.lastname')[0]
user.user_details.firstname = firstname
user.user_details.lastname = lastname
# if avatar:
# user.user_details.avatar = avatar
# if password != '':
# user.set_password(password)
user.user_details.save()
user.save()
return user
And in template I change the '' with this:
<form action="{% url 'show_profile' pk=user.id %}" method="PUT" enctype="multipart/form-data">
I don't know how to make to work?How can I do it?Thank you!
The problem is in <form action="{% url 'show_profile' pk=user.id %}" method="PUT" enctype="multipart/form-data">. There is no method PUT in html tag form. You have to use javascript to send such request.
P.S. it is possible to send put-like request using form, but it will look ugly and it wont be REST

Django post method returns only blank values for checkboxes

I have tried to look around for this specific query on SO, but could not find one.
I am new to Django and am using version 1.10 and python 3.4.
For the checkboxes I am using them in the template itself.
For some reason I am hesitant in using the checkbox widget in the forms.py file, I think it will disturb my existing UI(please correct me if I am wrong).
When I submit the form, the template returns blank quotes for the number of checkboxes I have ticked.
Here is my model:
class UsrGrpMaster(models.Model):
SrNo =models.IntegerField(unique=True)
UsrGrpID = models.AutoField(primary_key=True)
GrpName = models.CharField(max_length=50)
Purch = models.BooleanField(default=False)
PurchMod = models.BooleanField(default=False)
Sales = models.BooleanField(default=False)
SalesMod = models.BooleanField(default=False)
Stock = models.BooleanField(default=False)
StockMod = models.BooleanField(default=False)
JV = models.BooleanField(default=False)
JVMod = models.BooleanField(default=False)
DelPurch = models.BooleanField(default=False)
DelSales = models.BooleanField(default=False)
DelJV = models.BooleanField(default=False)
class Meta:
db_table = "UsrGrpMaster"
Here is my template:
<div class="body-set">
<div id="form">
<form class="form-horizontal" method="POST" action="{% url 'creategroup' %}">
<div class="form-group" align="center">
<label class=""><font size="6">Create a New User Group</font></label>{% if errormsg %}<br />
<font size="3" color="#FF0000">{{ errormsg }}</font>{% endif %}
</div>
<div class="form-group">
<label class="control-label col-sm-4" for="text">Name of the User Group:</label>
<div class="col-sm-5">
<input type="text" class="form-control" id="grpname" placeholder="Type in the new User Group Name" name="grpname">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-4" for="text">Permissions:</label>
<div class="col-sm-5">
<div><strong>Purchase Voucher</strong></div>
<label class="checkbox-inline"><input type="checkbox" name="checks[]" value="1">View</label>
<label class="checkbox-inline"><input type="checkbox" name="checks[]" value="2">Edit</label>
<label class="checkbox-inline"><input type="checkbox" name="checks[]" value="3">Delete</label>
</div><br /><br /><br />
<label class="control-label col-sm-4" for="text"></label>
<div class="col-sm-5">
<div><strong>Sales Voucher</strong></div>
<label class="checkbox-inline"><input type="checkbox" name="checks[]" value="4">View</label>
<label class="checkbox-inline"><input type="checkbox" name="checks[]" value="5">Edit</label>
<label class="checkbox-inline"><input type="checkbox" name="checks[]" value="6">Delete</label>
</div><br /><br /><br />
<label class="control-label col-sm-4" for="text"></label>
<div class="col-sm-5">
<div><strong>Stock</strong></div>
<label class="checkbox-inline"><input type="checkbox" name="checks[]" value="7">View</label>
<label class="checkbox-inline"><input type="checkbox" name="checks[]" value="8">Edit</label>
</div><br /><br /><br />
<label class="control-label col-sm-4" for="text"></label>
<div class="col-sm-5">
<div><strong>Journal Voucher / Income-Expense Voucher / Ledgers</strong></div>
<label class="checkbox-inline"><input type="checkbox" name="checks[]" value="9">View</label>
<label class="checkbox-inline"><input type="checkbox" name="checks[]" value="10">Edit</label>
<label class="checkbox-inline"><input type="checkbox" name="checks[]" value="11">Delete</label>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-4 col-sm-5">
<button type="submit" class="btn btn-primary">Create User Group</button>
</div>
</div>
</form>
</div>
Here is the class based View:
class CreateGroup(View):
#never_cache
def get(self, request, *args, **kwargs):
if 'adminusr' in request.COOKIES:
if request.session.get('errormsg', None):
errormsg = request.session['errormsg']
del request.session['errormsg']
else:
errormsg = ''
return render(request, 'adminpage/creategroup.html', {"errormsg": errormsg})
else:
return HttpResponseRedirect("/adminpage/")
def post(self, request, *args, **kwargs):
if request.method == 'POST':
GrpName = request.POST.get('grpname')
chq = request.POST.getlist('checks[]')
print(chq)
value = sninc(UsrGrpMaster, 'SrNo') #increments the sn and stores in DB
if checkduplicates(UsrGrpMaster, 'GrpName', GrpName) is not True:
qs = UsrGrpMaster(SrNo=value, GrpName=GrpName,
Purch=chq[1],
PurchMod=chq[2],
Sales=chq[4],
SalesMod=chq[5],
Stock=chq[7],
StockMod=chq[8],
JV=chq[9],
JVMod=chq[10],
DelPurch=chq[3],
DelSales=chq[6],
DelJV=chq[11]
)
qs.save()
else:
request.session['errormsg'] = "The user group already exists"
return HttpResponseRedirect("/adminpage/adminhome/creategroup/")
return HttpResponseRedirect("/adminpage/adminhome/")
Here is the browser and console clipping. Checked 9 boxes and submit shows 9 empty quotes.
template_browser_clipping
console_clipping
I want the form to provide me the value property of the checked boxes so I can store them in the database. Please guide me as to how to achieve this (with or without using forms.py).
Here is the Javascript:
$(document).ready(function(){
$('form').submit(function() {
if ($.trim($('input[name="grpname"]').val()) === "") {
$('input[name="grpname"]').css({'background-color' : '#ffe5e5'});
return false;
}
});
$('input').focusin(function() {
$(this).css({'background-color' : '#ffffff'});
});
$('input').blur(function() {
if ($.trim($(this).val()) === "") {
$(this).css({'background-color' : '#ffe5e5'});
}
});
});

Categories