how to do a live search in a ModelChoiceField form in the template html ... i write for example a number and a i will get just the data that have that number
i am using django 1.9
models.py
class Suivre(models.Model):
formationffF=models.ForeignKey(FormationDispo,on_delete=models.CASCADE)
numcniF=models.ForeignKey(Personne,on_delete=models.CASCADE)
session = models.CharField(max_length=50)
form.py
class Ajout3 (forms.Form):
numcniF=forms.ModelChoiceField(queryset=Personne.objects.all().order_by('-time'))
formationf =forms.ModelChoiceField(queryset=FormationDispo.objects.all().order_by('time') )
session = forms.CharField(required=True, widget=forms.TextInput())
tamplate.html
<form method="post">
{% load crispy_forms_tags %}
{% csrf_token %}
{{con|crispy}}
<button type="submit" class="btn btn-success" > SAVE</button>
</form>
I would suggest you to use django-admin and ajax_select
Create a file called admin.py in your app.
admin.py
from django.contrib import admin
from myproject.myapp.models import Suivre
from ajax_select import make_ajax_form
# creates model-centric interface where trusted users can manage content on your site.
class SuivreAdmin(admin.ModelAdmin):
model = Suivre
form = make_ajax_form(
Suivre,
{
'numcniF': 'all_personne', # ForeignKeyField
'formationf':'all_formationdispo'
})
# registers admin
admin.site.register(Suivre, SuivreAdmin)
Notice that I am using ajax_select library which will create interface shown in below image.
Install ajax_select:
pip install django-ajax-selects
Add the app:
settings.py
# settings.py
INSTALLED_APPS = (
...
'ajax_select', # <- add the app
...
)
AJAX_LOOKUP_CHANNELS = {
'all_formationdispo': {
'model': 'app.FormationDispo',
'search_field': 'name'
},
'all_personne': {
'model': 'app. Personne',
'search_field': 'name'
},
}
Include the urls in your project:
urls.py
# urls.py
from django.conf.urls import url, include
from django.conf.urls.static import static
from django.contrib import admin
from django.conf import settings
from ajax_select import urls as ajax_select_urls
admin.autodiscover()
urlpatterns = [
# place it at whatever base url you like
url(r'^ajax_select/', include(ajax_select_urls)),
Related
I'm trying to save the data submitted on a form, and redirect the user to a results.html.
------- Front template -------------------
Welcome to readability test V1
<form action="/addtext" method="POST">{% csrf_token %}
<input type="text" name="title"/>
<input type="text" name="content"/>
<input type="submit" value="Add"/>
</form>
---------- URLS.PY -----------------
from django.contrib import admin
from django.urls import path
from readtest.views import readtest, addtext
urlpatterns = [
path('admin/', admin.site.urls),
path('readability-test/', readtest),
path('results/', addtext),
enter code here
------------ VIEWS.PY ------------------------
from django.shortcuts import render
from django.http import HttpResponseRedirect
from .models import TestedText
# Create your views here.
def readtest(request):
return render(request, 'test.html')
def addtext(request):
a = TestedText(title=request.POST['title'], content=request.POST['content'])
a.save()
return HttpResponseRedirect('/results/')
------ ERROR IM GETTING ------------------
Page not found (404)
Request Method: POST
Request URL: http://127.0.0.1:8000/addtext
Using the URLconf defined in redability.urls, Django tried these URL patterns, in this order:
admin/
readability-test/
results/
The current path, addtext, didn't match any of these.
Update your urls.py file line path('results/', addtext) to path('addtext/', addtext)
from django.contrib import admin
from django.urls import path
from readtest.views import readtest, addtext
urlpatterns = [
path('admin/', admin.site.urls),
path('readability-test/', readtest),
path('addtext/', addtext),
I would like to incorporate an email form with Google Recaptcha similar or identical to this:
https://github.com/maru/django-contact-form-recaptcha
Into this existing django github project:
https://github.com/justdjango/video-membership
Where a website visitor could send emails to a Gmail account that I own directly from the form.
I edited the code from the video membership github project to include a contact page for this purpose.
How can this be accomplished?
video-membership-master/courses/urls.py:
from django.urls import path
from .views import ContactPageView
app_name = 'courses'
urlpatterns = [
path('contact/', ContactPageView.as_view(), name='contact')
]
video-membership-master/courses/views.py
from django.views.generic import TemplateView
class ContactPageView(TemplateView):
template_name = 'contact.html'
video-membership-master/courses/templates/contact.html:
{% extends 'courses/base.html' %}
{% block content %}
<h1>Contact</h1>
{% endblock %}
Using Django 2.1.5 + Bootstrap 4.2 and some Icons from fontawesome
Hello ,
after a long search I decided to post, because most answer are related to older Django versions.
I am relatively new to Django and I like to test all the Function/Class Views and Modelfields. Now I wanted to test how I can display images linked with my database in my template. But unfortunately, images want not display, all I see is image placeholder icon.
I created an app and 2 simple models, with musicians (with images) and cars. The upload via admin works and the blank url are accessible in the Template via {{ modelone.person_pic }}
PROBLEMS SOLVED - See down Below
aquaman / models.py
class Person(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
person_pic = models.ImageField(upload_to='artist/', max_length=255, null=True, blank=True )
def __str__(self):
return "{} - {}".format(self.first_name[:25], self.last_name[:25])
class Data_Sheet(models.Model):
car = models.CharField(max_length=30)
color = models.CharField(max_length=30)
def __str__(self):
return "{} - {}".format(self.car[:25], self.color[:25])
views.py
from django.shortcuts import get_object_or_404, render, redirect
from django.utils import timezone
from django.views.generic.list import ListView
from django.views.generic import TemplateView
from .models import Person, Data_Sheet
<…some other views…>
class ArtistView4(TemplateView):
template_name = 'aquaman/artistview4.html'
def get_context_data(self, **kwargs):
context = super(ArtistView4, self).get_context_data(**kwargs)
context['modelone'] = Person.objects.all()
context['modeltwo'] = Data_Sheet.objects.all()
return context
artistview4.html
{% extends 'base.html' %}
{% load static %}
{% block custom_css %}
<link rel="stylesheet" type="text/css" href="{% static 'css/clear_styles.css' %}">
{% endblock %}
{% block content %}
{% for visual in modelone %}
<div align="center">
<h4 class="">{{ visual.first_name }}</h4>
<h4 class="">{{ visual.last_name }}</h4>
<h4 class="">{{ visual.person_pic }}</h4> <!-- to check if url is displayed -->
</div>
<img src="{{ visual.person_pic.url }}">
</div>
{% endfor %}
{% endblock %}
urls.py
from django.urls import path
from . import views
from .views import AquaListView, AquaListView2, AquaListView3, ArtistView4
app_name='aquaman'
urlpatterns = [
path('home/', views.aqua_home, name='aqua_home'),
path('aqua_listview/', AquaListView.as_view(), name='aqua_listview'),
path('aqua_listview2/', AquaListView2.as_view(), name='aqua_listview2'),
path('aqua_listview3/', AquaListView3.as_view(), name='aqua_listview3'),
path('arstistview4/', ArtistView4.as_view(), name='artistview4'),
]
my approach
As far as I understand the documentation. I have to add this lines to the urls.py in the urlpattern, so that everything gets directed.
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
So my urls.py looks like this now
from django.urls import path
from django.conf import settings
from django.conf.urls.static import static
from . import views
from .views import AquaListView, AquaListView2, AquaListView3, ArtistView4
app_name='aquaman'
urlpatterns = [
path('home/', views.aqua_home, name='aqua_home'),
path('aqua_listview/', AquaListView.as_view(), name='aqua_listview'),
path('aqua_listview2/', AquaListView2.as_view(), name='aqua_listview2'),
path('aqua_listview3/', AquaListView3.as_view(), name='aqua_listview3'),
path('arstistview4/', ArtistView4.as_view(), name='artistview4'),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
This is what i added in my settings.py
TEMPLATES = [
{
<…>
'django.template.context_processors.media',
<…>
},
]
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
'/var/www/static/',
]
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
So far nothing changed. Django shows me the last name correctly in the template, but I only see image place holders and no images.
Django Server
Not Found: /media/artist/freddy_mercury.jpg
Not Found: /media/artist/kurt_cobain.jpg
Not Found: /media/artist/ella_fitzgerald.PNG
Not Found: /media/artist/amy_winehouse.PNG
[07/Feb/2019 18:42:49] "GET /media/artist/ella_fitzgerald.PNG HTTP/1.1" 404 2257
When i upload a image via admin from my desktop Django automatically saves the pictures in **MyProject/media/artist>** but at the same time django can not find these images?
If go directly to the images via http://127.0.0.1:8000/media/artist/kurt_cobain.jpg for example, django shows me this:
The current path, media/artist/kurt_cobain.jpg, didn't match any of these.
Even though Django puts the picture via upload in the BaseDir/media/artist folder.
Maybe I missed the "Serving files in development" aka if settings.DEBUG:
https://docs.djangoproject.com/en/2.1/ref/views/
But when I add this also nothing happens.
I really like to thank everyone, who might have a hint
Problem Solved
Alright, I misunderstand something in the Docs maybe it´s not so obvious.
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [...] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
This has to be added in the "MainApp/urls.py" not in your "MyOtherApps/urls.py". I thought just because I only need Images in a specific app I have to add these lines in these specific App urls.py.
Rock On & Peace
I am using tinymce and django. I have created models.py (content of forms.py also included in models.py only). The problem is that, when in the html file form.html in the tinymce init block :
i use : mode : "textareas",
my data is not updated in database, which i enter in the textarea of the form, (i believe my form is not being validated) however when I comment it out,, the textarea of form is loaded with very basic features of tinymce but the form is valid and data is updated to database when i hit the save button.
models.py :
enter code here
from django.db import models
from django.forms import ModelForm
from django.contrib.admin import widgets
from tinymce.widgets import TinyMCE
from django import forms
# Create your models here.
class HomePage(models.Model):
homecopy = models.TextField()
def __unicode__(self):
return 'Home Page Copy'
class HomePageForm(ModelForm):
class Meta:
model = HomePage
fields = ['homecopy']
#widgets = {'homecopy': forms.Textarea(attrs={'required':True})}
widgets = {'homecopy': TinyMCE(attrs={'cols': 80, 'rows': 30})}
form.html :
enter code here
{% load static %}
{% load staticfiles %}
<html>
<head> <title> TinyMce </title>
<script type="text/javascript" src="{% static "js/tiny_mce/tiny_mce.js" %}"></script>
<script type="text/javascript">
tinyMCE.init({
// General options
mode : "textareas",
theme : "advanced",
plugins : "pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,wordcount,advlist,autosave",
// Theme options
theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,fontselect,fontsizeselect,fullscreen,code",
theme_advanced_buttons2 : "bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,|,forecolor,backcolor",
theme_advanced_buttons3 : "tablecontrols,|,hr,sub,sup,|,charmap",
theme_advanced_toolbar_location : "top",
theme_advanced_toolbar_align : "left",
theme_advanced_statusbar_location : "bottom",
theme_advanced_resizing : true,
// Example content CSS (should be your site CSS)
//content_css : "/css/style.css",
template_external_list_url : "lists/template_list.js",
external_link_list_url : "lists/link_list.js",
external_image_list_url : "lists/image_list.js",
media_external_list_url : "lists/media_list.js",
// Style formats
style_formats : [
{title : 'Bold text', inline : 'strong'},
{title : 'Red text', inline : 'span', styles : {color : '#ff0000'}},
{title : 'Help', inline : 'strong', classes : 'help'},
{title : 'Table styles'},
{title : 'Table row 1', selector : 'tr', classes : 'tablerow'}
],
width: '700',
height: '400'
});
</script>
</head>
<body>
<style>
#text{
height : 500px;
width : 1000px;
}
</style>
</head>
<body>
<p><h2> Hi {{ name }} ..Save your text... </h2></p>
</br>
<form id = "form" action = "/myform/" method = "post">{% csrf_token %}
{{ form.as_p }}
<p><input type = "submit" id = "butt" value = "save"/></p>
</form>
</body>
</html>
views.py :
from django.shortcuts import render_to_response
from django.template import RequestContext,Context
from django.template.loader import get_template
from myapp.models import HomePage,HomePageForm
from django.http import HttpResponse,HttpResponseRedirect
from django.core.context_processors import csrf
from tinymce.widgets import TinyMCE
def MainHomePage(request):
homepage = HomePage.objects.get(pk = 1)
context = {'homepage' : homepage}
return render_to_response('index.html',context,context_instance=RequestContext(request))
def display(request):
context = {'name' : request.user}
return render_to_response('form.html',context,context_instance = RequestContext(request))
def save_form(request):
if request.method == 'POST':
#print request.POST.get('homecopy','')
#print "$$$$$$$$$$$$$$$$$$"
form = HomePageForm(request.POST)
if form.is_valid():
#print "%%%%%%%%%%%%%%%%"
form.save()
return render_to_response('display.html')
args = {}
args.update(csrf(request))
args['form'] = HomePageForm()
return render_to_response('form.html',args)
admin.py :
from django.contrib import admin
from myapp.models import HomePage
class TinyMCEAdmin(admin.ModelAdmin):
class Media:
js = ('/static/static/js/tiny_mce/tiny_mce.js','/static/static/js/tiny_mce/textareas.js',)
admin.site.register(HomePage, TinyMCEAdmin)
urls.py of main project :
from django.conf.urls import patterns, include, url
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'tiny.views.home', name='home'),
# url(r'^tiny/', include('tiny.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
url(r'^myform/', 'myapp.views.save_form'),
(r'^tinymce/', include('tinymce.urls')),
(r'^$','myapp.views.MainHomePage'),
)
project folder structure :
tiny -
tinymce
tiny -
setiings.py, urls,py , wsgi.py, __init__.py
myapp -
admin.py
models.py
__init__.py
views.py
tests.py
static -
static -
js -
tiny_mce -
langs, plugins, themes, utils, textareas.js, tiny_mce.js, tiny_mce_popup.js, tiny_mce_src.js
static_only
templates -
display.html, form.html, index.html
manage.py
test - database
Django-Registration has several form classes in the forms.py file. One is "class RegistrationFormTermsOfService(RegistrationForm) ..
What do I change in the rest of Django Registration code to enable this form in my registration flow instead of RegistrationForm?
Updating the accepted answer to conform with Django 1.5 and the latest version of django-registration:
in urls.py:
from registration.forms import RegistrationFormTermsOfService
from registration.backends.default.views import RegistrationView
urlpatterns = patterns('',
url(r'^accounts/register/$', RegistrationView.as_view(form_class=RegistrationFormTermsOfService), name='registration_register'),
# your other URLconf stuff follows ...
)
then update the registration_form.html template and add a tos field, e.g.:
<p>
<label for="id_tos">I accept the terms of service</label>
{% if form.tos.errors %}
<p class="errors">{{ form.tos.errors.as_text }}</p>
{% endif %}
{{ form.tos }}
</p>
You can simply go into your urls.py and override the form class by doing something like:
from registration.forms import RegistrationFormTermsOfService
(r'^accounts/register/$', 'registration.views.register', {'form_class' : RegistrationFormTermsOfService}),
Here is a practical example using a custom form and backend which sets username == email address, and only prompts the user for an email address at registration. In, for e.g. my_registration.py:
from django.conf import settings
from django.contrib.sites.models import RequestSite
from django.contrib.sites.models import Site
from registration import signals
from registration.forms import RegistrationForm
from registration.models import RegistrationProfile
from registration.backends.default import DefaultBackend
class EmailRegistrationForm(RegistrationForm):
def __init__(self, *args, **kwargs):
super(EmailRegistrationForm,self).__init__(*args, **kwargs)
del self.fields['username']
def clean(self):
cleaned_data = super(EmailRegistrationForm,self).clean()
if 'email' in self.cleaned_data:
cleaned_data['username'] = self.cleaned_data['username'] = self.cleaned_data['email']
return cleaned_data
class EmailBackend(DefaultBackend):
def get_form_class(self, request):
return EmailRegistrationForm
In my_registration_urls.py:
from django.conf.urls.defaults import *
from django.views.generic.simple import direct_to_template
from registration.views import activate
from registration.views import register
urlpatterns = patterns('',
url(r'^activate/complete/$',
direct_to_template,
{ 'template': 'registration/activation_complete.html' },
name='registration_activation_complete'),
# Activation keys get matched by \w+ instead of the more specific
# [a-fA-F0-9]{40} because a bad activation key should still get to the view;
# that way it can return a sensible "invalid key" message instead of a
# confusing 404.
url(r'^activate/(?P<activation_key>\w+)/$',
activate,
{ 'backend': 'my_registration.EmailBackend' },
name='registration_activate'),
url(r'^register/$',
register,
{ 'backend': 'my_registration.EmailBackend' },
name='registration_register'),
url(r'^register/complete/$',
direct_to_template,
{ 'template': 'registration/registration_complete.html' },
name='registration_complete'),
url(r'^register/closed/$',
direct_to_template,
{ 'template': 'registration/registration_closed.html' },
name='registration_disallowed'),
(r'', include('registration.auth_urls')),
)
Then in your core urls.py, ensure you include:
url(r'^accounts/', include('my_registration_urls')),
You'll need to write a new registration form somewhere in your project. You can inherit off of the existing authentication form if you're just expanding new fields. You'll then want to write a new backend to process the form. Finally you'll need to write your own url and auth_urls and redefine the urls to switch the backend and authentication form in the views by changing the variables that get passed to the view.
It's helpful to break open the source to see how things are working. I base my structure off of the original django-registration code to keep things consistent.
As to django 1.11 and django-registration 2.2 there are some updated imports... so if you get "No module named 'registration'" this could be the problem...
Replace:
from registration.backends.hmac.views import RegistrationView
by from django_registration.backends.activation.views import RegistrationView
from registration.forms import RegistrationForm
by from django_registration.forms import RegistrationForm
include('django_registration.backends.hmac.urls') in urls
by include('django_registration.backends.activation.urls')
Just to name a few... ;)
Src: https://django-registration.readthedocs.io/en/3.0/custom-user.html