Nothing returned when editing profile page - python

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

Related

Form with bootstrap

I'm trying to make the create form look better but it just doesn't work. It shows fine but when I try to submit it doesn't do anything. I've already tried with different forms of one field, I think I can't make it work because this has file fields and foreign keys, etc.
Why it doesn't work?
forms.py
class Lcreate(forms.ModelForm):
class Meta:
model = Auction
fields = ('name', 'img', 'description', 'category', 'starting_bid')
widgets = {
'description' : forms.Textarea(attrs={
'rows': '5',
'cols': '90',
'maxlength': '500',
}),
'name' : forms.Textarea(attrs={
'rows': '1',
'cols': '100',
'maxlength': '30',
}),
}
views.py
#login_required(login_url="login")
def create(request):
if request.method == "POST":
form = Lcreate(request.POST or None, request.FILES or None)
if form.is_valid():
user = request.user
starting_bid = form.cleaned_data["starting_bid"]
description = form.cleaned_data["description"]
name = form.cleaned_data["name"]
img = form.cleaned_data["img"]
category = form.cleaned_data["category"]
listing = Auction(user=user, starting_bid=starting_bid, description=description, name=name, img=img, category=category)
listing.save()
return redirect('index')
else:
form = Lcreate()
return render(request, "auctions/create.html", {
"form": Lcreate,
"categories": Category.objects.all()
})
html
<div class="space"></div>
<div class="create-form">
<h1>Create Listing</h1>
<form method="POST" enctype="multipart/form-data">
{%csrf_token%}
<div class="form-group">
<label for="name">Title</label>
<input autofocus class="form-control" id="name" type="text" name="name" placeholder="Title">
<div class="space"></div>
<label for="img">Image</label>
<input type="file" id="img" name="img" class="form-control-file">
<div class="space"></div>
<label for="description">Description</label>
<textarea class="form-control" name="description" id="description" rows="3" placeholder="description"></textarea>
<div class="space"></div>
<label for="category">Category</label>
<select class="form-control" id="category" name="category">
{% for category in categories %}
<option name="category">{{category.category_list}}</option>
{%endfor%}
</select>
<div class="space"></div>
<label for="starting_bid">Bid</label>
<input class="form-control" type="number" name="starting_bid" placeholder="Starting Bid">
</div>
<button type="submit" class="btn btn-primary">Post Auction</button>
</form>
</div>
It should be like this
views.py:
def create(request):
infos=listing.objects.all()
form = listingForm(request.POST, request.FILES)
if form.is_valid():
listing.objects.create(**form.cleaned_data)
return render(request, "auctions/index.html", {'infos':infos})
else:
return render(request, 'auctions/create.html', {'form': form})
HTML
<h2>Create Listings</h2>
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}{% load widget_tweaks %}
<div class="form-group row">
<label for="{{ form.id_name}}" class="col-sm-2 col-form-label">Title</label>
<div class="col-sm-10">
{{ form.name|add_class:"form-control" }}
</div>
</div>
<div class="form-group row">
<label for="{{ form.id_description}}" class="col-sm-2 col-form-label">Description</label>
<div class="col-sm-10">
{{ form.description |add_class:"form-control" }}
</div>
</div>
<div class="form-group row">
<label for="{{ form.id_starting_bid}}" class="col-sm-2 col-form-label">Starting Bid</label>
<div class="col-sm-10">
{{ form.id_starting_bid|add_class:"form-control" }}
</div>
</div>
<div class="form-group row">
<label for="{{ form.id_img }}" class="col-sm-2 col-form-label">Image</label>
<div class="col-sm-10">
{{ form.img |add_class:"form-control" }}
</div>
</div>
<div class="form-group row">
<label for="{{ form.id_category }}" class="col-sm-2 col-form-label">Category</label>
<div class="col-sm-10">
{{ form.category|add_class:"form-control" }}
</div>
</div>
<div class="form-group row">
<div class="col-sm-10">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</form>

Saving edited data via formsets

I am trying to edit multiple rows of data in a model via formsets. In my rendered form, I use javascript to delete (hide and assign DELETE) rows, and then save changes with post.
My view:
def procedure_template_modification_alt(request, cliniclabel, template_id):
msg = ''
clinicobj = Clinic.objects.get(label=cliniclabel)
template_id = int(template_id)
template= ProcedureTemplate.objects.get(templid = template_id)
formset = ProcedureModificationFormset(queryset=SectionHeading.objects.filter(template = template))
if request.method == 'POST':
print(request.POST.get)
# Create a formset instance with POST data.
formset = ProcedureModificationFormset(request.POST)
if formset.is_valid():
print("Form is valid")
instances = formset.save(commit=False)
print(f'instances:{instances}')
for instance in instances:
print(f'Instance: {instance}')
instance.template = template
instance.save()
msg = "Changes saved successfully."
print("Deleted forms:")
for form in formset.deleted_forms:
print(form.cleaned_data)
else:
print("Form is invalid")
print(formset.errors)
msg = "Your changes could not be saved as the data you entered is invalid!"
template= ProcedureTemplate.objects.get(templid = template_id)
headings = SectionHeading.objects.filter(template = template)
return render(request, 'procedures/create_procedure_formset_alt.html',
{
'template': template,
'formset': formset,
'headings': headings,
'msg': msg,
'rnd_num': randomnumber(),
})
My models:
class ProcedureTemplate(models.Model):
templid = models.AutoField(primary_key=True, unique=True)
title = models.CharField(max_length=200)
description = models.CharField(max_length=5000, default='', blank=True)
clinic = models.ForeignKey(Clinic, on_delete=models.CASCADE)
def __str__(self):
return f'{self.description}'
class SectionHeading(models.Model):
procid = models.AutoField(primary_key=True, unique=True)
name = models.CharField(max_length=200)
default = models.CharField(max_length=1000)
sortorder = models.IntegerField(default=1000)
fieldtype_choice = (
('heading1', 'Heading1'),
('heading2', 'Heading2'),
)
fieldtype = models.CharField(
choices=fieldtype_choice, max_length=100, default='heading1')
template = models.ForeignKey(ProcedureTemplate, on_delete=models.CASCADE, null=False)
def __str__(self):
return f'{self.name} [{self.procid}]'
My forms:
class ProcedureCrMetaForm(ModelForm):
class Meta:
model = SectionHeading
fields = [
'name',
'default',
'sortorder',
'fieldtype',
'procid'
]
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['name'].widget.attrs.update({'class': 'form-control'})
self.fields['default'].widget.attrs.update({'class': 'form-control'})
self.fields['sortorder'].widget.attrs.update({'class': 'form-control'})
self.fields['fieldtype'].widget.attrs.update({'class': 'form-control'})
ProcedureCreationFormset = formset_factory(ProcedureCrMetaForm, extra=3)
ProcedureModificationFormset = modelformset_factory(SectionHeading, ProcedureCrMetaForm,
fields=('name', 'default', 'sortorder','fieldtype', 'procid'),
can_delete=True,
extra=0
# widgets={"name": Textarea()}
)
The template:
{% block content %} {% load widget_tweaks %}
<div class="container">
{% if user.is_authenticated %}
<div class="row my-1">
<div class="col-sm-2">Name</div>
<div class="col-sm-22">
<input type="text" name="procedurename" class="form-control" placeholder="Enter name of procedure (E.g. DNE)"
value="{{ template.title }}" />
</div>
</div>
<div class="row my-1">
<div class="col-sm-2">Description</div>
<div class="col-sm-22">
<input type="text" name="proceduredesc" class="form-control" placeholder="Enter description of procedure (E.g. Diagnostic Nasal Endoscopy)"
value="{{ template.description }}" />
</div>
</div>
<form action="" method="post" enctype="multipart/form-data">
{% csrf_token %} {{ formset.management_form }}
<div class="row mt-3">
<div class="col-sm-1">Select</div>
<div class="col-sm-6">Heading</div>
<div class="col-sm-8">Default (Normal description)</div>
<div class="col-sm-2">Sort Order</div>
<div class="col-sm-4">Type</div>
<div class="col-sm-2">Action</div>
</div>
{% for form in formset %}
<div class="row procrow" id="row{{ forloop.counter0 }}">
<div class="" style="display: none;">{{ form.procid }}</div>
<div class="col-sm-6">
{{ form.name }}
</div>
<div class="col-sm-8">
<div class="input-group">
{{ form.default }}
</div>
</div>
<div class="col-sm-2">
<div class="input-group">
{{ form.sortorder }}
</div>
</div>
<div class="col-sm-4">
<div class="input-group">
{{ form.fieldtype }}
</div>
</div>
<div class="col-sm-2">
<div class="input-group">
<div class="input-group-append">
<button id="add{{ forloop.counter0 }}" class="btn btn-success add-row">+</button>
</div>
<div class="input-group-append">
<button id="del{{ forloop.counter0 }}" class="btn btn-danger del-row">-</button>
</div>
</div>
</div>
</div>
{% endfor %} {% endif %}
<div class="row my-3">
<div class="col-sm-8"></div>
<div class="col-sm-8">
<div class="input-group">
<div class="input-group-append mx-1">
<button id="save_report" type="submit" class="btn btn-success"><i class="fal fa-shield-check"></i>
Save Report Format</button>
</div>
<div class="input-group-append mx-1">
<button id="save_report" type="button" class="btn btn-danger"><i class="fal fa-times-hexagon"></i>
Cancel</button>
</div>
</div>
</div>
<div class="col-sm-8"></div>
</div>
<div>
{% for dict in formset.errors %} {% for error in dict.values %} {{ error }} {% endfor %} {% endfor %}
</div>
</form>
</div>
{% endblock %}
My data is displayed as below (Screenshot). I make changes with javascript when the delete button is pressed, so that the html becomes like this:
<div class="row procrow" id="row2" style="display: none;">
<div class="" style="display: none;"><input type="hidden" name="form-2-procid" value="25" id="id_form-2-procid"></div>
<div class="col-sm-6">
<input type="text" name="form-2-name" value="a" maxlength="200" class="form-control" id="id_form-2-name">
</div>
<div class="col-sm-8">
<div class="input-group">
<input type="text" name="form-2-default" value="v" maxlength="1000" class="form-control" id="id_form-2-default">
</div>
</div>
<div class="col-sm-2">
<div class="input-group">
<input type="number" name="form-2-sortorder" value="1000" class="form-control" id="id_form-2-sortorder">
</div>
</div>
<div class="col-sm-4">
<div class="input-group">
<select name="form-2-fieldtype" class="form-control" id="id_form-2-fieldtype">
<option value="heading1" selected="">Heading1</option>
<option value="heading2">Heading2</option>
</select>
</div>
</div>
<div class="col-sm-2">
<div class="input-group">
<div class="input-group-append">
<button id="add2" class="btn btn-success add-row">+</button>
</div>
<div class="input-group-append">
<button id="del2" class="btn btn-danger del-row">-</button>
</div>
</div>
</div>
<input type="checkbox" name="form-2-DELETE" id="id_form-2-DELETE" checked=""></div>
On submitting the data, I get the following output, and data does not reflect the deletion I did. It displays the same thing again. There are no errors. But my edited data is not being saved.
Output:
<bound method MultiValueDict.get of <QueryDict: {'csrfmiddlewaretoken': ['ka3avICLigV6TaMBK5a8zeVJlizhtsKW5OTDBLlYorKd7Iji9zRxCX2vvjBv6xKu'], 'form-TOTAL_FORMS': ['3'], 'form-INITIAL_FORMS': ['3'], 'form-MIN_NUM_FORMS': ['0'], 'form-MAX_NUM_FORMS': ['1000'], 'form-0-procid': ['23'], 'form-0-name': ['External ear canal'], 'form-0-default': ['Bilateral external ear canals appear normal. No discharge.'], 'form-0-sortorder': ['100'], 'form-0-fieldtype': ['heading1'], 'form-1-procid': ['24'], 'form-1-name': ['Tympanic membrane'], 'form-1-default': ['Tympanic membrane appears normal. Mobility not assessed.'], 'form-1-sortorder': ['500'], 'form-1-fieldtype': ['heading1'], 'form-2-procid': ['25'], 'form-2-name': ['a'], 'form-2-default': ['v'], 'form-2-sortorder': ['1000'], 'form-2-fieldtype': ['heading1'], 'form-2-DELETE': ['on']}>>
Form is valid
instances:[]
Deleted forms:
{'name': 'a', 'default': 'v', 'sortorder': 1000, 'fieldtype': 'heading1', 'procid': <SectionHeading: a [25]>, 'DELETE': True}
You actually need to delete the instances: Loop through the formsets' deleted_objects property after you called saved(commit=False) and delete them.

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

I wanna set minlength&maxlength in template of input tag

I wrote in index.html
<div class="heading col-lg-6 col-md-12">
<h2>New account registration</h2>
<form class="form-horizontal" action="regist_save/" method="POST">
<div class="form-group-lg">
<label for="id_username">username</label>

 {{ regist_form.username }}
</div>
 
<div class="form-group-lg">
<label for="id_email">email</label>

 {{ regist_form.email }}
</div>
<div class="form-group-lg">
<label for="id_password">password</label>
{{ regist_form.password1 }}
</div>
 
<div class="form-group-lg">
<label for="id_password">password(conformation)</label>
{{ regist_form.password2 }}
<p class="help-block">{{ regist_form.password2.help_text }}</p>
</div>
 
<div class="form-group-lg">
<div class="col-xs-offset-2">
<button type="submit" class="btn btn-primary btn-lg">SUBMIT</button>
<input name="next" type="hidden"/>
</div>
</div>
{% csrf_token %}
</form>
</div>
I wanna set minlength&maxlength in template of username&password input tag.If i wrote in html stye,it is
<form class="form-horizontal" action="regist_save/" method="POST">
<div class="form-group-lg">
<label for="id_username">username</label>

 <input id="id_username" name="username" type="text" value="" minlength="5" maxlength="12" placeholder="username" class="form-control">
</div>
 
<div class="form-group-lg">
<label for="id_email">email</label>

 {{ regist_form.email }}
</div>
<div class="form-group-lg">
<label for="id_password">password</label>
<input id="id_password1" name="password1" type="password1" value="" minlength="8" maxlength="12" placeholder="password1" class="form-control">
</div>
 
<div class="form-group-lg">
<label for="id_password">password(conformation)</label>
<input id="id_password2" name="password2" type="password2" value="" minlength="8" maxlength="12" placeholder="password2" class="form-control">
<p class="help-block">{{ regist_form.password2.help_text }}</p>
</div>
 
<div class="form-group-lg">
<div class="col-xs-offset-2">
<button type="submit" class="btn btn-primary btn-lg">SUBMIT</button>
<input name="next" type="hidden"/>
</div>
</div>
{% csrf_token %}
</form>
in forms.py
class RegisterForm(UserCreationForm):
class Meta:
model = User
fields = ('username', 'email','password1','password1',)
def __init__(self, *args, **kwargs):
super(RegisterForm, self).__init__(*args, **kwargs)
self.fields['username'].widget.attrs['class'] = 'form-control'
self.fields['email'].widget.attrs['class'] = 'form-control'
self.fields['password1'].widget.attrs['class'] = 'form-control'
self.fields['password2'].widget.attrs['class'] = 'form-control'
in views.py
#require_POST
def regist_save(request):
regist_form = RegisterForm(request.POST)
if regist_form.is_valid():
user = regist_form.save(commit=False)
password = regist_form.cleaned_data.get('password')
user.set_password(password)
user.save()
login(request, user)
context = {
'user': request.user,
}
return redirect('detail')
context = {
'regist_form': regist_form,
}
return render(request, 'registration/regist.html', context)
I wanna set username minlength="5" &maxlength="12" and password minlength="8" & maxlength="12".I wanna write it in template,although I searched the way in Google but i cannot find it.I think i can do it by template but do i misunderstand it?Can't i do it in template?
you can set maxlength and minlength by using these attributes with your desired limit and validation will work accordingly
Working example on W3schools

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