Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Missing DataDog metrics when using ThreadStats for a Celery task in Django
The problem I have a scheduled Celery task that queries x number of rows, does some processing and upon success (or error) it increments a specific metric using ThreadStats. For each execution of this task, the metric should be incremented by x at a specific time. The problem is that some of these increments are not posted to DataDog. Ex. if the total number of rows is 100 and the task processes x=10 at a time, some of those task executions fails to increment the metric and it ends up displaying only 60. Attempts for resolution This is what I tried to do without success: Manually flushing the metrics in the task by setting flush_in_thread=False and calling the flush() method. Using dogstatsd-collector library to delay the submission -
Permission denied: '/app/manage.py' Docker
I'm having a permissions issue when trying to run my docker-compose command docker-compose run app sh -c "django-admin.py startproject app ." ERROR: PermissionError: [Errno 13] Permission denied: '/app/manage.py' I've done some research and found a similar issue here: docker-compose , PermissionError: [Errno 13] Permission denied: '/manage.py' However I think I'm doing something wrong when trying to change permissions in my Dockerfile Dockerfile: FROM python:3.8-alpine MAINTAINER Nick ENV PYTHONUNBUFFERED 1 COPY ./requirements.txt /requirements.txt RUN pip install -r /requirements.txt RUN mkdir /app WORKDIR /app COPY ./app /app RUN adduser -D user RUN chown user:user -R /app/ RUN chmod +x /app USER user I add RUN chown user:user -R /app/ and RUN chmod +x /app running docker build . works succesfully however I still keep getting permissions issue docker-compose.yml version: "3" services: app: build: context: . ports: - "8000:8000" volumes: - ./app /app command: > sh -c "python manage.py runserver 0.0.0.0:8000" -
django-admin command can't be run because files are not in the right place
So I thought I installed anaconda and Django correctly but I guess I didn't because my django-admin commands don't work. As you can see here, I have the file paths for a couple Django files all screwed up: /Users/user/anaconda3/bin/django-admin /Users/user/anaconda3/bin/django-admin.py /Users/user/anaconda3/lib/python3.8/site-packages/Django-3.1.5.dist-info/* /Users/user/anaconda3/lib/python3.8/site-packages/django/* This makes it so I can't run any django-admin commands that I need to run to start a new project in PyCharm. -
Geodjango + PostGIS. Aggregate polygon area in square meters
I am using geodjango(3.1) + postgis and I want to receive the area of a polygon in square meteres. Therefore, I am using the Geographic Database Functions of Django. My code looks the following: City.objects.annotate(area=Area('geom')) I think the result I am reciving is in degree. When I use the distance function the same way, I get the right result in square meters. When I am executing ST_Area(geom, use_spheroid=true) as RawSQL, the result also fits and is in square meteres but I would like the avoid RawSQL. Thanks for any help =) -
Python Django Regex: multiple optional arguments
I use Django DRF @action decorator to create a search API view. I would like to match all these url and capture parameters: # 'my_search' captured in search_terms var http://127.0.0.1:8000/api/medias/search/my_search/ # 'my_search' captured in search_terms var, and '1' captured in tags_id var http://127.0.0.1:8000/api/medias/search/my_search/tags/1/ # 'my_search' captured in search_terms var, and '1/2/' captured in tags_id var (or a list like [1,2]) http://127.0.0.1:8000/api/medias/search/my_search/tags/1/2/ I actually have this code/regex, but that match only url with tags. @action(detail=False, methods=['get'], url_path=r'search/(?P<search_terms>[^/]+)/tags/(?P<tags_id>[\d/]+)', url_name='search') def search(self, request, search_terms, tags_id): ... If someone have an idea it will be great. -
How to use Bootstrap-Tooltips for each list item in Django_filters queryset result
I have a template matches.html that displays the Django_filters queryset result from dropdown choices. I cannot seem to figure out how to make Bootstrap-Tooltip work in this instance, and I have not found many examples or documentation to help. matches.html displays Django_filters Queryset results from startSearch template: <div class="row"> {% for animal in filter.qs %} #Queryset <div class="col-md-6 col-lg-4"> <div class="card rounded-0 card-hover-overlay"> <div class="position-relative" style="background-image:url('{{ animal.profilePic.url }}')"> <img class="card-img rounded-0" src="{{ animal.profilePic.url }}" alt=""> </div> <div class="card-img-overlay"> <h3><a href="{% url 'animals:animalDetail_view' animal.id %}">{{ animal.name }}</a></h3> <p class="text-white">{{ animal.tagLine }}</p> </div> <div class="card-footer bg-transparent"> <ul class="list-unstyled d-flex mb-0 py-2"> #for each list item, use Bootstrap-Tooltip <li><button class="btn-like px-2" data-toggle="tooltip" data-placement="top" title data-original-title="Favorite this listing"> <i class="fas fa-heart text-primary" aria-hidden="true"></i> <span>{{animal.favs}}</span> </button> </li> <li class="ml-auto"> <a class="px-2" href="{% url 'animals:animalDetail_view' animal.id %}">More Details</a> </li> </ul> </div> </div> </div> {% endfor %} <script> $(document).ready(function(){ $('[data-toggle="tooltip"]').tooltip(); }) </script> -
What does AWS_S3_MAX_MEMORY_SIZE do in django-storages
According to the documentation AWS_S3_MAX_MEMORY_SIZE(optional; default is 0 do not roll over) The maximum amount of memory (in bytes) a file can take up before being rolled over into a temporary file on disk. Can someone explain this a bit more? Is this a way I could throttle upload sizes? What does "being rolled over" refer to? Thank you -
Cannot run django-admin commands because files are located in anaconda3 folder?
So I thought I installed anaconda and Django correctly but I guess I didn't because my django-admin commands don't work. As you can see here, I have the file paths for a couple Django files all screwed up: /Users/user/anaconda3/bin/django-admin /Users/user/anaconda3/bin/django-admin.py /Users/user/anaconda3/lib/python3.8/site-packages/Django-3.1.5.dist-info/* /Users/user/anaconda3/lib/python3.8/site-packages/django/* This makes it so I can't run any django-admin commands that I need to run to start a new project in PyCharm. I'm a total noob so I'm sorry if this is a simple question. Thank you! -
Django REST framework: SearchFilter doesn't work with 2 and more values in search bar if they are from the same field
I use SearchFilter to search for therapists: class TherapistSearchListAPIView(generics.ListAPIView): permission_classes = [IsAuthenticated] search_fields = ['first_name', 'therapist_profile__skills__title', 'therapist_profile__counselling_areas__title'] filter_backends = [filters.SearchFilter] queryset = Therapist.objects.all() serializer_class = TherapistSearchSerializer Generally It works great, but there is a problem: When several values are entered in search bar, if among these values 2 or more values are from the same field, even though the request matches with any of therapists, the search returns NULL. Example: Therapist: [ { "first_name": "Thomas", "skills": [ { "id": "0658374347844fd7b69b3d033e17f9b1", "title": "Self-reflection" }, { "id": "2c6ab46d4ebb4cb1a46c934f0c30ebbe", "title": "Patience" }, { "id": "f22c8210dd4d4a3299ea8887c1da7c30", "title": "Flexibility" } ], "counselling_areas": [ { "id": "5fb0c57ced4c41129829b3620076dda4", "title": "Body dysmorphic disorder" } ] ] If I write in search bar "Thomas self-reflection patience", it will return me NULL even though everything matches with the therapist in database. How can I fix this? Is there any solution or I need to write my own search filtering function from the scratch? -
django not displaying error_messages in forms
i am new to django and i have this form i am working on i have tried everything possible i cant seem to display the form error messages. i have tried using a def clean method nothing happens when i try to submit an empty form..i have tired switing to using FormView i have also tried using function view i have tried using a for loop and adding {{ form.non_field_errors }} in my template nothing pops up. my app/forms.py from django import forms class ContactForm(forms.Form): name = forms.CharField( label='Your Name', min_length=2, max_length=25, required=True, error_messages ={'required':'Please tell Oluwafemi your name'}) email = forms.EmailField(label='Your Email', required=True, error_messages={'invalid':'Please fill in a valid email'}) subject = forms.CharField(label='Subject', min_length=4, max_length=100, required=True) message = forms.CharField(widget=forms.Textarea(attrs={'placeholder':'Write Oluwafemi a Message'}), error_messages ={'required':'Please write something for Oluwafemi'}) my app/views.py from django.views.generic import TemplateView from django.shortcuts import render from django.core.mail import send_mail from .forms import ContactForm from django.http import HttpResponseRedirect # Create your views here. class ProfilePageView(TemplateView): template_name = 'femi_profile.html' form_class = ContactForm success_url = 'femiir' def get(self, request, *args, **kwargs): form = self.form_class() return render(request, self.template_name, {'form': form}) def post(self, request, *args, **kwargs): form = self.form_class(request.POST) if form.is_valid(): name = form.cleaned_data['name'] email = form.cleaned_data['email'] subject = form.cleaned_data['subject'] message = … -
Mock a method that raise an exception a number of times
I have looked for how to do this all day, without luck. I'm using Django 1.11 and Python 2.7 (no possibility to upgrade). I have a method that calls an external API. This API sometimes fails with 504 or 502 errors. So, we decide to, in that case, retrieve the call some times (3 times for now). So, I wrote something like this. def call_external_api(arg_1, arg_2): attempts = 3 data = None ext_api = ExternalAPI() # wrapper class, its method call the external api while attempts > 0: try: data = ext_api.get_data_details(arg_1=arg_1, arg_2=arg_2) except Exception as exception: attempts -= 1 log_message(exception) raise ExternalAPIError('Error calling EXT-API: %s' % str(exception)) return data So, I want to test this, but I do not know how to mock the exception. I know that it is possible to use @patch(SomeClass, 'method_name') to simulate the call to another class, but how to simulate the exception, so the code enters on the except branch and reduces "attempt," repeating the cycle? Notes: I thought that if I can mock the exception, I could test that log_message was called 3 times. What do you think about this approach? -
How do I use filter search table in my Django project
How do I go about assertationError when using django-filter in my Django project assertationError:setting 'Meta.model' without either 'Meta.fields' or 'Meta.exclude' has been deprecated. -
How to save Audio file to django model from the server itself with REST API
I am: Sending .wav file with API Class Converting to .mp3 with pydub Saving converted file to MEDIA_ROOT I want: Save the converted file (.mp3) to my model. I have: AWS S3 bucket on production, everything saved in my models lands there. I have model with FileField: def content_file_name(instance, filename): filename = "{}_".format(today.strftime("%y-%d-%m")) + filename return os.path.join('content', "{}".format(instance.user.email), 'tracks', filename) class Track(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True ) # ... file = models.FileField( upload_to=content_file_name, null=True, blank=True) I am using MultiPartParser and audio gets saved correctly but the original one in .wav. I want to save mp3 once I convert it. from django.core.files.storage import FileSystemStorage class TrackAPIView(UpdateAPIView): serializer_class = FileSerializer permission_classes = (permissions.IsAuthenticated,) parser_classes = [MultiPartParser, ] queryset = Track.objects.all() lookup_field = 'uid' def put(self, request, *args, **kwargs): file_obj = request.data # Using File storage to save file for future converting fs = FileSystemStorage() file_name = fs.save(audio_file.name, audio_file) audio_file_url = fs.url(file_name) # Preparing paths for convertion upstream = os.path.dirname(os.path.dirname(os.path.dirname( os.path.abspath(__file__)))) path = os.path.join(upstream, 'media', audio_file.name) mp3_filename = '.'.join([audio_file.name.split('.')[0], 'mp3']) new_path = os.path.join( upstream, 'media', mp3_filename) # Converting to mp3 here wma_version = AudioSegment.from_file(path, "wav") wma_version.export(new_path, format="mp3") user_id = self.request.user.id # I was trying to create a Track instance, the mp3 … -
Django: store a json string as data attribute in Django template
In Django i am passing a json string to template and want to store it as a data attribute in an html tag and later use that json string in Jquery Like def sampleView(request) data = {"param1": 1, "param2": "testing"} json_string = json.dumps(data,indent=4,default=str) return render(request, 'my_home.html', dict(data=json_string)) Now i want to store it as a data attribute in html my_home.html .... <div id="test" data-sample={{ json_string }}>.... .... and in jquery i want to convert back to json. How can i do it -
Dajngo Session Data Not Being Stored
I am trying to store some session data using Django and Angular2. I noticed something strange, or do not understand. I was stuck on this for a while on my project. Instead, I tried to test a simple example to understand what's happening. Finally, I was able to store the session data when I made the requests using POSTMAN, and the sessionId was recognized. However when I made the request through my Angular app, the session data saving was successful but it was unable to access the saved session data on the next request. I also noticed that when done with Angular, a new session is created on every request. So it's not recognizing the session and creating a new session each time. Any ideas on what might be causing this? Thank you for your help. Django Views class TestSaveSessionView(APIView): authentication_classes = (TokenAuthentication,) def post(self, request): # set new data request.session['user_id'] = 20 request.session['team'] = 'Barcelona' return Response("Session Data Saved") class TestAccessSessionView(APIView): authentication_classes = (TokenAuthentication,) def post(self, request): response = "" print("USER ID", request.session.get('user_id')) if request.session.get('user_id'): user_id = request.session.get('user_id') response += "User Id : {0} <br>".format(user_id) if request.session.get('team'): team = request.session.get('team') response += "Team : {0} <br>".format(team) if not response: … -
Django Rest Framework and Heroku - Error 401
I just deployed my website on Heroku, an integral part of the functionality of the site is to receive post requests from another website of mine. I'm using DRF's TokenAuthentication for my authentication. In my local environment everything works perfectly, but the same cannot be said for the live website. Whenever I send a POST request I receive a 401 error, the new token is added to the request's header and the data is exactly the same as the data used in the local environment. Any help would be gladly appreciated. views.py class PetCreateView(CreateAPIView): serializer_class = PetSerializer permission_classes = [IsAuthenticated, ] def perform_create(self, serializer): if Breed.objects.filter(user_id=self.request.POST.get('breed_name', None)).exists(): pass else: Breed.objects.create( breed_name=self.request.POST.get('breed_name', None), size=self.request.POST.get('size', None), temperament=self.request.POST.get('temperament', None), energy=self.request.POST.get('energy', None), hypoallergenic=self.request.POST.get('hypoallergenic', None)) breed = Breed.objects.get(breed_name=self.request.POST.get('breed_name', None)) # Assigns a groomer the created Pet groomer = assign_groomer(breed) serializer.save(groomer=groomer, breed=breed) SpaReport.objects.create(breed=breed, groomer=groomer) settings.py ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'bootstrap3', 'captcha', 'django_celery_beat', 'django_celery_results', 'mathfilters', 'storages', 'account', 'sales', 'scrty', 'analytics' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', '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', ] ROOT_URLCONF = 'pettracker.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_DIR, ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', … -
Django custom manager breaks create method
I implemented a custom Manager which overrides get_queryset and returns custom QuerySet. Like: class CustomQuerySet(models.Queryset): def custom_method(self): return self.filter(foo='bar') class CustomManager(models.Manager): def get_queryset(self): return CustomQuerySet(self.model, using=self._db) and I'm using it as: objects = CustomManager() but running tests in which I'm using factories, it doesn't set value for created = (DateTimeField with auto_now_add=True) field during .create() method. Anyone encountered a similar problem? -
How to insert NULL value in existing object's field using Django
I am trying to insert the null value in some fields of a predefined object. my models.py: class myCustomeUser(AbstractUser): username = models.CharField(max_length=20, unique="True", blank=False) password = models.CharField(max_length=20, blank=False) is_Employee = models.BooleanField(default=False) is_Industry = models.BooleanField(default=False) def __str__(self): return self.username class Industry(models.Model): user = models.OneToOneField(myCustomeUser, on_delete=models.CASCADE, primary_key=True, related_name='industry_releted_user') name = models.CharField(max_length=200, blank=True) owner = models.CharField(max_length=200, blank=True) license = models.IntegerField(null=True, unique=True) industry_extrafield = models.TextField(blank=True) def __str__(self): return self.name class Employee(models.Model): user = models.ForeignKey(myCustomeUser, null=True, blank=True, on_delete=models.CASCADE) industry = models.ForeignKey(Industry, null=True, blank=True, on_delete=models.CASCADE) i_id = models.IntegerField(unique=True) name = models.CharField(max_length=200, blank=False, null=True) gmail = models.EmailField(null=True, blank=False, unique=True) rank = models.CharField(max_length=20, blank=False, null=True) employee_varified = models.BooleanField(default=False, blank=True, null=True) def __str__(self): return self.name I have already created an Employee object. Now I am trying to delete some of that existing Employee object's field in views.py by the following code: Identified_employee = Employee.objects.get(i_id=pk) if request.method == 'POST': Identified_employee.industry = NULL Identified_employee.i_id = NULL Identified_employee.rank = NULL Identified_employee.save() But it says error in terminal like: Traceback (most recent call last): File "G:\Python\lib\site-packages\djongo\cursor.py", line 51, in execute self.result = Query( File "G:\Python\lib\site-packages\djongo\sql2mongo\query.py", line 783, in __init__ self._query = self.parse() File "G:\Python\lib\site-packages\djongo\sql2mongo\query.py", line 868, in parse raise exe from e djongo.exceptions.SQLDecodeError: Keyword: None Sub SQL: None FAILED SQL: INSERT INTO "app_prevjob" … -
Adding Swagger Docs to Django Without Django REST FRAMEWORK
I am working on a Django project and there's requirement to build the APIs without using the Django rest-framework library. I'm having a hard time figuring out a work around as more available libraries are already tied to the Django rest-framework pip library. Can someone point me to an example, library or resource for self documented APIs using swagger docs that supports at least Python 3.7 -
Supporting search queries in Django Rest Framework
Im currently trying to allow users to search my database from the client side and return the response to them. I'm a little confused on where in the view I need to support the search query, or if the way I'm going about it is even correct. I've done some research already and found out about the SearchFilter from DRF but unsure how to incorporate it into my code. Here is my views for the resource i'm trying to search: class Recipes(ViewSet): def list(self, request): recipes = Recipe.objects.all() user = self.request.query_params.get('user', None) if user is not None: recipes = recipes.filter(author = user) serializer = RecipeSerializer(recipes, many=True, context={'request': request}) return Response(serializer.data) def retrieve(self, request, pk=None): try: recipe = Recipe.objects.get(pk=pk) serializer = RecipeSerializer(recipe, context={'request': request}) return Response(serializer.data) except Exception as ex: return HttpResponseServerError(ex) Based on my research I've found that I can use: serializer_class = RecipeSerializer queryset = Recipe.objects.all() filter_backends = (SearchFilter,) filter_fields = ('title', 'ingredients') in some way but i'm not exactly sure how. Any guidance is appreciated -
How to use on_delete CASCADE for some objects and ondelete DO_NOTHING for others in djando models
I have a Django model that refers to itself as below: parent = models.ForeignKey('self', ...) I need to act in some situations as on_delete=models.CASCADE and in other situations as on_delete=models.DO_NOTHING. How can I do that? -
how to use relationship in django
i have a Order and OrderProductDetail model class Order(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) is_paid = models.BooleanField(verbose_name='پرداخت شده / نشده') payment_date = models.DateTimeField(blank=True, null=True, verbose_name='تاریخ پرداخت') class OrderProductDetail(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE, verbose_name='سبد خرید') product = models.ForeignKey(Mahsoolat, on_delete=models.CASCADE, verbose_name='محصول') price = models.IntegerField(verbose_name='قیمت محصول') created_at = models.DateTimeField(verbose_name="تاریخ ثبت", default=datetime.datetime.now()) in views.py (orders have two items) orders = Order.objects.filter(owner_id=request.user.id, is_paid=True) at each item of orders contain several items now how can i retrieve all items of orders that exist in OrderProductDetail model -
How to return HTML in another page with AJAX?
So I created a form. In this form, I make GET requests to the server to search for particular users. The view responsible for using the query words returns a template as follows. html with the form <a href="{% url 'logout'}">Logout</a> <p>Welcome</p> <form id="search" method="GET" action="{% url 'results' %}" placeholder= "Choose a friend" autocomplete="off"> {{form}} <input type="submit" value="search" name="search"> </form> <a href="{% url 'liked' %}"> View Liked Songs</a> {% endblock %} `views to handle data passed into the form` def results(request): if request.method == "GET": search_query = request.GET.get("username") searched_user = UserProfile.objects.filter( user__username__contains=search_query ) return render( request, "searched_results.html", { "searched_user":searched_user }) else: return HttpResponse("Search returned nothing") This is where the issue is. Now I have two HTML files. One ought to display data returned in the results view but I want it displayed only wheni click a button in the other HTML file. This is what I mean; I have this HTML file which is rendered when the results/ route is used. {% extends "base.html" %} {% block spotify %} {%if searched_user %} {% for each_searched_user in searched_user %} <br/>{% for liked_songs in each_searched_user.liked_songs.all %}{{liked_songs}}<br/> {% endfor %} {% endfor %} {% endif %} {% endblock %} But I want the … -
UpdateView with form_class removes named submit input from POST
I want to get the input that was clicked by the user. The submit goes to an UpdateView with a ModelForm. I've added the name attribute to the submit inputs but when I do if 'approve' in self.request.POST: in get_context_data() it's False. I overridden def post() and it appears. Is there a way to do it without overriding def post()?. FYI, I've omitted some code that was just bloat and not relevant to the issue. Apologies if there's something in there that doesn't make sense. models.py class Definition(DefinitionInfo): SEV3 = 'info' SEV2 = 'warning' SEV1 = 'danger' sup_sevs = ( ('', 'Please select'), ('info', 'Sev3'), ('warning', 'Sev2'), ('danger', 'Sev1'), ) title = models.CharField(max_length=255) description = models.TextField(null=True, blank=True) resolution = models.TextField(null=True, blank=True) sup_sev = models.CharField(max_length=7, choices=sup_sevs, null=False, blank=False) forms.py class DefinitionForm(forms.ModelForm): class Meta: model = Definition fields = ['title', 'sup_sev', 'description', 'resolution'] widgets = { 'description': forms.HiddenInput(), 'resolution': forms.HiddenInput(), } views.py class DefinitionUpdate(LoginRequiredMixin, UpdateView): model = Definition context_object_name = 'definition' form_class = DefinitionForm template_name_suffix = '_form' success_url = reverse_lazy('definitions:index') def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) if self.request.method == 'POST': print(f'Post data: {self.request.POST}') else: context['approved'] = self.object.approved return context HTML <form id="defForm" class="container-sm w-50" enctype="multipart/form-data" method="post" action="."> {% csrf_token %} {{ form.delete … -
Django models file update for many to many query
All, Here is my dilemma. I've created the Django models.py file with 2 classes, CustTeamMembers and CustTeamName. There is a many to many relationship between the two called cust_members. What this means is a team member can be on many teams and many teams can have the same member. What I need to create is a way to choose one member for each team that is a team leader. That team member needs to come from the cust_members list. So far I have not had any luck. Any help would be appreciated. My models.py file: from django.db import models # This will hold the team members class CustTeamMembers(models.Model): member_first_name = models.CharField(max_length = 100) member_last_name = models.CharField(max_length = 100) member_email = models.EmailField(unique=True) member_phone = models.CharField(max_length = 25, blank=True) class Meta(object): ordering = ['member_last_name'] def __str__(self): return self.member_first_name + ' ' + self.member_last_name # This will hold the customer name class CustTeamName(models.Model): cust_name = models.CharField(max_length = 100) #cust_lead = models.ForeignKey(CustTeamMembers, on_delete=models.CASCADE, blank=True) cust_members = models.ManyToManyField(CustTeamMembers, blank=True) cust_meet = models.CharField(max_length = 40, blank=True) cust_status = models.TextField(blank=True) def __str__(self): return self.cust_name def get_members(self): return ", ".join([str(p) for p in self.cust_members.all()] ~Ed