Dajax is not working, I am not able to understand why. I am using Django 1.7
My ajax.py file looks this:
from dajax.core import Dajax
from dajaxice.decorators import dajaxice_register
#dajaxice_register
def jmc_foundation_tower_number(request, option):
print("It works!")
My template call is as follows:
<div class='col-lg-3'>
<select id='id_tower_number' name='tower_number' onchange="Dajaxice.core.views.jmc_foundation_tower_number(Dajax.process, {'option':$this.value})" onclick="Dajaxice.core.views.jmc_foundation_tower_number(Dajax.process, {'option':$this.value})" class='form-control'>
{% for tower in towers %}
<option value='{{ tower }}'>{{ tower }}</option>
{% endfor %}
</select>
</div>
My urls.py is as follows:
from django.conf.urls import patterns, include, url
from django.contrib import admin
from dajaxice.core import dajaxice_autodiscover, dajaxice_config
dajaxice_autodiscover()
urlpatterns = patterns('',
url(r'^index$', 'core.views.index', name='index'),
url(r'^admin/', include(admin.site.urls)),
url(dajaxice_config.dajaxice_url, include('dajaxice.urls')),
)
django-dajax and django-dajaxice
Should I use django-dajax or django-dajaxice?
In a word, No. I created these projects 4 years ago as a cool tool in
order to solve one specific problems I had at that time.
These days using these projects is a bad idea.
(...)
If you want to use this project, you are probably wrong. You should
stop couplig your interface with your backend or... in the long term
it will explode in your face.
jorgebastida/django-dajax
Apparently javascript function names with underscores('_') don't work when using functions like onclick.It's better to use functions like somefunction() instead of some_function() to make Dajax work.
The following is an example to make Helloworld using dajax
models.py:
from django.db import models
from dajax.core import Dajax
from dajaxice.decorators import dajaxice_register
#dajaxice_register
def say_hello(request,value):
dajax = Dajax()
dajax.alert(value)
return dajax.json()
urls.py:
urlpatterns = patterns('',
# Examples:
url(r'^$', 'server.views.index', name='index'),
where "server" in server.views.index is the application name inside your project
in index.html file you have to use a jquery function to call this dajax request as following
index.html:
<html>
<script>
function print_helloworld(){
var value = Dajaxice.server.models.say_hello(Dajax.process,{'value':'Hello World!'});
}
</script>
<body>
<button id='mybtn' class='btn btn-primary' onclick='print_helloworld()'>Hello World</button>
</body>
</html>
if you need to access the index file from public ip you have to add the {% csrf_token %} token before button
Related
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
Update: Using Django 1.2.1 and Python 2.5.2 as offered by Dreamhost.
I'm having issues with the last part of the Django tutorial where the urls.py is changed to use generic views. After I change the code I get 404's on the pages and even the index stops working.
I have gone over all of my templates to see if that was the issue but I removed any instance of poll and replaced it with object. I have also attached the template for the index/object_list.
I am running this on Dreamhost and the static urls I set with views worked fine.
urls.py
from brsplash.models import Poll
from django.conf.urls.defaults import *
from django.contrib import admin
from django.views.generic import *
admin.autodiscover()
info_dict = {
'queryset': Poll.objects.all(),
}
urlpatterns = patterns('',
(r'^$', 'django.views.generic.list_detail.object_list', info_dict),
(r'^(?P<object_id>\d+)/$', 'django.views.generic.list_detail.object_detail', info_dict),
url(r'^(?P<object_id>\d+)/results/$', 'django.views.generic.list_detail.object_detail', dict(info_dict, template_name='brsplash/results.html'), 'poll_results'),
(r'^(?P<poll_id>\d+)/vote/$', 'brsplash.views.vote'),
)
urlpatterns += patterns('',
(r'^admin/', include(admin.site.urls)),
poll_list.html
{% if object_list %}
<ul>
{% for object in object_list %}
<li>{{ object.question }}</li>
{% endfor %}
</ul>
{% else %}
<p>No polls are available</p>
{% endif %}
Django 1.3 introduced class-based generic views which will replace this function-based approach (see the note at the top of the documentation page) so perhaps it's best to use them instead.
With the class-based approach, your new detail-page url would look something like this:
from brsplash.models import Poll
...
from django.views.generic import ListView
urlpatterns = {'',
url(r'^$', ListView.as_view(model=Poll)),
...
}
This approach can be found in part 4 of the tutorial.
N.B.: I tend not to pass the template_name argument to as_view because, as stated in the docs:
ListView generic view uses a default template called <app name>/<model name>_list.html
You can upgrade to Django 1.3 on Dreamhost: blog.oscarcp.com/?p=167 –
jturnbull Sep 22 at 9:54
This fixed my issue with the urls.py issue I was having. Once I upgraded to 1.3.1 and changed the code to reflect it, my pages came back.
I have the following setup:
/landing_pages
views.py
urls.py
In urls.py I have the following which works when I try to access /competition:
from django.conf.urls.defaults import *
from django.conf import settings
from django.views.generic.simple import direct_to_template
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^competition$', 'landing_pages.views.page', {'page_name': 'competition'}, name="competition_landing"),
)
My views.py has something like this:
def page(request, page_name):
return HttpResponse('ok')
Then in a template I'm trying to do this:
{% load url from future %}
<a href="{% url 'landing_pages.views.page' page_name='competition'%}">
Competition
</a>
Which I apparently can't do:
Caught NoReverseMatch while rendering: Reverse for 'landing_pages.views.page' with arguments '()' and keyword arguments '{'page_name': u'competition'}' not found.
What am I doing wrong?
You ask in your comment to DrTyrsa why you can't use args or kwargs. Just think about it for a moment. The {% url %} tag outputs - as the name implies - an actual URL which the user can click on. But you've provided no space in the URL pattern for the arguments. Where would they go? What would the URL look like? How would it work?
If you want to allow the user to specify arguments to your view, you have to provide a URL pattern with a space for those arguments to go.
{% url [project_name].landing_pages.views.page page_name='competition' %}
Or better
{% url competition_landing 'competition' %}
when I use django.contrib.auth.views.password_reset_confirm without arguments at all it works and I can render the template without any problem, when adding uidb36 and token arguments it fails.
Caught NoReverseMatch while rendering: Reverse for 'django.contrib.auth.views.password_reset_confirm' with arguments '()' and keyword arguments '{'uidb36': '111', 'token': '1111111111111'}' not found.
Most likely it is an issue with your urls.py. You need to setup the right pattern to grab the uidb36 and token values passed as URL parameters. If not, it will throw a similar error to what you see above.
Something like:
(r'^reset/(?P<uidb36>[0-9A-Za-z]+)-(?P<token>.+)/$', 'django.contrib.auth.views.password_reset_confirm', {'template_name' : 'registration/password_reset.html', 'post_reset_redirect': '/logout/' })
registration/password_reset.html - is my custom template
logout - is my custom logout action
I had this issue in Django 1.3, and wasted a lot of time because the error can mask a number of underlying issues.
I needed to add this to the top of the reset email template:
{% load url from future %}
Also, the example in the Django docs didn't match the sample url:
{{ protocol}}://{{ domain }}{% url 'auth_password_reset_confirm' uidb36=uid token=token %}
So I had to change the auth_password_reset_confirm above to password_reset_confirm.
If you're using Django 1.6+ and run into something like this it could be that you need to update uidb36 to uidb64 in both your template and your urls.
Example url:
url(r'^password/reset/confirm/(?P<uidb64>[0-9A-Za-z]+)-(?P<token>.+)/$',
auth_views.password_reset_confirm
and reset link in template:
{{ protocol}}://{{ domain }}{% url 'django.contrib.auth.views.password_reset_confirm' uidb64=uid token=token %}
For Django 1.8+ users, just copy this URL to your main urls.py file, so that it recognizes the URL name
url(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',
'django.contrib.auth.views.password_reset_confirm',
name='password_reset_confirm'),
And add this mentioned by: #Lunulata to your password_reset_email.html file:
{{ protocol}}://{{ domain }}{% url 'django.contrib.auth.views.password_reset_confirm' uidb64=uid token=token %}
Try adding following to your urls.py
(r'^reset/(?P<uidb36>[0-9A-Za-z]{1,13})-(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', 'django.contrib.auth.views.password_reset_confirm'),
I found this to work, copied from the default url
url(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',
auth_views.password_reset_confirm, name='password_reset_confirm'),
Just add this line to your urls.py:
url('^', include('django.contrib.auth.urls')),
This enables the django reset_password workflow.
Then override your login.html to include the line:
<div class="password-reset-link">
href="{{ password_reset_url }}">{% trans 'Forgotten your password or username?' %}</a></div>
Now you should be able to use the builtin Django PasswordResetView included with Django as long as your email settings are set up.
if you are using app_name in every urls.py
suppose you have an app and in that app in urls.py you have mentioned app_name="accounts"
in order to retrieve the page you need to mention two things
template_name and success_url inside the PasswordResetView(template_name="accounts/password_reset.html" , success_url= reverse_lazy('accounts:password_reset_sent'))
dont forget to import reverse_lazy from django.urls inside urls.py
so your final code of accounts/urls.py should look like
My app name is landing instead of accounts
from django.urls import path
from . import views
from django.contrib.auth import views as auth_views
from django.urls import reverse_lazy
app_name='landing'
urlpatterns = [
path('',views.home,name="home"),
path('terms/',views.terms,name="terms"),
path('login/',views.loginUser,name="login"),
path('signup/',views.signupUser,name="signup"),
path('about/',views.about,name="about"),
path('logout/',views.logoutUser,name="logout"),
path('password_reset/',
auth_views.PasswordResetView.as_view(template_name='landing/password_reset.html',success_url=reverse_lazy('landing:password_reset_done')),
name="password_reset"),
path('password_reset_sent/',
auth_views.PasswordResetDoneView.as_view(template_name='landing/password_reset_sent.html'),
name="password_reset_done"),
path('reset/<uidb64>/<token>/',
auth_views.PasswordResetConfirmView.as_view(template_name='landing/password_reset_form.html',success_url=reverse_lazy('landing:password_reset_complete')),
name="password_reset_confirm"),
path('password_reset_complete/',
auth_views.PasswordResetCompleteView.as_view(template_name='landing/password_reset_done.html'),
name="password_reset_complete"),
]
you have to use app_name: before the name of url you have mentioned it is very important