I'm using django filters but I can't get the filter form to actually render on the page, only the submit button is showing. If I inspect the element, nothing else seems to be being sent to the template. THere is no error message or anything, I don't know where to go from here, how do I get the actual form to show,
filter.py
from django.contrib.auth.models import User
import django_filters
from .models import Project
class ProjectFilter(django_filters.FilterSet):
class Meta:
model = Project
fields = ['user', 'title']
views.py:
def search_view(request):
project_list = Project.objects.all()
project_filter = ProjectFilter(request.GET, queryset=(project_list)
return render(request, 'project_portal/filter.html', {'filter': project_filter})
urls.py:
path('search/', search_view, name='search'),
html:
{% load crispy_forms_tags %}
<!DOCTYPE html>
<div>
<form method="get">
{{ filter.form.as_p }}
<input type="submit"/>
</form>
{% for user in filter.qs %}
{{ user.title }}
{% endfor %}
</div
i think your error ...
==> project_filter = ProjectFilter(request.GET, queryset=(project_list)
must be :
project_filter = ProjectFilter(request.GET, queryset=project_list)
Related
I'm trying to create a page that, once a form submit button is clicked, will redirect to the home page. I'm using the 'onsubmit' function for that, but it isn't working.
HTML code
{% extends 'base.html' %}{% load static %}
{% block head %}
<link rel="stylesheet" href="{% static 'login.css' %}" />
<script src="{% static 'login.js'}"></script>
{% endblock %}
<!-- page code -->
{% block pagename %}
<p>SIGN IN</p>
{% endblock %}
{% block content %}
<div class="contentContainer">
<p>Please enter your competition ID:</p>
<form class="form" onsubmit="pageSwitch()">
<input type="text" id="entry" placeholder="ID ENTRY HERE...">
<input type="submit" id="entrySubmit" value="SUBMIT">
</form>
</div>
{% endblock %}
JS Code
function pageSwitch(){
window.location.replace("{% url 'home' %}");
}
urls.py Code
from django.contrib import admin
from django.urls import path
from files import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('test/', views.test, name='test'),
path('', views.login, name='login'),
path('home/', views.home, name='home'),
path('leaderboard/', views.lboard, name='lboard'),
path('scorecard/', views.score, name='score'),
path('submit/', views.submit, name='submit'),
path('base/', views.base, name='base'),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
'views.py' Code
from django.shortcuts import render
# Create your views here.
def test(request):
return render(request, 'test.html')
def base(request):
return render(request, 'base.html')
def login(request):
return render(request, 'login.html')
def home(request):
return render(request, 'home.html')
def lboard(request):
return render(request, 'leaderboard.html')
def score(request):
return render(request, 'score.html')
def submit(request):
return render(request, 'submit.html')
def base(request):
return render(request, 'base.html')
I'm not really sure what else to try, I've been messing around with either using anchors and 'onclick' instead, but that hasn't worked either, so I'm a bit stuck. This is my first time using Django, so all of the other explanations I've found have been a bit too complex for me to understand, including things that aren't in my code that have thrown me off a bit.
When using a form's onsubmit event to call a function and redirect to another page, it's important to prevent the default form submission behavior, which can interfere with the redirect. One solution is to add an event parameter to the function, and then use event.preventDefault() to stop the form submission. For example:
<form onsubmit="myFunction(event)">
...
</form>
<script>
function myFunction(event) {
event.preventDefault();
window.location.replace('https://example.com');
}
</script>
This way, the preventDefault() method will be called before the form is submitted, ensuring that the redirect will happen immediately.
Why is the form not showing in the browser?
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>{{ structure.name }} - Details</title>
</head>
<body>
{% if error_message %}
<p><strong>{{ error_message }}</strong></p>
{% endif %}
<h3>Structure: {{ structure }}</h3>
<h3>Ajouter enregistrement</h3>
<form action="{% url 'Structure:addrecord' structure.id %}" method="post">
{% csrf_token %}
{% for structure in all_structures %}
<input type="radio" id="record{{ forloop.counter }}" name="record" value="record.id">
<label for="record{{ forloop.counter }}">
Nom de l'enregistrement: {{ record.record_name }}
</label>
{% endfor %}
</form>
</body>
</html>
When I test this in my browser, and inspect it, it gives me a form of this size: 1340px * 0 px.
I even explicitly gave a style="height: 500px", but it still gives me an empty form.
Here's a screenshot
Thanks for the help guys!
Edit:
Views.py:
from django.shortcuts import render, get_object_or_404
from .models import Structure, Record
def index(request):
all_structures = Structure.objects.all()
return render(request, 'Structures/index.html', {'all_structures': all_structures})
def detail(request, structure_id):
#structure = Structure.objects.get(pk=structure_id)
structure = get_object_or_404(Structure, pk=structure_id)
return render(request, 'Structures/details.html', {'structure': structure})
def addRecord(request, structure_id, record.name, record.type, record.pos, record.long):
r = Record(structure='structure_id', name='record.name', type='record.type', pos='str(record.pos)', long='str(record.long)')
r.save()
return render(request, 'Structures/details.html', {'structure': structure})
Also, I do not quite understand this yet because I am using a video tutorial series by thenewboston's channel, the variables I am using in addRecord are not known, and I want to use them from the model. Here are the models and urls files as well:
models.py:
from django.db import models
class Structure(models.Model):
name = models.CharField(max_length=120)
path = models.CharField(max_length=200)
def __str__(self):
return self.name
class Type(models.Model):
typename = models.CharField(max_length=50)
def __str__(self):
return self.typename
class Record(models.Model):
structure = models.ForeignKey(Structure, on_delete=models.CASCADE) #each structure has many records, each per line
name = models.CharField(max_length=200)
type = models.ForeignKey(Type)
pos = models.IntegerField()
long = models.IntegerField()
def __str__(self):
return self.name
urls.py:
from django.conf.urls import url
from . import views
app_name = 'Structure'
urlpatterns = [
# /structures/
url(r'^$', views.index, name='index'),
# /structures/id
url(r'^(?P<structure_id>[0-9]+)/$', views.detail, name='detail'),
# /structures/addrecord
url(r'^(?P<structure_id>[0-9]+)/addrecord/$', views.addRecord, name='addrecord'),
]
Look for the value of all_structures that you are passing in context from views.
If it is empty or not passed, form fields won't be displayed as per your template code.
Try to print its value either in the console or in template. That's how to Debug.
Hope this helps.
I have a django formset and I am trying to render it row by row. Instead, the form is being render column by column (like a vertical form instead of horizontal). I am using django's form.as_table but it is still not rendering correctly. Any ideads?
form.html:
<form id="formset" class="original" action="{% url 'inventory:requests' inventory.id %}" method="post">{% csrf_token %}
<!-- Add New Row -->
{{formset.management_form}}
{% for form in formset.forms %}
{{ form.non_field_errors }}
{{ form.errors}}
<div class='item'>
<table>{{ form.as_table }}</table>
<p style=""><a class="delete" href="#">Delete</a></p>
</div>
{% endfor %}
<p><a id="add" href="#">Add another item</a></p>
<input type="submit" name="submit" value="Request Blocks" id="submitButton">
</form>
The form's as_table method just uses <tr></td> instead of <div> to render your form - but it will be rendered visually the same way.
To easily get control over your form, consider using django-crispy-forms. Here is is how you would make your form render horizontally:
In your forms.py, add this (in addition to your normal code):
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit
class ExampleFormSetHelper(FormHelper):
def __init__(self, *args, **kwargs):
super(ExampleFormSetHelper, self).__init__(*args, **kwargs)
self.form_method = 'post'
self.render_required_fields = True
self.template = 'bootstrap/table_inline_formset.html'
self.add_input(Submit("submit", "Save"))
Next, in your views.py:
from .forms import ExampleFormsetHelper, YourFormSet
def formset_view(request):
formset = YourFormSet()
helper = ExampleFormSetHelper()
return render(request, 'template.html',
{'formset': formset, 'helper': helper})
Finally, in your template, all you need is:
{% load crispy_forms_tags %}
{% crispy formset helper %}
For more details, the documentation has the specifics.
I'm using Django to construct a simple personal website. I just built a basic email form. Here's the models.py file for it:
from django.db import models
class Message(models.Model):
name = models.CharField(max_length=200, unique=True)
email = models.EmailField(unique=True)
subject = models.CharField(max_length=100, unique=True)
message = models.CharField(max_length=1000, unique=True)
def __unicode__(self):
return self.name
And here is the corresponding forms.py file:
from django import forms
from rksite.models import Message
class EmailForm(forms.ModelForm):
name = forms.CharField(max_length=200,help_text="Name:")
email = forms.EmailField(help_text="Email:")
subject = forms.CharField(max_length=100, help_text="Subject:")
message = forms.CharField(max_length=1000, widget=forms.Textarea, help_text="Message:")
class Meta:
model = Message #link the model to the form
And finally, I'll also include the form's html page below:
{% extends 'rksite/base.html' %}
{% block title %}RaghavKumarContact{% endblock %}
{% block content %}
<h1>Contact Me</h1>
<br />
<form class="span6" id="email_form" method="POST" action="/home/contact/">
{% csrf_token %}
{% for field in form.visible_fields %}
{{ field.errors }}
{{ field.help_text }}
{{ field|linebreaks }}
{% endfor %}
<br />
<button class="btn btn-primary" type="submit" name="send">Send</button>
</form>
{% endblock %}
Now, no matter what I do, the "br/" tag shows up inside the "Message" Textarea field. Here's what I see on my webpage:
How can I get rid of this tag from this Textarea?
EDIT:
This is what it'll look like if I don't have the linebreaksfilter applied:
What is an alternative to the linebreaks filter??
Don't use linebreaks here:
{{ field|linebreaks }}
That renders the widget for the form, then passes the entire rendered HTML block through the linebreaks filter. That filter converts newlines into <br /> tags, and the rendering for a Textarea widget includes a newline before the text:
def render(self, name, value, attrs=None):
if value is None:
value = ''
final_attrs = self.build_attrs(attrs, name=name)
return format_html('<textarea{}>\r\n{}</textarea>',
flatatt(final_attrs),
force_text(value))
(Source from https://github.com/django/django/blob/master/django/forms/widgets.py#L435)
I'm not sure why you'd want to pass the field values though linebreaks - an HTML textarea should handle regular linebreaks in the message text just fine, if that's what you're worrying about.
I am trying to create a contact form for my Django site but it's not working properly. There are three steps to the contact form. Step 1 has a box where you input the subject of the email. Step 2 has a box where you input the sender's email address. At this point, there are three buttons- "first step", "prev step", and "submit". If I click "submit", the site doesn't take me to step 3, which is supposed to be where you input the body of the email. Instead, it reroutes me back to the Step 1 page.
I did my research and I can't find anything online related to this particular problem.
Here is my views.py file, which is located in the django_test/django_test directory:
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from django.contrib import auth
from django.core.context_processors import csrf
from forms import MyRegistrationForm
from django.contrib.formtools.wizard.views import SessionWizardView
from django.core.mail import send_mail
from django.core.urlresolvers import reverse
#import logging
#logr = logging.getLogger(__name__)
def login(request):
c = {}
c.update(csrf(request))
return render_to_response('login.html', c)
def auth_view(request):
username = request.POST.get('username', '')
password = request.POST.get('password', '')
user = auth.authenticate(username=username, password=password)
if user is not None:
auth.login(request, user)
return HttpResponseRedirect('/accounts/loggedin')
else:
return HttpResponseRedirect('/accounts/invalid')
def loggedin(request):
return render_to_response('loggedin.html',
{'full_name': request.user.username})
def invalid_login(request):
return render_to_response('invalid_login.html')
def logout(request):
auth.logout(request)
return render_to_response('logout.html')
def register_user(request):
if request.method == 'POST':
form = MyRegistrationForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/accounts/register_success')
args = {}
args.update(csrf(request))
args['form'] = MyRegistrationForm()
return render_to_response('register.html', args)
def register_success(request):
return render_to_response('register_success.html')
class ContactWizard(SessionWizardView):
template_name = "contact_form.html"
def done(self, form_list, **kwargs):
form_data = process_form_data(form_list)
return render_to_response('done.html', {'form_data': form_data})
def process_form_data(form_list):
form_data = [form.cleaned_data for form in form_list]
logr.debug(form_data[0]['subject'])
logr.debug(form_data[1]['sender'])
logr.debug(form_data[2]['message'])
send_mail(form_data[0]['subject'],
form_data[2]['message'], form_data[1]['sender'],
[(my email address], fail_silently=False)
return form_data
This my forms.py file, also located in the django_test/django_test directory:
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
class MyRegistrationForm(UserCreationForm):
email = forms.EmailField(required=True)
class Meta:
model = User
fields = ('username', 'email', 'password1', 'password2')
def save(self, commit=True):
user = super(UserCreationForm, self).save(commit=False)
user.email = self.cleaned_data['email']
if commit:
user.save()
return user
class ContactForm1(forms.Form):
subject = forms.CharField(max_length=100)
class ContactForm2(forms.Form):
sender = forms.EmailField()
class ContactForm3(forms.Form):
message = forms.CharField(widget=forms.Textarea)
And my contact_form.html file, located in the django_test/templates directory:
{% extends "base.html" %}
{% block content %}
<h2>Contact Us</h2>
<p>Step {{ wizard.steps.step1 }} of {{ wizard.steps.count }}</p>
{% for field in form %}
{{field.error}}
{% endfor %}
<form action="/contact/" method="post">{% 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 }}
{% endif %}
</table>
{% if wizard.steps.prev %}
<button name="wizard_goto_step" type="submit" value="{{ wizard.steps.first }}">"first step"</button>
<button name="wizard_goto_step" type="submit" value="{{ wizard.steps.prev }}">"prev step"</buttom>
{% endif %}
<input type="submit" value="submit" />
</form>
{% endblock %}
And this is my urls.py file:
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
from django_test.api import ArticleResource
from django_test.forms import ContactForm1, ContactForm2, ContactForm3
from django_test.views import ContactWizard
article_resource = ArticleResource()
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^accounts/login/$', 'django_test.views.login'),
url(r'^accounts/auth/$', 'django_test.views.auth_view'),
url(r'^accounts/loggedin/$', 'django_test.views.loggedin'),
url(r'^accounts/invalid/$', 'django_test.views.invalid_login'),
url(r'^accounts/logout/$', 'django_test.views.logout'),
url(r'^accounts/register/$', 'django_test.views.register_user'),
url(r'^accounts/register_success/$', 'django_test.views.register_success'),
url(r'^articles/all/$', 'article.views.articles'),
url(r'^articles/create/$', 'article.views.create'),
url(r'^articles/get/(?P<article_id>\d+)/$', 'article.views.article'),
url(r'^articles/like/(?P<article_id>\d+)/$', 'article.views.like_article'),
url(r'^articles/add_comment/(?P<article_id>\d+)/$', 'article.views.add_comment'),
url(r'^articles/search/', 'article.views.search_titles'),
url(r'^articles/api/', include(article_resource.urls)),
url(r'^contact/', ContactWizard.as_view([ContactForm1, ContactForm2, ContactForm3])),
)
I'm not getting any error messages either, which is frustrating, so I don't know what I'm doing wrong. Thank you.
All I had to do was view the page source on the site. It turned out
<button name="wizard_goto_step" type="submit" value="{{ wizard.steps.prev }}">"prev step"</buttom>
in contact_form.html had a typo: </buttom>. I fixed the error and now I get the comment page.
The line should be:
<button name="wizard_goto_step" type="submit" value="{{ wizard.steps.prev }}">"prev step"</button>