I'm currently working on a project that require Django Forms but I ended up with some issues. My form doesn't display at all ... No field appear on my template.
So my code :
models.py
class Place(models.Model):
name = models.CharField(max_length=255)
longitudeMax = models.DecimalField(max_digits=8, decimal_places = 4 ,blank=True)
longitudeMin = models.DecimalField(max_digits=8, decimal_places = 4, blank=True)
latitudeMax = models.DecimalField(max_digits=8, decimal_places = 4, blank=True)
latitudeMin = models.DecimalField(max_digits=8, decimal_places = 4, blank=True)
datasetPath = models.CharField(max_length=255)
isActive = models.BooleanField(default=True)
def __str__(self):
return self.name
def get_place(self, name):
return None
forms.py
class NewPlaceForm(forms.Form):
name = forms.CharField(
widget=forms.TextInput(
attrs={
"placeholder" : "Name",
"class": "form-control"
}
))
longMax = forms.DecimalField(
widget=forms.NumberInput(
attrs={
"placeholder" : "Longitude Max",
"class": "form-control"
}
))
longMin = forms.DecimalField(
widget=forms.NumberInput(
attrs={
"placeholder" : "Longitude Min",
"class": "form-control"
}
))
latMax = forms.DecimalField(
widget=forms.NumberInput(
attrs={
"placeholder" : "Latitude Max",
"class": "form-control"
}
))
latMin = forms.DecimalField(
widget=forms.NumberInput(
attrs={
"placeholder" : "Latitude Min",
"class": "form-control"
}
))
class Meta:
model = Place
fields = ('name', 'longitudeMax', 'longitudeMin', 'latitudeMax', 'latitudeMin')
views.py
def upload(request):
msg = None
if request.method == "POST":
form = NewPlaceForm(request.POST)
if form.is_valid():
form.save()
msg = 'Place created'
else:
msg = 'Form is not valid'
else:
form = NewPlaceForm()
return render(request, "pages/place_upload.html", {"form": form, "msg" : msg})
urls.py
from django.urls import path, re_path
from app import views
urlpatterns = [
#Data modification page
path('pages/place_modification.html', views.modification, name="place_modification"),
#New place adding page
path('pages/place_upload.html', views.upload, name="place_upload"),
# Matches any html file
re_path(r'^.*\.html', views.pages, name='pages'),
# The home page
path('', views.index, name='home'),
]
html file
<form method="post" action="">
{% csrf_token %}
<div class="card-body">
<div class="row">
<div class="col-md-6 col-lg-4">
<div class="form-group">
<div class="input-group mb-3">
<div class="input-group-prepend">
</div>
{{ form.name }}
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6 col-lg-4">
<div class="form-group">
<div class="input-group mb-3">
<div class="input-group-prepend">
</div>
{{ form.longMax }}
</div>
</div>
<div class="input-group mb-3">
<div class="input-group-prepend">
</div>
{{ form.longMin }}
</div>
</div >
<div class="col-md-6 col-lg-4">
<div class="input-group mb-3">
<div class="input-group-prepend">
</div>
{{ form.latMax }}
</div>
<div class="input-group mb-3">
<div class="input-group-prepend">
</div>
{{ form.latMin }}
</div>
</div>
<div class="col-md-6 col-lg-4">
<div class="form-group form-floating-label">
<small id="emailHelp2" class="form-text text-muted">Use negative numbers for South and positive numbers for North</small>
</div>
<div class="form-group form-floating-label">
<small id="emailHelp2" class="form-text text-muted">Use negative numbers for West and positive numbers for East</small>
</div>
</div>
</div>
</div>
<div class="card-action">
<button type="submit" class="btn btn-success">Submit</button>
<button class="btn btn-danger">Cancel</button>
</div>
</form>
I don't see why it doesn't work and it's been several days that I try to make it work ... Did I do something wrong ? Have I forgot something ? Because I don't feel like I did and it's getting on my nerve ahaha
Django handles the form rendering out of the box, to display a basic form, try:
<form method="POST" action="{% url 'namespaced:url' %}">
{ csrf_token %}
{{ form.as_p }}
<input type="submit" value="submit">
</form>
That said, it looks like you're using bootstrap in your template, you might find the package django-bootstrap4 useful (https://github.com/zostera/django-bootstrap4).
Quick example:
pip install django-bootstrap4
and add bootstrap4 to your installed apps.
Then in your template:
{% load bootstrap4 %}
{# Load CSS and JavaScript #}
{% bootstrap_css %}
{% bootstrap_javascript jquery='full' %}
<form action="{% url 'namespaced:url' %}" method="post" class="form">
{% csrf_token %}
{% bootstrap_form form %}
{% buttons %}
<button type="submit" class="btn btn-primary">
Submit
</button>
{% endbuttons %}
</form>
If you want, you can render each field manually using:
{% bootstrap_field field %}, so you can do things like <div class="col-md-6">{% bootstrap_field my_field %}</div>, to manually arrange your form fields on the page.
Related
I am a newbie, and I am working on a website. On this website I have created admin panel to manage different products and attributes .
I have a page named size.html and and I am supposed to change it name and make it productAtributes.html and on this single page I want to do all add, update, delete operations for different Product attributes.
My code is as:
models.py
class Product(models.Model):
prod_ID = models.AutoField("Product ID", primary_key=True)
prod_Name = models.CharField("Product Name", max_length=30, null=False)
prod_Desc = models.CharField("Product Description", max_length=2000, null=False)
prod_Price = models.IntegerField("Product Price/Piece", default=0.00)
prod_img = models.ImageField("Product Image", null=True)
def __str__(self):
return "{}-->{}".format(self.prod_ID,
self.prod_Name)
class Size(models.Model):
size_id = models.AutoField("Size ID", primary_key=True, auto_created=True)
prod_size = models.CharField("Product Size", max_length=20, null=False)
def __str__(self):
return "{size_id}-->{prod_size}".format(size_id=self.size_id,
prod_size=self.prod_size)
class Color(models.Model):
color_id = models.AutoField("Color ID", primary_key=True, auto_created=True)
prod_color = models.CharField("Product Color", max_length=50, null=False)
def __str__(self):
return "{color_id}-->{prod_color}".format(color_id=self.color_id,
prod_color=self.prod_color)
class PaperChoice(models.Model):
paper_id = models.AutoField("Paper Choice ID", primary_key=True, auto_created=True)
paper_choices_name = models.CharField("Paper Choices", max_length=50, null=False)
def __str__(self):
return "{}-->{}".format(self.paper_id,
self.paper_choices_name)
views.py
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.shortcuts import render, redirect
from user.models import *
def size(request):
if request.method == 'POST':
size_store = request.POST['prod_size']
size_update = Size(prod_size=size_store)
size_update.save()
return redirect('/admin1/productSize')
else:
size_show = Size.objects.all()
# start paginator logic
paginator = Paginator(size_show, 3)
page = request.GET.get('page')
try:
size_show = paginator.page(page)
except PageNotAnInteger:
size_show = paginator.page(1)
except EmptyPage:
size_show = paginator.page(paginator.num_pages)
# end paginator logic
return render(request, 'admin1/size.html', {'size_show': size_show})
def size_edit(request, id):
size_edit = Size.objects.filter(size_id=id)
return render(request, 'admin1/size.html', {'size_edit': size_edit})
def size_edit_update(request, id):
if request.method == 'POST':
size_store = request.POST['prod_size']
size_update = Size(size_id=id, prod_size=size_store)
size_update.save()
return redirect('/admin1/productSize')
def size_delete(request, id):
size_deletee = Size.objects.filter(size_id=id)
size_deletee.delete()
return redirect('/admin1/productSize')
As I created add, update, delete functionality for Size I am going to do it same with color and Papaer choice.
size.html
{% extends 'admin1/layout/master.html' %}
{% block title %}Size{% endblock %}
{% block main %}
<h1>
<center>Size</center>
</h1>
<div class="container">
<div class="row">
<div class="col-lg-2"></div>
<div class="col-lg-10">
<button type="button" class="btn btn-primary mt-2" data-toggle="modal" data-target="#modal-primary">Add
Size
</button>
<div class="modal fade" id="modal-primary">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Add Product Size</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span></button>
</div>
<div class="modal-body mt-2">
<form action="{% url 'admin-product-size'%}" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<label>Product Size:</label>
<input type="text" name="prod_size" class="form-control w-50"><br>
<br>
<input type="Submit" name="Submit" value="Submit" class="btn btn-success w-50"><br>
<div class="modal-footer justify-content-between">
<button type="button" class="btn btn-outline-light" data-dismiss="modal">Close
</button>
</div>
</form>
</div>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</div>
<!-- /.modal -->
<br>
{% if size_show %}
<div class="container-fluid ">
<div class="row">
<div class="card mt-2 border border-secondary">
<div class="card-header">
<h3 class="card-title ">Product Table</h3>
</div>
<!-- /.card-header -->
<div class="card-body">
<table class="table table-bordered border border-info">
<thead>
<tr>
<th>Product Id</th>
<th>Product Size</th>
</tr>
</thead>
<tbody class="justify-content-center">
{% for x in size_show %}
<tr>
<td>{{x.size_id}}</td>
<td>{{x.prod_size}}</td>
<td><a href="/admin1/size_edit/{{x.size_id}} "
class="btn btn-outline-primary mt-2"><i
class="fa fa-pencil-square-o" aria-hidden="true"></i></a>
<a href="/admin1/size_delete/{{x.size_id}}"
class="btn btn-outline-danger mt-2"><i
class="fa fa-trash" aria-hidden="true"></i></a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<!-- /.card-body -->
<div class="card-footer clearfix ">
<ul class="pagination pagination-sm m-0 justify-content-center">
{% if size_show.has_previous %}
<li class="page-item"><a class="page-link"
href="?page={{size_show.has_previous_page_number}}">
Previous </a>
</li>
{% endif%}
{% for x in size_show.paginator.page_range %}
{% if size_show.number == x %}
<li class="page-item active"><a class="page-link" href="?page={{x}}">{{x}}</a></li>
{% else%}
<li class="page-item"><a class="page-link" href="?page={{x}}">{{x}}</a></li>
{% endif %}
{% endfor %}
{% if size_show.has_next %}
<li class="page-item"><a class="page-link"
href="?page={{size_show.has_next_page_number}}"> Next </a>
</li>
{% endif %}
</ul>
</div>
</div>
<!-- /.card -->
</div>
</div>
{% endif %}
{% if size_edit %}
{% for x in size_edit %}
<form action="/admin1/size_data_update/{{x.size_id}}" method="POST">
{% csrf_token %}
<label>Size Name:</label>
<input type="text" name="prod_size" value="{{x.prod_size}}" class="form-control w-50"><br>
<input type="Submit" name="Submit" value="Submit" class="btn btn-success w-50"><br>
</form>
{% endfor %}
{% endif %}
</div>
</div>
</div>
{% endblock %}
For performing oertions of views.py I have created size.html .Nut there around 10 to 12 product attributes ,and for that attributes I don't want to create seprate html pages.
I want to do all the operations for all the attributes in single html page. Is it possible?
Means according to the atrribut type request the page data should change dynamically, I do not have to create seprate template pages for each attribute.
You need to make the form in your views, not the Templates, I'm not sure if this is best practise but it's the only way I see you can do this, (using Class-Based Views would simplify this process a lot) but if you want to stick to functions, this is what you do.
Let's take an input line:
<label>Product Size:</label>
<input type="text" name="prod_size" class="form-control w-50"><br>
Let's use Django's tags and turn it into this:
<label>{{form.display_name}}:</label>
<input type="text" name="{{form.name}}" class="form-control w-50">
The class will probably be the same but you could extend the same functionality to the class or type fields.
In the backend, you want to make a list of all the elements you want to show, with nested dictionaries:
forms = [ # Each form
[ # Each field within the form, this way, you can have a different amount each time
{'display_name': 'Product Size', # label Display name
'name': 'prod_size'}, # name tag value
{'display_name': "it's value", # This is a different field
'name': 'just an example'}
],
]
Then you can do a for loop in the templates:
{% for form in forms %}
{$ for field in form %}
<label>{{field.display_name}}:</label>
<input type="text" name="{{field.name}}" class="form-control w-50">
I'm not exactly sure what you're trying to do in your code, so I didn't make this example too specific, but hopefully, it will give you inspiration to get you on the right track, if you need more help, just ask
I have implemented a Dependent dropdown list within Django but when I try to submit the form I get the following error 'Select a valid choice. That choice is not one of the available choices.'
I have spent a while looking on the web for the answer and have tried a few with little avail.
From my understanding and reading, this is an error because I render the form with a queryset of none. Then I use ajax to fill in the options. Even though I have updated the dropdown list, the form validation is checking my submitted answer against a queryset of none - thus the error.
So i'm hoping someone can help me to update the choices the form will accepted on form submission.
views.py
# stage6 is where I render my view and check validation
def stage6(request):
form_deal = DealForm(request.POST or None, prefix='inst')
if form_deal.is_valid():
form_deal.save()
messages.success(request, 'Deal added successfully.')
form_deal = DealForm()
context = {
'dform': form_deal,
}
return render(request, 'stages/stage6/stage6.html', context)
# This is used for my ajax request
def load_offers(request):
property_process_id = request.GET.get('propertyprocess_link')
offers = Offer.objects.filter(propertyprocess_link=property_process_id).order_by('id')
return render(request, 'stages/stage6/offers_dropdown_list.html', {'offers': offers})
forms.py
class DealForm(forms.ModelForm):
deal_date = forms.CharField(
label='',
widget=forms.TextInput(attrs={'type': 'date'})
)
target_move_date = forms.CharField(
label='',
widget=forms.TextInput(attrs={'type': 'date'})
)
def __init__(self, *args, **kwargs):
super(DealForm, self).__init__(*args, **kwargs)
# filter the foreign keys shown
self.fields['propertyprocess_link'].queryset = PropertyProcess.objects.filter(sector="Sales")
# filter used for ajax request
self.fields['offer_accepted'].queryset = Offer.objects.none()
# add a "form-control" class to each form input
# for enabling bootstrap
for name in self.fields.keys():
self.fields[name].widget.attrs.update({
'class': 'form-control',
})
class Meta:
model = Deal
fields = ('propertyprocess_link',
'deal_date',
'price_agreed',
'target_move_date',
'offer_accepted'
)
models.py
class Deal(models.Model):
propertyprocess_link = models.ForeignKey(PropertyProcess,
on_delete=models.CASCADE)
deal_date = models.DateField()
price_agreed = models.IntegerField()
target_move_date = models.DateField()
offer_accepted = models.ForeignKey(Offer,
on_delete=models.CASCADE)
class Meta:
verbose_name_plural = "deals"
def __str__(self):
return '%s, %s' % (
self.propertyprocess_link.property_link.address_line_1,
self.propertyprocess_link.property_link.postcode
)
html
{% block content %}
<div class="container-fluid header-container">
<div class="row">
<div class="col-sm-9 col-md-7 col-lg-5 mx-auto">
<div class="card-au card-signin my-5">
<div class="card-body">
<form id="offers-form" data-offers-url="{% url 'ajax_load_offers' %}" class=" text-center text-white" method="post" novalidate>
{% csrf_token %}
{{ dform.non_field_errors }}
<div class="form-colour mt-2">
{{ dform.propertyprocess_link.errors }}
<label class="mb-0 mt-1">Property Being Offered On:</label>
{{ dform.propertyprocess_link }}
</div><div class="form-colour mt-2">
{{ dform.offer_accepted.errors }}
<label class="mb-0 mt-1">Offer Being Accepted:</label>
{{ dform.offer_accepted }}
</div>
<div class="form-colour mt-2">
{{ dform.price_agreed.errors }}
<label class="mb-0 mt-1">Price Agreed:</label>
{{ dform.price_agreed }}
</div>
<div class="form-colour mt-2">
{{ dform.deal_date.errors }}
<label class="mb-0 mt-1">Deal Date:</label>
{{ dform.deal_date }}
</div>
<div class="form-colour mt-2">
{{ dform.target_move_date.errors }}
<label class="mb-0 mt-1">Target Move Date:</label>
{{ dform.target_move_date }}
</div>
<div class="mb-3"></div>
{# hidden submit button to enable [enter] key #}
<div class="hidden-btn" style="margin-left: -9999px"><input class="hidden-btn" type="submit" value=""/></div>
<div class="text-center mt-2">
<input type="submit" class="login-btn btn-green btn btn-lg border-green text-uppercase py-3" value="Add Deal" />
</div>
</form>
</div>
</div>
</div>
</div>
</div>
{% endblock content %}
{% block postloadjs %}
{{ block.super }}
<script>
$("#id_inst-propertyprocess_link").change(function () {
var url = $("#offers-form").attr("data-offers-url"); // get the url of the `load_offers` view
var propertyID = $(this).val(); // get the selected Property Process ID from the HTML input
$.ajax({ // initialize an AJAX request
url: url, // set the url of the request (= localhost:8000/ajax/load-offers/)
data: {
'propertyprocess_link': propertyID // add the Property Process id to the GET parameters
},
success: function (data) { // `data` is the return of the `load-offers` view function
$("#id_inst-offer_accepted").html(data); // replace the contents of the offers input with the data that came from the server
}
});
});
</script>
{% endblock postloadjs %}
Thanks very much for any help anyone can give.
In my django project, I have an HTML that renders questions header, and inside the question headers I have question items. In my model, Question headers and items are two different entities. I need to show for every header, just the items related to that header. As it shows all items for all questions without any filters. Greatly appreciate any help!
Model:
class Question(models.Model):
question = models.CharField(max_length=240)
mission_section = models.ForeignKey('Mission_Section', on_delete=models.CASCADE)
type_question = models.ForeignKey('Type_Question', on_delete=models.CASCADE)
categories_question = models.ForeignKey('Categories_Question', on_delete=models.CASCADE, default=1)
order = models.IntegerField(default=1)
def __str__(self):
return self.question
class Question_Option(models.Model):
question = models.ForeignKey('Question', on_delete=models.CASCADE,default=1)
option = models.CharField(max_length=240)
correct = models.BooleanField()
order = models.IntegerField(default=1)
View:
class Questions(LoginRequiredMixin, FormView):
template_name = "questions.tmpl"
def get(self, request, pk):
context = {
'pk': pk,
'section': Mission_Section.objects.get(pk = pk ),
'questions_items': Question_Option.objects.filter(question__mission_section__pk=pk).order_by('order','pk'),
'questions': Question.objects.filter(mission_section__pk = pk ),
'question_types' : Type_Question.objects.all(),
'questions_categories': Categories_Question.objects.all()}
return render(self.request, self.template_name, context)
HTML
<input type="hidden" class="form-control" id="section" name="section" value="{{section.id}}" required>
<h1>{{ section.name }}</h1>
<div id="contentDiv">
<ol>
{% for question in questions %}
<div name="question" class="form-group" id="question-{{question.id}}" >
<form class='my-ajax-form' id="form-question-{{question.id}}" method='GET' action='.' data-url='{{ request.build_absolute_uri|safe }}'>
<li><div class="input-group">
{% csrf_token %}
{{ form.as_p }}
<input type="text" value= "{{question.id}}" id="question" name="question-hidden" class="form-control">
<input type="text" value= "{{question.question}}" id="question_name_{{question.id}}" class="form-control" aria-label="Amount" onchange="UpdateQuestion({{question.id}})">
</div>
</form>
<br>
<!-- Options -->
<div id = "question_content_{{question.id}}" name="question-options" class="collapse">
<ol class="example list-group">
{% for qi in questions_items %}
<li class="list-group-item d-flex justify-content-between align-items-center" id={{qi.id}} name="opt-{{question.id}}-{{qi.id}}" onclick="setCorrect({{qi.id}},{{question.id}})" contenteditable="true">{{ qi.option }}
<span class="badge badge-warning badge-pill">-</span>
</li>
{% endfor %} </ol>
<div>
<div class="d-flex justify-content-center">Add Option</div>
<div class="d-flex justify-content-center"> <br><i class="fa fa-plus-circle fa-1x" aria-hidden="true"></i></div>
</div>
</div>
</div></li>
{% endfor %} </ol>
using this answer I figured it out Double loop in Django template
What I need is:
<div id = "question_content_{{question.id}}" name="question-options" class="collapse">
{% csrf_token %}
{{ form.as_p }}
<form class='ajax-form-option' id="form-option-{{question.id}}" method='GET' action='.' data-url='{{ request.build_absolute_uri|safe }}'>
<ol class="example list-group">
{% for qi in question.question_option_set.all %}
<li class="list-group-item d-flex justify-content-between align-items-center" id=option-{{qi.id}} name="opt-{{question.id}}-{{qi.id}}">
<div contenteditable="true">{{ qi.option }}</div>
<div>
<button type="button" name='option-check' class="btn btn-light" value={{qi.id}} id="check-option-{{question.id}}-{{qi.id}}">
<i class="fas fa-check"></i>
</button>
<button type="button" class="btn btn-warning" id="delete-option-{{question.id}}-{{qi.id}}" onclick="deleteOption({{qi.id}})">
<i class="fa fa-trash" aria-hidden="true"></i>
</button>
</div>
</li>
{% endfor %} </ol>
<div onclick="CreateOption({{question.id}})">
<div class="d-flex justify-content-center">Add Option</div>
<div class="d-flex justify-content-center"> <br><i class="fa fa-plus-circle fa-1x" aria-hidden="true"></i></div>
</div>
</form>
I am implementing search by two fields in form in Django.
I want to keep input data after search.
For example I input "C++" and chose "IT"
then I received Default values
I tried to parse request variable --- e.g. data = request.POST.copy()
but did not achieved result. What is the reason of this problem?
How can I solve this problem?
This is my code:
models.py
class Company(models.Model):
name = models.CharField(max_length=200)
about = models.TextField()
def __str__(self):
return self.name
class Vacancy(models.Model):
company_key = models.ForeignKey(Company, on_delete=models.CASCADE)
title = models.CharField(max_length=200)
salary = models.CharField(max_length=200, default='40.000')
text = models.TextField(default="The text about vacancy")
city = models.CharField(max_length=200, default='Москва')
date_str = models.CharField(max_length=50, default='12 сентября')
created_date = models.DateTimeField(default=timezone.now)
published_date = models.DateTimeField(blank=True, null=True)
CHOICES = [
('ALL', 'ALL'),
('IT', 'IT'),
('FINANCE', 'FINANCE'),
('OTHER', 'OTHER'),
]
department = models.CharField(
max_length=20,
choices=CHOICES,
default='ALL',
)
def publish(self):
self.published_date = timezone.now()
self.save()
def __str__(self):
return self.title
urls.py
urlpatterns = [
path('', HomePageView.as_view(), name='vacancy_list'),
path('search/', SearchResultsView.as_view(), name='search_results'),
path('vacancy/<int:pk>/', views.vacancy_detail, name='vacancy_detail'),
path('accounts/login/', BBLoginView.as_view(), name='login'),
path('accounts/profile/', profile, name='profile'),
path('accounts/logout/', BBLogoutView.as_view(), name='logout'),
views.py
class HomePageView(ListView):
model = Vacancy
template_name = 'vacancy_list/vacancy_list.html'
paginate_by = 2
page_kwarg = 'vacancy'
context_object_name = 'vacancies'
def vacancy_detail(request, pk):
vacancy = get_object_or_404(Vacancy, pk=pk)
return render(request, 'vacancy_list/vacancy_detail.html', {'vacancy': vacancy})
class SearchResultsView(ListView):
model = Vacancy
template_name = 'vacancy_list/search_results.html'
paginate_by = 2
page_kwarg = 'vacancy'
context_object_name = 'vacancies'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['query'] = self.request.GET.get('q')
# added param
context['query2'] = self.request.GET.get('q2')
return context
def get_queryset(self): # new
query = self.request.GET.get('q')
query2 = self.request.GET.get('q2')
object_list = Vacancy.objects.filter(
Q(title__icontains=query) and Q(department__icontains=query2)
)
return object_list
vacancy_list.html
{% block content %}
<div class="container col-md-8" style="margin:20px;">
<div class="container" style="margin-top: 40px; font-size: 2rem; padding-left: 0px;">
<form action="{% url 'search_results' %}" method="get">
<div class="row">
<div class="col-lg-8 col-md-6 col-xs-12">
<input name="q" type="text" placeholder="Search..." class="form-control">
</div>
<div class="col-lg-3 col-md-4 col-xs-12">
<select name="q2" class="form-control" id="exampleFormControlSelect1">
<option>ALL</option>
<option>IT</option>
<option>Finance</option>
<option>Other</option>
</select>
</div>
<div class="col-lg-1 col-md-2 col-xs-12" style="padding-left: 0px;">
<button class="btn btn-primary">Primary</button>
</div>
</div>
</form>
</div>
{% for vacancy in vacancies %}
<div class="card">
<div class="card-header">
<div class="row">
<div class="col-md-8">
<h1>{{vacancy.title}}</h1>
</div>
<div class="col-md-4 text-right">
<p> {{ vacancy.salary}} </p>
</div>
</div>
</div>
....
{% endfor %}
search_result.html
{% extends 'vacancy_list/base.html' %}
{% block content %}
<h1> {{request}}</h1>
<div class="container col-md-8" style="margin:20px;">
<div class="container" style="margin-top: 40px; font-size: 2rem; padding-left: 0px;">
<form action="{% url 'search_results' %}" method="get">
<div class="row">
<div class="col-lg-8 col-md-6 col-xs-12">
<input name="q" type="text" placeholder="Search..." class="form-control">
</div>
<div class="col-lg-3 col-md-4 col-xs-12">
<select name="q2" class="form-control" id="exampleFormControlSelect1">
<option>ALL</option>
<option>IT</option>
<option>Finance</option>
<option>Other</option>
</select>
</div>
<div class="col-lg-1 col-md-2 col-xs-12" style="padding-left: 0px;">
<button class="btn btn-primary">Primary</button>
</div>
</div>
</form>
</div>
{% for vacancy in vacancies %}
...
{% endfor %}
{% endblock %}
In your search results template, you should use {{ query }} and {{ query2 }} and a little bit of logic to populate the text and drop-down boxes.
When I register a new user the website was creating a profile automatically and was using default.jpg image. Suddenly it stopped working. And the error says that I have a problem with my 'image' field. This is the error I get:
IntegrityError at /accounts/register/
null value in column "image" violates not-null constraint
DETAIL: Failing row contains (20, pbkdf2_sha256$150000$72dkND5yT5M0$+/chH/5Vu76KM7oNMjU694EWFZ/p+B..., null, f, kazanda, f, 2019-04-21 17:41:29.969889+00, Andreas, Swarchft, Germany, Frankfurt, andreas_sw#gmail.com, t, null).
This is my models.py
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
image = models.ImageField(default='default.jpg', upload_to='profile_pics', null=True)
def __str__(self):
return self.user.username
def save(self, force_insert=False, force_update=False, using=None):
super().save()
img = Image.open(self.image.path)
if img.height > 250 or img.width > 250:
output_size = (250, 250)
img.thumbnail(output_size)
img.save(self.image.path)
def create_profile(sender, **kwargs):
if kwargs['created']:
user_profile = Profile.objects.create(user=kwargs['instance'])
post_save.connect(create_profile, sender=User)
my views.py
class UserRegistrationView(SuccessMessageMixin, CreateView):
form_class = UserCreationModelForm
model = User
success_url = reverse_lazy('login')
success_message = "Account for %(first_name)s was created successfully. You will get email notification when admin will activate your account!"
template_name = 'users/registration.html'
def get_success_message(self, cleaned_data):
return self.success_message % dict(cleaned_data)
#login_required
def profile(request):
if request.method == 'POST':
uform = UserUpdateForm(request.POST, instance=request.user)
pform = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile)
posts = Post.objects.filter(author=request.user)
if uform.is_valid() and pform.is_valid():
uform.save()
pform.save()
messages.success(request, 'Your account has been updated!')
return redirect('users:cabinet')
else:
uform = UserUpdateForm(instance=request.user)
pform = ProfileUpdateForm(instance=request.user.profile)
posts = Post.objects.filter(author=request.user)
context = {
'uform': uform,
'pform': pform,
'posts': posts
}
return render(request, 'users/user_detail.html', context)
#login_required
def cabinet(request):
profile = Profile.objects.all()
context = {
'profile': profile
}
return render(request, 'users/user_detail.html', context)
my registration.html
which is a form to create a user:
{% extends 'shared/base.html' %}
{% load staticfiles %}
{% load crispy_forms_tags %}
{% block content %}
<div class="content-section mt-5 pl-5 p-4">
<form method="post">
{% csrf_token %}
<fieldset class="form-group pr-4">
<legend class="mb-4">Join Today</legend>
<div class="form-row">
<div class="form-group col-md-3 mb-0">
{{ form.first_name|as_crispy_field }}
</div>
<div class="form-group col-md-3 mb-0">
{{ form.last_name|as_crispy_field }}
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6 mb-0">
{{ form.username|as_crispy_field }}
<div class="form-row">
<div class="form-group col-md-6 mb-0">
{{ form.country|as_crispy_field }}
</div>
<div class="form-group col-md-6 mb-0">
{{ form.city|as_crispy_field }}
</div>
<div class="form-row">
<div class="form-group col-md-12 mb-0">
{{ form.email|as_crispy_field }}
</div>
<div class="form-row">
<div class="form-group col-md-6 mb-0">
{{ form.password1|as_crispy_field }}
</div>
<div class="form-group col-md-6 mb-0">
{{ form.password2|as_crispy_field }}
</div>
<!-- <div class="form-check">
{{ form.access_challenge }}
<label class="form-check-label" for="Checkbox"> Access Challenge Country</label>
</div> -->
</fieldset>
<div class="form-group">
<button style="border-radius: 0; width: 200px; padding-left: 4px;" class="btn btn-info btn-block" type="submit">Sign Up</button>
</div>
</form>
<div class="border-top pt-3">
<small class="text-muted">
Already Have An Account? <a class="ml-2" href="{% url 'login' %}">Sign In</a>
</small>
</div>
</div>
{% endblock %}
Here is my post_form.html
{% extends 'shared/base.html' %}
{% load staticfiles %}
{% load crispy_forms_tags %}
{% block content %}
<div class="content-section mt-5 pl-5 p-4">
<form method="post" id="personForm" data-cities-url="{% url 'users:ajax_load_cities' %}" novalidate>
{% csrf_token %}
<fieldset class="form-group">
<legend class="mb-4">Church Info</legend>
<div class="form-row">
<div class="form-group col-md-3 small">
{{ form.area|as_crispy_field }}
</div>
<div class="form-group col-md-3 small">
{{ form.country|as_crispy_field }}
</div>
</div>
<div class="form-row">
<div class="form-group col-md-3 small">
{{ form.name|as_crispy_field }}
</div>
<div class="form-group col-md-3 small">
{{ form.city|as_crispy_field }}
</div>
</div>
<div class="form-row">
<div class="form-group col-md-3 small">
{{ form.email|as_crispy_field }}
</div>
<div class="form-group col-md-3 small">
{{ form.website|as_crispy_field }}
</div>
</div>
<div class="form-row">
<div class="form-group col-md-3 small">
{{ form.address|as_crispy_field }}
</div>
<div class="form-group col-md-3 small">
{{ form.phone|as_crispy_field }}
</div>
</div>
<div class="form-row">
<div class="form-group col-md-3 small">
{{ date_posted }}
</div>
<div class="form-group col-md-3 small">
{{ author }}
</div>
</div>
<div class="form-group">
<button style="border-radius: 0; width: 200px; padding-left: 4px;" class="btn btn-info btn-block" type="submit">Submit</button>
</div>
</form>
<div class="border-top pt-3">
<small class="text-muted">
Already Have An Account? <a class="ml-2" href="{% url 'login' %}">Sign In</a>
</small>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
$("#id_area").change(function () {
var url = $("#personForm").attr("data-cities-url");
var areaId = $(this).val();
$.ajax({
url: url,
data: {
'area': areaId
},
success: function (data) {
$("#id_country").html(data);
}
});
});
</script>
{% endblock %}
Here is my forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from django.contrib.auth import get_user_model
from .models import Profile, Post, User, Country
class UserCreationModelForm(UserCreationForm):
class Meta:
model = User
fields = ['username', 'first_name', 'last_name', 'country', 'city', 'email', 'password1', 'password2']
class UserUpdateForm(forms.ModelForm):
username = forms.CharField()
email = forms.EmailField()
class Meta:
model = User
fields = ['username', 'first_name', 'last_name', 'country', 'city', 'email']
class ProfileUpdateForm(forms.ModelForm):
class Meta:
model = Profile
fields = ['image']
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ('name', 'area', 'country', 'city', 'address', 'email', 'phone', 'website')
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['country'].queryset = Country.objects.none()
if 'area' in self.data:
try:
area_id = int(self.data.get('area'))
self.fields['country'].queryset = Country.objects.filter(area_id=area_id).order_by('name')
except (ValueError, TypeError):
pass # invalid input from the client; ignore and fallback to empty City queryset
elif self.instance.pk:
self.fields['country'].queryset = self.instance.area.country_set.order_by('name')