Could not parse the remainder: '-save' from 'waypoints-save' - django

I am trying a simple app in geodjango by following http://invisibleroads.com/tutorials/geodjango-googlemaps-build.html.
My view function is
# Import django modules
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.template.loader import render_to_string
# Import system modules
import json
# Import custom modules
from waypoints.models import Waypoint
def save(request):
'Save waypoints'
for waypointString in request.POST.get('waypointsPayload', '').splitlines():
waypointID, waypointX, waypointY = waypointString.split()
waypoint = Waypoint.objects.get(id=int(waypointID))
waypoint.geometry.set_x(float(waypointX))
waypoint.geometry.set_y(float(waypointY))
waypoint.save()
return HttpResponse(simplejson.dumps(dict(isOk=1)), mimetype='application/json')
And urls.py is
from django.conf.urls import patterns, include, url
urlpatterns = patterns('waypoints.views',
url(r'^$', 'index', name='waypoints-index'),
url(r'^save$', 'save', name='waypoints-save'),
)
It is showing an error http://dpaste.com/3EJVX0G
Template index.html is here http://pastebin.com/125Dm6Bz
Please help me.I am new to django.

The parameter to the {% url %} tag must always be in quotes if it's a literal string (this has been the case since version 1.5, which is quite a long time).
The one that's causing the error is this:
$.post("{% url waypoints-save %}"
which should be:
$.post("{% url "waypoints-save" %}"
but you make the same mistake several times in that template.

Related

Page not found for the template returned by TemplateResponse in Django

I have an app which is called sitepages which have three models I wanna pass their objects to a html page called listing.html which is inside templates/sitepages
the sitepages urls.py contains:
from django.views.generic import TemplateView
from django.urls import include
from django.urls import path
from sitepages import views
app_name = "sitepages"
urlpatterns = [
path("news-events-listing/", views.view, name='listing'),
]
the sitepages/views.py:
from .models import Listing, Details1, Details2
from django.template.response import TemplateResponse
def view(request):
return TemplateResponse(request, 'sitepages/listing.html', {
'first_pages': Details1.objects.all(),
'seconde_pages': Details1.objects.all(),
'listing_page': Listing.objects.first(),
})
in the root urls.py I added:
path("", include("sitepages.urls", namespace='sitepages'))
when I put in any template the following:
Listing
it redirects me to the url /news-events-listing but no page is found and it gives me 404 error...what am I doing wrong? why the template is not returned? I should mention that I'm using wagtail for the whole site (I don't know if it's related)
In your root urls.py, make sure your new line
path("", include("sitepages.urls", namespace='sitepages'))
appears before the path("", include(wagtail_urls)) line. The wagtail_urls pattern matches any URL path and passes it to Wagtail to be handled as a Wagtail page, so any patterns after it will never be reached.

How to go from one page to another in django

I'm new to Django and python (infact my first language which I've only been learning for 3 months)
I'm creating this website using Django and I'm not able to go from one page to another using the href tag. it throws at me a 404 error saying "current path didn't match any of these"
This is my code
views.py
from django.shortcuts import render
from django.http import HttpResponseRedirect
from .models import off
# Create your views here.
def homepage(request):
return render(request=request,
template_name='main/home.html',
context={'toll' : off.objects.all})
def secondpage(request):
return render(request = request,
template_name = 'main/next.html')
main/urls.py
from django.urls import path
from . import views
app_name = 'main'
urlpatterns = [
path('',views.homepage,name='homepage'),
path('',views.secondpage,name='secondpage')
]
templates/mains/home.html
<div class="topnav">
Link
Link
Link
</div>
I also request the helper to simply it for me as I wouldn't be able to handle complex and advanced python terminology
Thanks In Advance From a Friend
Arvind
I think you should read this to start with Django.

Can I print just the content of a html template in django?

I am using Django with python to create a web application, I am a beginner in this. I hope that you can help me.
I want to print this page by clicking a button.
Now, I am just trying to generate the pdf first.
I want just to print the content, like that
I tried these functions.
#views.py
from django.views.generic.detail import DetailView
from MagasinProject.views import PdfMixin
from MagasinProject.utils import generate_pdf, render_to_pdf_response, pdf_decorator
from django.contrib.auth.models import User
from django.shortcuts import render
def test_view(request):
resp = HttpResponse(content_type='application/pdf')
result = generate_pdf('demande/demande.html', file_object=resp)
return result
#urls.py
from django.urls import path
from . import views
from django.conf.urls import url
urlpatterns=[
path('demande',views.index, name='demande'),
url(r'^test_view$', views.test_view),
]
This is what I got
You can print the HTML page with a print button like this (see w3schools):
<button onclick="window.print()">Print this page</button>

How to add Django statements to Javascript

I'm trying to implement some JS code in django so anytime i click a button, it returns the current year.. how do i do this
I've tried using some JS events handler in my django based templates
from datetime import datetime
from django.template import Template, Context
from django.http import HttpResponse as toHTML
cont = Context({'dat':datetime.now()})
def say_year(request):
htm = Template("<button onclick='alert({dat})'>click me</button>")
htm = htm.render(cont)
return toHTML(htm)
i'm expecting an alert box showing full datetime.now() methods
I prefer that you do it that way in order to have full control over the template.
1 - make the views.py that way :
from datetime import datetime
from django.template import Template, Context
from django.shortcuts import render
def say_year(request):
context = {
'dat': datetime.now()
}
return render(request, 'mytemplate.html', context)
2- The urls.py should look that way :
from django.contrib import admin
from django.urls import path
from your_app import views
urlpatterns = [
path('admin/', admin.site.urls),
path('my_template/', views.say_year )
]
3- You create a templates folder in the root directory of your project where all your templates will live.
For your question i have create my_template.html and it should be that way :
<button onclick="alert('{{dat}}')">click me</button>
If you have more questions please let me know.

How to use different form in Django-Registration

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