Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django add parameter to url after login fails, in custom authenticator
I override the authenticate function to return to login but with url parameters if the auth fails, simply for deferent javascript behavior's accounts/auth_backend/RoleModelBackend(ModelBackend)/authenticate() # if user pass or email or role is wrong login... else: login_url = reverse("login") redirect_url = login_url + "?" + urlencode({"user_type": role}) # role return redirect(request, redirect_url) mainAppName/urls urlpatterns = [ path("admin/", admin.site.urls), path("accounts/", include("accounts.urls")), ... ] accounts/urls urlpatterns = [ path("login", views.custom_login, name="login"), # Use the custom login view path("", include("django.contrib.auth.urls")), path("accounts/", include("django.contrib.auth.urls")), ] i get error Reverse for '<WSGIRequest: POST '/accounts/login/'>' not found. '<WSGIRequest: POST '/accounts/login/'>' is not a valid view function or pattern name. on the redirect line in authenticate() is there a better way to pass the frontend information other than url params? else how do i ge this to work? django 4.2 -
Mayan EDMS - not showing the uploaded docs
I'm working on a project to use one of the open source document system and work customize it based on the need, so I'm start installing Mayan EDMS with the following steps: Clone the repository https://gitlab.com/mayan-edms/mayan-edms Create a virtual environment python3 -m venv venv Activate the environment source venv/bin/activate Install the requirements pip install -r requirements.txt Run ./manage.py common_initial_setup Run python manage.py makemigrations Run python manage.py migrate Run the server python manage.py runserver All these steps done without errors but when access the Mayan on my local host and try to upload a document, this message appears but I cannot see the doc anywhere! The message appears after uploading Known that I can see the docs in the mayan/media/shared_files but the SQLite is empty and while uploading there is no any error! I search a lot to figure out the issue but I cannot find any solution I appreciate your support in this issue -
How to manage sessions in Django
Hi Ive created a django app that uses the spotify api to give users their top track and artist information, however, ive realised that my site if someone inputs the url /top-tracks without authenticating using the spotify auth they see the last users top track data. I was wondering how i go about this so that they have to authenticate themselves. Im new to app development any help would be appreciated. Repo: https://github.com/KevinL0206/spotify_stats_project from django.conf import settings from django.shortcuts import render, redirect from spotipy.oauth2 import SpotifyOAuth from django.http import HttpResponse from spotify_stats_project import settings from decouple import config from spotify_stats_project import settings from urllib.parse import urlencode from django.shortcuts import redirect from django.urls import reverse from django.http import HttpResponse import random import string import requests import base64 import datetime class SpotifyAPI(object): access_token = None access_token_expires = datetime.datetime.now() access_token_did_expire = True client_id = None client_secret = None scope = None redirect_uri=None token_url = "https://accounts.spotify.com/api/token" def __init__(self, client_id, client_secret,redirect_uri,scope, *args, **kwargs): super().__init__(*args, **kwargs) self.client_id = client_id self.client_secret = client_secret self.redirect_uri = redirect_uri self.scope = scope def is_token_expired(self): # Check if the access token has expired access_token = self.get_access_token() if not access_token: return True def login(self): authorization_url = 'https://accounts.spotify.com/authorize?' + urlencode({ "response_type" : "code", … -
Celery signatures .s(): early or late binding?
This blog post of Adam Johnson perfectly illustrates the difference between early binding and late binding closures in Python. This is also explained here. I've got a function my_func which corresponds to a Celery task (it's decorated with @shared_task). It expects some arguments. I run it with the following piece of code, using Celery signatures as described in the documentation (see also this StackOverflow answer): from functools import partial from django.db import transaction from example.tasks import my_func # next line can be found at the end of some other functions which involve a transaction transaction.on_commit(my_func.s(param1, param2).delay)) Are Celery signatures early binding or late binding? And how to demonstrate it in an elegant way? If they are early binding, the following line of code should be equivalent: transaction.on_commit(partial(my_func.delay, param1, param2)) If they are late binding, I think I could be facing a pesky bug with my current code, in some edge cases... -
Django url parameter setting
I try to have open url like: mysite.doamin/table/name1 mysite.doamin/table/name2 but without any success.... urls.py from django.urls import path from django.views.generic import TemplateView from . import views from .views import Table, TableFilter urlpatterns = [ path('', views.dashboard, name='dashboard'), path('table/<name>', Table.as_view(), name='table'), path('filters_form/', TableFilter.as_view(), name='filters_form'), path('search/', views.search, name='search'), ] template/navbar.html Table </a> <ul class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink"> <li> <a class="dropdown-item" href="{% url 'table' cms %}">Cms</a> </li> <li> <a class="dropdown-item" href="{% url 'table' cms %}">Sectools</a> </li> </ul> I want to set a parameter, to switch de models and show any models in the table template.... Reverse for 'table' with arguments '('',)' not found. 1 pattern(s) tried: ['table\\/(?P<name>[^/]+)\\Z'] -
Working with DHL API in my Django project
I am trying to integrate DHL API in my django project but it is not working. Can someone help refer any comprehensive article on how to do it. I created an App on the DHL developer portal. I have my API Key and Secret Key -
validator could not be imported Check your AUTH_PASSWORD_VALIDATORS setting
i made validators.py and added my custom password validators like check for uppercase and special characters and after that i added those in my auth password validators in my settings.py like this AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 'OPTIONS': { 'max_similarity': 0.7, 'user_attributes': ("username", "first_name", "last_name", "email") } }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 'OPTIONS': { 'min_length': 8, } }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, \# custom coded validators { 'NAME': 'app1.validators.UppercaseValidator', }, { 'NAME': 'app1.validators.SpecialCharValidator', }, ] this is my forms.py ` from django import forms from django.contrib.auth.password_validation import validate_password class SignupForm(forms.Form): firstname = forms.CharField(max_length=20) lastname = forms.CharField(max_length=20) email = forms.EmailField() username = forms.CharField(max_length=30) password = forms.CharField(widget=forms.PasswordInput, validators=[validate_password])` and while signing up im getting this error ImproperlyConfigured at /signup/ The module in NAME could not be imported: app1.validators.UppercaseValidator. Check your AUTH_PASSWORD_VALIDATORS setting. Any help is appreciated before it is giving me error based on validators that django has bydefault but after adding my own validator it giving me error i mentioned -
Deploy Django to Vercel
error: 404: NOT_FOUND github: https://github.com/opielapatryk/python-portfolio Hello I have little problem with deploying my django portfolio. I was trying to deploy Django portfolio website to Vercel, but I have error mentioned above I was trying to edit path in vercel.json but nothing works -
Django-import-exportImport a ManyToMany field
I have a Agent class model class Agent(models.Model): registration_number = models.CharField(max_length=50, unique=True) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) And I have a AgentList class model class AgentList(models.Model): name = models.CharField(max_length=50) agents = models.ManyToManyField(Agent) What I want is when I click the "Import" button in my admin get a page with two field : Select the CSV (with the registration_number, first_name, last_name) Write a name for the list All agent will be saved in Agent and it will make a new "AgentList" link to those I imported. I already try some custom import page, but I'm starting to think it exist a better way. ATM my AgentListAdmin look like this : @admin.register(AgentList) class AgentListAdmin(ImportMixin, admin.ModelAdmin): list_display = ("name",) filter_horizontal = ("agents", ) def get_dataset(self, file): """ Returns the dataset from the uploaded file. """ dataset = tablib.Dataset() try: dataset.load(file.read().decode('utf-8'), format='csv') except Exception as e: raise ValidationError(str(e)) return dataset def import_action(self, request, *args, **kwargs): """ Import action. """ if request.method == 'POST': form = forms.Form(request.POST, request.FILES) if form.is_valid(): file = request.FILES['file'] dataset = self.get_dataset(file) result = self.process_dataset(dataset, request=request, confirm_form=None) if result.has_errors(): self.message_user(request, result, messages.ERROR) else: self.message_user(request, result, messages.SUCCESS) return HttpResponseRedirect(request.get_full_path()) else: form = forms.Form() context = self.admin_site.each_context(request) context.update( { 'form': form, 'opts': … -
badly formed hexadecimal UUID string
I don't understand what the problem here. -
How to use sitemap gemerator extention in vs code
I use sitemap generator extention in vs code to generate a sitemap for my website code in vs code, I works find but no url path for the sitemap was generated, pls how can I generate the url I tried vs code sitemap generator extention to generate a sitemap , sitemap.xml was generated without sitemap url -
Django - ValueError at / The 'image' attribute has no file associated with it
I am working on Django project I receive the following error: "ValueError at / The 'image' attribute has no file associated with it." models.py from django.contrib.auth.models import User from django.db import models # Create your models here. class Catagory(models.Model): name = models.CharField(max_length=255) class Meta: ordering = ('name',) verbose_name_plural = 'Catagories' def __str__(self): return self.name class Item(models.Model): Catagory = models.ForeignKey(Catagory, related_name='items', on_delete=models.CASCADE) name = models.CharField(max_length=255) description =models.TextField(blank=True, null=True) price = models.FloatField() image = models.ImageField(upload_to='item_images', blank=True, null=True) is_sold = models.BooleanField(default=False) created_by = models.ForeignKey(User, related_name='items', on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name html <div class="card" style="width: 18rem;"> <img src="{{ item.image.url }}" class="card-img-top" alt="image"> <div class="card-body"> <h5>{{ item.name }}</h5> <p class="text-secondary">Price: {{ item.price }}</p> </div> </div> Error during template rendering How can I handle this error -
Shopify Django App Admin Link Not working After Deploying on Amazon EC2 Instance
I have made a test Shopify app in Django. What this app essentially does is downloads invoice of orders through Shopify admin dashboard admin links. The app was working fine on my local host when I was using ngrok tunnels. The invoices were being downloading on command but when I deployed this app on an AWS EC2 Instance the admin links are not working. The Invoice Pdf is being generated properly but I guess it is not being sent as an HttpResponse. def download_invoice(request, raw_order, template_name): raw_order['product_data'] = product_data dir_path = settings.MEDIA_ROOT with tempfile.TemporaryDirectory(dir=dir_path) as tmpdir: output_filename = tmpdir + '\\' + "my-invoice.pdf" path=os.path.join(os.path.dirname(__file__),'./templates/home') templateLoader = jinja2.FileSystemLoader(searchpath=path) templateEnv = jinja2.Environment(loader=templateLoader) TEMPLATE_FILE = template_name template = templateEnv.get_template(TEMPLATE_FILE) outputText = template.render(data=raw_order) pdfkit.from_string(outputText, output_filename) filename = "my-invoice.pdf" wrapper = FileWrapper(open(output_filename, 'rb')) print(output_filename) # breakpoint() # pass response = HttpResponse(wrapper, content_type=mimetypes.guess_type(output_filename)[0]) response['Content-Length'] = os.path.getsize(output_filename) response['Content-Disposition'] = "attachment; filename=" + filename return response This function downloads the pdf when it is called on my app's interface but it does not download the invoice when it is called in Shopify Admin Link. Maybe there is an issue EC2 security group. My Inbound Rules My Outbound Rules As far as I think there is some problem with … -
Web Frontend Development: What way should I choose? [closed]
I have a Django project in which I want to show a different page depending on the screen size the user has. If they are on a mobile device, I want them only to see a column of buttons with all the urls references on the whole screen ( Like a pile of buttons one on top of the other). When they are on a computer screen, I already have a predefiened template. Whats the best approach for this matter ? I searched for Django options and try with https://pypi.org/project/django-mobile-detect/ but I didnt manage to get it that way. Im new in front end and I dont want to mess my current progress. What method should I use ? pip install django-mobile-detect I try with this django mobile detect repo and try with mobil.detectMiddleware. -
Could You Please suggest me How to ignore HTTP_X_ORIGINAL_URLHeader in IIS Server for Django RestAPI
Whene we call api from Postman with X_ORIGINAL_URL in headers then we want to ignore HTTP_X_ORIGINAL_URL ADD Inbound rules Rule name: "set server variables" Requested URL: "Matches the Pattern" Using: "Regular Expressions" Pattern: "^([a-z]{2}-[a-z]{2})/(.*)" Conditions: Input: "{Languages:{R:1}}" Type: "Matches the Patterns" Pattern: "(.+)" Action: Type: "Rewrite" Rewrite URL: "{R:2}" -
How to display AWS S3 Bucket media objects in Angular using Django API
I am using a Django (PostgreSQL) Backend for my application. On my frontend, I am using Angular. I have an API view that is used to retrieve Post model instances where each instance has a "media" field containing an image object stored in an Amazon S3 Bucket. On my Angular frontend, I am trying to display the S3 Bucket media image using the src attribute and setting it to the URL of the image in the bucket, however, I am getting a 403 forbidden error. Below are my configurations. What am I missing that is causing the 403 Forbidden error? I have the following setting configurations in my Djnaog settings.py: AWS_ACCESS_KEY_ID = config('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = config('AWS_SECRET_ACCESS_KEY') AWS_REGION_NAME = config('AWS_REGION_NAME') # Set the S3 bucket name you created earlier AWS_STORAGE_BUCKET_NAME = config('AWS_STORAGE_BUCKET_NAME') # Set the S3 URL format AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com' # Set the S3 file URL access AWS_DEFAULT_ACL = None # Set the S3 storage class AWS_S3_OBJECT_PARAMETERS = {'StorageClass': 'STANDARD_IA'} # Set the static and media file configurations STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' # To serve media files directly from S3 MEDIA_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/media/' On my frontend, I have the following Angular ng service: getUserFeed(token: string): Observable<any> { const … -
Django Upload Mutliple Files in another viewset
I have two models Post and PostAttachments. I want to modify the create method for Post Viewset to allow upload of multiple files. models.py class Post(BaseModel): title = models.CharField(max_length=255) description = models.TextField(blank=True, null=True) user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) class PostAttachment(BaseModel): attachment = models.FileField(upload_to=post_attachment_upload_to, validators=[ FileExtensionValidator(allowed_extensions=['mkv', 'mp4', 'png', 'jpg']) ]) post = models.ForeignKey(Post, on_delete=models.CASCADE) def __str__(self): return self.attachment.name serializer.py class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = '__all__' class PostAttachmentSerializer(serializers.ModelSerializer): class Meta: model = PostAttachment fields = '__all__' views.py class PostViewSet(viewsets.ModelViewSet): parser_classes = (MultiPartParser, FormParser) queryset = Post.objects.all() serializer_class = PostSerializer @transaction.atomic def create(self, serializer): """ Create a new post and its attachments. """ post = super().create(serializer) # Get the attachments data from the serializer. attachments_data = serializer.data['attachments'] # Validate the attachments using the PostAttachment serializer with many=True. PostAttachmentSerializer(data=attachments_data, many=True).is_valid(raise_errors=True) # Attach the post to all attachment objects using the created post's ID. for attachment_data in attachments_data: attachment_data['post'] = post.id PostAttachment.objects.create(**attachment_data) I am trying to upload file by creating PostAttachment Object within the create method of posts and then link them with the post. For reference this is my postman Postman Request -
Django Update Both Custom User and UserProfile Models
I'm working on a Django project, and I'm encountering some issues with my test cases. Specifically, I'm having problems with two test cases related to user profile updates and user creation. Could someone please help me identify what might be causing these test failures and how to fix them? Any insights or guidance would be greatly appreciated. Here's the error message I'm getting: ====================================================================== FAIL: test_update_user_profile (user.tests.test_user_api.PrivateUserApiTests) Test updating the user profile for the authenticated user. ---------------------------------------------------------------------- Traceback (most recent call last): File "/app/user/tests/test_user_api.py", line 301, in test_update_user_profile self.assertEqual(self.profile.bio, payload['profile']['bio']) AssertionError: 'Profile bio.' != 'Updated bio.' - Profile bio. + Updated bio. ====================================================================== FAIL: test_create_user_success (user.tests.test_user_api.PublicUserApiTests) Test creating a user is successfull. ---------------------------------------------------------------------- Traceback (most recent call last): File "/app/user/tests/test_user_api.py", line 95, in test_create_user_success self.assertEqual(res.status_code, status.HTTP_201_CREATED) AssertionError: 400 != 201 ---------------------------------------------------------------------- test_user_api.py CREATE_USER_URL = reverse('user:create') ME_URL = reverse('user:me') def create_user(**params): return get_user_model().objects.create_user(**params) def create_profile(user, **params): defaults = { 'picture': None, 'bio': 'My bio.', 'dob': '2000-12-12', 'pronouns': 'She/Her', 'gender': 'Female', } defaults.update(params) profile = UserProfile.objects.create(user=user, **defaults) return profile class PublicUserApiTests(TestCase): def setUp(self): self.client = APIClient() def test_create_user_success(self): payload = { 'name': 'Test Name', 'email': 'test@example.com', 'password': 'testpass123', 'profile': { 'picture': None, 'bio': 'Create bio.', 'dob': '2000-01-01', 'gender': 'Male', } } res … -
Can't change the src of un image in javascript in django
So I have a javascript file that I try change the src of a image with in django. However, it keeps adding a subdirectory called the directory my image is in (the directory being in the static folder). It looks like this: Root/ Project/ Templates/ games/ game-one.html static/ pre-dev/ behav.js seven.png in my javascript file because i cant use django tags I wrote it like this: document.getElementById('img_eight').src = "static/pre-dev/seven.png" and the image adress then looks like this: https://website.com/pre-dev/static/pre-dev/seven.png I would like to keep it as a js file, and I want to keep my images where they are I have tried moving my behav.js a directory down. but it gives me the same output. no matter what I change the src in my javascript file to I always get /pre-dev/. Any help would be great. -
google cloud kubernetes ingress not redirecting to https
i deployed a django application in google cloud kubernetes, its all working i can access my site from https and use it. but when i type in the url the domain it opens with http, if i write https i can access too, i searched a lot and tried a lot of stuff in the internet still no success. there is a annotation kubernetes.io/ingress.allowHTTP: "false" # <-- this one this works disableing the http access, but i want to redirect to https not blocking, if i write in the browser url my domain it goes to http first. its all working the ssl and nginx ingress, i just can't redirect the access from http to https. here is my nginx ingress apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: django-ingress annotations: nginx.ingress.kubernetes.io/rewrite-target: / kubernetes.io/ingress.global-static-ip-name: django-ip spec.ingressClassName: "nginx" nginx.ingress.kubernetes.io/force-ssl-redirect: "true" # <--- this one is not working nginx.ingress.kubernetes.io/backend-protocol: "HTTPS" nginx.ingress.kubernetes.io/use-forwarded-headers: "true" spec: tls: - hosts: - example-django.com secretName: django-certs defaultBackend: service: name: django-svc port: name: django-core-http rules: - host: example-django.com http: paths: - path: / pathType: Prefix backend: service: name: django-svc port: name: django-core-http tried annotations kubernetes.io/ingress.allowHTTP: "false" nginx.ingress.kubernetes.io/force-ssl-redirect: "true" nginx.ingress.kubernetes.io/ssl-redirect: "true" -
Django: create an object with m2m fields using class based views
I'm completely stuck, I want to know the right way to save an object that has m2m fields. It works with the admin site (not quite right: a field that should be chosen randomly is chosen through a multiplechoicefield but at least the instance is created ) but not the CreateView (nothing happens no object is created) models.py class Foo(models.Model): #this field is chosen with CheckboxSelectMultiple bar = models.ManyToManyField(Bar) #this field is supposed to be calculated according to the previous choices baz = models.ManyToManyField(Baz) I tried overriding save method but it did not work . forms.py class FooForm(forms.ModelForm): bar = forms.ModelChoiceField(Bar.objects.all()) def save(self, *args, **kwargs): adding = self.instance._state.adding instance = super().save(*args, **kwargs) super().save(*args, **kwargs) if adding: instance.baz.add( *Baz.objects.filter(bar=instance.bar) .values_list('id', flat=True) .order_by('?') ) return instance I also tried (commit = False ) and save_m2m(). -
Django query: transform two for loops into a queryset
I have 3 simple models: from django_better_admin_arrayfield.models.fields import ArrayField class BuildItem(models.Model): base = models.ForeignKey(Item, on_delete=models.CASCADE) level = models.IntegerField(default=1) mandatory_skills = ArrayField(models.IntegerField(null=True, blank=True), default=list) class Item(BaseModel): name = models.CharField(max_length=100) class Skill(BaseModel): item = models.ForeignKey(Item, on_delete=models.CASCADE, blank=True, null=True, related_name="skills") effect = models.IntegerField(null=True, blank=True) value = models.IntegerField(null=True, blank=True) I would like to retrieve the sum of the value fields of the skills multiply by the level field of builditem, where the pk fields of the skills are in the mandatory_field list, if the effect field of skill is equal to 1. I wrote some code that works with for loop: array_life = [] for builditem in BuildItem.objects.all(): for skill in builditem.base.skills.all(): if skill.pk in builditem.mandatory_skills: if skill.effect == 1 and skill.value < 2: array_life.append(skill.value * builditem.level) sum_life = sum(array_life) I would like to transform this code into a queryset. (I tried many things but without success) Can anyone help me ? -
Using Celery tasks in Django to update aggregated data
In my Django project, I have a use case where I have some complex Python functions which are computationally expensive: they involve numerous calculations based on a recurrence relation. They are already well optimized but still take a few seconds to run in some cases. In this context, I'm thinking about using Celery tasks to carry out the calculations and to update aggregated data in dedicated tables of my PostgreSQL database. However, I have a feeling it's not going to be easy to ensure the integrity of the data and to avoid unnecessary calculations. Race conditions and unreliable error handling / retry mechanisms are some of the pitfalls I have in mind. What are the best practices in this case? What do I need to pay particular attention to? Are you aware of open source Django projects doing something similar? I'm using Django 4.2, PostgreSQL 15, Redis 7.2 (as a cache), Celery 5.3, RabbitMQ 3.12 (as a broker). -
Running ChannelsLiveServerTestCase does not create database for browser
I tried using pytest to test my frontend Django code with Selenium. In order to do that, a server has to be mocked which is when I stumbled upon this StackOverflow question, asking for the ChannelsLiveServerTestCase equivalent for pytest. Since the code didn't work when browsing to the server, showing the yellow Django error page (connection to server at "127.0.0.1", port 5432 failed: FATAL: database "test" does not exist), I tried isolating the issue by removing complexity and using unittest's ChannelsLiveServerTestCase instead, following channels official tutorial. It however yielded the same results. It seems like the database is not being created properly for the frontend. What's weird is, that within the function, database calls can be made normally and the test database exists (checked with pdb). But as soon as the web server is browsed to using Selenium, the yellow error page shows up again – almost as if the asgi server is running in a completely different thread, unable to access the database? I trimmed down the issue to the minimum and created a small repository for easily reproducing the issue: https://github.com/alfonsrv/django-asgitest Any idea where I'm going wrong? Thanks -
Django widget won't change input to date
It should be so simple. I'm following all the rules and all the answers from previous questions but it still won't happen. I have a Bottle model, that has it's own inline formset form to it's parent Wine. The date on which I bought the bottle, should show up as a standard date picker. I cannot for the life of my figure out where it goes wrong. The input type should change from "text" to "date", but it won't. I'm using crispy forms and bootstrap 5, but disabling those also does nothing. My models (only relevant models shown): from django.db import models from django.conf import settings from django.utils import timezone from django.contrib import admin from django.forms import ModelForm class Wine(models.Model): producer = models.ForeignKey(Producer, null=True, blank=True, on_delete=models.CASCADE, default=0) name = models.CharField(max_length=200) year = models.IntegerField(blank=True, null=True) alcohol = models.FloatField(blank=True, null=True) grape = models.ManyToManyField(Grape) colour = models.ForeignKey(Colour, null=True, blank=True, on_delete=models.CASCADE, default=0) wine_type = models.ForeignKey(WineType, null=True, blank=True, on_delete=models.CASCADE, default=0) notes = models.TextField(max_length=2000, blank=True, null=True) wishlist = models.BooleanField(default=False) def __str__(self): return self.name def get_bottles(self): a = [] for bottle in self.Bottle.all(): a.append((bottle.date_bought)) return a def available_bottle(self): number = self.Bottle.filter(available=True).count() return number class Bottle(models.Model): wine = models.ForeignKey(Wine, related_name='Bottle', on_delete=models.CASCADE) date_bought = models.DateField(null=True) bottleprice = models.CharField(max_length=200, blank=True,) …