Django MEDIA_ROOT Development in Windows Environment - django

In my settings.py ive added the following
print(BASE_DIR)
print(MEDIA_URL)
print(MEDIA_ROOT)
It prints the following
d:/OneDrive/!code_projects/!django_projects/mgTut
/media/
d:/OneDrive/!code_projects/!django_projects/mgTut/media/
But when I start the server, I am seeing this error
FileNotFoundError: [Errno 2] No such file or directory: 'd:\\OneDrive\\!code_projects\\!django_projects\\mgTut\\media\\media\\images\\profile_image\\0C0A8604_1_mKlAyCG.JPG'
I'm not quite sure where to go from here. My media_root is supposed to replace, but it doesn't seem to be when it's called.
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR + '/media/').replace('\\', '/')
My models.py class:
class UserProfile(models.Model):
user = models.OneToOneField(User)
description = models.CharField(max_length=200, default='')
city = models.CharField(max_length=50, default='')
state = models.CharField(max_length=2, default='')
website = models.URLField(default='')
phone = models.IntegerField(default=0)
avatar = models.ImageField(upload_to=b'media/images/profile_image',
default='media/images/profile_image/Profile_Blank.PNG')
avatar_thumbnail = ImageSpecField(source='avatar',
processors=[ResizeToFill(100, 100)],
format='JPEG',
options={'quality': 60})
def __str__(self):
return '%s - %s' % (self.user, self.description)
profile = UserProfile.objects.all()[0]
print(profile.avatar_thumbnail.url) # > /media/CACHE/images/982d5af84cddddfd0fbf70892b4431e4.jpg
print(profile.avatar_thumbnail.width) # > 100
Full error:
d:/OneDrive/!code_projects/!django_projects/mgTut
/media/
d:/OneDrive/!code_projects/!django_projects/mgTut/media/
Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x000002EDDFA09048>
Traceback (most recent call last):
File "D:\OneDrive\!code_projects\!django_projects\windows_venv\lib\site-packages\django\utils\autoreload.py", line 227, in wrapper
fn(*args, **kwargs)
File "D:\OneDrive\!code_projects\!django_projects\windows_venv\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run
autoreload.raise_last_exception()
File "D:\OneDrive\!code_projects\!django_projects\windows_venv\lib\site-packages\django\utils\autoreload.py", line 250, in raise_last_exception
six.reraise(*_exception)
File "D:\OneDrive\!code_projects\!django_projects\windows_venv\lib\site-packages\django\utils\six.py", line 685, in reraise
raise value.with_traceback(tb)
File "D:\OneDrive\!code_projects\!django_projects\windows_venv\lib\site-packages\django\utils\autoreload.py", line 227, in wrapper
fn(*args, **kwargs)
File "D:\OneDrive\!code_projects\!django_projects\windows_venv\lib\site-packages\django\__init__.py", line 27, in setup
apps.populate(settings.INSTALLED_APPS)
File "D:\OneDrive\!code_projects\!django_projects\windows_venv\lib\site-packages\django\apps\registry.py", line 108, in populate
app_config.import_models()
File "D:\OneDrive\!code_projects\!django_projects\windows_venv\lib\site-packages\django\apps\config.py", line 202, in import_models
self.models_module = import_module(models_module_name)
File "C:\Program Files\Python36\lib\importlib\__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 978, in _gcd_import
File "<frozen importlib._bootstrap>", line 961, in _find_and_load
File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 655, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed
File "d:\OneDrive\!code_projects\!django_projects\mgTut\account\models.py", line 27, in <module>
print(profile.avatar_thumbnail.url) # > /media/CACHE/images/982d5af84cddddfd0fbf70892b4431e4.jpg
File "D:\OneDrive\!code_projects\!django_projects\windows_venv\lib\site-packages\imagekit\cachefiles\__init__.py", line 84, in url
return self._storage_attr('url')
File "D:\OneDrive\!code_projects\!django_projects\windows_venv\lib\site-packages\imagekit\cachefiles\__init__.py", line 74, in _storage_attr
existence_required.send(sender=self, file=self)
File "D:\OneDrive\!code_projects\!django_projects\windows_venv\lib\site-packages\django\dispatch\dispatcher.py", line 193, in send
for receiver in self._live_receivers(sender)
File "D:\OneDrive\!code_projects\!django_projects\windows_venv\lib\site-packages\django\dispatch\dispatcher.py", line 193, in <listcomp>
for receiver in self._live_receivers(sender)
File "D:\OneDrive\!code_projects\!django_projects\windows_venv\lib\site-packages\imagekit\registry.py", line 53, in existence_required_receiver
self._receive(file, 'on_existence_required')
File "D:\OneDrive\!code_projects\!django_projects\windows_venv\lib\site-packages\imagekit\registry.py", line 61, in _receive
call_strategy_method(file, callback)
File "D:\OneDrive\!code_projects\!django_projects\windows_venv\lib\site-packages\imagekit\utils.py", line 166, in call_strategy_method
fn(file)
File "D:\OneDrive\!code_projects\!django_projects\windows_venv\lib\site-packages\imagekit\cachefiles\strategies.py", line 15, in on_existence_required
file.generate()
File "D:\OneDrive\!code_projects\!django_projects\windows_venv\lib\site-packages\imagekit\cachefiles\__init__.py", line 93, in generate
self.cachefile_backend.generate(self, force)
File "D:\OneDrive\!code_projects\!django_projects\windows_venv\lib\site-packages\imagekit\cachefiles\backends.py", line 109, in generate
self.generate_now(file, force=force)
File "D:\OneDrive\!code_projects\!django_projects\windows_venv\lib\site-packages\imagekit\cachefiles\backends.py", line 96, in generate_now
file._generate()
File "D:\OneDrive\!code_projects\!django_projects\windows_venv\lib\site-packages\imagekit\cachefiles\__init__.py", line 97, in _generate
content = generate(self.generator)
File "D:\OneDrive\!code_projects\!django_projects\windows_venv\lib\site-packages\imagekit\utils.py", line 152, in generate
content = generator.generate()
File "D:\OneDrive\!code_projects\!django_projects\windows_venv\lib\site-packages\imagekit\specs\__init__.py", line 150, in generate
img = open_image(self.source)
File "D:\OneDrive\!code_projects\!django_projects\windows_venv\lib\site-packages\pilkit\utils.py", line 21, in open_image
target.seek(0)
File "D:\OneDrive\!code_projects\!django_projects\windows_venv\lib\site-packages\django\core\files\utils.py", line 20, in <lambda>
seek = property(lambda self: self.file.seek)
File "D:\OneDrive\!code_projects\!django_projects\windows_venv\lib\site-packages\django\db\models\fields\files.py", line 51, in _get_file
self._file = self.storage.open(self.name, 'rb')
File "D:\OneDrive\!code_projects\!django_projects\windows_venv\lib\site-packages\django\core\files\storage.py", line 38, in open
return self._open(name, mode)
File "D:\OneDrive\!code_projects\!django_projects\windows_venv\lib\site-packages\django\core\files\storage.py", line 300, in _open
return File(open(self.path(name), mode))
FileNotFoundError: [Errno 2] No such file or directory: 'd:\\OneDrive\\!code_projects\\!django_projects\\mgTut\\media\\media\\images\\profile_image\\0C0A8604_1_mKlAyCG.JPG'
UPDATE: It's isolated to the URLs provided by ImageKit. Printing profile.avatar_thumbnail.url is what's throwing the error.
Tried adding replace to it, same problem.
print(profile.avatar_thumbnail.url.replace('\\', '/')) # > /media/CACHE/images/982d5af84cddddfd0fbf70892b4431e4.jpg
print(profile.avatar_thumbnail.width.replace('\\', '/')) # > 100
URLCONF:
from django.conf.urls import url, include
from django.contrib import admin
from django.urls import reverse_lazy
from django.conf import settings
from django.conf.urls.static import static
from django.contrib.auth.views import (
LoginView,
LogoutView,
PasswordResetView,
PasswordResetDoneView,
PasswordChangeView,
PasswordChangeDoneView,
PasswordResetView,
PasswordResetConfirmView,
PasswordResetCompleteView
)
from . import views
urlpatterns = [
url(r'^login/$',
LoginView.as_view(template_name='account/login.html'),
name='login'),
url(r'^logout/$',
LogoutView.as_view(next_page=reverse_lazy('login')),
name='logout'),
url(r'^register/$',
views.register,
name='register'),
url(r'^password_change/$',
PasswordChangeView.as_view(
template_name='account/password_change_form.html'
),
name='password_change'),
url(r'^password_change/done/$',
PasswordChangeDoneView.as_view(
template_name='account/password_change_done.html'
),
name='password_change_done'),
url(r'^password_reset/$',
PasswordResetView.as_view(
template_name='account/password_reset_form.html'
),
name='password_reset'),
url(r'^password_reset/done/$',
PasswordResetDoneView.as_view(
template_name='account/password_reset_done.html'
),
name='password_reset_done'),
url(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',
PasswordResetConfirmView.as_view(
template_name='account/password_reset_confirm.html'
),
name='password_reset_confirm'),
url(r'^reset/done/$',
PasswordResetCompleteView.as_view(
template_name='account/password_reset_complete.html'
),
name='password_reset_complete'),
url(r'^admin/',
admin.site.urls),
url(r'^$',
views.home,
name='homepage'),
url(r'^account/',
include('account.urls')),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

Related

Constantly get an error "no such table" whatever I do

I am pretty new to django and database management as well, therefore there is certainly a possibility that I do not understand some crucial things about them.
I've been trying to solve this error by myriads of ways for a few days (It occured as a result of a declaration of a new field in existing model called Habit), I tried:
resetting database with reset_db (django-extensions)
flushing it with native django flush command (now I do understand
that it was a wrong method)
recreating a whole app in another virtual environment with creation
of fresh databases
faking migrations with --fake (out of desperation basically)
manually changing fields in a db with sql browser
deleting sqlite database manually and making migrations
Here are my models:
from django.db import models
from django.utils import timezone
from datetime import timedelta
import datetime
# Create your models here.
class Day(models.Model): # Creating table for this model didn't cause any trouble
date = models.DateField(auto_now_add=True)
def __str__(self):
return str(self.date)
class Habit(models.Model):
name = models.CharField(max_length=200)
targ_init_time = models.TimeField(auto_created=False, auto_now_add=False, default=datetime.time())
targ_term_time = models.TimeField(auto_created=False, auto_now_add=False, default=datetime.time())
true_init_time = models.TimeField(auto_created=False, auto_now_add=False, blank=True, default=datetime.time())
true_term_time = models.TimeField(auto_created=False, auto_now_add=False, blank=True, default=datetime.time())
is_completed = models.BooleanField(default=False)
day = models.ForeignKey(Day, on_delete=models.CASCADE, related_name='habits') # --That New Field I've added--
def find_duration(self):
total_targ_time = timedelta(hours=self.targ_term_time.hour, minutes=self.targ_term_time.minute) - timedelta(hours=self.targ_init_time.hour, minutes=self.targ_init_time.minute)
total_true_time = timedelta(hours=self.true_term_time.hour, minutes=self.true_term_time.minute) - timedelta(hours=self.true_init_time.hour, minutes=self.true_init_time.minute)
return [total_true_time, total_targ_time]
def format_time(self):
time = self.find_duration()
true = float(".".join(str(time[0]).split(":"))[0:4])
targ = float(".".join(str(time[1]).split(":"))[0:4])
if true < 1:
true = str(int(true * 100)) + ' mins'
else:
true = str(true) + ' hours'
if targ < 1:
targ = str(int(targ * 100)) + ' mins'
else:
targ = str(targ) + ' hours'
return [true, targ]
def find_productivity(self):
total_both_time = self.find_duration()
try:
productivity = int(total_both_time[0] / total_both_time[1] * 100)
except ZeroDivisionError:
productivity=0
return productivity
def __str__(self):
return self.name
Views:
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from django.urls import reverse
from django.template import loader
from datetime import timedelta, time
from .models import Habit
from .forms import HabitForm, EditHabitForm
# Create your views here.
def dayViewHabitIndex(request):
all_habits = Habit.objects.all()
form = HabitForm()
template = loader.get_template("Tracker/one_day_habits.html")
productivity_list = [habit.find_productivity() for habit in all_habits]
try:
median_productivity = int(sum(productivity_list) / len(productivity_list))
except ZeroDivisionError:
median_productivity = 0
context = {'habits_list':all_habits, 'median_productivity':median_productivity, 'form':form}
return HttpResponse(template.render(context, request))
def addHabit(request):
new_habit = HabitForm(request.POST)
if new_habit.is_valid():
new_habit.save()
return HttpResponseRedirect(reverse('Tracker:index'))
def editHabitsTime(request, habit_id):
certain_habit = Habit.objects.get(id=habit_id)
template = loader.get_template('Tracker/editHabitsTime.html')
form = EditHabitForm()
context = {'certain_habit':certain_habit, 'form':form}
return HttpResponse(template.render(context, request))
def editSuccess(request, habit_id, template='Tracker/editHabitsTime.html'):
changes = EditHabitForm(request.POST, instance=Habit.objects.get(id=habit_id))
if changes.is_valid():
changes.save()
return HttpResponseRedirect(reverse('Tracker:index'))
else:
return render(request, template, {'form':form, 'warning':'Something Went Wrong'})
App urls:
from django.urls import path
from . import views
app_name = 'Tracker'
urlpatterns = [
path('', views.dayViewHabitIndex, name='index'),
path('createHabit/', views.addHabit, name='addHabit'),
path('<int:habit_id>/edit/', views.editHabitsTime, name='editHabit'),
path('<int:habit_id>/success/>', views.editSuccess, name='saveChanges'),
]
Forms:
from django.forms import ModelForm
from django.utils.translation import gettext_lazy as _
from django.forms.fields import DateField
from django import forms
from . import models
HABIT_NAMES = zip([habit.name for habit in models.Habit.objects.all()], [habit.name for habit in models.Habit.objects.all()])
class HabitForm(ModelForm):
class Meta:
model = models.Habit
#widgets = {'name': forms.Select(choices=HABIT_NAMES)}
fields = '__all__'
labels = {'name': _(''), 'targ_init_time':_(''), 'targ_term_time':_(''), 'true_init_time':_(''), 'true_term_time':_(''), 'is_completed':_('') }
class EditHabitForm(ModelForm):
class Meta:
model = models.Habit
exclude = ('name', 'targ_init_time', 'targ_term_time', )
Full Error Message:
(WebApp-G_WmOMr9) D:\CodingPython\New_Folder_For_Great_And_Strucrurised_Work\WebApp>python manage.py makemigrations
Traceback (most recent call last):
File "C:\Users\User\.virtualenvs\WebApp-G_WmOMr9\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\User\.virtualenvs\WebApp-G_WmOMr9\lib\site-packages\django\db\backends\sqlite3\base.py", line 413, in execute
return Database.Cursor.execute(self, query, params)
sqlite3.OperationalError: no such table: Tracker_habit
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "manage.py", line 22, in <module>
main()
File "manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "C:\Users\User\.virtualenvs\WebApp-G_WmOMr9\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line
utility.execute()
File "C:\Users\User\.virtualenvs\WebApp-G_WmOMr9\lib\site-packages\django\core\management\__init__.py", line 395, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Users\User\.virtualenvs\WebApp-G_WmOMr9\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv
self.execute(*args, **cmd_options)
File "C:\Users\User\.virtualenvs\WebApp-G_WmOMr9\lib\site-packages\django\core\management\base.py", line 368, in execute
self.check()
File "C:\Users\User\.virtualenvs\WebApp-G_WmOMr9\lib\site-packages\django\core\management\base.py", line 392, in check
all_issues = checks.run_checks(
File "C:\Users\User\.virtualenvs\WebApp-G_WmOMr9\lib\site-packages\django\core\checks\registry.py", line 70, in run_checks
new_errors = check(app_configs=app_configs, databases=databases)
File "C:\Users\User\.virtualenvs\WebApp-G_WmOMr9\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config
return check_resolver(resolver)
File "C:\Users\User\.virtualenvs\WebApp-G_WmOMr9\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver
return check_method()
File "C:\Users\User\.virtualenvs\WebApp-G_WmOMr9\lib\site-packages\django\urls\resolvers.py", line 408, in check
for pattern in self.url_patterns:
File "C:\Users\User\.virtualenvs\WebApp-G_WmOMr9\lib\site-packages\django\utils\functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Users\User\.virtualenvs\WebApp-G_WmOMr9\lib\site-packages\django\urls\resolvers.py", line 589, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "C:\Users\User\.virtualenvs\WebApp-G_WmOMr9\lib\site-packages\django\utils\functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Users\User\.virtualenvs\WebApp-G_WmOMr9\lib\site-packages\django\urls\resolvers.py", line 582, in urlconf_module
return import_module(self.urlconf_name)
File "C:\Users\User\AppData\Local\Programs\Python\Python38-32\lib\importlib\__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
File "<frozen importlib._bootstrap>", line 991, in _find_and_load
File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 783, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "D:\CodingPython\New_Folder_For_Great_And_Strucrurised_Work\WebApp\HabitTracker\urls.py", line 21, in <module>
path('', include('Tracker.urls')),
File "C:\Users\User\.virtualenvs\WebApp-G_WmOMr9\lib\site-packages\django\urls\conf.py", line 34, in include
urlconf_module = import_module(urlconf_module)
File "C:\Users\User\AppData\Local\Programs\Python\Python38-32\lib\importlib\__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
File "<frozen importlib._bootstrap>", line 991, in _find_and_load
File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 783, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "D:\CodingPython\New_Folder_For_Great_And_Strucrurised_Work\WebApp\Tracker\urls.py", line 3, in <module>
from . import views
File "D:\CodingPython\New_Folder_For_Great_And_Strucrurised_Work\WebApp\Tracker\views.py", line 12, in <module>
from .forms import HabitForm, EditHabitForm
File "D:\CodingPython\New_Folder_For_Great_And_Strucrurised_Work\WebApp\Tracker\forms.py", line 8, in <module>
HABIT_NAMES = zip([habit.name for habit in models.Habit.objects.all()], [habit.name for habit in models.Habit.objects.all()])
File "C:\Users\User\.virtualenvs\WebApp-G_WmOMr9\lib\site-packages\django\db\models\query.py", line 287, in __iter__
self._fetch_all()
File "C:\Users\User\.virtualenvs\WebApp-G_WmOMr9\lib\site-packages\django\db\models\query.py", line 1308, in _fetch_all
self._result_cache = list(self._iterable_class(self))
File "C:\Users\User\.virtualenvs\WebApp-G_WmOMr9\lib\site-packages\django\db\models\query.py", line 53, in __iter__
results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)
File "C:\Users\User\.virtualenvs\WebApp-G_WmOMr9\lib\site-packages\django\db\models\sql\compiler.py", line 1156, in execute_sql
cursor.execute(sql, params)
File "C:\Users\User\.virtualenvs\WebApp-G_WmOMr9\lib\site-packages\django\db\backends\utils.py", line 98, in execute
return super().execute(sql, params)
File "C:\Users\User\.virtualenvs\WebApp-G_WmOMr9\lib\site-packages\django\db\backends\utils.py", line 66, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "C:\Users\User\.virtualenvs\WebApp-G_WmOMr9\lib\site-packages\django\db\backends\utils.py", line 75, in _execute_with_wrappers
return executor(sql, params, many, context)
File "C:\Users\User\.virtualenvs\WebApp-G_WmOMr9\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\User\.virtualenvs\WebApp-G_WmOMr9\lib\site-packages\django\db\utils.py", line 90, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "C:\Users\User\.virtualenvs\WebApp-G_WmOMr9\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\User\.virtualenvs\WebApp-G_WmOMr9\lib\site-packages\django\db\backends\sqlite3\base.py", line 413, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.OperationalError: no such table: Tracker_habit
Thanks for help in advance!
these queries in your forms are executed and cause the error even before your "makemigrations" is doing the actual makemigrations:
HABIT_NAMES = zip([habit.name for habit in models.Habit.objects.all()], [habit.name for habit in models.Habit.objects.all()])
I would comment it out and try again.
Have you tried running the following command?
python manage.py migrate --run-syncdb
According to doc
--run-syncdb¶
Allows creating tables for apps without migrations. While this isn’t
recommended, the migrations framework is sometimes too slow on large
projects with hundreds of models.

Django unable to resolve the import type

Iam a newbie learning django iam struck here can someone help on this.
i followed this tutorial https://www.youtube.com/watch?v=RMTVAIVrdtM
Iam using pycharm IDE, created on the similar lines but still iam getting the error.
from poll import view as poll_views ### Getting error in this line .....----<<<<<<<
urlpatterns = [
path('admin/', admin.site.urls),
path(''.poll_views.home,name='home'),
path('create/'.poll_views.create, name='create'),
path('vote/<poll_id>'.poll_views.vote, name='vote'),
path('results/<poll_id>'.poll_views.results, name='results'),
]
views.py
from django.shortcuts import render
# Create your views here.
def home(request):
context = {}
return render(request, 'poll/home.html',context)
def create(request):
context = {}
return render(request, 'poll/create.html',context)
def vote(request, poll_id):
context = {}
return render(request, 'poll/vote.html',context)
def results(request, poll_id):
context = {}
return render(request, 'poll/results.html',context)
On terminal
(test) C:\Users\Learner\projects\poll_project>python manage.py migrate
Traceback (most recent call last):
File "C:\Users\Learner\projects\poll_project\manage.py", line 21, in <module>
main()
File "C:\Users\Learner\projects\poll_project\manage.py", line 17, in main
execute_from_command_line(sys.argv)
File "C:\Users\Learner\Envs\test\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line
utility.execute()
File "C:\Users\Learner\Envs\test\lib\site-packages\django\core\management\__init__.py", line 395, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Users\Learner\Envs\test\lib\site-packages\django\core\management\base.py", line 328, in run_from_argv
self.execute(*args, **cmd_options)
File "C:\Users\Learner\Envs\test\lib\site-packages\django\core\management\base.py", line 366, in execute
self.check()
File "C:\Users\Learner\Envs\test\lib\site-packages\django\core\management\base.py", line 392, in check
all_issues = self._run_checks(
File "C:\Users\Learner\Envs\test\lib\site-packages\django\core\management\commands\migrate.py", line 64, in _run_checks
issues.extend(super()._run_checks(**kwargs))
File "C:\Users\Learner\Envs\test\lib\site-packages\django\core\management\base.py", line 382, in _run_checks
return checks.run_checks(**kwargs)
File "C:\Users\Learner\Envs\test\lib\site-packages\django\core\checks\registry.py", line 72, in run_checks
new_errors = check(app_configs=app_configs)
File "C:\Users\Learner\Envs\test\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config
return check_resolver(resolver)
File "C:\Users\Learner\Envs\test\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver
return check_method()
File "C:\Users\Learner\Envs\test\lib\site-packages\django\urls\resolvers.py", line 407, in check
for pattern in self.url_patterns:
File "C:\Users\Learner\Envs\test\lib\site-packages\django\utils\functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Users\Learner\Envs\test\lib\site-packages\django\urls\resolvers.py", line 588, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "C:\Users\Learner\Envs\test\lib\site-packages\django\utils\functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Users\Learner\Envs\test\lib\site-packages\django\urls\resolvers.py", line 581, in urlconf_module
return import_module(self.urlconf_name)
File "c:\users\Learner\appdata\local\programs\python\python39\lib\importlib\__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1021, in _gcd_import
File "<frozen importlib._bootstrap>", line 998, in _find_and_load
File "<frozen importlib._bootstrap>", line 977, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 790, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "C:\Users\Learner\projects\poll_project\poll_project\urls.py", line 19, in <module>
from poll import view as poll_views
ImportError: cannot import name 'view' from 'poll' (C:\Users\Learner\projects\poll_project\poll\__init__.py)
Please find the project folder screenshot below.
this is my folder structure
Can someone please help me where iam going wrong ???
The import statement should be like
If want to import specific view
from poll.views import <nameoftheview> as poll_views
Or if you want to import all the views
import poll.views as poll_views
Update: Correct error in your urls.py (also pointed out by #sheraram)
urlpatterns = [
path('admin/', admin.site.urls),
path('create/', poll_views.create, name='create'),
path('vote/<poll_id>', poll_views.vote, name='vote'),
path('results/<poll_id>', poll_views.results, name='results'),
path('', poll_views.home,name='home'),
]
url takes following argument path(route, view, name{optional})
but you are giving path(route.view, name)
replace . after route by ,

django.db.utils.ProgrammingError: relation "auth_permission" does not exist

I am having a working sqlite database in my local environment. On heroku I am using psql. But I am getting following error when I try to run
$ heroku run python manage.py migrate
Traceback (most recent call last):
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
psycopg2.ProgrammingError: relation "auth_permission" does not exist
LINE 1: ...ntent_type_id", "auth_permission"."codename" FROM "auth_perm...
^
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "manage.py", line 15, in <module>
execute_from_command_line(sys.argv)
File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line
utility.execute()
File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 316, in run_from_argv
self.execute(*args, **cmd_options)
File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 350, in execute
self.check()
File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 379, in check
include_deployment_checks=include_deployment_checks,
File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 366, in _run_checks
return checks.run_checks(**kwargs)
File "/app/.heroku/python/lib/python3.6/site-packages/django/core/checks/registry.py", line 71, in run_checks
new_errors = check(app_configs=app_configs)
File "/app/.heroku/python/lib/python3.6/site-packages/django/core/checks/urls.py", line 40, in check_url_namespaces_unique
all_namespaces = _load_all_namespaces(resolver)
File "/app/.heroku/python/lib/python3.6/site-packages/django/core/checks/urls.py", line 57, in _load_all_namespaces
url_patterns = getattr(resolver, 'url_patterns', [])
File "/app/.heroku/python/lib/python3.6/site-packages/django/utils/functional.py", line 37, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/app/.heroku/python/lib/python3.6/site-packages/django/urls/resolvers.py", line 533, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "/app/.heroku/python/lib/python3.6/site-packages/django/utils/functional.py", line 37, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/app/.heroku/python/lib/python3.6/site-packages/django/urls/resolvers.py", line 526, in urlconf_module
return import_module(self.urlconf_name)
File "/app/.heroku/python/lib/python3.6/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 994, in _gcd_import
File "<frozen importlib._bootstrap>", line 971, in _find_and_load
File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/app/codeTrial/urls.py", line 20, in <module>
path('', include('coderunner.urls')),
File "/app/.heroku/python/lib/python3.6/site-packages/django/urls/conf.py", line 34, in include
urlconf_module = import_module(urlconf_module)
File "/app/.heroku/python/lib/python3.6/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 994, in _gcd_import
File "<frozen importlib._bootstrap>", line 971, in _find_and_load
File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/app/coderunner/urls.py", line 4, in <module>
from . import views
File "/app/coderunner/views.py", line 34, in <module>
'perm_obj': Permission.objects.get(name='Can add Questions'),
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/query.py", line 393, in get
num = len(clone)
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/query.py", line 250, in __len__
self._fetch_all()
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/query.py", line 1186, in _fetch_all
self._result_cache = list(self._iterable_class(self))
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/query.py", line 54, in __iter__
results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1065, in execute_sql
cursor.execute(sql, params)
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 68, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 77, in _execute_with_wrappers
return executor(sql, params, many, context)
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/utils.py", line 89, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: relation "auth_permission" does not exist
LINE 1: ...ntent_type_id", "auth_permission"."codename" FROM "auth_perm...
^
This is not a problem in using psql on heroku I guess, because when I try to copy the same application to another Linux machine and try to recreate sqlite database it gives sqlite3.OperationalError: no such table: auth_permission.
Same error occurs when I try migration after deleting all the 14 migration files from the app/migration folder.
I don't get why at least Django database tables are not getting created. Is it due to anything wrong in the app/models.py file?
In case you need to review my models.py file, here it is:
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.core.validators import MinValueValidator
# Create your models here.
class Questions(models.Model):
author = models.ForeignKey(User, on_delete=models.CASCADE)
published_on = models.DateTimeField(auto_now_add=True)
question_text = models.CharField(max_length=200)
question_desc = models.CharField(max_length=500)
pre_code_snippet = models.TextField()
output_format = models.CharField(max_length=500)
timeout = models.IntegerField(default=5, validators=[MinValueValidator(0)])
run_testcase1_input = models.TextField(max_length=50)
run_testcase1_output = models.TextField()
submit_testcase1_input = models.TextField(max_length=50)
submit_testcase1_output = models.TextField()
submit_testcase2_input = models.TextField(max_length=50)
submit_testcase2_output = models.TextField()
times_submitted = models.IntegerField(default=0)
times_correct = models.IntegerField(default=0)
times_wrong = models.IntegerField(default=0)
score = models.IntegerField(default=10,
validators=[MinValueValidator(5)])
class Meta:
verbose_name = 'Questions'
verbose_name_plural = 'Questions'
def __str__(self):
return self.question_text
class Submissions(models.Model):
username = models.ForeignKey(User, on_delete=models.CASCADE)
submitted_on = models.DateTimeField(auto_now_add=True)
submitted_snippet = models.TextField()
question = models.ForeignKey(Questions, on_delete=models.CASCADE)
class Meta:
verbose_name = 'Submissions'
verbose_name_plural = 'Submissions'
def __str__(self):
return (str(self.username) + '# [' + str(self.question) + ']')
class UserProfile(models.Model):
username = models.OneToOneField(User, on_delete=models.CASCADE)
score = models.IntegerField(default=0,
validators=[MinValueValidator(0)])
class Meta:
verbose_name = "UserProfile"
verbose_name_plural = "UserProfiles"
def __str__(self):
return str(self.username)
#receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
UserProfile.objects.create(username=instance)
#receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
instance.userprofile.save()
project/settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'coderunner.apps.CoderunnerConfig',
]
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
db_from_env = dj_database_url.config()
DATABASES['default'].update(db_from_env)
I am using Django_2.1.2. I did not find any proper solution for this issue yet. Let me know if I need to provide any other information.
In case you need the full source code, here is my Github link.
Oh yeah, I found the problem. Even after posting my question down here, I was searching for the exact issue, I found a related article where some one has commented there is an issue with his form.py file as per the traceback log. So I thought in my case also there might be some issues in other files beyond my suspected files like models.py, settings.py or migration files. So I checked the Tracebacks again and found this...
File "/app/codeTrial/urls.py", line 20, in <module>
path('', include('coderunner.urls')),
which ultimately executes coderunner/urls.py, where I import coderunner/views.py contents.
File "/app/coderunner/urls.py", line 4, in <module>
from . import views
And in coderunner/views.py I was actually trying to create an object of Permission class outside any view functions/classes. So it is obvious while importing views.py from url.py, views.py gets executed. That means it was accessing the auth model before it was even created, which actually raised the exception auth_permission does not exist. So I handled that code in views.py and tried migrating again... Boom!! Successfully migrated.
In my dev environment there was no issues in migration, because auth model was created by the time I implemented the unhandled code in coderunner/views.py.
You have to comment your root URL routes of all apps
Comment your apps from INSTALLED_APPS list
Run python manage.py migrate. It will migrate the initial migrations of Django itself.
Now uncomment all the comments you've made in the first two steps

django 2.0 url.py include namespace="xyz"

I've a problem with the routing django.conf.urls include() - main project folder - urls.py
Line 22 of urls.py (pip freeze and urls.py - see below) throws the error in the console:
Quit the server with CONTROL-C.
[02/Jan/2018 14:22:49] "GET /api/compositions/ HTTP/1.1" 200 30058
[02/Jan/2018 14:22:53] "GET /api/compositions/1/ HTTP/1.1" 200 6195
Performing system checks...
Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7f17ee06e400>
Traceback (most recent call last):
File "/home/ernst/django_virtualenv/lib/python3.4/site-packages/django/utils/autoreload.py", line 225, in wrapper
fn(*args, **kwargs)
File "/home/ernst/django_virtualenv/lib/python3.4/site-packages/django/core/management/commands/runserver.py", line 120, in inner_run
self.check(display_num_errors=True)
File "/home/ernst/django_virtualenv/lib/python3.4/site-packages/django/core/management/base.py", line 364, in check
include_deployment_checks=include_deployment_checks,
File "/home/ernst/django_virtualenv/lib/python3.4/site-packages/django/core/management/base.py", line 351, in _run_checks
return checks.run_checks(**kwargs)
File "/home/ernst/django_virtualenv/lib/python3.4/site-packages/django/core/checks/registry.py", line 73, in run_checks
new_errors = check(app_configs=app_configs)
File "/home/ernst/django_virtualenv/lib/python3.4/site-packages/django/core/checks/urls.py", line 13, in check_url_config
return check_resolver(resolver)
File "/home/ernst/django_virtualenv/lib/python3.4/site-packages/django/core/checks/urls.py", line 23, in check_resolver
return check_method()
File "/home/ernst/django_virtualenv/lib/python3.4/site-packages/django/urls/resolvers.py", line 397, in check
for pattern in self.url_patterns:
File "/home/ernst/django_virtualenv/lib/python3.4/site-packages/django/utils/functional.py", line 36, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/home/ernst/django_virtualenv/lib/python3.4/site-packages/django/urls/resolvers.py", line 536, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "/home/ernst/django_virtualenv/lib/python3.4/site-packages/django/utils/functional.py", line 36, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/home/ernst/django_virtualenv/lib/python3.4/site-packages/django/urls/resolvers.py", line 529, in urlconf_module
return import_module(self.urlconf_name)
File "/home/ernst/django_virtualenv/lib/python3.4/importlib/__init__.py", line 109, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 2254, in _gcd_import
File "<frozen importlib._bootstrap>", line 2237, in _find_and_load
File "<frozen importlib._bootstrap>", line 2226, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 1200, in _load_unlocked
File "<frozen importlib._bootstrap>", line 1129, in _exec
File "<frozen importlib._bootstrap>", line 1471, in exec_module
File "<frozen importlib._bootstrap>", line 321, in _call_with_frames_removed
File "/home/ernst/django_virtualenv/mwrench/mwrench/urls.py", line 23, in <module>
url(r'^api/compositions/', include("compositions.api.urls", namespace="compositions-api")),
File "/home/ernst/django_virtualenv/lib/python3.4/site-packages/django/urls/conf.py", line 39, in include
'Specifying a namespace in include() without providing an app_name '
django.core.exceptions.ImproperlyConfigured: Specifying a namespace in include() without providing an app_name is not supported. Set the app_name attribute in the included module, or pass a 2-tuple containing the list of patterns and app_name instead.
urls.py:
from compositions.api.views import AlloyelementDetailAPIView
1 # Without settings the API URL queries do not work
2 from django.conf.urls.static import static
3 from django.conf import settings
4 from django.conf.urls import include, url
5 from django.contrib import admin
6 from mwrench.views import (
7 template,
8 ChartData,
9 CompositionAPI,
10 testview
11 )
12 from rest_framework.urlpatterns import format_suffix_patterns
13 from accounts.views import (login_view, register_view, logout_view)
14
15 urlpatterns = [
16 url(r'^admin/', admin.site.urls),
17 url(r'^', include('compositions.urls' )),
...
22 url(r'^api/compositions/', include("compositions.api.urls", namespace="compositions-api")),
console$ pip freeze
Django==2.0
Jinja2==2.10
Markdown==2.6.10
MarkupSafe==1.0
PyYAML==3.12
appdirs==1.4.3
certifi==2017.11.5
chardet==3.0.4
deprecation==1.0.1
django-braces==1.12.0
django-crispy-forms==1.7.0
django-filter==1.1.0
djangorestframework==3.7.7
gunicorn==19.7.1
idna==2.6
include==0.2.1
iso8601==0.1.12
jsonpatch==1.21
jsonpointer==1.14
keystoneauth1==3.3.0
mysqlclient==1.3.12
numpy==1.13.3
openstacksdk==0.9.19
os-client-config==1.28.0
pbr==3.1.1
psycopg2==2.7.3.2
pytz==2017.3
requests==2.18.4
requestsexceptions==1.3.0
reverse==0.1.0
six==1.11.0
stevedore==1.28.0
url==0.4.2
urllib3==1.22
I already tried defining the app_name= variable within the urls.py, as suggested here How to register DRF router url patterns in django 2. The problem occured after porting from Django 1.11 to 2.0.
Is there a better way except calling the view by defining the name="yournametothedetailview" directly from the project urls.py.
Thank you very much,
best Ernst!
Just in case you have updated from an older version of Django it would be advisable if you go to the specific app urls.py file and add the following line just above the url patterns;
app_name = 'current_app_name'
Below is an example of how it will look like;
app_name = 'current_app_name'
urlpatterns = [
url(r'^$', views.index, name='index'),
]
i think to be able to reference a namespace ->
in your urls.py of composition app you're supposed to set the variable app_name = 'your app name'

Django Rest Framework AttributeError 'function' object has no attribute 'model' in router.register

I try my first Django API using Django Rest Framework. Everything was fine, but I change something and stuck in this AttributeError and don't understand what to do. my code looks like in tutorial and it is half past 4 am, I really need help.
so,
this is the callback
python3 manage.py makemigrations
Traceback (most recent call last):
File "manage.py", line 15, in <module>
execute_from_command_line(sys.argv)
File "/home/dev/test/demo/lib/python3.5/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line
utility.execute()
File "/home/dev/test/demo/lib/python3.5/site-packages/django/core/management/__init__.py", line 365, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/dev/test/demo/lib/python3.5/site-packages/django/core/management/base.py", line 288, in run_from_argv
self.execute(*args, **cmd_options)
File "/home/dev/test/demo/lib/python3.5/site-packages/django/core/management/base.py", line 332, in execute
self.check()
File "/home/dev/test/demo/lib/python3.5/site-packages/django/core/management/base.py", line 364, in check
include_deployment_checks=include_deployment_checks,
File "/home/dev/test/demo/lib/python3.5/site-packages/django/core/management/base.py", line 351, in _run_checks
return checks.run_checks(**kwargs)
File "/home/dev/test/demo/lib/python3.5/site-packages/django/core/checks/registry.py", line 73, in run_checks
new_errors = check(app_configs=app_configs)
File "/home/dev/test/demo/lib/python3.5/site-packages/django/core/checks/urls.py", line 13, in check_url_config
return check_resolver(resolver)
File "/home/dev/test/demo/lib/python3.5/site-packages/django/core/checks/urls.py", line 23, in check_resolver
return check_method()
File "/home/dev/test/demo/lib/python3.5/site-packages/django/urls/resolvers.py", line 397, in check
for pattern in self.url_patterns:
File "/home/dev/test/demo/lib/python3.5/site-packages/django/utils/functional.py", line 36, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/home/dev/test/demo/lib/python3.5/site-packages/django/urls/resolvers.py", line 536, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "/home/dev/test/demo/lib/python3.5/site-packages/django/utils/functional.py", line 36, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/home/dev/test/demo/lib/python3.5/site-packages/django/urls/resolvers.py", line 529, in urlconf_module
return import_module(self.urlconf_name)
File "/usr/lib/python3.5/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 986, in _gcd_import
File "<frozen importlib._bootstrap>", line 969, in _find_and_load
File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 665, in exec_module
File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
File "/home/dev/test/demo/api_demo/api_demo/urls.py", line 7, in <module>
router.register(r'developers', views.DevViewSet)
File "/home/dev/test/demo/lib/python3.5/site-packages/rest_framework/routers.py", line 72, in register
base_name = self.get_default_base_name(viewset)
File "/home/dev/test/demo/lib/python3.5/site-packages/rest_framework/routers.py", line 152, in get_default_base_name
return queryset.model._meta.object_name.lower()
AttributeError: 'function' object has no attribute 'model'
this is url.py file
from django.conf.urls import url, include
from django.contrib import admin
from rest_framework import routers
from developers import views
router = routers.DefaultRouter()
router.register(r'developers', views.DevViewSet)
urlpatterns = [
url(r'^admin', admin.site.urls),
url(r'^api_demo', include(router.urls)),
]
this is views.py
from rest_framework.viewsets import ModelViewSet
from developers.models import Developers
from .serializers import DevSerializer
class DevViewSet(ModelViewSet):
queryset = Developers.objects.all
serializer_class = DevSerializer
and serializer
from rest_framework import serializers
from .models import Developers
class DevSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Developers
fields = ('name', 'surname', 'skills', 'education', 'employment_history')
and models
from django.db import models
class Education(models.Model):
university = models.CharField(max_length=50)
year_of_graduation = models.DateField()
class Empl_history(models.Model):
company = models.CharField(max_length=50)
role = models.CharField(max_length=30)
fr = models.DateField(verbose_name='from')
to = models.DateField()
class Developers(models.Model):
name = models.CharField(max_length=50)
surname = models.CharField(max_length=30)
skills = models.ForeignKey('Skills', on_delete=models.CASCADE)
education = models.ManyToManyField(Education)
employment_history = models.ManyToManyField(Empl_history)
class Skills(models.Model):
SKILLS_CHOICES = (
('p', 'Python'),
('d', 'Django'),
('drf', 'Django Rest Framework'),
)
skills_choices = models.CharField(max_length=2, choices=SKILLS_CHOICES,)
and in settings I added this 'rest_framework' and 'developers' to INSTALLED_APPS, also I add this code in the end
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
'rest_framework.authentication.SessionAuthentication',
),
'PAGE_SIZE': 10
}
Will be very thankfull for any advice and critic
For the queryset declaration you need to call the function and return the QuerySet rather then pass the reference to the function e.g. change queryset = Developers.objects.all to queryset = Developers.objects.all()
from rest_framework.viewsets import ModelViewSet
from developers.models import Developers
from .serializers import DevSerializer
class DevViewSet(ModelViewSet):
queryset = Developers.objects.all()
serializer_class = DevSerializer
from django.conf.urls import url, include
from django.contrib import admin
from rest_framework import routers
from developers import views
router = routers.DefaultRouter()
router.register(r'developers', views.DevViewSet)
urlpatterns = [
url(r'^admin', admin.site.urls),
url(r'', include(router.urls)),
]