Customize options inside the ModelChoiceField Django forms - python

I have a django form like this:
class AddUserGroupFrom(forms.ModelForm):
class Meta:
model = UsersGroups
fields = (
'tag',
)
widgets = {
'tag': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Work, home, etc..'}),
}
def __init__(self, *args, **kwargs):
super(AddUserGroupFrom, self).__init__(*args, **kwargs)
self.fields['city'] = forms.ModelChoiceField(
queryset=Group.objects.values_list('city').all().distinct(),
widget=forms.Select(attrs={
'class': 'form-select form-select-sm mb-3',
'aria-label': '.form-select-sm example',
}),
label='Choose city name',
empty_label='Select city',
)
self.fields['group'] = forms.ModelChoiceField(
queryset=Group.objects.values_list('group_number').all(),
widget=forms.Select(attrs={
'class': 'form-select form-select-sm mb-3',
'aria-label': '.form-select-sm example',
}),
label='Choose group number',
empty_label='Select group',
)
The problem that in my select field options displayed as tuples
Form representation
Templates look like this:
<form action="" method="post">
{% csrf_token %}
<div class="mb-3">
<label for="{{ add_group_form.tag.id_for_label }}" class="form-label">{{ add_group_form.tag.label }}</label>
{{ add_group_form.tag }}
</div>
<label for="{{ add_group_form.city.id_for_label }}">{{ add_group_form.city.label }}</label>
{{ add_group_form.city }}
<label for="{{ add_group_form.group.id_for_label }}">{{ add_group_form.group.label }}</label>
{{ add_group_form.group }}
<input type="submit" value="Save changes" class="btn btn-success">
</form>
How can I remove tuple-style representation in options inside the select field?
I tried to iterate within indexes in templates:
{{ add_group_form.city[0] }}
But it throws error:
Could not parse the remainder: '[0]' from 'add_group_form.city[0]'

You can create a tuple with the city values and assign it to the choices of the form field. Normally you do not define the form fields in the init method. It looks like city is not a model field. That's why I changed it to a ChocieField.
(code is not tested, change it if needed)
class AddUserGroupFrom(forms.ModelForm):
city = forms.ChoiceField(
choices=[],
empty_label='Select city',
label='Choose city name',
widget=forms.Select(attrs={
'class': 'form-select form-select-sm mb-3',
'aria-label': '.form-select-sm example',
}),
)
group = forms.ModelChoiceField(
queryset=Group.objects.all(),
empty_label='Select group',
label='Choose group number',
widget=forms.Select(attrs={
'class': 'form-select form-select-sm mb-3',
'aria-label': '.form-select-sm example',
}),
)
class Meta:
model = UsersGroups
fields = ('tag',)
widgets = {
'tag': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Work, home, etc..'}),
}
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
city_list = Group.objects.values_list('city', flat=True)
city_choices = [(city, city) for city in city_list]
self.fields['city'].choices = city_choices

Related

Save random integer into form of Django

I am trying to save po_id as a unique key of the "Order table". So I am generating a random number in the Order Form. But the issue is that somehow I can not save the form, even though all the fields are filled up.
models.py
def random_string():
return str(random.randint(10000, 99999))
class Order(models.Model):
po_id = models.CharField(max_length=4, default = random_string)
supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE)
product = models.ForeignKey(Product, on_delete=models.CASCADE)
forms.py
class OrderForm(forms.ModelForm):
class Meta:
model = Order
fields = ['supplier', 'product', 'po_id']
widgets = {
'supplier': forms.Select(attrs={'class': 'form-control', 'id': 'supplier'}),
'product': forms.Select(attrs={'class': 'form-control', 'id': 'product'}),
}
views.py
def create_order(request):
from django import forms
form = OrderForm()
if request.method == 'POST':
forms = OrderForm(request.POST)
if forms.is_valid():
po_id = forms.cleaned_data['po_id']
supplier = forms.cleaned_data['supplier']
product = forms.cleaned_data['product']
order = Order.objects.create(
po_id=po_id,
supplier=supplier,
product=product,
)
return redirect('order-list')
context = {
'form': form
}
return render(request, 'store/addOrder.html', context)
Order.html
<form action="#" method="post" novalidate="novalidate">
{% csrf_token %}
<div class="form-group">
<label for="po_id" class="control-label mb-1">ID</label>
{{ form.po_id }}
</div>
<div class="form-group">
<label for="supplier" class="control-label mb-1">Supplier</label>
{{ form.supplier }}
</div>
<div class="form-group">
<label for="product" class="control-label mb-1">Product</label>
{{ form.product }}
</div>
<div>
<button id="payment-button" type="submit" class="btn btn-lg btn-success btn-block">
<span id="payment-button-amount">Save</span>
</button>
</div>
Can help me with how I can solve the issue?

Changing image in django user change form

I am making a django webapp where users can upload profile image. I have also created an EDIT PROFILE page by using the default USERCHANGEFORM. But the problem is, that I cannot update the profile picture from that form. I can delete it but not upload new one? Help needed.
This is my USER CREATION FORM:
class SignUpForm(UserCreationForm):
photo = forms.ImageField(required=False)
bio = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Enter your bio'}))
designation = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Enter your designation'}))
university = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Enter your university'}))
company_name = forms.CharField(widget=forms.TextInput(attrs={'placeholder': "Enter your company's name"}))
grad_year = forms.IntegerField(widget=forms.TextInput(attrs={'placeholder': 'What year did you graduate in?'}))
phone = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Enter your phone number'}))
address = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Enter your present address'}))
city = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Enter your city'}))
company_category = forms.CharField(widget=forms.TextInput(attrs={'placeholder': "Enter your company's category"}))
company_desc = forms.CharField(widget=forms.TextInput(attrs={'placeholder': "Enter your company's description"}))
company_site = forms.CharField()
no_employees = forms.IntegerField(widget=forms.TextInput(attrs={'placeholder': 'Enter no. of employees in your company'}))
technologies = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'What technologies are you interested in?'}))
markets = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'What markets are you interested in?'}))
linkedin = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Enter your Linked In profile'}))
def __init__(self, *args, **kwargs):
super(UserCreationForm, self).__init__(*args, **kwargs)
del self.fields['password2']
for fieldname in ['password1']:
self.fields[fieldname].help_text = None
self.fields['password1'].widget.attrs.update({'placeholder': 'Enter your password'})
self.fields['first_name'].widget.attrs.update({'placeholder': 'Enter your first name'})
self.fields['last_name'].widget.attrs.update({'placeholder': 'Enter your last name'})
self.fields['company_site'].widget.attrs.update({'placeholder': "Enter company's website"})
for field in ['email',
'password1',
'first_name',
'last_name',
'bio',
'designation',
'university',
'company_name',
'grad_year',
'phone',
'photo',
'address',
'city',
'company_category',
'company_desc',
'company_site',
'no_employees',
'technologies',
'markets',
'linkedin']:
self.fields[field].widget.attrs['class'] = "col-lg-4 col-md-12 col-sm-12 col-xs-12 offset-lg-2 ml-6 form-control"
self.fields[field].widget.attrs['style'] = "padding:20px;"
self.fields['photo'].widget.attrs['class'] = "col-lg-8 col-md-12 col-sm-12 col-xs-12 offset-lg-1 "
class Meta:
model = User
widgets = {
"email": forms.fields.TextInput(attrs={'placeholder':'Enter your email'}),
}
fields = ('email',
'password1',
'first_name',
'last_name',
'photo',
'bio',
'designation',
'university',
'company_name',
'grad_year',
'phone',
'address',
'city',
'company_category',
'company_desc',
'company_site',
'no_employees',
'technologies',
'markets',
'linkedin')
This is my USER CHANGE FORM
class EditProfileForm(UserChangeForm):
def __init__(self, *args, **kwargs):
super(UserChangeForm, self).__init__(*args, **kwargs)
for field in [
'first_name',
'last_name',
'bio',
'designation',
'university',
'company_name',
'grad_year',
'phone',
'address',
'city',
'company_category',
'company_desc',
'company_site',
'no_employees',
'technologies',
'markets',
'linkedin']:
self.fields[field].widget.attrs['class'] = "col-lg-8 col-md-12 col-sm-12 col-xs-12 offset-lg-2 ml-6 form-control"
self.fields[field].widget.attrs['style'] = "padding:20px;"
self.fields['photo'].widget.attrs['class'] = "col-lg-8 col-md-12 col-sm-12 col-xs-12 offset-lg-2 ml-6"
self.fields['password'].widget.attrs['class'] = "hidden"
class Meta:
model = User
fields = ('first_name',
'last_name',
"photo",
"bio",
"designation",
"university",
"company_name",
"grad_year",
"phone",
"address",
"city",
"company_category",
"company_desc",
"company_site",
"no_employees",
"technologies",
"markets",
"linkedin"
)```
Basically you are getting the instance but you are not only able to update only the picture.
Try this!
In your EditProfileForm
replace
super(UserChangeForm, self).__init__(*args, **kwargs)
to
super(EditProfileForm, self).__init__(*args, **kwargs)
same in your SignUpForm
replace
super(UserCreationForm, self).__init__(*args, **kwargs)
to
super(SignUpForm, self).__init__(*args, **kwargs)
And you forgot to add photo inside EditProfileForm for field in [...]
{% load static %}
{% block content %}
<!-- Inner Page Banner Area Start Here -->
<div class="inner-page-banner-area" style="background-image: linear-gradient(to bottom,#002147, #fdc800);">
<div class="container">
<div class="pagination-area">
<h1>Edit Profile</h1>
</div>
</div>
</div>
<!-- Inner Page Banner Area End Here -->
<!-- Account Page Start Here -->
<div class="section-space accent-bg">
<div class="container">
<div class="row">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div class="profile-details tab-content">
<div class="tab-pane fade active in" id="Personal">
<h3 class="title-section title-bar-high mb-40">Edit Profile</h3>
<form id='login-form' style='text-align:left;' method="post" enctype="multipart/form-data">
<div class="form-group mt-1">
{% csrf_token %}
{% for field in form %}
<p>
<div class="mb-n5">{% if field.field.required %}{{ field.label_tag}}<span style='color:red;'>*</span>
{% else %}{{ field.label_tag}}
{% endif %}</div>
{% if field.name == 'password' %}
Change Password
{% else %}
{{ field }}
{% endif %}
<br>
{% for error in field.errors %}
<p style="color: red">{{ error }}</p>
{% endfor %}
</p>
</br>
{% endfor %}
</div>
<button class="view-all-primary-btn" type="submit">Save</button>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
{% include 'partials/_footer.html' %}
{% endblock %}

Django Formset Redirect with pk/id

I'm trying to pass in the parent id of a formset into a view, but it doesn't seem to work for me for some reason. I do this in other apps without issue but this particular one returns "None" as a pk. The only difference being my formset model doesn't usually contain a foreignkey relationship. If I render the parent by itself, I can pass the pk just fine. Please help :)
Exception Value: Reverse for 'company-detail' with keyword
arguments '{'pk': None}' not found. 1 pattern(s) tried:
['customers/(?P[0-9a-z-]+)/detail/$']
'''
urls.py
'''
url(r'^(?P<pk>[0-9a-z-]+)/detail/$', CompanyDetailView.as_view(),
name='company-detail'),
'''
forms.py
'''
class CompanyCreateForm(forms.ModelForm):
class Meta:
model = CompanyModel
fields = [
'name',
'website',
'rate',
]
widgets = {
'name': forms.TextInput(attrs={
'class': 'form-control',
'placeholder': ''}),
'website': forms.URLInput(attrs={
'class': 'form-control',
'placeholder': ''}),
'rate': forms.NumberInput(attrs={
'class': 'form-control',
'placeholder': ''}),
}
SitesFormSet = inlineformset_factory(
CompanyModel,
SiteModel,
fields=('street1',
'street2',
'city',
'state',
'zipcode',
'country',
'phone',
'distance',
),
widgets={
'street1': forms.TextInput(attrs={
'class': 'form-control'
}),
'street2': forms.TextInput(attrs={
'class': 'form-control'
}),
'city': forms.TextInput(attrs={
'class': 'form-control'
}),
'state': forms.TextInput(attrs={
'class': 'form-control'
}),
'zipcode': forms.NumberInput(attrs={
'class': 'form-control'
}),
'country': forms.TextInput(attrs={
'class': 'form-control'
}),
'phone': forms.TextInput(attrs={
'class': 'form-control'
}),
'distance': forms.NumberInput(attrs={
'class': 'form-control'
})
},
extra=1
)
'''
views.py
'''
def companycreateview(request):
if request.method == 'POST':
companyform = CompanyCreateForm(request.POST)
if companyform.is_valid():
company = companyform.save(commit=False)
sitesform = SitesFormSet(request.POST, request.FILES, instance=company)
if sitesform.is_valid():
company.save()
sitesform.save()
return redirect('customers:company-detail', pk=company.pk)
else:
companyform = CompanyCreateForm()
sitesform = SitesFormSet()
context = {
'company': companyform,
'sites': sitesform,
}
return render(request, 'customers/new-company.html', context)
class CompanyDetailView(DetailView):
model = CompanyModel
context_object_name = 'company'
template_name = 'customers/company-detail.html'
def get_context_data(self, **kwargs):
context = super(CompanyDetailView, self).get_context_data(**kwargs)
context['sites'] = SiteModel.objects.filter(company=self.get_object())
context['contacts'] = ContactModel.objects.filter(site__company=self.get_object())
context['reports'] = ServiceReportModel.objects.filter(site__company=self.get_object())
return context
'''
new-company.html.html
'''
<form action="" method="post">
{% csrf_token %}
<div class="form-row">
<div class="form-group col-md-12 form-col-md form-col-right-just {% if report.equipment.errors %}bg-danger{% endif %}">
<label for="{{ company.name.id_for_label }}"><Strong>Company Name</Strong></label></a>
{{ company.name }}
</div>
</div>
<div class="form-row">
<div class="form-group col-md-12 form-col-md form-col-right-just {% if report.equipment.errors %}bg-danger{% endif %}">
<label for="{{ company.website.id_for_label }}"><Strong>Website</Strong></label></a>
{{ company.website }}
</div>
</div>
<div class="form-row">
<div class="form-group col-md-12 form-col-md form-col-right-just {% if report.equipment.errors %}bg-danger{% endif %}">
<label for="{{ company.rate.id_for_label }}"><Strong>Hourly Rate</Strong></label></a>
{{ company.rate }}
</div>
</div>
{{ sites.management_form }}
{{ sites.non_form_errors }}
{% for child_form in sites %}
{{ child_form.sites_id.as_hidden }}
{{ child_form.company.as_hidden }}
<div class="form-row">
<div class="form-group col-md-12 form-col-md">
<label for="{{ child_form.id_for_label }}"><Strong>{{ child_form.label }}</Strong></label>
{{ child_form }}
{% if child_form.errors %}
{% for error in child_form.errors %}
{{ error|escape }}
{% endfor %}
{% endif %}
</div>
</div>
{% endfor %}
<div class="form-row">
<div class="form-group col-md-12 form-col-md form-col-left-just">
<button type="submit" class="btn btn-primary btn-detail"><Strong>Submit</Strong></button>
</div>
</div>
</form>
I think you need to make a small change to your url patterns. The error shows that the following pattern found no matches:
['customers/(?P[0-9a-z-]+)/detail/$']
Try adding <pk> directly after ?P:
customers/(?P<pk>[0-9a-z-]+)/detail/$
In your urls.py:
I think you missed pk in urlpatterns.
url('customers/(?P<pk>[0-9a-z-]+)/detail/$',.......)
In you views.py:
As your coding indentation if somehow sitesform is invalid then it'll try to redirect. But company is not saved yet into database. So pk is None. The code should be like below:
if companyform.is_valid():
company = companyform.save(commit=False)
sitesform = SitesFormSet(request.POST, request.FILES, instance=company)
if sitesform.is_valid():
company.save()
sitesform.save()
return redirect('customers:company-detail', pk=company.pk)

always getting "This field is required" error on Django form

I had a form with some fields and it was working fine. But when adding new field in the Model django raise an error
when I run the server and click on submit then it shows error for the new field This field is required although I am providing data for this field in the form.
Model.py
class UserInformation(models.Model):
firstName = models.CharField(max_length=128)
lastName = models.CharField(max_length=128)
userName = models.CharField(max_length=128)
institution = models.CharField(choices = [("#xyz.org","XYZ"), ("#abc.edu","ABC")], max_length=128)
userEmail = models.CharField(default="N/A", max_length=128)
phoneNumber = models.CharField(max_length=128)
orchidNumber = models.CharField(max_length=128)
PI = models.CharField(max_length=128)
PIUsername = models.CharField(max_length=128)
PIInstitution = models.CharField(default="N/A",choices = [("#xyz.org","XYZ"), ("#abc.edu","ABC")], max_length=128)
PIEmail = models.CharField(default="N/A", max_length=128)
PIPhoneNumber = models.CharField(max_length=128)
In this model
PIEmail is the field which I have added.
forms.py
class UserInformationForm(ModelForm):
firstName = forms.CharField(max_length=254,
widget=forms.TextInput({
'class': 'form-control',
}))
lastName = forms.CharField(
widget=forms.TextInput({
'class': 'form-control',
}))
userName = forms.CharField(
widget=forms.TextInput({
'class': 'form-control',
}))
institution = forms.ChoiceField( choices = [("#xyz.org","XYZ"), ("#abc.edu","ABC")]
,widget=forms.Select({
'class': 'form-control',
}))
phoneNumber = forms.CharField( required=False,
widget=forms.TextInput({
'class': 'form-control',
}))
orchidNumber = forms.CharField( required=False,
widget=forms.TextInput({
'class': 'form-control',
}))
PI = forms.CharField(
widget=forms.TextInput({
'class': 'form-control',
}))
PIUsername = forms.CharField(
widget=forms.TextInput({
'class': 'form-control',
}))
ctsaPIInstitution = forms.ChoiceField( choices = [("#xyz.org","XYZ"), ("#abc.edu","ABC")]
,widget=forms.Select({
'class': 'form-control',
}))
PIPhoneNumber = forms.CharField(
widget=forms.TextInput({
'class': 'form-control',
}))
userEmail = forms.CharField( required=False,
widget=forms.TextInput({
'class': 'form-control',
}))
PIEmail = forms.CharField( required=False,
widget=forms.TextInput({
'class': 'form-control',
}))
class Meta:
model = UserInformation
exclude = ()
and here is my register.html
<div class="row">
<section id="registerForm">
<div style="font-size:15px; color:red;">
The fields marked with an asterisk (*) are mandatory.
</div><br/>
<form method="post" action=".">{% csrf_token %}
<div class="form-group">
<label for="id_firstName" >First Name (*)</label>
{{ form.firstName }}
</div>
<div class="form-group">
<label for="id_lastName" >Last Name (*)</label>
{{ form.lastName }}
</div>
<div class="form-group">
<label for="id_email">Username (*)</label>
{{ form.userName }}
</div>
<div class="form-group">
<label for="id_intitution">Institution (*)</label>
{{ form.institution }}
</div>
<div class="form-group">
<label for="id_phone" >Contact Number</label>
{{ form.phoneNumber }}
</div>
<div class="form-group">
<label for="id_orcid">Orcid ID (Get Orcid ID)</label>
{{ form.orchidNumber }}
</div>
<div class="form-group">
<label for="id_ctsaPI">Prinicipal Investigator (*)</label>
{{ form.PI }}
</div>
<div class="form-group">
<label for="id_PI">CTSA Prinicipal Investigator Username (*)</label>
{{ form.PIUsername }}
</div>
<div class="form-group">
<label for="id_ctsaPI">Prinicipal Investigator Institute (*)</label>
{{ form.PIInstitution }}
</div>
<div class="form-group">
<label for="id_PIName"> Prinicipal Investigator Phone Number (*)</label>
{{ form.PIPhoneNumber }}
</div>
<div class="form-group">
<label for="id_UserEmail">User Email (*)</label>
{{ form.userEmail }}
</div>
<div class="form-group">
<label for="id_PI">PI Email (*)</label>
{{ form.PIEmail }}
</div>
<div class="form-group" >
<br/>
<input type="submit" value="Submit" class="btn btn-primary" />
</div>
</form>
</section>
view.py
#csrf_protect
def register(request):
if request.method == 'POST':
form = UserInformationForm(request.POST)
if form.is_valid(): //// here it is breaking
form.save()
else:
form = UserInformationForm()
variables = { 'form': form }
return render(request, 'registration/register.html',variables)
I am not sure what is wrong in this code
I'm not sure if this helps but sometimes I find the errors returned look like a bit of a red herring and end up driving me mad for hours on end. I am no expert and from where I am sitting the code for your form looks fine to me which is probably why it was working before. However in your html file you have two labels specified with the same id, the second one just happens to be on the PIEmail field that you have recently added. Coincidence? Maybe! It's a long shot but perhaps change that initially and see if it makes any difference.
Change:
<div class="form-group">
<label for="id_PI">PI Email (*)</label>
{{ form.PIEmail }}
</div>
to:
<div class="form-group">
<label for="id_PIEmail">PI Email (*)</label>
{{ form.PIEmail }}
</div>
Note: The other instance is on the PIUsername field.

Edit Listing Form is Duplication

I have a listing system on my website and am currently creating a page which allows the user to edit their listing, I've got most of it working however I am stuck on saving their updated form. Currently if they save the edited form rather than updating the model it creates a whole new listing entry and still leaves the old one there. If anyone could please look at my code that would be great, I've been stuck on this problem for so long!
View -
#login_required(redirect_field_name='login')
def editlisting(request, pk):
post = JobListing.objects.get(pk=pk)
if str(request.user) != str(post.user):
return redirect("index")
if request.method == "POST":
print("test")
form = JobListingForm(request.POST, instance=post, force_update=True)
if form.is_valid():
form.save()
return redirect('index')
else:
print("else")
form = JobListingForm(instance=post)
context = {
"form": form
}
return render(request, "editlisting.html", context)
Model -
class JobListing(models.Model):
region_choice = (
('Auckland', 'Auckland'),
('Wellington', 'Wellington'),
('Christchurch', 'Christchurch')
)
industry_choice = (
('Accounting', 'Accounting'),
('Agriculture, fishing & forestry', 'Agriculture, fishing & forestry'),
('Automotive', 'Automotive'),
('Banking, finance & insurance', 'Banking, finance & insurance'),
('Construction & Architecture', 'Construction & Architecture'),
('Customer service', 'Customer service'),
)
employment_type_choice = (
('Full Time', 'Full Time'),
('Part Time', 'Part Time'),
('One-off', 'One-off'),
('Other', 'Other')
)
user = models.CharField(max_length=50)
job_title = models.CharField(max_length=30)
pay_rate = models.DecimalField(max_digits=10, decimal_places=2)
employment_type = models.CharField(max_length=10, choices=employment_type_choice)
job_description = models.CharField(max_length=2000)
business_address_region = models.CharField(max_length=50, choices=region_choice)
business_address_suburb = models.CharField(max_length=50)
business_industry = models.CharField(max_length=50, choices=industry_choice)
email = models.EmailField(max_length=50, blank=True, null="True")
telephone = models.IntegerField(blank=True, null='True')
active_listing = models.BooleanField(default=True)
class Meta:
verbose_name = 'Job Listing'
def clean(self):
if not (self.email or self.telephone):
raise ValidationError("You must specify either email or telephone")
if not self.email:
self.email = "Not Provided"
def __unicode__(self):
return "%s" % self.job_title
Piece of code from my registration app which could be affecting it?
def signup(self, request, user):
SignUpProfile.objects.create(
user=user,
account_type=self.cleaned_data['account_type'],
contact_number=self.cleaned_data['contact_number']
)
Form -
class JobListingForm(forms.ModelForm):
class Meta:
model = JobListing
fields = ['job_title', 'pay_rate', 'employment_type', 'job_description', 'business_address_region',
'business_address_suburb', 'business_industry', 'telephone', 'email']
widgets = {
'job_title': forms.TextInput(attrs={'class': 'form-input', 'placeholder': 'Job Title'}),
'pay_rate': forms.NumberInput(attrs={'class': 'form-input', 'placeholder': 'Hourly Rate or One Off Amount'}),
'employment_type': forms.Select(attrs={'class': 'form-input'}),
'job_description': forms.Textarea(attrs={'class': 'form-textarea',
'placeholder': 'Tell us additional information about your job listing e.g. Times, Business Info, Number of positions etc. (2000 Character Limit)'}),
'business_address_region': forms.Select(attrs={'class': 'form-input'}),
'business_address_suburb': forms.TextInput(attrs={'class': 'form-input', 'placeholder': 'Business Suburb'}),
'business_industry': forms.Select(attrs={'class': 'form-input'}),
'email': forms.EmailInput(attrs={'class': 'form-input', 'placeholder': 'Email'}),
'telephone': forms.NumberInput(attrs={'class': 'form-input', 'placeholder': 'Contact Numnber'}),
}
Form HTML -
<div id="createjoblisting">
<h1 class="pageheader">Edit Your Job Listing</h1>
<form class="createjoblisting" id="createjoblisting_form" method="post" action="{% url 'createjoblisting' %}">
{% csrf_token %}
{{ form.non_field_errors }}
<p> <label for="id_username" class="form-input-label">Job Title</label><br>
{{ form.job_title }}<br><p>{{ form.job_title.errors }}
<p><label for="id_username" class="form-input-label">Pay Rate</label><br>
{{ form.pay_rate }}<br></p>{{ form.pay_rate.errors }}
<p><label for="id_username" class="form-input-label">Employment Type</label><br>
{{ form.employment_type }}<br><p>{{ form.employment_type.errors }}
<p><label for="id_username" class="form-input-label">Job Description</label><br>
{{ form.job_description }}<br><p>{{ form.job_description.errors }}
<p><label for="id_username" class="form-input-label">Business Region</label><br>
{{ form.business_address_region }}<br><p>{{ form.business_address_region.errors }}
<p><label for="id_username" class="form-input-label">Business Suburb</label><br>
{{ form.business_address_suburb }}<br><p>{{ form.business_address_suburb.errors }}
<p><label for="id_username" class="form-input-label">Business Industry</label><br>
{{ form.business_industry }}<br><p>{{ form.business_industry.errors }}
<p><label for="id_username" class="form-input-label">Contact Number (Must provide either Contact Number or Email)</label><br>
{{ form.telephone }}<br><p>{{ form.telephone.errors }}
<p><label for="id_username" class="form-input-label">Email</label><br>
{{ form.email }}<br><p>{{ form.email.errors }}
<button type="submit" class="form-button">Update Job Listing</button>
</form>
</div>
URLS -
urlpatterns = [
url(r'^createjoblisting/', views.createjoblisting, name='createjoblisting'),
url(r'^(?P<pk>[0-9]+)/editprofile/', views.editprofile, name='editprofile'),
url(r'^(?P<pk>[0-9]+)/editlisting/', views.editlisting, name='editlisting'),
url(r'^editlistingportal/', views.editlistingportal, name='editlistingportal'),
]
Your form's action is wrong. Change it to:
<form action="{% url 'editlisting' %}" class="createjoblisting" id="createjoblisting_form" method="post" >
As you have copied the creation template, your form posts your data to the view which creates the listing instead of editing it.

Categories