Fields I have added in django forms are not visible on webpage.
Attached model, view and html for the reference below.
This is an additional filed which I intent to add to the forms, I am new to Django and learning by enhancing the current project.
"estimated_headcount" is the new filed I have added in the forms.
Thanks
Model
class EstimatedHeadcount(models.Model):
count = models.CharField(max_length=100)
def __unicode__(self):
return self.name
class Meta:
default_permissions = []
#staticmethod
def __gotoadmin__():
return True
forms.py
class ClientProfileForm(forms.ModelForm):
class Meta:
model = ClientProfile
fields = ('full_name', 'short_name', 'account_payable',
'require_job_number', 'currency', 'segment', 'market', 'estimated_headcount', 'is_technicolor',
'address')
views.py
def client_profile(request):
all_profiles = ClientProfile.objects.filter(status='active')
profile = None
pid = request.GET.get('pid')
client_profile_form = ClientProfileForm()
if pid:
profile = ClientProfile.objects.get(id=pid)
client_profile_form = ClientProfileForm(instance=profile)
if request.method == 'POST':
client_profile_form = ClientProfileForm(request.POST, instance=profile)
if client_profile_form.is_valid():
profile = client_profile_form.save()
profile.csv_mapping = profile.full_name
profile.save()
if profile:
for task_type in TaskType.objects.all():
if not profile.task_costs.filter(task_type=task_type):
task_cost = TaskCost(task_type=task_type)
task_cost.save()
profile.task_costs.add(task_cost)
return render(request, "prod/client_profile.html", {'all_profiles': all_profiles,
'profile': profile,
'client_profile_form': client_profile_form})
clientprofile.html
<div class="content">
<form id='add_new_client_form' method="post" action="">
{% csrf_token %}
<table class="table">
<tbody>
{{ client_profile_form.as_table }}
</tbody>
<tfoot>
<tr>
<td></td>
<td>
<button class="lock" type="button"
onclick="unlock(this, '#add_new_client_form')">Unlock
</button>
<button type="submit">SAVE</button>
</td>
</tr>
</tfoot>
</table>
</form>
</div>
As far as I can tell from your code, there is no relation between the ClientProfile model and the EstimatedHeadcount model.
estimated_headcount should be a field on the ClientProfile model.
class ClientProfile(models.Model):
...
estimated_headcount = models.CharField(max_length=100)
Side note: I would expect the estimated headcount to be a numeric value, so an IntegerField or PositiveIntegerField might be a better choice.
Related
I'm going to receive data and save it using form and save it. But I can't get any result. Let me know what I'm doing wrong.
I set up a model. And I wrote a form to get the input. Forms.Form was used. At first, I used modelform, but I wrote it like this because there seemed to be no difference.
Is label important in the form? You can't get the data value because you can't connect the label?
heeelp!
models.py
class PayHistory(models.Model):
branch = models.ForeignKey(Branch, on_delete=models.CASCADE, null=True)
package_recommandation_date = models.DateField(null=True)
package_payment_date = models.DateField(null=True)
forms.py
class PackageForm(forms.Form):
package_recommandation_date = forms.CharField(label='package_recommandation_date')
package_payment_date = forms.CharField(label='package_payment_date')
...
## i changed like this(1)
class PackageForm(forms.ModelForm):
class Meta:
model = PayHistory
fields = ['package_recommandation_date', 'package_payment_date']
views.py
class PackageView(FormView):
model = PayHistory
template_name = 'branches/package-create.html'
success_url = reverse_lazy('/')
form_class = PackageForm
def form_valid(self, form):
form = form.save(commit=False)
form.save()
return super().form_valid(form)
### I realize what you mean. I changed it like this(2) and it was saved in DB.
def form_valid(self, form):
data = PayHistory()
data.package_recommandation_date = form.cleaned_data['package_recommandation_date']
data.package_payment_date = form.cleaned_data['package_payment_date']
data.save()
return super().form_valid(form)
# HTML
{% block content %}
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<div class="table-content">
<!-- 검색 -->
<table border="0">
<tr class="input-tr">
<td><input type="date" class="input1" name="package_recommandation_date"
value="{{ form.package_recommandation_date.value|default_if_none:'' }}" required>
</td>
<td><input type="date" class="input2" name="package_payment_date"
value="{{ form.package_payment_date.value|default_if_none:'' }}">
</td>
...
<td><button type="submit" class="input-button input16">적용</button></td>
# static/js
const package_recommandation_date = document.querySelector("package_recommandation_date");
const package_payment_date = document.querySelector("package_payment_date");
console.info(package_recommandation_date, package_payment_date)
#output
-> null null
I would like to have dropdowns filters for users browsing their book collection. The dropdown values are currently populated with every corresponding field value in the model, I only want users to get values relevant to them e.g. I have only publisher associatted to my books, 'Marvel', so I should only see Marvel in the publisher drop down when I go to filter my books.
I am not able to pass the user value to the form drop downs, even after setting up the initialization function. I keep getting error no such attribute as 'uid' or'user' in the view when I am passing the value to the form.
Models.py
class ComicInput(models.Model):
Publisher = models.CharField(max_length=20, default='Marvel', choices=Publisher_Choices, null=True, blank=True )
Title = models.CharField(max_length=50,default='', blank=False)
Type = models.CharField(max_length=30, choices=Type_Choices, null=True, blank=True ) #default='Reg'
Number = models.IntegerField(default='', blank=False)
Category = models.CharField( max_length=12,default="Hold",choices=Category_Choices,blank=True, null=True)
uid = models.ForeignKey(User,on_delete=models.CASCADE, editable=False) #default=False, null=True)
def __unicode__(self):
return '%s %s %s' % (self.uid,self.Title, self.Number, self.Grade, self.Series, self.CoverPic, self.Category)
class Meta:
ordering = ('Title', 'Series', 'Number')
Views.py
###################### Collection Viewer #############
#login_required(login_url="/login/")
def ComicInventory(self):
title_list = TitleChoiceField()
publisher_list = PublisherChoiceField()
sellingnotes_list = NotesChoiceField()
category_list = CategoryChoiceField()
if self.GET.get('titles'): # On screen drop down Filter for titles
selected_title = self.GET.get('titles')
displayInventory=ComicInput.objects.filter(Title=selected_title,uid=self.user)
DisplaySumValue=ComicInput.objects.all().filter(Title=selected_title,uid=self.user).aggregate(Sum('Value'))
else:
displayInventory=ComicInput.objects.filter(uid=self.user)
DisplaySumValue=ComicInput.objects.all().aggregate(Sum('Value'))
context = {
'displayInventory': displayInventory,
'DisplaySumValue': DisplaySumValue,
'title_list': title_list,
}
return render(self, 'app/viewer.html',context)
HTML
<body>
<h1><Strong>Here are your comics;</Strong></h1>
<div class="panel-heading">
**<!.. this is the Choice Field on HTML ..!>**
<div class="panel-title pull-left">
<form method="get" action="{% url 'ComicInventory' %}">
{{ category_list }}
<input type="submit" value="Filter">
</form>
</div>
<div class="container">
<table class="table table-striped">
<thead class="thead-dark">
<tr>
<th scope="col">Publisher</th>
<th scope="col">Title</th>
<th scope="col">Number</th>
<th scope="col">Edition</th>
</tr>
</thead>
{% for inv in displayInventory %}
<tbody class="table table-hover">
<tr>
<td>{{inv.Publisher}}</td>
<td>{{inv.Title}}</td>
<td>{{inv.Number}}</td>
<td>{{inv.Edition}}</td>
alt="{{inv.Publisher}} image",height="60", width="100" /></a></td>
<td> Edit </td>
<td> Delete </td>
</tr>
{% endfor %}
</tbody>
<tfoot>
<tr>
<td><b>Total Value: {{DisplaySumValue}} </b></td>
</tr>
</tfoot>
</table>
</div>
</body>
EDIT
Form.py
##Updated Model ChoiceField that initiates self, so I can get the user and pass it to the view ##
class TitleChoiceField(forms.Form):
class Meta:
model = ComicInput
fields = ('Title', 'uid',)
def __init__(self,uid, *args, **kwargs):
super(TitleChoiceField, self).__init__(*args, **kwargs)
self.fields['titles'].queryset=ComicInput.objects.filter(uid=self.user).values_list("Title", flat=True).distinct().order_by('Title')
Django AttributeError: Form object has no attribute '_errors'
Updated the forms like so based on the above post:
Forms.py
class TitleChoiceField(forms.Form):
class Meta:
model = ComicInput
fields = ('Title','uid',)
titles = forms.ModelChoiceField(queryset =ComicInput.objects.all())
def __init__(self, uid=None, *args, **kwargs):
super(TitleChoiceField, self).__init__(*args, **kwargs)
self.user = uid
usrqry = ComicInput.objects.filter(uid=self.user).values_list('Title', flat=True).distinct().order_by('Title')
self.fields['titles'].queryset=usrqry
My goal is to create a page that lists all the courses available in the database and have the user select which courses they would like to be a tutor for.
I have a CustomUser model, a courses model, and finally a TutorTeachesCourse model that takes user and courses as foreign keys.
# model.py
from django.contrib.auth.models import AbstractUser
class CustomUser(AbstractUser):
is_tutee = models.BooleanField(default=False)
is_tutor = models.BooleanField(default=False)
courses = models.ManyToManyField(Courses)
class Courses(models.Model):
course_name = models.CharField(max_length=100, null = False)
course_number = models.CharField(max_length=100, null = False)
department = models.ForeignKey(Department, on_delete=models.CASCADE)
course_description = models.CharField(max_length=1000, blank=True)
#tutor = models.ManyToManyField(CustomUser) #moved m2m relationship to user model
objects = models.Manager()
def __str__(self):
return self.course_name
# forms.py
class EditTutoredCoursesForm(forms.Form):
model = CustomUser
course = forms.ModelMultipleChoiceField(
queryset = Courses.objects.all(),
widget = forms.CheckboxSelectMultiple,
)
def clean(self):
cleaned_data = super(EditTutoredCoursesForm, self).clean()
is_tutor = cleaned_data.get('is_tutor')
if not is_tutor:
raise forms.ValidationError('Validation error.')
def save(self,commit=True):
rel=super(EditTutoredCoursesForm,self).save(commit=False)
rel.is_tutor=self.cleaned_data['is_tutor']
if commit:
rel.save()
return rel
# views.py
def edit_tutored_courses(request):
user = request.user
if request.method == 'POST':
form = EditTutoredCoursesForm(request.POST)
if form.is_valid():
user.courses.set(form.cleaned_data['courses'])
user = form.save(commit=True)
messages.success(request, 'Success!')
return redirect(reverse('view_profile'))
else:
form = EditTutoredCoursesForm()
context = {
'form' : form,
}
return render(request, 'edit_tutored_courses.html', context)
And here the page where the user selects/unselects the courses they wish to tutor/not tutor.
# edit_tutored_courses.html
<table style="width:50%">
<tr>
<th>Course Name</th>
</tr>
<form method="POST" action="">
{% csrf_token %}
{% for is_tutor in form %}
{% for course in is_tutor %}
<tr>
<td>{{ course }}</td>
<td>{{ user }}</td>
</tr>
{% endfor %}
{% endfor %}
</table>
<input type="submit" value="Save Changes"/>
</form>
I can display the courses on my page but I don't know how to make changes to the database. I want the checkboxes to mean that once I click "submit" the table TutorTeachesCourses populates with that user with the checked courses, and if I uncheck the boxes it means it deletes the existing one. (That means I also need to make the page automatically check the boxes that exists int he database. How do I do all of this?
So I am completely new to Django, I want to have a user enter a keyword into an HTML form then have each row from the database where an attribute matches that keyword displayed on the page. I've tried various ways of doing this and am not sure what I am doing wrong. Any help would be appreciated.
search.html
<div class="container">
<form method="GET" action="{% url 'search' %}">
<div class="form-group">
<input type="text" name="make" placeholder="Car Make" />
<label>
<button type="submit" class="btn btn-danger"> Go </button>
</label>
</div>
</form>
{% if results %}
<table>
<tr>
<th scope="col"></th>
<th scope="col">Car Make</th>
<th scope="col">Car Model</th>
<th scope="col">Car Type</th>
<th scope="col">Number of Seats</th>
<th scope="col">Price</th>
</tr>
{% for item in results%}
<tr>
<td>{{item.makename}}</td>
<td>{{item.model}}</td>
<td>{{item.seriesname}}</td>
<td>{{item.seatingcapacity}}</td>
<td>{{item.pricenew}}</td>
</tr>
{% endfor %}
</table>
{% endif %}
</div>
views.py
class SearchView(TemplateView):
template_name = 'carproject/search.html'
model = Vehicles
def get(self, request):
form = AdvancedSearch()
return render(request, self.template_name, {'form': form})
def search(self, request):
makequery = self.request.GET.get['make']
if makequery:
results = self.Vehicles.objects.filter(makename__icontains(makequery))
return render(request, self.template_name, {'results': results})
Models.py
class Vehicles(models.Model):
carid = models.IntegerField(db_column='CarID', primary_key=True)
makename = models.CharField(db_column='MakeName', max_length=45)
model = models.CharField(db_column='Model', max_length=45)
seriesname = models.CharField(db_column='SeriesName', max_length=45)
seriesyear = models.TextField(db_column='SeriesYear')
pricenew = models.IntegerField(db_column='PriceNew')
fuelsystem = models.CharField(db_column='FuelSystem', max_length=45)
enginesize = models.CharField(db_column='EngineSize', max_length=10)
tankcapacity = models.CharField(db_column='TankCapacity', max_length=10)
power = models.CharField(db_column='Power', max_length=10)
seatingcapacity = models.IntegerField(db_column='SeatingCapacity')
standardtransmission = models.CharField(db_column='StandardTransmission', max_length=45)
bodytype = models.CharField(db_column='BodyType', max_length=45)
drive = models.CharField(db_column='Drive', max_length=3)
wheelbase = models.CharField(db_column='WheelBase', max_length=10)
class Meta:
managed = False
db_table = 'vehicles'
You can just do Vehicles.objects.filter(makename__icontains=request.GET.get("make","somevalueasdefault")) in your get function. Maybe I am missing something, but I am not sure why you have rendered the view like that in a class-based view. Just as an example, you can do like below.
class SearchView(TemplateView):
template_name = "carproject/search.html"
def get(self, kwargs):
context = super(SearchView, self).get_context_data(**kwargs)
context['queryset'] = Vehicles.objects.filter(makename__icontains=request.GET.get("make","sdefault"))
return context
I have a simple Book Author relationship
class Author(models.Model):
first_name = models.CharField(max_length=125)
last_name = models.CharField(max_length=125)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
class Book(models.Model):
title = models.CharField(max_length=225)
author = models.ForeignKey(Author)
class AuthorForm(forms.ModelForm):
class Meta:
model = Author
class BookForm(forms.ModelForm):
class Meta:
model = Book
This is what I have in my view
def addbook(request):
BookFormSet = inlineformset_factory(models.Author, models.Book, extra=1)
if request.method == 'GET':
author = models.AuthorForm()
books = BookFormSet()
else:
author = models.AuthorForm(request.POST)
if author.is_valid():
books = BookFormSet(request.POST)
if books.is_valid():
print(books)
return render_to_response('bookadd.html', locals(), context_instance = RequestContext(request))
My template looks like this
<form action="/books/add_new" method="post">
{% csrf_token %}
<table>
<tr>
<td>First name: </td>
<td>{{ author.first_name }}</td>
<td>{{author.first_name.errors}}</td>
</tr>
<tr>
<td>Last name</td>
<td>{{ author.last_name }}</td>
<td>{{author.last_name.errors}}</td>
</tr>
</table>
{{ books.management_form }}
{{ books.as_table }}
<br/>
<input type="submit" value="Submit" />
</form>
If I leave the title field blank and hit enter, on post back the book title field disappears, and I cannot figure out what to do about it. I want the field to be there with any data that was entered by the user.
You might try
author = models.AuthorForm(request.POST)
books = BookFormSet(request.POST)
if author.is_valid():
instead of
author = models.AuthorForm(request.POST)
if author.is_valid():
books = BookFormSet(request.POST)