I am sure that I'm being very dense, but have spent days trying to work out what I've done wrong.
I have
installed django-crispy-forms (using pip)
added 'CRISPY_TEMPLATE_PACK' to my settings
added 'crispy_forms' to my applications
done a 'collectstatic' from the downloaded tar file (since templates and CSS aren't included in the pip)
added '{% crispy_forms_tags %} to my form html file
imported from crispy_forms.helper and crispy_forms.layout to my forms.py
I'm using Bootstrap 3, which I'm coding directly rather than using bootstrap-toolkit
The Bootstrap renders fine on all my pages and so do the form fields, but the buttons won't appear.
My html is as follows:
{% extends 'base.html' %}
{% load crispy_forms_tags %}
<html>
<title>Add Guest</title>
<div class='container'>
{% block col1 %}
<div class='row'>
<div class="span3">
{% endblock %}
{% block col2 %}
<div class="span9">
<ul>
{% crispy form %}
</ul>
</div><!--/span9-->
{% endblock %}
</div><!--row-->
</div><!--/container-->
</html>
If I change the crispy tag to {% crispy MyForm MyForm.helper %} I get 'VariableDoesNotExist at' plus a continuous of many (real) languages. Rendered as above the form fields appear but not the button.
My forms.py looks like this:
from django.forms import ModelForm
from django import forms
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Fieldset, ButtonHolder, Submit
from .models import Author
class NewAuthorForm(forms.ModelForm):
class Meta:
model = Author
# If you pass FormHelper constructor a form instance
# It builds a default layout with all its fields
helper = FormHelper()
helper.form_method = 'post'
helper.add_input(Submit('save', 'save', css_class = 'btn-primary'))
I know that there's some redundancy here in terms of imports, but figure that isn't the problem.
Lastly, my base.html is:
<!DOCTYPE html>
<html>
<head>
<title>Bootstrap 101 Template</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Bootstrap -->
<link href="{{ STATIC_URL }}css/bootstrap.min.css" rel="stylesheet">
<!-- note that there’s also blue.uni-form.css and dark.uni-form.css available if you want to try chan-->
<link rel="stylesheet" href="{{ STATIC_URL }}crispy_forms/static/uni_form/uni-form.css" type="text/css" />
<link rel="stylesheet" href="{{ STATIC_URL }}crispy_forms/static/uni_form/default.uni-form.css" type="text/css" />
<!-- uni-form JS library, optional -->
<script src="{{ STATIC_URL }}crispy_forms/static/uni_form/uni-form.jquery.js" type="text/javascript"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class='container'>
{% block col1 %}
<div class='row'>
<div class="span3">
{% endblock %}
{% block col2 %}
<div class="span9">
</div><!--/span9-->
{% endblock %}
</div><!--row-->
</div><!--/container-->
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://code.jquery.com/jquery.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="{{ STATIC_URL }}js/bootstrap.min.js"></script>
</body>
</html>
I've put the crispy form templates in my templates folder, which is at the same level as manage.py. As I say, all the bootstrap renders fine.
I'm stumped. Any ideas gratefully received
I have absolutely no idea why, but somehow removing
from __future__ import absolute_import
from views fixed the issue for me and now my buttons are showing up.
P.S Found this question, googling for a solution and decided to signup and hopefully help the next one with such a problem :).
It's an old post, but if I made it here on my searches, it's likely someone else will.
I'm using Django 1.11.9 and django-crispy-forms 1.7.0. You're on the right track, you actually want to add the 'submit' button in init for the class, not within Meta.
See below:
from django.forms import ModelForm
from django import forms
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Fieldset, ButtonHolder, Submit
from .models import Author
class NewAuthorForm(forms.ModelForm):
class Meta:
model = Author
def __init__(self, *args, **kwargs):
super(NewAuthorForm, self).__init__(*args, **kwargs)
# If you pass FormHelper constructor a form instance
# It builds a default layout with all its fields
self.helper = FormHelper()
self.helper.form_method = 'post'
self.helper.add_input(Submit('save', 'save', css_class = 'btn-primary'))
http://django-crispy-forms.readthedocs.io/en/latest/crispy_tag_forms.html#fundamentals
Related
I am using Django version 3.0 to create a sign up application for various departments at my school. I have connected the form to a model and the model is stored in a postgressql database. After I start the server using python manage.py runserver and I complete the form and click save, the form refreshes and I get the OK HTTP Code 200 from the server accessed through the terminal, but when I query the postgressql database using pg Admin interface the data has not been stored. Can anyone see where I am going wrong? This process worked before, I'm not sure if the data is just being stored in another table. Please help out if you can.
This is my base.html file:
{% load static %}
<!DOCTYPE html>
<html>
<head>
<title>Signup Prototype</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
<link href='//fonts.googleapis.com/css?family=Lobster&subset=latin,latin-ext' rel='stylesheet' type='text/css'>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="{% static 'js/jquery.js' %}"></script>
<link rel="stylesheet" href="{% static 'css/bootstrap.css' %}">
<script src="{% static 'js/bootstrap.js' %}"></script>
<link type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.6/themes/redmond/jquery-ui.css" rel="Stylesheet" />
<script language="javascript" type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.6/jquery-ui.min.js"></script>
<script type="text/javascript">
$(function(){
$("#id_date").datepicker();
});
</script>
{{form.media}}
</head>
<body>
<header class="page-header">
<div class="container">
<a href="{% url 'Engineering' %}" class="top-menu">
</a>
<h1>Signup </h1>
</div>
</header>
<main class="content container">
<div class="row">
<div class="col">
{% block content %}
{% endblock %}
</div>
</div>
</main>
</body>
</html>
This is my engineering.html file that displays the form
<html>
{% extends 'base.html' %}
{% load static %}
{% block content %}
<h2>Engineering</h2>
<form method="POST" class="engineering-form">{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="save btn btn-default">Save</button>
</form>
{% endblock %}
<html>
This is my .views file:
from django.shortcuts import render
from .forms import Engineering
def engineering(request):
form = Engineering()
return render(request, 'my_app/engineering.html', {'form': form})
This is my form
class Engineering(forms.ModelForm):
name = forms.CharField(label="Name")
etoken_user = forms.BooleanField(required = False, label="Etoken Use")
mfa_use = forms.BooleanField(required = False, label="MFA Use")
usage_type = forms.CharField(label="Usage Type")
email = forms.EmailField(label="Email")
user_id = forms.CharField(label="USERid")
date = forms.DateTimeField(label="Date") # date just time stamp the date they are using
class Meta: #tells django which model should be used to create the form
model = Engineering
fields = ('name','etoken_user', 'mfa_use','usage_type','email','user_id','date')
widgets = {
'datetime':DateTimeWidget(attrs={'id':'UTC' },usel10n=True, bootstrap_version=4)
}
this is the model
class Engineering(models.Model):
user_name = models.CharField(max_length = 100)
etoken_use = models.BooleanField()
mfa_use = models.BooleanField()
usage_type = models.CharField(max_length = 100)
date_recorded = models.DateTimeField(auto_now_add = True)
email = models.EmailField(max_length = 150)
user_id = models.CharField(max_length = 20)
As the earlier answer noted, you are not doing anything with the data posted from the forms in the view.
from django.shortcuts import render
from .forms import Engineering
def engineering(request):
form = Engineering()
if request.method == 'POST':
form = Engineering(request.POST)
if form.is_valid():
form.save()
# probably a redirect over here.
return render(request, 'my_app/engineering.html', {'form': form})
yes, because your view does not do anything with the data on POST.
See https://docs.djangoproject.com/en/3.0/topics/forms/#the-view
I am using Django 3.0 and python 3.8.2 to develop an ads website. To add a post, I used Django formtools wizard. It worked and everything goes nicely. I could save the multiform data. However, I could not retrieve the files from the FileSystemStorage so I can save them. Hence, any help to achieve this or suggestion is much appreciated. I want to retrieve uploaded files, save them to the data base and then delete them from the wizard (from the FileSystemStorage). Note: there is no error and everything is working except that the uploaded files are not saved to the data base even though they are available in the FileSystemStorage. Thus, I want to retrieve them to be able to save them to the data base.
Here is the view class:
TEMPLATES = {"CommonForm": "towns/salehslist/ads_main_form.html",
"JobForm": "towns/salehslist/forms/jobPostForm.html",
}
FORMS = [
("CommonForm", CommonForm),
("JobForm", JobForm, JobImagesForm),
]
class PostWizard(SessionWizardView):
# The form wizard itself; will not be called directly by urls.py,
# but rather wrapped in a function that provide the condition_dictionary
_condition_dict = { # a dictionary with key=step, value=callable function that return True to show step and False to not
"CommonForm": True, # callable function that says to always show this step
"JobForm": select_second_step, # conditional callable for verifying whether to show step two
}
file_storage = FileSystemStorage(
location=os.path.join(settings.MEDIA_ROOT, "photos")
)
def get_template_names(self):
return [TEMPLATES[self.steps.current]]
def done(self, form_list, form_dict, **kwargs):
# form_data = [form.cleaned_data for form in form_list]
# print(form_data)
data = {k: v for form in form_list for k, v in form.cleaned_data.items()}
data["posted_by"] = self.request.user
instance = Job.objects.create(**data)
print("YOU ARE HERE")
print(self.request.FILES.getlist("files"))
for file in self.request.FILES.getlist("files"):
print(file)
img_instance = JobImages.objects.create(job=instance, images=file)
img_instance.save()
return HttpResponse("<h1>Post Page </h1>")
Here is the url:
url(r'^post/$', PostWizard.as_view(FORMS, condition_dict = PostWizard._condition_dict)),
Here is the html template:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
{% load static %}
{% load crispy_forms_tags %}
{% load i18n %}
<script type="text/javascript" src="{% static 'towns/assets/fontawesome-free-5-12-0-we/js/all.js' %}">
</script>
<link rel="stylesheet" type="text/css" href="{% static 'towns/assets/bootstrap-4.4.1/dist/css/bootstrap.min.css' %}">
<link rel="stylesheet" type="text/css" href="{% static 'towns/assets/fontawesome-free-5-12-0-we/scc/fontawesome.min.css' %}">
<!-- file uploader font -->
<link type="text/css" rel="stylesheet" media="all" href="{% static 'towns/assets/fileuploader-2.2/dist/font/font-fileuploader.css' %}" >
<link rel="stylesheet" type="text/css" href="{% static 'towns/style/forms/jobPostForm.css' %}">
</head>
<body>
<div class="container">
<div class="row h-100">
<div class="col-lg-6 my-auto">
<div class="breadcrumb">
<div class="ads-form-title">
Job Post
</div>
</div>
<form class="" action="" method="POST" enctype="multipart/form-data" novalidate id="jobPost">
{% csrf_token %}
{{ wizard.management_form }}
{{ wizard.form.media }}
<hr>
<div class="form-group">
<div>
{{ wizard.management_form }}
{% if wizard.form.forms %}
{{ wizard.form.management_form }}
{% for form in wizard.form.forms %}
{{ form|crispy }}
{% endfor %}
{% else %}
{{ wizard.form|crispy }}
{% endif %}
</div>
</div>
<hr>
<!-- upload images -->
<!-- file input -->
<input type="file" name="files" class="files">
<center>
<button type="submit" class="btn btn-primary" style="position:relative; width: 33%; height: 100%;"> Submit </button>
</center>
</form>
</div>
</div>
</div>
<script type="text/javascript" src=" {% static 'towns/assets/jquery-3.5.0.min.js' %}">
</script>
<script type="text/javascript" src=" {% static 'towns/assets/bootstrap-4.4.1/dist/js/bootstrap.min.js' %}">
</script>
<script type="text/javascript" src="{% static 'towns/assets/fileuploader-2.2/dist/jquery.fileuploader.min.js' %}" >
</script>
</body>
</html>
When user hit submit button of the form wizard, def post() method is called. def post() will
validate the form and
save data and files into session.
then if the current page is the last page, it will
render_done, which is def done()
The reason why your request.files is empty is because, the current request does not have files or data associated with it. All your data and files are saved to the session when you hit the submit buttons which are preceding the done() method.
Since I do not know how your form is structured, I am not sure how to definetely solve your problem. But something like below should do:
# iterate over all forms in the form_list
for form in form_list:
# check if current form has files
if bool(self.get_form_step_files(form)):
# if yes, do something
uploadedfiles = form.files
print(uploadedfiles)
for key, value in uploadedfiles.items():
jobimage = JobImage(job=?, image=value)
jobimage.save()
Update
wihtout your model, form structure, and template, it is difficult to come out with complete solution. I am posting a minimum working example.
1. in models.py
class MyPost(models.Model):
field1 = models.CharField(max_length=50)
field2 = models.CharField(max_length=50)
class Photo(models.Model):
mypost = models.ForeignKey(MyPost, on_delete=models.CASCADE)
photo = models.FileField(blank=True, null=True)
2. In forms, you will not include photoform, because you are trying to uplaod more than one images.
from .models import MyPost, Image
from django import forms
class step_first_form(forms.ModelForm):
class Meta:
model = MyPost
fields = ['field1']
class step_second_form(forms.ModelForm):
class Meta:
model = MyPost
fields = ['field2']
in template, you can keep your first template same as whatever you have. For the second one, say, you will have MyPost's field2 and 2 image inputs, you will change it to:
<form action="" method="post" enctype="multipart/form-data">{% csrf_token %}
<table>
{{ wizard.management_form }}
{% if wizard.form.forms %}
{{ wizard.form.management_form }}
{% for form in wizard.form.forms %}
{{ form }}
{% endfor %}
{% else %}
{{wizard.form.field2}}
<input type="file" name ="imagefile1" >
<input type="file" name ="imagefile2" >
{% endif %}
</table>
.......
.....
.....
</form>
make sure you include enctype="multipart/form-data" otherwise your files will not be uploaded.
make sure you have different names for filefield otherwise only one
will be saved to your model.
4. in views.py
def done(self, form_list, form_dict, **kwargs):
data = [form.cleaned_data for form in form_list]
# you can print out and inspect this data, and you will know
# the below code.
# you will need to modify data[0]['field1'] etc ...
print(data)
mypost = MyPost()
mypost.field1 = data[0]['field1']
mypost.field2=data[1]['field2']
mypost.save()
print('mypost')
print(mypost)
# the below part is for saving image files to model
for form in form_list:
# check which form has files
if bool(self.get_form_step_files(form)):
uploadedfiles= form.files
print(form.files)
for key, value in uploadedfiles.items():
photo = Photo(mypost=mypost,photo=value)
photo.save()
else:
print('not bool')
return render ##### whatever template you want to render
I am trying to create a dropdown of countires which can be searchable based on this doc, however almost disappointed to find any solution by googling.
I am using django-cities-light package and django-autocomplete-light, and all I need to do is creating a field of countries/cities and populating it in a form and making it searchable,
in setting.py and installed apps:
INSTALLED_APPS = [
'dal',
'dal_select2',
'app.apps.MyownAppConfig',
'users.apps.UsersConfig',
'crispy_forms',
'tinymce',
'cities_light',
'django.contrib.admin',
'django.contrib.auth',
...
]
in models.py:
from tinymce.models import HTMLField
from cities_light.models import Country
class Post(models.Model):
...
descript = HTMLField(blank=True, null=True)
location = models.ForeignKey(Country, blank=True, null=True, on_delete=models.CASCADE)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('post-detail', kwargs={'pk': self.pk})
in views.py:
class CountryAutocomplete(LoginRequiredMixin, autocomplete.Select2QuerySetView):
def get_queryset(self):
if not self.request.user.is_authenticated:
return Country.objects.none()
qs = Country.objects.all()
if self.q:
qs = qs.filter(name__icontains=self.q)
return qs
In forms.py:
class postform(forms.ModelForm):
class Meta:
model = Post
fields ='__all__'
exclude = ['date_published']
widgets = {
'location': autocomplete.ModelSelect2(url='country-autocomplete' , attrs={'data-placeholder': 'select location...', 'data-minimum-input-length': 4})
}
search_fields = ['name']
and in postform.html:
{% extends "app/base.html" %}
{% load crispy_forms_tags %}
{% load static %}
{% block content %}
<main>
<form id="dropdownForm" method="POST" action="" enctype="multipart/form-data">
<fieldset class="form-group">
{% csrf_token %}
<div class="content-section">
{{ form.descript }}
<label>location</label>
{{ form.location }}
</div>
</fieldset>
</form>
</main>
<script type="text/javascript" src="{% static 'admin/js/vendor/jquery/jquery.js' %}"></script>
{{ form.media }}
{% endblock content %}
and in url.py:
urlpatterns = [path('country-autocomplete/', CountryAutocomplete.as_view(model=Country), name='country-autocomplete')]
But what I get is this:
Moreover, in terminal I see this msg:
"GET /static/vendor/select2/dist/css/select2.css HTTP/1.1" 404 1832
I also had a look to all available questions in SO, including this one, but didn't help that much. Could you please help me with this problem a bit?
This is a weird error to me. If you are using venv, try to remove the django-autocomplete-light folder and again replace it with a new one, and then check if you still get the same error! Also in your base.html file, make sure the .js links are in order, because extra script could be loaded on the top of the previews one, so the developer should take care of them. It should be something like:
<script type="text/javascript" src="{% static 'admin/js/vendor/jquery/jquery.js' %}"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"</script>
<link href="{% static '/autocomplete_light/select2.css' %}" type="text/css" media="all" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2#4.1.0-beta.1/dist/js/select2.min.js"></script>
Try to use webkit inspector to check if jquery is not loaded twice.
I am working on a Django Project, where a student will write his/her course name in a form and click on Calculate button and the system will use the Fuzzy Logic to calculate the performance of students based on the details of that specific course and then show the result of that calculation below the Calculate Button.
What I have done so far are below.
views.py:
from django.shortcuts import render, redirect
from django.contrib import messages
from .forms import PerformanceCalculatorForm
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from .models import Subject, Detail
from .fuzzy_logic_algo import fuzz_algo
def performanceCalculator(request):
if request.method == 'POST':
performance_form = PerformanceCalculatorForm(request.POST)
if performance_form.is_valid():
sub = performance_form.cleaned_data.get('subject')
skype = Details.objects.filter(subject__subject=sub, user__username=User.username).get('skype_session_attendance')
internal_course = Details.objects.filter(subject__subject=sub, user__username=User.username).get('internal_course_marks')
prg_lab = Details.objects.filter(subject__subject=sub, user__username=User.username).get('programming_lab_activity')
mid_marks = Details.objects.filter(subject__subject=sub, user__username=User.username).get('mid_term_marks')
final_marks = Details.objects.filter(subject__subject=sub, user__username=User.username).get('final_term_marks')
result = fuzz_algo(skype, internal_course, prg_lab, mid_marks, final_marks)
context = {
'result': result,
}
return render(request, 'users/performance_calculator.html', context)
else:
performance_form = PerformanceCalculatorForm()
return render(request, 'users/performance_calculator.html', {'performance_form': performance_form})
models.py:
from django.db import models
from django.contrib.auth.models import User
from PIL import Image
class Subject(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
subject = models.CharField(max_length=100)
def __str__(self):
return '{} ({})'.format(self.subject, self.user.username)
class Detail(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
subject = models.OneToOneField(Subject, on_delete=models.CASCADE)
skype_session_attendance = models.FloatField()
internal_course_marks = models.FloatField()
programming_lab_activity = models.FloatField()
mid_term_marks = models.FloatField()
final_term_marks = models.FloatField()
def __str__(self):
return f'{self.subject, (self.user.username)} Details'
forms.py:
from django import forms
class PerformanceCalculatorForm(forms.Form):
class Meta:
fields = ['subject']
performance_calculator.html:
{% load static %}
<!DOCTYPE html>
<html>
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="{% static 'esacp/main.css' %}">
<title>Expert System for Assessing Programming Course Performance</title>
</head>
<body>
<main role="main" class="container">
<div class="row">
<div class="col-md-8">
{% if messages %}
{% for message in messages %}
<div class="alert alert-{{ message.tags }}">
{{ message }}
</div>
{% endfor %}
{% endif %}
{% if not request.user.is_superuser and not request.user.is_staff %}
<div class="account-heading">
<h2>
Performance Calculator
</h2>
</div>
<div class="content-section">
<form method="POST">
{% csrf_token %}
<fieldset class="form-group">
<legend class="border-bottom mb-4">Profile</legend>
{{ performance_form|crispy }}
{{ result }}
</fieldset>
</form>
</div>
{% endif %}
</div>
</div>
</main>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
</body>
</html>
Can anyone tell me that how would I accomplish it that a user (student) enters the course name in the form when he/she is on .../performance_calculator.html, his record is saved, and matched with the courses assigned to him, after the matched, the activity details of student that course is taken and those are assigned to separate variables, the those variables are passed to fuzz_algo() function, then the result of that function is printed on the Front End?
I have been working on it since 2 days and not getting it. Any help will be surely appreciated.
Let me go with some really problematic things first. Your PerformanceCalculator view, in the POST conditional, you never save() the form, and therefore your next queries will return empty objects, which I believe the fuzz_algo will return None (Assumption) and displays nothing on the render.
Actually best practice is: on the last line of your POST conditional, use redirect instead of render as it will load you again the page without the POST data.
And I think that all the above thing you have tried already (because you said you tried 2 days), but wonder why it still renders nothing, because by redirect it will ask again with a GET request and will lose the data in the variable result.
Now with the "not so important" thing, as I see in your code and you don't have intention of saving your form in database, this is probably a better approach on the Client Side instead of Server Side. To do it on the server side please check https://docs.djangoproject.com/en/3.0/topics/http/sessions/ to use sessions variables to keep it alive and not lose after redirect, also there is EASY work around (but doesn't work in all the cases) is to .. let's say "abuse" the messages library of django, it will pass a message to the client side on your next LOAD.
So on your views.py import the messages library and add this before redirect
messages.success(request, result)
Now in your template add this
{% if messages %}
{% for message in messages %}
{{ message }}
{% endfor %}
{% endif %}
I'm new to Django, but I think I did something similar to what you are trying to do.
1. With a model similar to yours - had the user fill out the form and then made sure the model was populated with the data from the form. I didn't realize at first that I needed to make sure every field in the form was filled out or nothing would be saved to the model. (It is in the docs, I just didn't pick up on it).
2. Then when I wanted to use the data in the model, I just made sure that the model was imported.I also imported a separate python file to perform the computation on the parameters.
Then in the view I assigned a variable = to the model object for example for the Model Search_Profile in my case I had
params=Search_Profile.objects.last()
since in my case I just wanted the last profile, but you could make it any object you wanted.
With that information I could then import the function from a .py file In my case
C=calculate(params.keyword_string,params.other_string)
At that point I could then render the template with both the parameters and whatever I needed from the calculation function in the .py file by using
return render(request,'mainapp/show_calculation.html',{'params':params,'new_entries':new_entries,'C':C})
It took me a while to figure that this worked, and maybe there are better ways, but it at least worked for what I was trying to do.
Looking at your code, I suspect you're a better coder than I am, but maybe the above might help. In your form you only have the subject field and don't have the user field. In my situation I think that led to my model not being filled.
The other thing I had to do to figure it out for my case was to get away from crispy forms or widget-tweeks, but I don't think that matters much.
So I have recently started looking into the Django framework, but it appends some white space in the top of my views even though the layout.html and layout.css is the same for each view.
layout.html
<html>
<head>
<meta charset="utf-8" />
{% load staticfiles %}
<link rel="stylesheet" type="text/css" href="{% static 'layout.css' %}" />
<link href='https://fonts.googleapis.com/css?family=Inconsolata' rel='stylesheet' />
</head>
<body>
<div class="content">
<div class="navbar">
Homepage.
Home
Projects
About
</div>
<div class="text">
{% block stuff %}
{% endblock %}
</div>
</div>
</body>
</html>
This is my views
def index(request):
return render(
request,
'home/index.html',
{
'greetings': "Welcome to my site!",
}
)
def about(request):
return render(
request,
'home/about.html',
{
'greetings': "Welcome to my site!",
}
)
home/index.html and home/about.html both look like
{% extends "layout.html" %}
{% block stuff %}
{{ greetings }}
{% endblock %}
about page pushed down
As seen in the image the view for the about.html page is push down, and I really cannot figure out why.
After inspecting the elements I found that for the about page, the header is added to the body tag.
inspecting the elements
Anyone who can help me out?
This is most likely because of CSS. To find out where the space is coming from, click on inspect element and choose select an element to inspect it. Then slightly move the mouse around the page until you find that space and click on it. You can then find out where the space is coming from in the Styles tab.
Also make sure there are no <br>tags in your html template
The view is certainly not the culprit here, it's just a python function which takes in a request and returns a response. The HTML looks fine too, check your CSS once again(or post it here) or you can always check the source code on your browser and inspect element the page through the Developer tools to check where the whitespace is coming from.