Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to exclude product of all the variables based on condition in python
import numpy as np x_1 = getval1 x_2 = getval2 x_3 = getval3 x_4 = getval4 y_1 = getx(x_1) y_2 = getx(x_2) y_3 = getx(x_3) y_4 = getx(x_4) z_1 = gety(x_1, y_1) z_2 = gety(x_2, y_2) z_3 = gety(x_3, y_3) z_4 = gety(x_4, y_4) val = np.prod( list({float(z_1), float(z_2), float(z_3), float(z_4)})) I have the code as above and im trying to find if y_1 value is 20 and i get z_1 value from it and assign it to 'val' variable and not to include other variables like z_2, z_3,z_4 in np.prod(). similarly if y_2 value is 20 i dont want other variables like z_1,z_3,z_4 to include in 'val' variable. it applies for y_3 and y_4 as well for eg: if y_1 == '20' then val = float(z_1) if then statement is not available in python.is there any other way to check this for y_1, y_2, y_3, y_4 variables? -
Iterating Through a Database Django
I have a model in my database called Item. This is the model class Item(models.Model): item_title = models.CharField("Item title: ", max_length=50) item_description = models.CharField("Item description: ", max_length=200) starting_price = models.FloatField( default = 0) picture = models.ImageField(upload_to = 'gallery') finishTime = models.DateTimeField("Finish time: ") ownerID = models.ForeignKey(User, on_delete = models.CASCADE) higestBid = models.FloatField() highestBidderID = models.IntegerField(blank=True, default=-1) active = models.BooleanField(default = True) I want to create a function in views.py , which will check the 'active' field of each item in the database. How can I do that? I have tried to do this: items = list(Item.object.values()) for i in range(items): print(item[i].active) However it does not work. Any help is appreciated -
CORS headers missing when addressing the backend by computer name, but not when using IP
The system architecture is roughly this (at least the components related to the issue at hand): A JavaScript GUI as a client (webapp) hosted using Nginx as a webserver, a Django-based backend proxied by said Nginx instance and both are hosted on the same machine. I'm accessing the network they're both in using a VPN.The issue is that it all works like a charm when addressing the host machine by its IP (https://10.11.12.113/#!/). When using the computer name (https://computer-name/#!/) instead of the IP, I cannot get past the login screen and the browser console lists CORS headers missing as the reason.When inspecting any response received from the backend when using IP, they have the required headers, most importantly Access-Control-Allow-Origin: '*' (asterisk for debugging purposes). These headers are theoretically added to the request twice: by django-cors-headers as middleware and by Nginx by a global directive found in the nginx.config file. The IP and the server name are correctly associated as can be verified by pinging the machine by its IP where computer name is mentioned in the ping command output. The host OS is Windows Server 2012 R2 by the way.So what could be the reason of this strange behavior?Note: I'm … -
itrerate over a python object in django html
I'm trying to generate the HTML code form my web app automatically despite the change the data in the backend {% for object in objects %} <tr> <td>{{ object.attr1 }}</td> <td>{{ object.attr2 }}</td> <td>{{ object.attr3 }}</td> </tr> {% endfor %} instead of hardcoding each attribute I want to iterate over the objects and generate the code inside automatically Thanks -
How I can escape from using sessions in Django?
What I'm trying to do? I want to display 2 registration forms separately of each other on the same page. The forms are: built-in User model and my self created UserProfile. To track, on what form user is now, I use sessions. It some sort of flags for me at the moment. Why I don't want to use sessions? I discovered a 'bug', at least for me, that I don't know how to fix. Bug appears if user passed first registration form, and close browser/tab. Next time user opens registration page, it will show second registration form, instead of first, as expected. Where bug happens, but now with code. When user opens register page first time, built-in UserCreationForm will be show, because there is no session called username yet. def get(self, request): if request.session.get("username", None): self.context["form"] = RegisterProfile() else: self.context["form"] = UserCreationForm() I'm using CBV, so it's OK that function called get and first argument is self. Also I created context dictionary as instance variable, so I can just add new field form to it. Next, if user fill in given form (note, that first form is built-in User's form) built-in User instance will be created and it's username will … -
Python module not found in docker container
I'm trying to run a django-cookiecutter project, but I'm getting a ModuleNotFoundError: No module named 'iprestrict' error in some of the containers. I checked out our repository that my colleagues can successfully build and run using both Docker for Windows and Docker for Linux. I've been debugging this for a while, but now I'm at a loss and asking for your help. This is my setup: $ uname -r 5.0.0-36-generic $ lsb_release -a No LSB modules are available. Distributor ID: Ubuntu Description: Ubuntu 19.04 Release: 19.04 Codename: disco $ docker -v Docker version 19.03.3, build a872fc2f86 $ docker-compose -v docker-compose version 1.25.0, build 0a186604 $ service docker status ● docker.service - Docker Application Container Engine Loaded: loaded (/lib/systemd/system/docker.service; enabled; vendor preset: enabled) Active: active (running) since Wed 2019-11-20 13:02:07 CET; 1h 59min ago Docs: https://docs.docker.com Main PID: 9382 (dockerd) Tasks: 41 Memory: 518.6M CGroup: /system.slice/docker.service ├─ 9382 /usr/bin/dockerd -H fd:// --containerd=/run/containerd/containerd.sock ├─14817 /usr/bin/docker-proxy -proto tcp -host-ip 0.0.0.0 -host-port 5432 -container-ip 172.30.0.2 -container-port 5432 └─14829 /usr/bin/docker-proxy -proto tcp -host-ip 0.0.0.0 -host-port 8025 -container-ip 172.30.0.3 -container-port 8025 To get a clean start I ran the following commands in my project directory: $ docker-compose down --volumes $ docker-compose build --no-cache The project is … -
django detail() got an unexpected keyword argument 'pk'
url.py path('detail/<int:pk>', movie.views.detail, name='detail') views.py def detail(request, primary_key): moviedetail = get_object_or_404(movieinfo, pk=primary_key) return render(request, 'movie/detail.html', { 'moviedetail':moviedetail }) moviehome.html <a href="{% url 'detail' movieinfos.movie_id%}"> detail() got an unexpected keyword argument 'pk' Could you please help me?? How do i have to fix it?? -
Django contains on a many to many field
I am trying to get a user that has the skills needed for a shift. This means the user needs to have the exact skills or more. I tried this. But this does not work for relation fields User.objects.filter(skills__contains=skills) The in operator also does not work because I need a user that has all the skills and not a user which has a subset of the skills required. Is there a way to retrieve the user where the asked about skills are a subset of the user skills? -
Setting up and serving static files for Django
I am on the verge of deploying my website but I have to firstly solve the issuer$ of serving static files via a web server for django. I have the following layout that is modifiable but is what I am working with so far website |-> PWEB | |-> exchange | | |-> migrations | | |-> static | | | |-> exchange | | |-> templates | |-> PWEB | |-> static-server | |-> static | | |-> exchange Both static folders right now contain exactly the same files but as I need to know exactly (I have tried various methods before) what to specify and where on how to access the static files. Here is the static definition in the settings.py file: STATIC_URL = '/static/' STATIC_ROOT = '' STATICFILES_DIRS = ( os.path.join(BASE_DIR, "static"), ) and here is an example of how the files are accessed within a html code: {% load static %} <!DOCTYPE HTML> <!-- Massively by HTML5 UP html5up.net | @ajlkn Free for personal and commercial use under the CCA 3.0 license (html5up.net/license) --> <html> <style> {% block style %} {% endblock style %} </style> <head> {% block head%} {% endblock head %} <meta charset="utf-8" /> … -
'index_together' refers to field 'three' which is not local to model 'Entry'
Why am I getting this error? If remove index_together from the Post class, then everything works, but you can’t do this for certain reasons. class Post(models.Model): one = .. two = .. three = .. class Meta: abstract = True index_together = [ ['one'], ['one', 'two','three'] ] class Comment(Post): pass zinnia.Entry: (models.E016) 'index_together' refers to field 'three' which is not local to model 'Entry'. HINT: This issue may be caused by multi-table inheritance. zinnia.Entry: (models.E016) 'index_together' refers to field 'two' which is not local to model 'Entry'. HINT: This issue may be caused by multi-table inheritance. zinnia.Entry: (models.E016) 'index_together' refers to field 'one' which is not local to model 'Entry'. I do not quite understand, where does Entry. but here is what is class Entry(load_model_class(ENTRY_BASE_MODEL)): """ The final Entry model based on inheritence. """ def load_model_class(model_path): """ Load by import a class by a string path like: 'module.models.MyModel'. This mechanism allows extension and customization of the Entry model class. """ dot = model_path.rindex('.') module_name = model_path[:dot] class_name = model_path[dot + 1:] try: _class = getattr(import_module(module_name), class_name) return _class except (ImportError, AttributeError): raise ImproperlyConfigured('%s cannot be imported' % model_path) ENTRY_BASE_MODEL = getattr(settings, 'ZINNIA_ENTRY_BASE_MODEL', 'zinnia.models_bases.entry.AbstractEntry') ZINNIA_ENTRY_BASE_MODEL = 'apps.blogextra.models.Post' -
Django-crispy-forms with bootstrap4 not showing selected result in browse file field
Attempting to use bootstrap4 with django for forms. Installed crispy forms and and everything seems to work as I expected except for the browse file button selection functionality. When a file selection window comes up and file is choose from expolorer it does not show as selected it the field. However when the form is submitted everything works as expected and the file is uploaded. Am I missing a helper class setting? I could not find one that looked like it addresses this. Any help is appreciated, details below. rendered html Environment: Windows 10 bootstrap4 Python 3.7.4 Django 2.2.5 Django crispy forms 1.8.0 Models.py from django.db import models # Create your models here. class Csvfile_model(models.Model): name = models.CharField(max_length=50) csv_file_name = models.FileField(upload_to='csv_file/') forms.py from django import forms from crispy_forms.helper import FormHelper from .models import * class CsvForm(forms.ModelForm): helper = FormHelper() class Meta: model = Csvfile_model fields = ['name', 'csv_file_name'] views.py def csv_upload(request): if request.method == "POST": form = CsvForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('sucess') else: form = CsvForm() return render(request, 'csv_upload.html', {'form' : form}) def sucess(request): return HttpResponse('sucessfully uploaded') csv_upload.html <!-- templates/home.html --> {% extends 'base.html' %} {% load crispy_forms_tags %} {% crispy form form.helper %} {% block title %}Home{% … -
Trying to read a text file in django
Im unable to read the contents of a file from view.py Below is my code: def home_view (request, *args, **kwargs): ksh_test_result=AutomationTestResult.objects.values('tatr2tafmc__jobcommand', 'ksh_completion','ftp_log_abs_path','aftp_log_abs_path').distinct() ksh_drilldown_data=AutomationTestResult.objects.all() for ksh in ksh_test_result: ftp_log_file[ksh.tatr2tafmc__jobcommand]=open(ksh.ftp_log_abs_path, 'r').read() aftp_log_file[ksh.tatr2tafmc__jobcommand]=open(ksh.aftp_log_abs_path, 'r').read() print(ftp_log_file) print(aftp_log_file) context={ "ksh_list" : ksh_test_result, "ksh_drilldown" : ksh_drilldown_data, "ftp_log" : ftp_log_file, "aftp_log" : aftp_log_file } return render(request, "home.html", context) I'm reading the path of the file from a database. When I run this code i get the following error code Starting development server at http://0.0.0.0:8000/ Quit the server with CONTROL-C. Internal Server Error: / Traceback (most recent call last): File "/home/nmehta/Projects/GATI/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/nmehta/Projects/GATI/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/nmehta/Projects/GATI/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/nmehta/Projects/GATI/src/KTA/dashboard/views.py", line 11, in home_view ftp_log_file[ksh.tatr2tafmc__jobcommand]=open(ksh.ftp_log_abs_path, 'r').read() AttributeError: 'dict' object has no attribute 'ftp_log_abs_path' [20/Nov/2019 14:31:27] "GET / HTTP/1.1" 500 65923 -
How to go from one page to another in django
I'm new to Django and python (infact my first language which I've only been learning for 3 months) I'm creating this website using Django and I'm not able to go from one page to another using the href tag. it throws at me a 404 error saying "current path didn't match any of these" This is my code views.py from django.shortcuts import render from django.http import HttpResponseRedirect from .models import off # Create your views here. def homepage(request): return render(request=request, template_name='main/home.html', context={'toll' : off.objects.all}) def secondpage(request): return render(request = request, template_name = 'main/next.html') main/urls.py from django.urls import path from . import views app_name = 'main' urlpatterns = [ path('',views.homepage,name='homepage'), path('',views.secondpage,name='secondpage') ] templates/mains/home.html <div class="topnav"> <a href="{% url 'next' %}">Link </a> <a href="#">Link </a> <a href="#">Link </a> </div> I also request the helper to simply it for me as I wouldn't be able to handle complex and advanced python terminology Thanks In Advance From a Friend Arvind -
Why get error django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet (Django 2.1.5)?
Tell me why I get this error and how to fix it? Tried to write django.setup() at the top of the file, but got a RuntimeError error: populate() isn't reentrant Code of mu model and traceback -
how make a filter or autocomplete in a field in django from html page
I newbie in django, I make a django form and show this in a html, in this form I have a field products, when a user going to select a product in this field shows all products, but to find a product not is easy because the products not can be filter when the user write, then the user have search from all the products in this field How I can make to filter when a user write for the product name -
Django management command with arg.parser and confirm
I' writing a small django management command where I parse user input: class Command(BaseCommand): help = 'Management command to transfer User Data from one user to the other' def add_arguments(self, parser): parser.add_argument( '-o', '--old', dest='old', default='', help="ID of Username from whom data is removed", required=True) parser.add_argument( '-n', '--new', dest='new', default=1086, help="ID of Username of receives data", required=False) ... Later I force a confirm to the user confirm = input('You are about to transfer data from {} to {}. Proceed? (Y/n)').format( old_user.username, new_user.username ) while True: if confirm not in ('Y', 'n', 'yes', 'no'): confirm = input('Please enter either "yes" or "no": ') continue if confirm in ('Y', 'yes'): break else: return Unfortunately this fails with NameError: name 'y' is not defined I think what is happening is that arg.parser tries to parse the value. How can I stop it in my confirm loop? -
why am I not getting the second validation?
I am trying to validate my signup form, but I am getting the desired output from the first, and third, but I try to validate if it's short or too common. I got nothing, but I can have matched validation if(data['message']['email'] == 'Enter a valid email address.' || data['message']['email'] == 'User with this Email address already exists.'){ $("#erroremail").html(data['message']['email'][0]); } if(data['message']['password2'] == 'This password is too short.'){ $("#errorpass").html(data['message']['password2'][0]); } if(data['message']['password2'] == "The two password fields didn't match."){ $("#errorpass").html(data['message']['password2'][0]); } JSON response message: email: ["User with this Email address already exists."] password2: Array(3) 0: "This password is too short. It must contain at least 8 characters." 1: "This password is too common." 2: "This password is entirely numeric." -
Cant render new context to template from another view In Django
I create an app to check how to run background tasks in Django but I catch such error in rendering that I can't explain and I have not found a similar question anywhere. I cant figure up where are an error. There is my views.py from django.shortcuts import render, get_object_or_404, redirect from django.http import JsonResponse from django.http import HttpResponseBadRequest, HttpResponseRedirect, HttpResponse from django.urls import reverse import json import datetime from .models import Simulation, get_simulation from .forms import SimulationForm # Create your views here. def simulation_page(request): context = { "simulations_exists": Simulation.objects.all().exists() } return render(request, 'simulation_page.html', context) def simulate(request): if request.method == 'POST': # data = json.loads(request.body) action = data['action'] # 0 or 1 that mean run or stop sim = get_simulation() if action == "0" and sim.status == True: sim.status = False sim.save() elif action == "1" and sim.status == False: sim.status = True sim.save() context = { "simulations_exists": True, "days_passed": sim.get_simulation_day(), "simulation_today_str": (sim.today).strftime("%d %B, %Y"), # 06/12/18 -> 12 June, 2018 "simulation_status": sim.status } return render(request, "simulation_page.html", context=context) return HttpResponseBadRequest() There is my simulation_page.html template: {% extends "base.html" %} {% block content %} <h1>Simulation</h1> <div id='simulation_info'> simulation_status: {{simulation_status}} </div> <div class='container'> {% if not simulations_exists %} <p><a href="{% url 'simulation:simulation_create' … -
Django - Logging not working in production
This issue is driving me nuts. For the longest time logging was working fine, after I changed the format a little bit and made new sub folders it won't work when running the app in prod mode (with nginx + gunicorn) but logging will work when using "runserver". The Gunicorn Log does not show any issue, the app itself works fine... LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': ">>> %(asctime)s | %(levelname)s | %(name)s:%(lineno)s | %(message)s", 'datefmt': "%Y-%m-%d | %H:%M:%S" }, 'simple': { 'format': '%(levelname)s %(message)s' }, }, 'handlers': { 'file': { 'level': 'DEBUG', # 'class': 'logging.handlers.TimedRotatingFileHandler', 'class': 'logging.handlers.RotatingFileHandler', 'maxBytes': 15728640, # 1024 * 1024 * 15B = 15MB 'filename': LOG_DIR + '/app/WSx.log', 'formatter': 'verbose', # 'interval': 1, # 'when': 'midnight', 'backupCount': 7, }, 'user_file': { 'level': 'DEBUG', # 'class': 'logging.handlers.TimedRotatingFileHandler', 'class': 'logging.handlers.RotatingFileHandler', 'maxBytes': 15728640, # 1024 * 1024 * 15B = 15MB 'filename': LOG_DIR + '/user/User.log', 'formatter': 'verbose', # 'interval': 1, # 'when': 'midnight', 'backupCount': 30, }, 'debug_file': { 'level': 'DEBUG', # 'class': 'logging.handlers.TimedRotatingFileHandler', 'class': 'logging.handlers.RotatingFileHandler', 'maxBytes': 15728640, # 1024 * 1024 * 15B = 15MB 'filename': LOG_DIR + '/debug/WSX_DEBUG.log', 'formatter': 'verbose', # 'interval': 1, # 'when': 'midnight', 'backupCount': 7, }, }, 'loggers': { … -
How is it possible to have inlines inside inlines when using a formset in django
I want to apply in my formset the case of having a form-Case model, and in inlines having Offers - Offer model of inlines also, Yachts - Yacht model. models.py class Case(models.Model): client=models.ForeignKey(Client,null=True,verbose_name="Client",on_delete = models.CASCADE) date_created = models.DateTimeField("Date of Case Creation", null=True,blank=True, default=datetime.datetime.now) comment = models.CharField("Comments",max_length=500, blank=True, null=True) class Offer(models.Model): date_created = models.DateTimeField("Date of Offer creation", null=True,blank=True, default=datetime.datetime.now) notes=models.CharField("Offer Notes",max_length=100, blank=True) case=models.ForeignKey(Case,verbose_name="Case",on_delete = models.CASCADE) class Yacht(models.Model): name = models.CharField(max_length=50, verbose_name="Name") price_per_day=models.DecimalField("Price(€) / Day", max_digits=8, decimal_places=2, default=0,blank=True) passengers = models.IntegerField("Passengers",blank=True,null=True) class OfferHasYacht(models.Model): offer=models.ForeignKey(Offer,null=True,verbose_name="Offer",on_delete = models.CASCADE) yacht=models.ForeignKey(Yacht,null=True,verbose_name="Yacht",on_delete = models.CASCADE) In forms.py the : OfferOfferHasYachtFormSet=inlineformset_factory(Offer,OfferHasYacht,form=OfferHasYachtForm,extra=1) works fine having as form the Offer and as inlines the OfferHasYacht(excluding the offer from OfferHasYachtForm) class OfferHasYachtForm(ModelForm): yacht = ModelChoiceField(required=True,queryset=Yacht.objects.all(),widget=autocomplete.ModelSelect2(url='yacht-autocomplete')) class Meta: model = OfferHasYacht fields = ['yacht'] def __init__(self, *args, **kwargs): super(OfferHasYachtForm, self).__init__(*args, **kwargs) self.fields['yacht'].label = "Choose Yacht" but when trying to declare the formset: CaseOfferHasYachtFormSet=inlineformset_factory(Case,OfferHasYacht,form=OfferHasYachtForm,extra=1) the django complaining that: ValueError: 'intranet.OfferHasYacht' has no ForeignKey to 'intranet.Case'. How is it possible to solve that in order to have a view that I can create or update a case having offers (as inlines) and every offer having yachts (as inlines). -
Memcached works in Django shell but not for view functions
I am trying to implement view based caching using memcached in my django project. I have brew installed it in my machine and also installed python-memcached in my virtual env. Memcache works in python3 manage.py shell. >>> from django.core.cache import cache >>> cache.set('foo', 'bar', 600) >>> cache.get('foo') 'bar' But when I put the cache_page() decorator on my view function and load the view I do not get any set or get logs on memcached -vv. I have the following in my settings.py: CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': '127.0.0.1:11211', } } Pardon me, I have very basic understanding of the caching process. I know that memcache stores cached data as key value pairs but how does it pick a key for the decorated view? If I cache the ListView will I be able to query using different filters from the cache? A few comments and links to online resources will be helpful. -
How do I access a complete row through a foreign key in Django?
guys :) Let's say I have the following code: class Model3D(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=300) settings_of_model = models.ForeignKey('Settings', on_delete=models.CASCADE, null=True) class Settings(models.Model): id = models.AutoField(primary_key=True) extruder_Temperature = models.PositiveIntegerField(null=True) layer_Height = models.DecimalField(max_digits=100, decimal_places=100, null=True) model_id = models.ForeignKey('Model3D', on_delete=models.CASCADE) printer_Name = models.ForeignKey('Printer', on_delete=models.CASCADE, null=True) Every model has one row in table settings with the settings for the model. How can I access this row to get it for an specific model? The following code did not work. def get_settings(id_of_model): settings_of_model = Model3D.objects.filter(id=id_of_model)prefetch_related('Settings') return settings_of_model Can you help? -
uWSGI - never sleep mod?
I have a django app, running with uwsgi behind nginx server, all on same debian and python2.7. On the first start of the application, everything goes very well, the queries are fast. If I never question the application for a long time (> 1h maybe more), the first new query takes a long time to answer and after waiting then everything reworks correctly. As if the service was in standby and make time to respawn. I would never wait, even if the service has not been solicited for several hours. That is possible ? I have tried "cheaper" configuration, same result. My ini file : [uwsgi] logto = $(APP_LOGS_DIR)/uwsgi.log chdir = $(APP_SRC_DIR) manage-script-name = true mount = /=$(APP_SRC_DIR)/wsgi.py plugins = python virtualenv = $(APP_VENV) master = true processes = 4 socket = 0.0.0.0:9001 static-map = /static=$(APP_SRC_DIR)/static/ vacuum = True buffer-size = 8192 vacuum = true cheaper-algo = spare cheaper = 2 cheaper-initial = 3 workers = 4 cheaper-step = 1 and a part my nginx conf : upstream app { server 127.0.0.1:9001; } server { [...] location / { include uwsgi_params; uwsgi_pass app ; } } -
How to write a self referencing Django Model?
I have a Django model "Inspection" which has: InspectionID (PK) PartID SiteID Date Comment Report Signiture I want to be able to have a one to many relationship between the inspection ID and date. So one ID can have inspections at many dates. How would I do this? I currently have the following: class Inspection(models.Model): InspectionID = models.IntegerField(primary_key=True, unique=True) PartID = models.ForeignKey('Part', on_delete=models.CASCADE) SiteID = models.ForeignKey('Site', on_delete=models.CASCADE) Date = models.DateField(auto_now=False, auto_now_add=False) Comment = models.CharField(max_length=255, blank=True) Report = models.FileField(upload_to='docs', null=True, blank=True) Signiture = models.CharField(max_length=255, blank=True) I thought about using models.ForeignKey but I really don't know how to implement that properly in this situation. -
How can redefine attribute in abstract model?
Hello I have two models class A(models.Model): slug = models.SlugField() class Meta: abstract = True class B(models.Model): slug = models.CharField() class Meta: abstract = True I get error AttributeError: Manager isn't available; B is abstract How do can to redefine attribute in abstract class? class A cannot be changedю