Django Rest Auth - Key error on Email Confirmation - django

I am trying to setup email verification in DRF using rest-auth.
The registration works correctly and the verification email is sent. However, when going to the verification link I receive a key error.
What I understand is that means that this verification key doesn't exist, but I don't understand how to fix that given that the registration process was supposedly a success?
I have the following paths in my urls.py:
path('', include('rest_framework.urls', namespace='rest_framework')),
path('', include('rest_auth.urls')),
path('registration/', include('rest_auth.registration.urls')),
path('registration/', RegisterView.as_view(), name='account_signup'),
re_path(r'^account-confirm-email/', VerifyEmailView.as_view(), name='account_email_verification_sent'),
re_path(r'^account-confirm-email/(?P<key>[-:\w]+)/$', VerifyEmailView.as_view(), name='account_confirm_email'),
The following settings in my settings.py:
ACCOUNT_AUTHENTICATION_METHOD = 'email'
LOGIN_REDIRECT_URL = '/'
ACCOUNT_EMAIL_VERIFICATION = 'mandatory'
ACCOUNT_CONFIRM_EMAIL_ON_GET = False
ACCOUNT_EMAIL_REQUIRED = True
And this is a screenshot of the error I am getting:
Key error

how I solved this issue
I had to create a view to verify the email my self, also note that I have a custom user model which is the goal when working on a big project
views.py
from rest_auth.registration.views import RegisterView
from django.contrib.auth import get_user_model
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import status
from rest_framework.exceptions import NotFound
from rest_framework.views import APIView
from rest_framework.permissions import AllowAny
from allauth.account.models import EmailConfirmation, EmailConfirmationHMAC
from django.http import HttpResponseRedirect
class ConfirmEmailView(APIView):
permission_classes = [AllowAny]
def get(self, *args, **kwargs):
self.object = confirmation = self.get_object()
confirmation.confirm(self.request)
# A React Router Route will handle the failure scenario
return HttpResponseRedirect('/api/rest-auth/login/')
def get_object(self, queryset=None):
key = self.kwargs['key']
email_confirmation = EmailConfirmationHMAC.from_key(key)
if not email_confirmation:
if queryset is None:
queryset = self.get_queryset()
try:
email_confirmation = queryset.get(key=key.lower())
except EmailConfirmation.DoesNotExist:
# A React Router Route will handle the failure scenario
return HttpResponseRedirect('/login/failure/')
return email_confirmation
def get_queryset(self):
qs = EmailConfirmation.objects.all_valid()
qs = qs.select_related("email_address__user")
return qs
urls.py
from django.contrib import admin
from django.urls import path, re_path
from django.conf.urls import url, include
from rest_auth.registration.views import VerifyEmailView, RegisterView
from rest_auth.views import PasswordResetView, PasswordResetConfirmView
from users.api.views import ConfirmEmailView
urlpatterns = [
path('admin/', admin.site.urls),
url('api/rest-auth/', include('rest_auth.urls')),
url('api/account/', include('users.api.urls')),
url('api/rest-auth/registration/', include('rest_auth.registration.urls')),
url(r'^verify-email/$', VerifyEmailView.as_view(), name='account_email_verification_sent'),
url(r'^rest-auth/registration/account-confirm-email/(?P<key>[-:\w]+)/$', ConfirmEmailView.as_view(), name='account_confirm_email'),
url(r'^rest-auth/password/reset/$', PasswordResetView.as_view(), name='password_reset'),
url(r'^rest-auth/password/reset/confirm/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', PasswordResetConfirmView.as_view(), name='password_reset_confirm'),
]
settings.py
INSTALLED_APPS = [
...
'django.contrib.sites',
'rest_framework',
'rest_framework.authtoken',
'rest_auth',
'rest_auth.registration',
'allauth',
'allauth.account',
'users',
]
SITE_ID = 1
# to use old_password when setting a new password
OLD_PASSWORD_FIELD_ENABLED = True
# to keep the user logged in after password change
LOGOUT_ON_PASSWORD_CHANGE = False
ACCOUNT_USER_MODEL_USERNAME_FIELD = None
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_USERNAME_REQUIRED = False
ACCOUNT_AUTHENTICATION_METHOD = 'email'
ACCOUNT_UNIQUE_EMAIL = True
ACCOUNT_LOGOUT_ON_GET = True
# UNSURE
ACCOUNT_EMAIL_CONFIRMATION_EXPIRE_DAYS = 1
ACCOUNT_EMAIL_VERIFICATION = "mandatory"
ACCOUNT_LOGIN_ATTEMPTS_LIMIT = 5
ACCOUNT_LOGIN_ATTEMPTS_TIMEOUT = 86400 # 1 day in seconds
ACCOUNT_LOGOUT_REDIRECT_URL ='/accounts/login/'
LOGIN_REDIRECT_URL = '/accounts/profile'
SOCIALACCOUNT_EMAIL_VERIFICATION = 'none'
# EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = 'youremail#gmail.com'
EMAIL_HOST_PASSWORD = 'yourpassword'
DEFAULT_FROM_EMAIL = 'youremail#gmail.com'
DEFAULT_TO_EMAIL = EMAIL_HOST_USER
EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL = '/'
NOTE: I noticed that the URLs have to be in that order to work for me when they weren't in that order it didn't work for me. I also noticed that reset passwords give issues too so the fix is also there. I hope this solves your problem. and in case you post a reply and I haven't responded, just mail me at 'opeyemiodedeyi#gmail.com'

This might be an old post but I just wanna share what I used as a solution in hopes that it helps someone else experiencing a similar issue.
# import the confirm_email views from allauth.accounts.views
from allauth.account.views import confirm_email
# once that's done, change your url view portion from
# VerifyEmailView.as_view() to the newly imported view
re_path(r"^account-confirm-email/(?P<key>[-:\w]+)/$", confirm_email,
name="account_confirm_email"),

Related

why my own template_name doesn't show instead of default template_name in django?

I need to show my own template_name for (passwordResetConfirm) when I use template_name here I get the default Django template also when I get the successful message from (PasswordResetComplete) I get from the same place I mean (the default Django template too).
however, I get no errors of code.so, How can I get my own template_name in this case?
urls.py
from . import views
from django.conf.urls import url
from django.contrib.auth.views import (
LoginView,
logout,
PasswordResetView,
PasswordResetDoneView,
PasswordResetConfirmView,
PasswordResetCompleteView,
)
from django.core.urlresolvers import reverse_lazy
from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
# django\contrib\admin\templates\registration\password_reset_done.html
app_name = 'account'
class PasswordReset(PasswordResetView):
template_name = 'account/password_reset_form.html'
success_url = reverse_lazy('account:password_reset_done')
email_template_name = 'account/reset_password_email.html'
class PasswordResetDone(PasswordResetDoneView):
template_name = 'account/password_reset_done.html'
success_url = reverse_lazy('account:password_reset_complete')
class PasswordResetConfirm(PasswordResetConfirmView):
success_url = reverse_lazy('account:password_reset_complete')
template_name = 'account/password_reset_confirm.html'
def func(self, request):
return render(request, self.template_name)
class PasswordResetComplete(PasswordResetCompleteView):
template_name = 'account/password_reset_complete.html'
urlpatterns = [
# /account/
url(r'^$', views.index, name="home"),
# /account/login/
url(r'^login/$', LoginView.as_view(template_name='account/login.html'), name='login_page'),
# /account/logout/
url(r'^logout/$', logout, {'template_name': 'account/logout.html'}, name='logout'),
# /account/register/
url(r'^register/$', views.register, name='register'),
# /account/profile/
url(r'^profile/$', views.view_profile, name='view_profile'),
# /account/profile/edit/
url(r'^profile/edit/$', views.edit_profile, name='edit_profile'),
# /account/change-password/
url(r'^change-password/$', views.change_password, name='change_password'),
# /account/password-reset/
url(r'^password-reset/$', PasswordReset.as_view(), name='password_reset'),
# /account/password-reset/done/
url(r'^password-reset/done/$', PasswordResetDone.as_view(), name='password_reset_done'),
# /account/password-reset/confirm/
url(r'^password-reset/confirm/(?P<uidb64>[0-9A-Za-z]+)/(?P<token>.+)/$', PasswordResetConfirm.as_view(), name='password_reset_confirm'),
# /account/password-reset/complete/
url(r'^password-reset/complete/$', PasswordResetComplete.as_view(), name='password_reset_complete'),
]
settings.py
STATIC_URL = '/static/'
# Edit the login src url redirect
LOGIN_REDIRECT_URL = 'account:view_profile'
# Edit the login src url redirect in PasswordResetCompleteView
LOGIN_URL = 'account:login_page'
# To activating PasswordResetConfirmView
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
this image explains the files that I have files image
this image shows password_reset pagepassword reset image it work's
I had the same issue, upon trying out different things, this is what worked
url(r'password_reset/$', auth_views.PasswordResetView.as_view(template_name='password_reset.html', email_template_name='registration/password_reset_email.html', subject_template_name='registration/password_reset_email.html', success_url='/password_reset_done/', from_email='your#email.com')),
url(r'password_reset_done/', auth_views.PasswordResetDoneView.as_view(template_name='registration/password_reset_done.html')),
url(r'password_reset_confirm/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', auth_views.PasswordResetConfirmView.as_view(template_name='registration/password_reset_confirm.html', success_url='registration/password_reset_complete.html'))
I didnot create custom classes, like you did.

Django rest - router is not creating url path, giving 404, and the api webpage has incorrect urls listed

ive created some urls with the default router as per the below:
api.urls
from django.urls import path, include
from rest_framework import routers
from rest_framework_bulk.routes import BulkRouter
from . import views
router = routers.DefaultRouter()
#### NEW ####
router.register(r'data/credentials/', views.DataCredentials)
router.register(r'data/site_circuits', views.DataSiteCircuits)
router.register(r'data/subnets/', views.SubnetsSet)
router.register(r'data/device_conns/', views.DataDeviceConns)
router.register(r'data/email_subscriber/', views.DataEmailSubscriber)
router.register(r'data/pd_user/', views.DataOnCall)
router.register(r'data/bgp/', views.DataBGP)
router.register(r'data/device/routingtable/', views.DataDeviceRoutingTable)
router.register(r'monitoring/bgp/', views.MonitoringBGP)
router.register(r'monitoring/script_results/', views.MonitoringScriptResults)
router.register(r'monitoring/circuit_maintenance/', views.MonitoringCircuitMaintenance)
router.register(r'monitoring/device/routingtable/', views.MonitoringDeviceRoutingTable)
#### LEGACY ####
router.register(r'credentials', views.CredentialDataROView)
router.register(r'tasks', views.TaskSet)
router.register(r'subnets', views.SubnetsSet)
router.register(r'device_conns', views.DeviceConnViewSet)
router.register(r'script_results', views.ScriptResultsView)
router.register(r'circuit_maintenance', views.CircuitMaintenanceView)
router.register(r'email_subscriber', views.EmailSubscriberROView)
router.register(r'pd_user', views.OnCallROView)
router.register(r'bgp_monitoring_data', views.BGPMonitoringDataView)
router.register(r'bgp_status', views.BGPStatusView)
router.register(r'rt_get_devices', views.MonitoringRoutingTableGetDevice)
router.register(r'rt_get_tables', views.MonitoringRoutingTableGet)
router.register(r'rt_upload', views.MonitoringRoutingTableUpload)
router.register(r'contact_type', views.ContactTypeROView)
# Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browsable API.
urlpatterns = [
path('', include(router.urls)),
path('api-auth/', include('rest_framework.urls')),
#### NEW ####
path('data/site_subnets/', views.DataSiteSubnets.as_view()),
path('data/site_circuits_subnets/', views.DataSiteCircuitSubnets.as_view()),
path('data/device/routing_table/', views.DataDeviceRoutingTable.as_view({'get': 'list','put': 'update'})),
path('data/geomapping/', views.DataGeoMapping.as_view()),
path('monitoring/oncall/', views.MonitoringOnCall.as_view()),
path('monitoring/site_connectivity/', views.MonitoringSiteConnectivity.as_view()),
#### LEGACY ####
path('ss_monitoring_data/', views.SiteSupernetMontioringDataROView.as_view()),
path('monitoring/routing_data', views.MontioringGetRoutingData.as_view()),
path('conn_set_single/<int:site_id>/<int:circuit_id>/', views.MonitoringConnectivitySetSingle.as_view()),
path('conn_set/', views.MonitoringConnectivitySet.as_view()),
path('site_circuits_pending/<int:days>/', views.SiteCircuitsPendingDataROView.as_view({'get': 'list'})),
path('upcoming_circuit_maintenance/<int:days>/', views.UpcomingCircuitMaintenanceView.as_view({'get': 'list'})),
path('aws_bgpdata_set/', views.MonitoringBGPDataSet.as_view()),
path('aws_dc_set/', views.MonitoringAWSDirectConnectSet.as_view()),
path('aws_vpn_set/', views.MonitoringAWSVPNSet.as_view()),
path('four_g_set/', views.FourGDataSet.as_view()),
path('contact_set/', views.ContactSet.as_view()),
path('site_contact_set/', views.SiteContactSet.as_view()),
path('device_version_set/', views.DeviceVersionSet.as_view()),
]
home.urls
from django.urls import path
from . import views
app_name = 'home'
urlpatterns = [
path('', views.index, name='index'),
....
and then I attempt to hit the URL http://localhost:8100/api/data/device/routingtable/ and I am greeted with a 404, would anyone know why this is?
and when I hit my api home page and it lists urls, they are mapped to the wrong views:
HTTP 200 OK
Allow: GET, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept
{
...
"data/device/routingtable/": "http://localhost:8100/api/rt_upload/",
...
}
views.py:
class DataDeviceRoutingTable(viewsets.ModelViewSet):
time_threshold = datetime.now() - timedelta(minutes=2)
queryset = DeviceData.objects.all().select_related('device','device_use').order_by('monitoring_order')
serializer_class = SerializerDataRoutingTable
permission_classes = (IsAdminUser,)
filter_class = DeviceData
filter_backends = (filters.SearchFilter,)
search_fields = ('device__hostname','device_use__use')
serialisers.py:
class SerializerDataRoutingTable(serializers.ModelSerializer):
hostname = serializers.ReadOnlyField(source='device.hostname', )
site_id = serializers.ReadOnlyField(source='device.site_id', )
routing_table = serializers.SerializerMethodField(source='routing_table',)
use = serializers.ReadOnlyField(source='device_use.use', )
def get_routing_table(self, instance):
try:
return json.loads(instance.routing_table)
except:
return instance.routing_table
class Meta:
model = DeviceData
fields = ('id','site_id','device_id','hostname','use', 'timestamp', 'routing_table')
depth = 1
urls.py:
from django.urls import path, include
from django.conf import settings
from django.contrib.auth import views as auth_views
from django.contrib import admin
import app_settings.views
admin.autodiscover()
handler400 = 'app_settings.views.bad_request'
handler403 = 'app_settings.views.permission_denied'
handler404 = 'app_settings.views.page_not_found'
handler500 = 'app_settings.views.server_error'
urlpatterns = [
path('', include('home.urls')),
path('api/', include('api.urls')),

django links to the comment function in the backend does not work

After transfer the website to another server with higher python version stoped working the links in the backend to the comment function. Does somebody know where could the problem be? Thank you.
I´m using django 1.6 (I hope I could update it soon)
This is code in the settings.py on the root level (only the important parts)
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.syndication',
'django_comments',
'blog',
'hyper',
'webmanager',
'watson',
)
INSTALLED_APPS += ('django_summernote', )
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'webmanager.middleware.MyPageMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'urls'
SITE_ID='1'
#WSGI_APPLICATION = 'marxelhino.wsgi.application'
# fluent-comments settings:
FLUENT_COMMENTS_USE_EMAIL_MODERATION = True
FLUENT_COMMENTS_MODERATE_AFTER_DAYS = 14
FLUENT_COMMENTS_CLOSE_AFTER_DAYS = 60
FLUENT_COMMENTS_AKISMET_ACTION = 'moderate'
AKISMET_API_KEY = None # Add your Akismet key here to enable Akismet support
AKISMET_IS_TEST = True # for development/example apps.
This is the code I have in the urls.py on the root level
from django.conf.urls import patterns, include, url
from django.conf import settings
from django.conf.urls.static import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from marxelhino.feeds import Latest
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'marxelinho.views.home', name='home'),
url(r'^$', 'blog.views.index', name='index'),
url(r'^blog/(?P<slug>[a-zA-Z0-9_.-]+)/$$', 'blog.views.detail', name='detail'),
url(r'^blog/by_year/(?P<year>\d{4})/$', 'blog.views.post_year', name='list-years'),
url(r'^blog/(?P<year>\d{4})/(?P<month>\d{1,2})/$', 'blog.views.post_month', name='list-month'),
url(r'^blog/(?P<year>\d{4})/(?P<month>\d{1,2})/(?P<day>\d{1,2})/$', 'blog.views.post_day', name='list-day'),
url(r'^category/(?P<slug>[a-zA-Z0-9_./-]+)/$$', 'blog.views.category_detail', name='category_detail'),
#url(r'^blog/comments/', include('fluent_comments.urls')),
url(r'^comments/', include('django_comments.urls')),
(r'^latest/feed/$', Latest()),
url(r'^tinymce/', include('tinymce.urls')),
url(r'^search/', include('search.urls')),
url(r'^summernote/', include('django_summernote.urls')),
url(r'^accounts/', include('registration.backends.default.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)),
(r'^static/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.STATIC_ROOT}),
(r'^media/(?P<path>.*)$', 'django.views.static.serve',
# (r'^suche/', include('haystack.urls')),
{'document_root': settings.MEDIA_ROOT}),
)
the code in urls.py in the folder django_comments
from django.conf.urls import patterns, url
urlpatterns = patterns('django_comments.views',
url(r'^post/$', 'comments.post_comment', name='comments-post-comment'),
url(r'^posted/$', 'comments.comment_done', name='comments-comment-done'),
url(r'^flag/(\d+)/$', 'moderation.flag', name='comments-flag'),
url(r'^flagged/$', 'moderation.flag_done', name='comments-flag-done'),
url(r'^delete/(\d+)/$', 'moderation.delete', name='comments-delete'),
url(r'^deleted/$', 'moderation.delete_done', name='comments-delete-done'),
url(r'^approve/(\d+)/$', 'moderation.approve', name='comments-approve'),
url(r'^approved/$', 'moderation.approve_done', name='comments-approve-done'),
)
urlpatterns += patterns('',
url(r'^cr/(\d+)/(.+)/$', 'django.contrib.contenttypes.views.shortcut', name='comments-url-redirect'),
)
and this code is in the folder fluent_comments and in the file views.py
from django.core.exceptions import ObjectDoesNotExist, ValidationError
from django.db import models
from django.http import HttpResponse, HttpResponseBadRequest
from django.template.loader import render_to_string
from django.template import RequestContext
from django.contrib import comments
from django.contrib.comments import signals
from django.contrib.comments.views.comments import CommentPostBadRequest
from django.utils.html import escape
from django.views.decorators.csrf import csrf_protect
from django.views.decorators.http import require_POST
from fluent_comments import appsettings
import json
#csrf_protect
#require_POST
def post_comment_ajax(request, using=None):
"""
Post a comment, via an Ajax call.
"""
if not request.is_ajax():
return HttpResponseBadRequest("Expecting Ajax call")
# This is copied from django.contrib.comments.
# Basically that view does too much, and doesn't offer a hook to change the rendering.
# The request object is not passed to next_redirect for example.
#
# This is a separate view to integrate both features. Previously this used django-ajaxcomments
# which is unfortunately not thread-safe (it it changes the comment view per request).
# Fill out some initial data fields from an authenticated user, if present
data = request.POST.copy()
if request.user.is_authenticated():
if not data.get('name', ''):
data["name"] = request.user.get_full_name() or request.user.username
if not data.get('email', ''):
data["email"] = request.user.email
# Look up the object we're trying to comment about
ctype = data.get("content_type")
object_pk = data.get("object_pk")
if ctype is None or object_pk is None:
return CommentPostBadRequest("Missing content_type or object_pk field.")
try:
object_pk = long(object_pk)
model = models.get_model(*ctype.split(".", 1))
target = model._default_manager.using(using).get(pk=object_pk)
except ValueError:
return CommentPostBadRequest("Invalid object_pk value: {0}".format(escape(object_pk)))
except TypeError:
return CommentPostBadRequest("Invalid content_type value: {0}".format(escape(ctype)))
except AttributeError:
return CommentPostBadRequest("The given content-type {0} does not resolve to a valid model.".format(escape(ctype)))
except ObjectDoesNotExist:
return CommentPostBadRequest("No object matching content-type {0} and object PK {1} exists.".format(escape(ctype), escape(object_pk)))
except (ValueError, ValidationError) as e:
return CommentPostBadRequest("Attempting go get content-type {0!r} and object PK {1!r} exists raised {2}".format(escape(ctype), escape(object_pk), e.__class__.__name__))
# Do we want to preview the comment?
preview = "preview" in data
# Construct the comment form
form = comments.get_form()(target, data=data)
# Check security information
if form.security_errors():
return CommentPostBadRequest("The comment form failed security verification: {0}".format)
# If there are errors or if we requested a preview show the comment
if preview:
comment = form.get_comment_object() if not form.errors else None
return _ajax_result(request, form, "preview", comment, object_id=object_pk)
if form.errors:
return _ajax_result(request, form, "post", object_id=object_pk)
# Otherwise create the comment
comment = form.get_comment_object()
comment.ip_address = request.META.get("REMOTE_ADDR", None)
if request.user.is_authenticated():
comment.user = request.user
# Signal that the comment is about to be saved
responses = signals.comment_will_be_posted.send(
sender = comment.__class__,
comment = comment,
request = request
)
for (receiver, response) in responses:
if response is False:
return CommentPostBadRequest("comment_will_be_posted receiver {0} killed the comment".format(receiver.__name__))
# Save the comment and signal that it was saved
comment.save()
signals.comment_was_posted.send(
sender = comment.__class__,
comment = comment,
request = request
)
return _ajax_result(request, form, "post", comment, object_id=object_pk)
def _ajax_result(request, form, action, comment=None, object_id=None):
# Based on django-ajaxcomments, BSD licensed.
# Copyright (c) 2009 Brandon Konkle and individual contributors.
#
# This code was extracted out of django-ajaxcomments because
# django-ajaxcomments is not threadsafe, and it was refactored afterwards.
success = True
json_errors = {}
if form.errors:
for field_name in form.errors:
field = form[field_name]
json_errors[field_name] = _render_errors(field)
success = False
json_return = {
'success': success,
'action': action,
'errors': json_errors,
'object_id': object_id,
'use_threadedcomments': bool(appsettings.USE_THREADEDCOMMENTS),
}
if comment is not None:
context = {
'comment': comment,
'action': action,
'preview': (action == 'preview'),
'USE_THREADEDCOMMENTS': appsettings.USE_THREADEDCOMMENTS,
}
comment_html = render_to_string('comments/comment.html', context, context_instance=RequestContext(request))
json_return.update({
'html': comment_html,
'comment_id': comment.id,
'parent_id': None,
'is_moderated': not comment.is_public, # is_public flags changes in comment_will_be_posted
})
if appsettings.USE_THREADEDCOMMENTS:
json_return['parent_id'] = comment.parent_id
json_response = json.dumps(json_return)
return HttpResponse(json_response, content_type="application/json")
def _render_errors(field):
"""
Render form errors in crispy-forms style.
"""
template = '{0}/layout/field_errors.html'.format(appsettings.CRISPY_TEMPLATE_PACK)
return render_to_string(template, {
'field': field,
'form_show_errors': True,
})
and this code in the folder fluent_comments and in the file urls.py
try:
# Django 1.6 requires this
from django.conf.urls import url, patterns, include
except ImportError:
# Django 1.3 compatibility, kept in minor release
from django.conf.urls.defaults import url, patterns, include
urlpatterns = patterns('fluent_comments.views',
url(r'^post/ajax/$', 'post_comment_ajax', name='comments-post-comment-ajax'),
url(r'', include('django.contrib.comments.urls')),
)

Django-hosts redirect form non-www to www

The site generates different URLs that all look like http://example.com/'somepath'. What I want to do is to redirect users from http://example.com/'somepath' to http://www.example.com/'somepath'. As I found out it's possible to do with django-hosts.
As it's said in instructions I have the following in settings.py:
ALLOWED_HOSTS = ['www.example.com', 'example.com']
INSTALLED_APPS = [
...,
'django_hosts',
]
MIDDLEWARE = [
'django_hosts.middleware.HostsRequestMiddleware',
...
'django_hosts.middleware.HostsResponseMiddleware',
]
ROOT_URLCONF = 'appname.urls'
ROOT_HOSTCONF = 'appname.hosts'
DEFAULT_HOST = 'www'
DEFAULT_REDIRECT_URL = "http://www.example.com"
PARENT_HOST = "example.com"
In hostsconf/urls:
from django.conf.urls import url
from .views import wildcard_redirect
urlpatterns = [
url(r'^(?P<path>.*)', wildcard_redirect),
]
In hostsconf/views:
from django.conf import settings
from django.http import HttpResponseRedirect
DEFAULT_REDIRECT_URL = getattr(settings, "DEFAULT_REDIRECT_URL", "http://www.example.com")
def wildcard_redirect(request, path=None):
new_url = DEFAULT_REDIRECT_URL
if path is not None:
new_url = DEFAULT_REDIRECT_URL + "/" + path
return HttpResponseRedirect(new_url)
But looks like it doesn't work because if I go to http://example.com/'somepath' it returns "400 Bad Request" and http://www.example.com/'somepath' points to the correct destination. What am I doing wrong?
Try the default settings PREPEND_WWW
https://docs.djangoproject.com/en/1.10/ref/settings/#prepend-www

Django remember me doesn't work

I want, to close session when browser is closed, but if user checked remember me, session must be open after browser close, so i did this one but it doesn't work, it always closes.
my settings.py:
SESSION_EXPIRE_AT_BROWSER_CLOSE = True
my views.py
if request.POST['rememberme']:
settings.SESSION_EXPIRE_AT_BROWSER_CLOSE = False
views.py
from django.contrib.auth import views as auth_views
def login_user(request, template_name='registration/login.html', extra_context=None):
response = auth_views.login(request, template_name)
if request.POST.has_key('remember_me'):
request.session.set_expiry(1209600) # 2 weeks
urls.py
urlpatterns = [
url(r'^login/$', login_user, name='auth_login'),
]