Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django REST API JWT user verification failed : No active account found with the given credentials
i am using django JWT for account validation but fails for every user that is not super user but works for superuser created using python manage.py createsuperuser Here is the model for User profile class AccountManager(BaseUserManager): def create_user(self, name, phone, email, password=None, **extra_fields): """ Creates and saves a User with z given name,phone,email and password. """ user = self.model(name=name,email=self.normalize_email(email),phone=phone) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, name, phone, email, password=None, **extra_fields): user = self.create_user(name, phone, email, password, **extra_fields) user.is_admin = True user.is_superuser = True user.is_staff = True return user class Account(AbstractBaseUser): email = models.EmailField(verbose_name='email address',max_length=255,unique=True,) phone = models.CharField(max_length=15,unique=True) name = models.CharField(max_length=150,unique=True) picture = models.ImageField(blank=True, null=True) date_joined = models.DateTimeField(default=timezone.now) last_login = models.DateTimeField(null=True) staff = models.BooleanField(default=False) admin = models.BooleanField(default=False) is_active = models.BooleanField(default=False) objects = AccountManager() USERNAME_FIELD = 'phone' REQUIRED_FIELDS = ['name', 'phone', 'email', 'password'] def __str__(self): return self.name and here is my signup API function that creates a normal user def signup(request): if request.method == 'POST': try: values = [request.POST.get('name'),request.POST.get('email'),request.POST.get('phone'),request.POST.get('password'),request.POST.get('password2')] user = Account.objects.create_user(name=values[0],phone=values[2],email=values[1],password=values[3]) user.save() # send email verification current_site = get_current_site(request) mail_subject = 'Activate your account.' message = f'{current_site.domain}/account/activate/{urlsafe_base64_encode(force_bytes(user.pk))}/{account_activation_token.make_token(user)}' to_email = values[1] send_mail(mail_subject, message, 'youremail', [to_email]) return JsonResponse({'success': 'User registered successfully.But need to activate account.'}) except Exception: extype, exc, tb = sys.exc_info() print(f"\t\t****** … -
Test a custom django filter
Written a filter that is functioning as it should class ExternalProductActiveStatusFilter(admin.SimpleListFilter): title = "EP Active status" parameter_name = "ep active status" def lookups(self, request, model_admin): return [ ("active", "Active"), ("inactive", "Inactive"), ] def queryset(self, request, queryset): if self.value() == "active": return queryset.distinct().filter(external_products__active=True) if self.value() == "inactive": return queryset.exclude(external_products__active=True) Now I want to test it but can't get it to work. Looked into old SO questions but the solutions do not do the trick. These ones in particular, Test a custom filter in admin.py(7 years old) and Django filter testing My test as of right now def test_externalproductactivestatusfilter_active(self): self.product1 = baker.make( "products.Product", id=uuid4(), title="Active product" ) self.product2 = baker.make( "products.Product", id=uuid4(), title="Inactive product" ) self.external_product1 = baker.make( "external_products.ExternalProduct", internal_product=self.product1, active=True, ) self.external_product2 = baker.make( "external_products.ExternalProduct", internal_product=self.product1, active=False, ) request = MockRequest() f = ExternalProductActiveStatusFilter( None, {"active": "Active"}, Product, ProductAdmin ) result = f.queryset(request, Product.objects.all()) print(result) result is None -
Django rest framework filtering and grouping items in serializer
I have models like this: class schoolCycle(models.Model): name = models.CharField(max_length=255) code = models.CharField(max_length=255) class measurements(models.Model): name = models.CharField(max_length=255) weight = models.FloatField() school_cycle_id = models.ForeignKey(schoolCycle,on_delete=models.DO_NOTHING, related_name='measurements') code = models.CharField(max_length=255) class aspects(models.Model): name = models.CharField(max_length=255) code = models.CharField(max_length=255) measurement_id = models.ForeignKey(measurements,on_delete=models.DO_NOTHING, related_name='aspects') class standards(models.Model): name = models.CharField(max_length=255) code = models.CharField(max_length=255) weight = models.FloatField() aspect_id = models.ForeignKey(aspects,on_delete =models.DO_NOTHING, related_name='standards') as can be seen, "standard" refers an 'aspect' and aspect refers 'a measurement" and measurement refers a 'school cycle' as foreign key. in want to create a seriallizer like this: [{ "measurement 1" : { "school cycle 1" :{ "aspect 1": { {"standard 1" : ...}, {"standard 2" : ...}, } "aspect 2": { {"standard 3" : ...}, {"standard 4" : ...}, } } "school cycle 2" :{ "aspect 3": { {"standard 5" : ...}, {"standard 6" : ...}, } "aspect 4": { {"standard 7" : ...}, {"standard 8" : ...}, } } "measurement 2" : { "school cycle 3" :{ "aspect 5": { {"standard 9" : ...}, {"standard 10" : ...}, } "aspect 6": { {"standard 11" : ...}, {"standard 12" : ...}, } } "school cycle 4" :{ "aspect 7": { {"standard 13" : ...}, {"standard 14" : ...}, } "aspect 8": … -
how to set delay to restart container in docker-compose?
I have a problem with the initial launch of docker-compose up, when DB is not initialized yet and django throws an error. I tried to use 'restart_police', but it didn't help and the webservice was restarted almost without waiting and forward the DB service, regardless of which reload period I wouldn't set version: "3.9" services: web: build: . command: bash -c "python manage.py makemigrations && python manage.py migrate && python manage.py runserver 0.0.0.0:8000" volumes: - .:/app ports: - "8000:8000" deploy: restart_policy: condition: on-failure delay: 15s environment: - POSTGRES_NAME=${POSTGRES_DB} - POSTGRES_USER=${POSTGRES_USER} - POSTGRES_PASSWORD=${POSTGRES_PASSWORD} - POSTGRES_HOST=db depends_on: - db db: container_name: db_pg image: postgres hostname: postgres environment: POSTGRES_DB: ${POSTGRES_DB} POSTGRES_USER: ${POSTGRES_USER} POSTGRES_PASSWORD: ${POSTGRES_PASSWORD} POSTGRES_HOST: db volumes: - ./data/db:/var/lib/postgresql/data restart: unless-stopped pgadmin: image: dpage/pgadmin4 depends_on: - db ports: - "5555:80" environment: PGADMIN_DEFAULT_EMAIL: pgadmin4@pgadmin.org PGADMIN_DEFAULT_PASSWORD: admin volumes: - ./data/pgadmin:/var/lib/pgadmin/data -
Django Model '<' not supported between instances of 'str' and 'int'
I have a Django script which runs fine locally, but on Render.com it fails with this error: Sep 4 01:01:54 PM create_tasks(limit=limit) Sep 4 01:01:54 PM File "/opt/render/project/src/scripts/pull_from_outscraper.py", line 94, in create_tasks Sep 4 01:01:54 PM for task_object in task_objects[0:limit]: Sep 4 01:01:54 PM File "/opt/render/project/src/.venv/lib/python3.9/site-packages/django/db/models/query.py", line 422, in __getitem__ Sep 4 01:01:54 PM or (k.stop is not None and k.stop < 0) Sep 4 01:01:54 PM TypeError: '<' not supported between instances of 'str' and 'int'``` -
Avoid hardcoding of a model name
Django 4.1 class Task(models.Model): cypher = models.CharField( max_length=255, null=False, default="", ) class Meta: db_table = "{}_{}_{}".format(TablePrefixes.FIPI.value, __package__, "Task") Here in db_table I hardcoded "Task". Could you tell me whether it is possible to somehow avoid hardcoding? -
Django template includes + extends
This is my Directory Tree. base.html: {% load static %} <!DOCTYPE html> <html lang="en"> {% include 'weapons/head/head.html' %} {% include 'weapons/body/body.html' %} </html> body.html: {% load static %} <body> {% block content %}{% endblock content %} </body> home.html: {% extends 'weapons/base/base.html' %} {% block content %} <span>Hello!</span> {% endblock content %} When I visit my home.html, it doesn't appear to be working correctly. I see nothing on my page, however the "Hello!" message is expected to be shown. What is the problem? -
Django modelformset_factory error is not displayed in template
I have a modelformset_factory displaying 20 forms with 20 staff names whose phone numbers are to be entered but if there is an error(s), they are not displayed in the template and the entered data are also lost. And even if the forms are valid I am not redirected to the home page. Fresh forms are loaded all the times I click submit button. class PhoneEntryView(LoginRequiredMixin, FormView): template_name = "myportal/ca_entry_form.html" success_url = '/myportal/home-page' def get_initial(self): initial = super().get_initial() logged_in_user = User.objects.get(id=self.kwargs['pk']) staff_list = Staff.objects.filter(manager=logged_in_user) initial_staff = [{'staff': staff} for staff in staff_list] staff_qs = Staff.objects.none() StaffFormSet = modelformset_factory(Staff, form=StaffForm, formset=StaffModelFormSet, extra=len(staff_list), max_num=len(staff_list), validate_max=True) formset = StaffFormSet(queryset=staff_qs, initial=initial_staff) initial['initial_staff'] = initial_staff initial['StaffFormSet'] = StaffFormSet initial['formset'] = formset initial['staff_qs'] = staff_qs return initial def get_form_class(self, *args, **kwargs): return self.get_form() def get_form(self, *args, **kwargs): return self.get_initial()['formset'] def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['formset'] = self.get_form() context['form_message'] = 'Update phone directory for your staff' return context def post(self, request, *args, **kwargs): StaffFormSet = self.get_initial()['StaffFormSet'] initial_staff = self.get_initial()['initial_staff'] submitted_form = StaffFormSet(request.POST, initial=initial_staff) if submitted_form.is_valid(): self.form_valid(submitted_form) print("This form is valid, Sir!") else: print("Non Form Errors: ", submitted_form.non_form_errors()) self.get_context_data()['formset'] = submitted_form self.form_invalid(submitted_form) return super().post(request, *args, **kwargs) def form_valid(self, form, **kwargs): saved_forms = form.save(commit=False) #Save forms here return … -
how to deploy ec2 instance using ASGI django application (apache2 production)
please any one help to solve this issues how to deploy ec2 instance using ASGI django application (apache2 production) . -
Legend Picking using matplotlib (python file )
I created an API using django for plot visualisation I am connected to my database and i would like to add to my plot this animation of legend picking , but something wrong , someone can correcting me ? def one (df_a, a, b, c=2): X = df_a.iloc[:, a:b].to_numpy() l = X.shape[0] D = np.zeros((l, l)) idx = range(len(X)) for j in range(1, X.shape[0]): A = X D[j, idx] = np.abs(A).max(1) d = D.sum(0) / l diff = np.sort(d)[1:] - np.sort(d)[:-1] if np.where(diff > c * np.median(diff))[0].size != 0: t = np.sort(d)[np.where(diff > c * np.median(diff))[0] + 1].min() return df_a.iloc[np.where(d >= t)].index def two (df_a, a, b, c): outliers = one(df_a, a, b, c) colors = 'red' plt.figure(figsize=(20, 10)) plt.xlabel('pi ---> ') plt.ylabel('ab ---> ') plt.plot(df_a.to_numpy()[:, 1:].T, 'blue') for i, outlier in enumerate(outliers): plt.plot(df_abs.loc[outlier].iloc[1:], c=colors[i], label=outlier) plt.legend() legend = plt.legend() legend.set_picker(True) def on_pick(event): legline = event.artist origline = lined[legline] visible = not origline.get_visible() origline.set_visible(visible) legline.set_alpha(1.0 if visible else 0.2) fig.canvas.draw() fig.canvas.mpl_connect('pick_event', on_pick) plt.show() ``` -
Django many-to-many filtering gives "No operator matches the given name and argument types."
I have the following models in my Django project: model Profile(models.Model): user = models.OneToOneField(User) faculties = models.ManyToManyField('users.Faculty', related_name='profiles') Now I want to define a function that gives me all coworkers of a user/profile like so: def coworkers(self): coworkers = User.objects.none() for faculty in self.faculties.all(): coworkers |= User.objects.filter(Q(profile__faculties__id__exact=faculty.id)) return coworkers But then I always run in a ProgrammingError at /exercise/ operator does not exist: character varying = integer or No operator matches the given name and argument types. You might need to add explicit type casts. ) was the direct cause of the following exception:. I also tried: faculties = [f.id for f in self.faculties.all()] coworkers = User.objects.filter(Q(profile__faculties__id__in=faculties) Both versions also do not work with __exact instead of __in. Any help? -
CSS text trasform not taking affect to the data in database
I'm new to django and I've a problem that in my forms.py I've added "text-transform:capitalize" and it is working properly in the UI but when the data is saved the value becomes the old one. -
Error to run manage.py. I'm trying to run manage.py server but it hit some error! I've just trying to run a timetable generator
PS C:\Users\user\Desktop\TimetableGenerationSystem-master\projttgs> python manage.py runserver Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Python310\lib\threading.py", line 1016, in _bootstrap_inner self.run() File "C:\Python310\lib\threading.py", line 953, in run self._target(*self._args, **self._kwargs) File "C:\Python310\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Python310\lib\site-packages\django\core\management\commands\runserver.py", line 134, in inner_run self.check(display_num_errors=True) File "C:\Python310\lib\site-packages\django\core\management\base.py", line 546, in check raise SystemCheckError(msg) django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: ?: (urls.E009) Your URL pattern 'timetable_generation/render/pdf' [name='pdf'] has an invalid view, pass Pdf.as_view() instead of Pdf. WARNINGS: account.Profile: (models.W042) Auto-created primary key used when not defining a primary key type, by default 'django.db.models.AutoField'. HINT: Configure the DEFAULT_AUTO_FIELD setting or the AccountConfig.default_auto_field attribute to point to a subclass of AutoField, e.g. 'django.db.model s.BigAutoField'. ttgen.Department: (models.W042) Auto-created primary key used when not defining a primary key type, by default 'django.db.models.AutoField'. HINT: Configure the DEFAULT_AUTO_FIELD setting or the TtgenConfig.default_auto_field attribute to point to a subclass of AutoField, e.g. 'django.db.models. BigAutoField'. ttgen.Instructor: (models.W042) Auto-created primary key used when not defining a primary key type, by default 'django.db.models.AutoField'. HINT: Configure the DEFAULT_AUTO_FIELD setting or the TtgenConfig.default_auto_field attribute to point to a subclass of AutoField, e.g. 'django.db.models. BigAutoField'. ttgen.Room: (models.W042) Auto-created primary key used when not defining … -
RecursionError: maximum recursion depth exceeded (pythonanywhere)
I've deployed a DRF project on pythonanywhere. I have several endpoints like products, collections, carts and ... products and collection endpoints are ok. but it's not ok when I try to visit other endpoints like carts (all endpoints work in local) 2022-09-04 07:36:45,190: Error running WSGI application 2022-09-04 07:36:45,210: RecursionError: maximum recursion depth exceeded 2022-09-04 07:36:45,211: File "/home/piriecommerce/.virtualenvs/myenv/lib/python3.9/site- packages/django/core/handlers/wsgi.py", line 131, in __call__ 2022-09-04 07:36:45,211: response = self.get_response(request) -
DJango model logic
is it possible to have a logic based on the choices like: class model(models.Model): a = something(choices) b = foreingkey to c etc and then if a choices are yes show c ForeignKey table or just like that class model(models.Model): a = something(choices) b = something else etc if a choice is yes show b else only a -
html & django resize img-parent div to one size
In my application I let the user upload images. They are all displayed in a grid system. But because of there different aspect ratio it´s of course not possible that they have the same size. Are there any possibilities although the images aren´t the same size but let the parent-div be the same size for all projects. Thanks here is my template <div class="container"> <div class="row"> {% for project in projects %} <div class="col-lg-3 col-md-4 col-sm-6"> <div class="border border-dark"> <img class="card-img-top" src="{{project.featured_images.url}}" alt="Card image cap"> <h5 class="text-center">{{project.title}}</h5> </a> <ul class="list-group list-group-horizontal"> <li class="list-group-item flex-fill">{{project.price}} €</li> <li class="list-group-item flex-fill">{{project.location}}</li> </ul> </div> </div> {% endfor %} </div> </div> -
CSRF token from POST incorrect when running 2 Django containers in the same Docker host
I run two Django projects in a Docker host with Compose and both projects communicate with each other through a Docker network called mynetwork. Everything works fine, however, when I log in the admin section of project A and then open a new tab to log into the admin section of project B, then user from project A get disconnected with this message: CSRF verification failed. Request aborted. Reason given for failure: CSRF token from POST incorrect. And vice versa, when I log in the admin section of project B and load a tab with the admin section of project A, user of project B is disconnected. Both projects use custom AUTH_USER_MODEL. I tried to deactivate CsrfViewMiddleware middleware and play with the parameters below but I don't notice any change. How can I solve this issue ? settings.py Project A & B MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', "corsheaders.middleware.CorsMiddleware", 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', # 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django_structlog.middlewares.RequestMiddleware', 'django_structlog.middlewares.CeleryMiddleware', ] AUTH_USER_MODEL = 'authentication.User' # SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'http') # CSRF_USE_SESSIONS = True # CSRF_COOKIE_HTTPONLY = True docker-compose.yml Project A version: '3.8' services: django: build: context: . dockerfile: ./compose/local/django/Dockerfile image: controller_django command: python manage.py runserver 0.0.0.0:8001 volumes: - .:/app expose: - 8001 ports: … -
AttributeError: 'NoneType' object has no attribute 'aptTime' in Django
I have an appointment model for patient to book appointment with a doctor, i used a custom user model for both doctor and patients, using is_staff and is_patient to differentiate them... class Appointment(models.Model): doctor = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='staff', on_delete=models.SET_NULL, null=True) patient = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='+', on_delete=models.SET_NULL, null=True) aptTime = models.DateTimeField(blank=True, null=True) pending_approval = models.BooleanField(default=True, null=True) approved = models.BooleanField(default=False, null=True) in my views.py i am trying to set the patient to request.user and doctor to the context i passed through the url, so i have the form_valid method to create appointment like this... class AppointmentCreateView(CreateView): model = Appointment fields = ['aptTime'] template_name = 'patients/Appointment-Createview.html' def form_valid(self, form, *args, **kwargs): form.instance.doctor = self.kwargs['pk'] #TODO change to doctor instance form.instance.aptTime = self.object.aptTime form.instance.patient = self.request.user form.save() i got an error saying ValueError: Cannot assign "1": "Appointment.doctor" must be a "User" instance. Internal Server Error: /patient/Appointment-Create/1/ After searching around SO i was able to change my code to... ...Some code... def form_valid(self, form, *args, **kwargs): User = get_user_model() doc = User.objects.get(id=self.kwargs['pk']) form.instance.doctor = doc #TODO change to doctor instance form.instance.aptTime = self.object.aptTime form.instance.patient = self.request.user form.save() now i'm getting a new error saying form.instance.aptTime = self.object.aptTime AttributeError: 'NoneType' object has no attribute 'aptTime' I am using … -
Is it better to interact query_set like Sets or use built-in functions?
I want to write a complex query that needs union and intersection. When I checked this QA, I found two approaches. So my need would be accomplished by needed_keys = [A, B, C] qs1 = model.objects.filter(entity=needed_keys[0]) for entity in needed_keys: qs1 = qs1 | model.objects.filter(entity=entity) qs2 = qs2 & qs1 or needed_keys = [A, B, C] qs1 = model.objects.filter(entity=needed_keys[0]) for entity in needed_keys: qs1 = qs1.union(model.objects.filter(entity=entity)) qs2 = qs2.intersection(qs1) based on one of the answers, I assume that the first approach would evaluate the result of the queries and then calculate the result of the AND or OR at the python level, Although I haven't seen anything about this evaluation in Django's doc. To sum up, my questions are, Which approach is better? Is Django really evaluates 'model.objects.filter(entity=entity)' each time in the loop of the first approach? P.S. please do not focus on the variable names or structure of the code, the goal was just to illustrate the situation. the type of 'entity' is textField, so I can't use 'model.objects.filter(entity__in=needed_keys)' when I checked the output of 'q2.query', the first approach was more readable for me but I want to be sure about its performance too. -
How can i give 2 domains to my Django project that contain 2 differen apps inside that is hosted on digital ocens app platform?
I have a Django project that is hosted on the Digital Oceans App Platform. My project contains 2 Django apps inside I want to give the main domain to 1 Django app and the subdomain to the other Django app. I'm using google domains. If someone kindly guides me how can I do this with the Digital Oceans App platform? -
break the loop when list len reaches to 5 (In for loop)
I am building a simple python program and I am trying to filter some response based on limit to run the for loop or while loop. What I am trying to do ? I am trying to stop the loop when list len reaches to 5. It can be a for loop and while loop. views.py def filter_array(request): new_array = [] count = 1 quit = False for m in res.get("blogs"): for likes in m.get("likes"): try: count += 1 if likes == "user_1": new_array.append(likes) if count == 5: quit = True break except: quit = True break print(new_array) return new_array json response in views.py res = { "blogs": [ { "title": "Blog 1", "description": "Blog description", "likes": [ "user_1", "user_2", ] }, { "title": "Blog 2", "description": "Blog description", "likes": [ "user_4", "user_5", ] }, { "title": "Blog 3", "description": "Blog description", "likes": [ "user_3", ] }, { "title": "Blog 4", "description": "Blog description", "likes": [ "user_3", "user_4", "user_5", ] }, { "title": "Blog 5", "description": "Blog description", "likes": [ "user_4", "user_5", ] }, ] } When I run the above code then It is appending all the json items in the array. But I want to append in list … -
how can I use multiple {% block content %} inside base template in django?
So, I have this base html where for example I am using it like this <html> <body> <nav> navbar </nav> <div class= "content"> {% block content %} {% endblock %} </div> ............. My question is can I use multiple block contents in the same base html ? So that I can extend the parent and add elements in whatever block I want ? like this - <html> <body> <nav> navbar </nav> <div class= "content"> {% block content %} {% endblock %} </div> <div class = "summaries"> {% block content %} {% endblock %} </div> ............. Question might sound rookie. I am new to Django! -
'utf-8' codec can't decode byte 0x8b in position 0: invalid start byte django
so i have variable contains with bytes and i want to write it to text and download it. but to use write, it's must in bytes. so how to make from bytes to string? now i got error like this. i tried to decode it, but it cannot works. 'utf-8' codec can't decode byte 0x8b in position 0: invalid start byte here's the code: def create_file(f): print(f) #f = b'\x8b\x86pJ' response = HttpResponse(content_type="text/plain") response['Content-Disposition'] = 'attachment; filename=file.txt' filename = f print(filename) # filename = b'\x8b\x86pJ' download = filename.decode('utf-8') response.write(download) print(response) return response -
Python Django - unsupported operand type(s) for -: 'float' and 'NoneType'
I'm a beginner to python and Django, I tried to do searching but I can't find my answer to this. Can anybody help me with this please. code from my html: <td class="px-2 py-1 align-middle text-center"> {{ schedule.count_available|floatformat:0|intcomma }} </td> my model: class Schedule(models.Model): code = models.CharField(max_length=100) vessel = models.ForeignKey(Vessel,on_delete=models.CASCADE) depart = models.ForeignKey(Location,on_delete=models.CASCADE, related_name='depart_location') destination = models.ForeignKey(Location,on_delete=models.CASCADE, related_name='destination') schedule= models.DateTimeField() fare= models.FloatField() status = models.CharField(max_length=2, choices=(('1','Active'),('2','Cancelled')), default=1) date_created = models.DateTimeField(default=timezone.now) date_updated = models.DateTimeField(auto_now=True) def __str__(self): return str(self.code + ' - ' + self.vessel.vessel_number) def count_available(self): booked = Booking.objects.filter(schedule=self).aggregate(Sum('seats'))['seats__sum'] return self.vessel.seats - booked error: error image -
Mixins cause a blow up when migrating
Mixins: class ExamPartMixin(models.Model): exam_part = models.ForeignKey('exam_parts.ExamPart', null=True, on_delete=models.CASCADE, ) class NameMixin(models.Model): name = models.CharField(max_length=255, null=False, default="") def __str__(self): return self.name class Meta: abstract = True Model: class ExamSection(NameMixin, ExamPartMixin, CommentMixin): class Meta: constraints = [ models.UniqueConstraint( fields=['exam_part', 'name'], name='part_section') ] Problem wnem migrating exam_sections.ExamSection: (models.E016) 'constraints' refers to field 'exam_part' which is not local to model 'ExamSection'. HINT: This issue may be caused by multi-table inheritance. task_descriptions.TaskDescription: (models.E016) 'constraints' refers to field 'exam_part' which is not local to model 'TaskDescription'. HINT: This issue may be caused by multi-table inheritance. Could you help me? Should I refrain from using mixins here? I like mixins and would like to use them.