I am trying to use django-autocomplete-light 3.2.1 in my Django (1.10) project with python (3.5) and I found great difficulty in using it. Then I try to follow the live demo shown in the tutorial and pull down all file to my local drive for replication (like the one on http://dal-yourlabs.rhcloud.com/select2_outside_admin/), however in vain. To me, I want to make my local demo work so that I can work my own one based on this.
Specifically, when I follow the following codes and run the site, it shows the errors of NoReverseMatch at /select2_outside_admin/ with description of Reverse for 'linked_data' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: [] I have no idea what is going wrong. I attached my codes as below and please advise what to do if you know the solution. Many thanks:
settings.py:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'select2_outside_admin',
# Autocomplete
'dal',
# Enable plugins
'dal_select2',
'dal_queryset_sequence',
]
urls.py:
from django.conf.urls import url, include
from django.contrib import admin
from .views import UpdateView
urlpatterns = [
url(r'^admin/', admin.site.urls),
# url(r'^select2_outside_admin/', include('select2_outside_admin.urls')),
url(
r'^select2_outside_admin/$',
UpdateView.as_view(),
name='select2_outside_admin',
),
]
models.py:
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
#python_2_unicode_compatible
class TModel(models.Model):
name = models.CharField(max_length=200)
test = models.ForeignKey(
'self',
null=True,
blank=True,
related_name='related_test_models'
)
owner = models.ForeignKey(
'auth.user',
null=True,
blank=True,
related_name='owned_linked_models',
)
for_inline = models.ForeignKey(
'self',
null=True,
blank=True,
related_name='inline_test_models'
)
def __str__(self):
return self.name
forms.py:
from dal import autocomplete
from django import forms
from .models import TModel
class TForm(forms.ModelForm):
def clean_test(self):
owner = self.cleaned_data.get('owner', None)
value = self.cleaned_data.get('test', None)
if value and owner and value.owner != owner:
raise forms.ValidationError('Wrong owner for test')
return value
class Meta:
model = TModel
fields = ('name', 'owner', 'test')
widgets = {
'test': autocomplete.ModelSelect2(url='linked_data',
forward=('owner',))
}
class Media:
js = (
'linked_data.js',
)
views.py:
from django.shortcuts import render
from django.core.urlresolvers import reverse_lazy
from django.views import generic
from select2_outside_admin.forms import TForm
from select2_outside_admin.models import TModel
# Create your views here.
class UpdateView(generic.UpdateView):
model = TModel
form_class = TForm
template_name = 'select2_outside_admin.html'
success_url = reverse_lazy('select2_outside_admin')
def get_object(self):
return TModel.objects.first()
Related
I'm getting this error while i am using my own AUTHENTICATION_BACKENDS
Model class tainfo.apps.users.models.User doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.
my own backend:
from django.contrib.auth.backends import ModelBackend
import re
from tainfo.apps.users.models import User
def get_user_by_account(account):
try:
if re.match(r'1[3-9]\d{9}',account):
user = User.objects.get(mobile=account)
else:
user = User.objects.get(username=account)
return user
except User.DoesNotExist:
return None
class UsernameMobileAuthBackend(ModelBackend):
def authenticate(self,request,username=None,password=None,**kwargs):
user = get_user_by_account(username)
if user and user.check_password(password) and user.is_active:
return user
I put this in my devsettings.py:
AUTHENTICATION_BACKENDS = ['users.utils.UsernameMobileAuthBackend',]
if i delete this from settings,then this error will gone,but i that case i won't be able to use my own auth backends.
any idea what i have done wrong?
thanks
updates:
my user model
from django.contrib.auth.models import AbstractUser
from django.db import models
# Create your models here.
class User(AbstractUser):
mobile = models.CharField(max_length=11, unique=True, verbose_name='mobile',blank=True)
email_active = models.BooleanField(default=False, verbose_name='emailisactive')
class Meta:
db_table = 'tb_users'
verbose_name = 'user'
verbose_name_plural = verbose_name
def __str__(self):
return self.username
devsettings:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'users.apps.UsersConfig',
'contents.apps.ContentsConfig',
'verifications.apps.VerificationsConfig',
]
AUTH_USER_MODEL = 'users.User'
AUTHENTICATION_BACKENDS = ['users.utils.UsernameMobileAuthBackend',]
dirs.png
resolved:
from django.contrib.auth.backends import ModelBackend
import re
from tainfo.apps.users.models import User
turns out it was the path that i used in utils..
apps's path is in my sys.path ,and i should use 'from users.models import User',like this :
from django.contrib.auth.backends import ModelBackend
import re
from users.models import User
Thanks everyone
so i'm following the Django project in the textbook "Python crash course 2nd ed" and i'm into the mapping URLS section for those who know, and when i try my system cant seem to runserver anymore, i'm encountering the following error: AttributeError: module 'django.db.models' has no attribute 'BigAutoField'
if anyone can help, it would be great, thanks already. i'm fairly new to django and trying my way around it but i don't really know what or where to find the error..
it worked actually fine before i added the two urls.py:
from django.urls import path, include
from django.contrib import admin
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('learning_logs.urls'), name='learning_logs'),
]
and
"""Defines url patterns for learning_logs."""
from django.urls import path
from . import views
app_name = 'learning_logs'
urlpatterns = [
# Home page.
path('', views.index, name='index'),
]
the models.py is
from django.db import models
# Create your models here.
class Topic(models.Model):
"""A topic the user is learning about"""
text = models.CharField(max_length=200)
date_added = models.DateTimeField(auto_now_add=True)
def __str__(self):
"""return a string representation of the model"""
return self.text
class Entry(models.Model):
"""something specific learned about a topic"""
topic = models.ForeignKey(Topic, on_delete=models.CASCADE)
text = models.TextField()
date_added = models.DateTimeField(auto_now_add=True)
class Meta:
verbose_name_plural = 'entries'
def __str__(self):
"""return a string representation of the model"""
if len(self.text) >= 50:
return f"{self.text[:50]}..."
else:
return "..."
It is the version you have to change.
Django 1.8 does not have BigAutoField.
Here's url to Django 1.8 doc
I followed the turial at django-rest-framework quickstart
I have two URLs namely /users/ and /groups/
The group works perfectly:
but the user url gets a error like this:
server error 500
I set DEBUG to False then add some host to ALLOWED_HOST in settings.py:
DEBUG = False
ALLOWED_HOSTS = [
'127.0.0.1',
'localhost'
]
INSTALLED_APPS = [
'rest_framework',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
my urls.py:
from django.contrib import admin
from django.urls import include, path
from rest_framework import routers
from django_rest.django_rest_app import views
router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet)
router.register(r'groups', views.GroupViewSet)
# 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', namespace='rest_framework'))
]
this is my serializers.py:
from django.contrib.auth.models import User, Group
from rest_framework import serializers
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ['url','username','email','group']
class GroupSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Group
fields = ['url','name']
and this is my views.py:
from django.shortcuts import render
from django.contrib.auth.models import User, Group
from rest_framework import viewsets
from rest_framework import permissions
from django_rest.django_rest_app.serializers import UserSerializer, GroupSerializer
class UserViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows users to be viewed or edited.
"""
queryset = User.objects.all().order_by('-date_joined')
serializer_class = UserSerializer
permission_classes = [permissions.IsAuthenticated]
class GroupViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows groups to be viewed or edited.
"""
queryset = Group.objects.all()
serializer_class = GroupSerializer
permission_classes = [permissions.IsAuthenticated]
UPDATE
when I set DEBUG to True again, I got this:
Field name group is not valid for model User
I'm still a beginner, I hope you can help
Thanks.
You have made mistake in UserSerializer class
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ['url','username','email','group']
Please change as follows
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ['url','username','email','groups']
there is no field named 'group' in User model. Instead it is 'groups'.
I am unable to do PUT operation in Django rest framework, I am able to GET, POST, DELETE operation.
This is the error
I have tried using #api_view but there also its not,
I mostly refer the djangorestframework website
Below is my code:
serializers.py
from rest_framework import serializers
from snippets.models import Snippet
#from django.contrib.auth.models import *
class SnippetSerializer(serializers.ModelSerializer):
class Meta:
model = Snippet
fields = ('id','title','code')
Models.py
from __future__ import unicode_literals
from django.db import models
# Create your models here.
class Snippet(models.Model):
created = models.DateTimeField(auto_now_add=True)
title = models.CharField(max_length=100, blank=True, default='')
code = models.CharField(max_length=100, blank=True, default='')
class Meta:
ordering = ('created',)
Views.py
from rest_framework import viewsets
from rest_framework.decorators import api_view
from snippets.serializers import SnippetSerializer
class SnippetViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows users to be viewed or edited.
"""
queryset = Snippet.objects.all().order_by('id')
serializer_class = SnippetSerializer
urls.py
rom django.conf.urls import url, include
from rest_framework import routers
from django.contrib import admin
from snippets import views
router = routers.DefaultRouter()
router.register(r'snippet', views.SnippetViewSet)
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', include(router.urls)),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
]
Looking at the documentation of DefaultRouter, it looks like that PUT method can only be used with {basename}-detail type of URLs.
While you are using it directly on /snippet url where it is not allowed.
I followed the qblog tutorial, using python 2.7.10 and django 1.9.5.
When i enter the admin's blog interface, and clicked add blog entry, then it shown me below:
TemplateDoesNotExist at /admin/blog/entry/add/
django_markdown/editor_init.html
but i have installed django-markdown already. I would like to show the code below:
models.py:
class Entry(models.Model):
title = models.CharField(max_length=200)
body = MarkdownField()
slug = models.SlugField(max_length=200, unique=True)
publish = models.BooleanField(default=True)
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
tags = models.ManyToManyField(Tag)
objects = EntryQuerySet.as_manager()
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse("entry_detail", kwargs={"slug": self.slug})
class Meta:
verbose_name = "Blog Entry"
verbose_name_plural = "Blog Entries"
ordering = ["-created"]
admin.py:
from django.contrib import admin
from . import models
from django_markdown.admin import MarkdownModelAdmin
from django_markdown.widgets import AdminMarkdownWidget
from django.db.models import TextField
class EntryAdmin(MarkdownModelAdmin):
list_display = ("title", "created")
prepopulated_fields = {"slug": ("title",)}
# Next line is a workaround for Python 2.x
formfield_overrides = {TextField: {'widget': AdminMarkdownWidget}}
admin.site.register(models.Entry, EntryAdmin)
admin.site.register(models.Tag)
qblog/urls.py:
from django.conf.urls import patterns, include, url
from django.contrib import admin
import settings
urlpatterns = patterns(
'',
url(r'^admin/', include(admin.site.urls)),
url(r'^markdown/', include("django_markdown.urls")),
url(r'^', include('blog.urls')),
)
if settings.DEBUG:
from django.conf.urls.static import static
urlpatterns += static(settings.STATIC_URL,document_root=settings.STATIC_ROOT)
You need to add the editor_init.html file in your project.
If your project root is project/ there should be a directory called templates in there. If that directory does not exist, create it (so the path would be project/templates).
Place the editor_init.html file in this directory and everything should work.
You can find more information about setting up templates here and in the django docs.