Update in django - python

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

Related

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

my form not updating database, it sends GET instead of POST

i'm new trying to learn Django by building my e-commerce website.
In my terminal i'm getting GET and POST, although i specified action to POST
image result in my terminal
this code works great before i add translation to my website, but after adding Internationalization to my project, the form is no longer working(the form is not translated because it is comment section)
models.py:
class Comment(models.Model):
STATUS = (
('New', 'New'),
('True', 'True'),
('False', 'False'),
)
product = models.ForeignKey(Product, on_delete=models.CASCADE)
user = models.ForeignKey(User, on_delete=models.CASCADE)
subject = models.CharField(max_length=50, blank=True)
comment = models.CharField(max_length=250, blank=True)
rate = models.IntegerField(default=1)
ip = models.CharField(max_length=20, blank=True)
status = models.CharField(max_length=10, choices=STATUS, default='New')
create_at = models.DateTimeField(auto_now_add=True)
update_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.subject
class CommentForm(ModelForm):
class Meta:
model = Comment
fields = ['subject', 'comment', 'rate']
views.py:
def addcomment(request, id):
url = request.META.get('HTTP_REFERER') # get last url
# return HttpResponse(url)
if request.method == 'POST': # check post
form = CommentForm(request.POST)
if form.is_valid():
data = Comment() # create relation with model
data.subject = form.cleaned_data['subject']
data.comment = form.cleaned_data['comment']
data.rate = form.cleaned_data['rate']
data.ip = request.META.get('REMOTE_ADDR')
data. product_id = id
current_user = request.user
data.user_id = current_user.id
data.save() # save data to table
messages.success(request, "Your review has ben sent. Thank you for your interest.")
return HttpResponseRedirect(url)
return HttpResponseRedirect(url)
html code:
<div class="collapse" id="reviewForm">
<form class="review-form"
action="/cart/addcomment/{{ product.id }}" method="post">
{% csrf_token %}
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="sr-only" for="reviewEmail">subject:</label>
<input class="form-control form-control-sm" name="subject" type="text" placeholder="Your subject" required>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<label class="sr-only" for="reviewText">Review:</label>
<textarea class="form-control form-control-sm" name="comment" rows="5" placeholder="Your review " required></textarea>
</div>
</div>
<div class="row">
<div class="col-md-6 d-flex justify-content-between">
<div class="p-2">
<div class="form-group">
<div class="input-rating">
<strong class="">Please rate: </strong>
<div class="stars">
<input type="radio" id="star5" name="rate" value="5" /><label for="star5"></label>
<input type="radio" id="star4" name="rate" value="4" /><label for="star4"></label>
<input type="radio" id="star3" name="rate" value="3" /><label for="star3"></label>
<input type="radio" id="star2" name="rate" value="2" /><label for="star2"></label>
<input type="radio" id="star1" name="rate" value="1" /><label for="star1"></label>
</div>
</div>
</div>
</div>
<div class="p-2 d-flex justify-content-between">
{% if user.id is not None %}
<button class="btn btn-outline-dark" type="submit">
Post Review
</button>
{% else %}
You must be logged in to post a review
{% endif %}
</div>
</div>
</div>
</form>
</div><br>
urlpatterns:
path('addcomment/int:id', views.addcomment, name='addcomment'),
admin.py:
#admin.register(Comment)
class CommentAdmin(admin.ModelAdmin):
list_display = ['subject', 'comment', 'status', 'create_at']
list_filter = ['status']
readonly_fields = ('subject', 'comment', 'user', 'product', 'rate', )
thanks
Here is the code in one codeblocks
models.py
class Comment(models.Model):
STATUS = (
('New', 'New'),
('True', 'True'),
('False', 'False'),
)
product = models.ForeignKey(Product, on_delete=models.CASCADE)
user = models.ForeignKey(User, on_delete=models.CASCADE)
subject = models.CharField(max_length=50, blank=True)
comment = models.CharField(max_length=250, blank=True)
rate = models.IntegerField(default=1)
ip = models.CharField(max_length=20, blank=True)
status = models.CharField(max_length=10, choices=STATUS, default='New')
create_at = models.DateTimeField(auto_now_add=True)
update_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.subject
class CommentForm(ModelForm):
class Meta:
model = Comment
fields = ['subject', 'comment', 'rate']
views.py
def addcomment(request, id):
url = request.META.get('HTTP_REFERER') # get last url
# return HttpResponse(url)
if request.method == 'POST': # check post
form = CommentForm(request.POST)
if form.is_valid():
data = Comment() # create relation with model
data.subject = form.cleaned_data['subject']
data.comment = form.cleaned_data['comment']
data.rate = form.cleaned_data['rate']
data.ip = request.META.get('REMOTE_ADDR')
data. product_id = id
current_user = request.user
data.user_id = current_user.id
data.save() # save data to table
messages.success(request, "Your review has ben sent. Thank you for your interest.")
return HttpResponseRedirect(url)
return HttpResponseRedirect(url)
urlpatterns
urlpatterns = [
path('addcomment/<int:id>', views.addcomment, name='addcomment')]
html
<div class="collapse" id="reviewForm">
<form class="review-form"
action="/cart/addcomment/{{ product.id }}" method="post">
{% csrf_token %}
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="sr-only" for="reviewEmail">subject:</label>
<input class="form-control form-control-sm" name="subject" type="text" placeholder="Your subject" required>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<label class="sr-only" for="reviewText">Review:</label>
<textarea class="form-control form-control-sm" name="comment" rows="5" placeholder="Your review " required></textarea>
</div>
</div>
<div class="row">
<div class="col-md-6 d-flex justify-content-between">
<div class="p-2">
<div class="form-group">
<div class="input-rating">
<strong class="">Please rate: </strong>
<div class="stars">
<input type="radio" id="star5" name="rate" value="5" /><label for="star5"></label>
<input type="radio" id="star4" name="rate" value="4" /><label for="star4"></label>
<input type="radio" id="star3" name="rate" value="3" /><label for="star3"></label>
<input type="radio" id="star2" name="rate" value="2" /><label for="star2"></label>
<input type="radio" id="star1" name="rate" value="1" /><label for="star1"></label>
</div>
</div>
</div>
</div>
<div class="p-2 d-flex justify-content-between">
{% if user.id is not None %}
<button class="btn btn-outline-dark" type="submit">
Post Review
</button>
{% else %}
You must be logged in to post a review
{% endif %}
</div>
</div>
</div>
</form>
</div><br>
Create Forms.py file and add the form fields below with proper indentation like this:
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ['subject', 'comment', 'rate']

Django Forms posting not working - Django simply renders the page again

Basically I have set up a form to create organizations. When I hit the Save button, it simply renders the page again - the POST is not working.
See my code below:
models.py
from django.db import models
from accounts.models import User
from datetime import datetime, date
#// ------------ FUNCTIONS -------------//
# Generate Organisation IDs for each organisation
def org_id_generate():
last_org = Organization.objects.all().order_by('org_id').last()
if not last_org:
return 'ORG_001'
else:
last_org_id = last_org.org_id
number_in_id = int(last_org_id[4:7])
new_number_in_id = number_in_id + 1
new_org_id = 'ORG_' + str(new_number_in_id).zfill(3)
return new_org_id
#// ------------ MODELS -------------//
class Organization(models.Model):
org_id = models.CharField(primary_key=True, max_length=7, default=org_id_generate, editable=False)
organization_code = models.CharField(max_length=20)
company_name = models.CharField(verbose_name="Company Name", max_length=60)
legal_name = models.CharField(verbose_name="Legal Name", max_length=100)
industry_distribution = models.BooleanField(verbose_name="Distribution", default=False)
industry_education = models.BooleanField(verbose_name="Education", default=False)
industry_healthcare = models.BooleanField(verbose_name="Healthcare", default=False)
industry_manufacturing = models.BooleanField(verbose_name="Manufacturing", default=False)
industry_retail = models.BooleanField(verbose_name="Retail", default=False)
industry_services = models.BooleanField(verbose_name="Services", default=False)
business_registration_no = models.CharField(verbose_name="Business Registration Number", max_length=15, blank=True)
vat_registration_no = models.CharField(verbose_name="VAT Registration Number", max_length=15, blank=True)
created_date = models.DateTimeField(default=datetime.now)
created_by = models.ForeignKey(User, on_delete=models.DO_NOTHING, related_name="Created_By", verbose_name="Created By")
effective_start_date = models.DateField(auto_now_add=False)
effective_end_date = models.DateField(auto_now_add=False, blank=True, null=True)
update_date = models.DateTimeField(default=datetime.now)
last_updated_by = models.ForeignKey(User, on_delete=models.DO_NOTHING, related_name="Last_Updated_By", verbose_name="Last Updated By")
def __str__(self):
return self.company_name
forms.py
from django import forms
from organizations.models import Organization
class OrganizationAddForm(forms.ModelForm):
class Meta:
model = Organization
exclude = ['created_date', 'update_date', ]
views.py
from django.shortcuts import get_object_or_404, render, redirect
from organizations.models import Organization
from forms import OrganizationAddForm
from accounts.models import User
from django.contrib.auth.decorators import login_required
#login_required()
def settings(request):
return render(request, 'settings/settings.html')
#login_required()
def organizations_settings(request):
orgs = Organization.objects.all()
context = {
'orgs': orgs,
}
return render(request, 'settings/settings_organizations.html', context)
#login_required
def organization_add(request):
if request.method == 'POST':
user_email = request.user.email
form = OrganizationAddForm(request.POST)
if form.is_valid():
form.organization_code = form.cleaned_data['organization_code']
form.company_name = form.cleaned_data['company_name']
form.legal_name = form.cleaned_data['legal_name']
form.business_registration_no = form.cleaned_data['brn']
form.vat_registration_no = form.cleaned_data['vat']
form.industry_distribution = form.cleaned_data['industry_distribution']
form.industry_education = form.cleaned_data['industry_education']
form.industry_healthcare = form.cleaned_data['industry_healthcare']
form.industry_manufacturing = form.cleaned_data['industry_manufacturing']
form.industry_retail = forms.cleaned_data['industry_retail']
form.industry_services = form.cleaned_data['industry_services']
form.effective_start_date = form.cleaned_data['effective_start_date']
form.effective_end_date = form.cleaned_data['effective_end_date']
form.created_by = form.cleaned_data[user_email]
form.last_updated_by = form.cleaned_data[user_email]
form.save()
return redirect('organizations_settings')
else:
form = OrganizationAddForm()
return render(request, 'settings/add_organization.html', {'form': form})
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.settings, name="settings"),
path('organizations/', views.organizations_settings, name='organizations_settings'),
path('organization_create', views.organization_create, name="organization_create"),
path('organizations/add/', views.organization_add, name="organization_add"),
]
Page Source Code
<!-- Add Organization Form -->
<div class="container form-style">
<i class="fas fa-arrow-left"></i> Back
<div class="form-header">
<h3>Add Organization</h3>
</div>
<form action="{% url 'organization_add' %}" method="POST">
{% csrf_token %}
<div class="container">
<!-- Row 1 -->
<div class="row">
<div class="col-md-4">
<label for="organization_code">Organization Code<span class="star-red">*</span></label>
<input type="text" name="organization_code" class="form-control" required>
</div>
<div class="col-md-4">
<label for="company_name">Organization Name<span class="star-red">*</span></label>
<input type="text" name="company_name" class="form-control" required>
</div>
<div class="col-md-4">
<label for="legal_name">Legal Name<span class="star-red">*</span></label>
<input type="text" name="legal_name" class="form-control" required>
</div>
</div>
<!-- Row 2 -->
<div class="row mt-4">
<!-- <div class="col-md-4">
<label for="industry">Industry<span class="star-red">*</span></label>
<select name="industry" class="selectpicker">
<option value="distribution">Distribution</option>
<option value="education">Education</option>
<option value="healthcare">Healthcare</option>
<option value="manufacturing">Manufacturing</option>
<option value="retail">Retail</option>
<option value="services">Services</option>
</select>
</div> -->
<div class="col-md-6">
<label for="brn">Business Registration No.</label>
<input type="text" name="brn" class="form-control">
</div>
<div class="col-md-6">
<label for="vat">VAT Registration No.</label>
<input type="text" name="vat" class="form-control">
</div>
</div>
<!-- Row 3 -->
<h5 class="mt-4">Industry</h5>
<div class="row">
<div class="col-md-4">
<div class="form-check">
<input type="checkbox" name="industry_distribution" class="form-check-input">
<label for="industry_distribution" class="form-check-label">Distribution</label>
</div>
</div>
<div class="col-md-4">
<div class="form-check">
<input type="checkbox" name="industry_education" class="form-check-input">
<label for="industry_education" class="form-check-label">Education</label>
</div>
</div>
<div class="col-md-4">
<div class="form-check">
<input type="checkbox" name="industry_healthcare" class="form-check-input">
<label for="industry_healthcare" class="form-check-label">Healthcare</label>
</div>
</div>
</div>
<div class="row mt-2">
<div class="col-md-4">
<div class="form-check">
<input type="checkbox" name="industry_manufacturing" class="form-check-input">
<label for="industry_manufacturing" class="form-check-label">Manufacturing</label>
</div>
</div>
<div class="col-md-4">
<div class="form-check">
<input type="checkbox" name="industry_retail" class="form-check-input">
<label for="industry_retail" class="form-check-label">Retail</label>
</div>
</div>
<div class="col-md-4">
<div class="form-check">
<input type="checkbox" name="industry_services" class="form-check-input">
<label for="industry_services" class="form-check-label">Services</label>
</div>
</div>
</div>
<!-- Row 4 -->
<div class="row mt-4">
<div class="col-md-6">
<label for="effective_start_date">Effective Start Date<span class="star-red">*</span></label>
<input type="date" name="effective_start_date" class="form-control" required>
</div>
<div class="col-md-6">
<label for="effective_end_date">Effective End Date:</label>
<input type="date" name="effective_end_date" class="form-control">
</div>
</div>
<!-- Hidden Input - User -->
<input type="hidden" name="user_email" />
<div class="float-right mt-3">
<button type="submit" class="btn btn-custom save">Save and Close</button>
</div>
</div>
</form>
</div>
Any help would be greatly appreciated. If you need any additional info, let me know and I will edit the post.
I did not find any code to show the errors in html.
According to the function in views, if the form is not valid, then it renders the page with the form.
Try to add {{form.errors}} to you the html file to see if it has errors?
I managed to solve it.
views.py
#login_required
def organization_add(request):
if request.method == 'POST':
form = OrganizationAddForm(request.POST)
if form.is_valid():
form.organization_code = form.cleaned_data['organization_code']
form.company_name = form.cleaned_data['company_name']
form.legal_name = form.cleaned_data['legal_name']
form.business_registration_no = form.cleaned_data['business_registration_no']
form.vat_registration_no = form.cleaned_data['vat_registration_no']
form.industry_distribution = form.cleaned_data['industry_distribution']
form.industry_education = form.cleaned_data['industry_education']
form.industry_healthcare = form.cleaned_data['industry_healthcare']
form.industry_manufacturing = form.cleaned_data['industry_manufacturing']
form.industry_retail = form.cleaned_data['industry_retail']
form.industry_services = form.cleaned_data['industry_services']
form.effective_start_date = form.cleaned_data['effective_start_date']
form.effective_end_date = form.cleaned_data['effective_end_date']
org = form.save(commit=False)
org.created_by = request.user
org.last_updated_by = request.user
org.save()
return redirect('organizations_settings')
else:
form = OrganizationAddForm()
return render(request, 'settings/add_organization.html', {'form': form})
The issue was that it was not able to capture the user email for the Created By and Last Updated By fields.
This is resolved by using:
org = form.save(commit=False)
org.created_by = request.user
org.last_updated_by = request.user
Note that the following two posts helped me:
Using request.user with Django ModelForm
Cannot assign "42": "Event.user_id" must be a "User" instance

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'})
}

Error of Django's forms instance

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 ?

Categories