Module 'django.db.models' has no attribute 'FileBrowseField' - django

I would like to have on my Django 2.1.1 site django-filebrowser-no-grappelli. I've followed this indications but at the end of the procedure, when I restart my server, I've this error:
header_image = models.FileBrowseField("Image", max_length=200,
directory="images/", extensions=[".jpg"], blank=True) AttributeError:
module 'django.db.models' has no attribute 'FileBrowseField'
This are the files of my project:
MODELS.PY
from django.db import models
from django.urls import reverse
from tinymce import HTMLField
from filebrowser.fields import FileBrowseField
class Post(models.Model):
"""definizione delle caratteristiche di un post"""
title = models.CharField(max_length=70, help_text="Write post title here. The title must be have max 70 characters", verbose_name="Titolo", unique=True)
short_description = models.TextField(max_length=200, help_text="Write a post short description here. The description must be have max 200 characters", verbose_name="Breve descrizione dell'articolo")
contents = HTMLField(help_text="Write your post here", verbose_name="Contenuti")
publishing_date = models.DateTimeField(verbose_name="Data di pubblicazione")
updating_date = models.DateTimeField(auto_now=True, verbose_name="Data di aggiornamento")
header_image = models.FileBrowseField("Image", max_length=200, directory="images/", extensions=[".jpg"], blank=True)
slug = models.SlugField(verbose_name="Slug", unique="True", help_text="Slug is a field in autocomplete mode, but if you want you can modify its contents")
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse("singlearticleView", kwargs={"slug": self.slug})
class Meta:
verbose_name = "Articolo"
verbose_name_plural = "Articoli"
VIEWS.PY
from django.shortcuts import render
from .models import Post
from django.views.generic.detail import DetailView
from django.views.generic.list import ListView
class SingleArticle(DetailView):
model = Post
template_name = "single_article.html"
class ListArticles(ListView):
model = Post
template_name = "list_articles.html"
def get_queryset(self):
return Post.objects.order_by('-publishing_date')
URLS.PY
from django.urls import path
from .views import ListArticles, SingleArticle
urlpatterns = [
path("", ListArticles.as_view(), name="listarticlesView"),
path("<slug:slug>/", SingleArticle.as_view(), name="singlearticleView"),
]
ADMIN.PY
from django.contrib import admin
from .models import Post
class PostAdmin(admin.ModelAdmin):
"""creazione delle caratteristiche dei post leggibili nel pannello di amministrazione"""
list_display = ["title", "publishing_date", "updating_date", "id"]
list_filter = ["publishing_date"]
search_fields = ["title", "short_description", "contents"]
prepopulated_fields = {"slug": ("title",)}
fieldsets = [
(None, {"fields": ["title", "slug"]}),
("Contenuti", {"fields": ["short_description", "contents"]}),
("Riferimenti", {"fields": ["publishing_date"]}),
]
class Meta:
model = Post
admin.site.register(Post, PostAdmin)
URLS.PY PROJECT
from django.contrib import admin
from django.urls import path, include
from filebrowser.sites import site
urlpatterns = [
path('admin/filebrowser/', site.urls),
path('grappelli/', include('grappelli.urls')),
path('admin/', admin.site.urls),
path('', include('app4test.urls')),
path('tinymce/', include('tinymce.urls')),
]
I've started all of this because I will use TinyMCE and a file browser application is necessary. When I deactive the string header_image in models.py the project running well but, obviously, when I try to upload an image I've an error.
Where I made a mistake?

your import is done like this:
from filebrowser.fields import FileBrowseField
but you're trying to use the field following way:
header_image = models.FileBrowseField(...)
It's not part of the models package, just do it without the models. part:
header_image = FileBrowseField(...)

Related

TemplateDoesNotExist: home.html, femat/law_list.html

Why I am getting the above error while I have not defined or requested "law_list.html"? Where does the law_list.html come from? It should be something wrong with model and class based view. I am using Django 3.1.3.
#models.py
from django.db import models
class Law(models.Model):
name = models.CharField(max_length=100)
E = models.FloatField(null=False, blank=False, default=0)
def __str__(self):
return '{} {}'.format(self.name, self.E)
#views.py
from django.views.generic import ListView
from .models import Law
class HomeView(ListView):
model = Law
template_name = 'home.html'
#urls.py
from django.urls import path
from .views import HomeView
urlpatterns = [
path('', HomeView.as_view(), name='home'),
]
This should do it:
template_name= "femat/home.html"

Django Models not showing in template

I am finding it quite difficult to display django models in template. The Model does not show at all in the template. Any help will indeed be appreciated.
models.py
from django.db import models
from django.urls import reverse
from datetime import datetime
class Blog(models.Model):
name= models.CharField(max_length = 200)
company= models.CharField(max_length = 200)
post = models.CharField(max_length = 200)
author= models.ForeignKey('auth.User', on_delete = models.PROTECT)
mantra= models.CharField(max_length = 200, help_text='make it short and precise')
photo= models.ImageField(upload_to='photos/jobs/%Y/%m/%d/', blank=False, null=False)
publish = models.BooleanField(default =True)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('index')
views.py
from django.shortcuts import render
from django.views.generic import TemplateView,ListView
from django.views.generic.edit import CreateView
from .models import Blog
class Home(ListView):
model = Blog
context_object_name = 'test'
template_name='test.html'
fields = ['name', 'company', 'post', 'author', 'mantra', 'continent', 'photo']
urls.py
from django.urls import path
from .views import Home
urlpatterns=[
path('', Home.as_view(), name='index'),
]
Template
<p>{{test.name}}</p>
<p>{{test.author}}</p>
<p>{{test.post}}</p>
You should loop on the queryset:
{% for object in test %}
<p>{{object.name}}</p>
<p>{{object.author}}</p>
<p>{{object.post}}</p>
{% endfor %}

What would be the format of urls.py for class based views?

I am new to django so i want to know how to write urls.py for a project.
I want to make backend api for inventory management system.
When i type localhost:8000/inventory_backend/dep/, I am having following error:
**Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order:
The current path, inventory_backend/dep/, didn't match any of these.
My code for mysite/urls.py**
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^inventory_backend/', include('inventory_backend.urls')
),
url(r'^admin/', admin.site.urls) ,
]
inventory_backend/urls.py:
from inventory_backend.views import DepartmentsView,InventoriesView
from rest_framework import routers
router = routers.SimpleRouter()
router.register(r'dep/',DepartmentsView )
router.register(r'inv/',InventoriesView )
urlpatterns = router.urls
serializers.py
from rest_framework import serializers
from inventory_backend.models import Departments,Inventories
class DepartmentsSerializer(serializers.ModelSerializer):
class Meta:
model : Departments
fields: ('id','name')
class InventoriesSerializer(serializers.ModelSerializer):
dept = DepartmentsSerializer(many=True)
class Meta:
model : Inventories
fields : ('id','name','description','dept')
models.py
from django.db import models
class Departments(models.Model):
name = models.CharField(max_length=200)
def __str__(self):
return self.name
class Inventories(models.Model):
name = models.CharField(max_length=200)
description = models.CharField(max_length=200)
dept = models.ManyToManyField(Departments)
def __str__(self):
return self.name
views.py
from rest_framework import viewsets
from inventory_backend.models import Inventories,Departments
from inventory_backend.serializers import InventoriesSerializer,
DepartmentsSerializer
class DepartmentsView(viewsets.ModelViewSet):
queryset = Departments.objects.all();
serializer_class = DepartmentsSerializer;
class InventoriesView(viewsets.ModelViewSet):
queryset = Inventories.objects.all();
serializer_class = InventoriesSerializer;
Change your inventory_backend.urls.py,
urlpatterns = [
url(r'^', include(router.urls))
]

How to make HyperlinkedModelSerializer in Django Rest Framework work for foreignkeys?

I am new to Django Rest Framework and am struggling to get my serialisations to work correctly for a foreignkey relationship between two models. I have tried to reduce my setup down to be as simple as possible but I still can't understand how it is supposed to work. I am trying to use HyperlinkedModelSerializer so (from the docs) 'that it uses hyperlinks to represent relationships'. When I try to visit the url for either the list or detail view for {model X} on the test server I get:
'Could not resolve URL for hyperlinked relationship using view name
"{model Y}-detail". You may have failed to include the related model
in your API, or incorrectly configured the lookup_field attribute on
this field.'
What am I doing wrong?
My models:
from django.db import models
class Project(models.Model):
name = models.CharField(max_length=50)
description = models.TextField()
class ProjectPhoto(models.Model):
project = models.ForeignKey(
Project, related_name='photos', on_delete=models.CASCADE
)
image = models.ImageField()
caption = models.CharField(max_length=100)
date_added = models.DateTimeField(auto_now_add=True)
My serializers
class ProjectSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Project
fields = ('name', 'description', 'photos')
class ProjectPhotoSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = ProjectPhoto
fields = ('image', 'caption', 'date_added', 'project'))
My views:
from rest_framework import viewsets
from projects.models import Project, ProjectPhoto
from projects.serializers import ProjectSerializer, ProjectPhotoSerializer
class ProjectViewSet(viewsets.ModelViewSet):
queryset = Project.objects.all().order_by('name')
serializer_class = ProjectSerializer
class ProjectPhotoViewSet(viewsets.ModelViewSet):
queryset = ProjectPhoto.objects.all().order_by('date_added')
serializer_class = ProjectPhotoSerializer
EDIT:
My urls:
from django.conf.urls import url, include
from rest_framework import routers
from projects import views
router = routers.DefaultRouter()
router.register(r'^projects', views.ProjectViewSet)
router.register(r'^project-photos', views.ProjectPhotoViewSet)
urlpatterns = [
url(r'^', include(router.urls)),
]
these are then added in my main app urls.py file. I don't think this is problem as if I change the serializer to ModelSerializer then everything works fine.
I think your problem is in your urls.py file, see the code and picture
rest/urls.py file
from django.conf.urls import url, include
from rest_framework import routers
from .views import ProjectViewSet, ProjectPhotoViewSet
router = routers.SimpleRouter()
router.register(r'project', ProjectViewSet)
router.register(r'project-photo', ProjectPhotoViewSet)
urlpatterns = [
url(r'^', include(router.urls)),
]
Principal urls.py file:
from django.conf.urls import url, include
from django.contrib import admin
from rest import urls as urls_rest
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^rest/', include(urls_rest)),
]
and other option, try to use this code in your serializers.py file:
from rest_framework import serializers
from .models import Project, ProjectPhoto
class ProjectPhotoSerializer(serializers.ModelSerializer):
class Meta:
model = ProjectPhoto
fields = ('image', 'caption', 'date_added', 'project')
class ProjectSerializer(serializers.ModelSerializer):
class Meta:
model = Project
fields = ('name', 'description', 'photos')
depth = 2
You have 3 options to use serializers (see picture below)

manyToMany with django rest framework

I am currently using the default CRUD operations provided by django-rest-framework. It works well with normal models but one of my model has many-many relation with another tag model. Here is the code for models
class ActivityType(models.Model):
title = models.CharField(max_length=200)
slug = models.CharField(max_length=250,unique=True)
def __unicode__(self):
return self.slug
class Activity(models.Model):
owner = models.ForeignKey('auth.user')
title = models.CharField(max_length=200)
slug = models.CharField(max_length=250,unique=True)
description = models.TextField()
tags = models.ManyToManyField(ActivityType)
created = models.DateTimeField(auto_now_add=True, blank=True)
def __unicode__(self):
return self.slug
What i want to know is what is the best method to integrate DRF with the same, if possible without writing all CRUD operations from scratch.
In your serializers.py
from rest_framework import serializers
from rest_framework import generics
from models import Activity
from models import ActivityType
class ActivityTypeSerializer(serializers.ModelSerializer):
class Meta:
model = ActivityType
fields = ('id', 'title', 'slug')
class ActivitySerializer(serializers.ModelSerializer):
tags = ActivityTypeSerializer(many=True, read_only=True)
class Meta:
model = Activity
fields = ('id', 'owner', 'title', 'slug', 'description', 'tags', 'created')
in your views.py
from rest_framework import viewsets
from serializers import ActivitySerializer
from serializers import ActivityTypeSerializer
from models import Activity
from models import ActivityType
class ActivityViewSet(viewsets.ModelViewSet):
queryset = Activity.objects.all()
serializer_class = ActivitySerializer
class ActivityTypeViewSet(viewsets.ModelViewSet):
queryset = ActivityType.objects.all()
serializer_class = ActivityTypeSerializer
and in your urls.py
from rest_framework.urlpatterns import format_suffix_patterns
from rest_framework import routers, serializers, viewsets
from rest_framework import generics
from rest_framework import viewsets, routers
from your_app.views import ActivityTypeViewSet
from your_app.views import ActivityViewSet
router = routers.DefaultRouter()
router.register(r'activitytypes', ActivityTypeViewSet)
router.register(r'activities', ActivityViewSet)
Also make sure the restframework urls are included as described in docs
urlpatterns = patterns('',
# your other urls
url(r'^api/$', include('rest_framework.urls', namespace='rest_framework')),
url(r'api/accounts/', include('rest_framework.urls', namespace='rest_framework')),
)