Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django django-filter django-tables2 limit query results
I am trying to limit the number of rows displayed in a table filtered using django-filter and build by django-tables2. I did not find anything here or in the docs (I don't want to use pagination). I know I can slice the queryset but I also want to have the table sortable and can't figure out how to do both. This is my views.py: def filtered_table(request): f = itemFilter(request.GET, queryset=ItemModel.objects.all()) has_filter = any(field in request.GET for field in set(f.get_fields())) table = None if has_filter: if not request.GET.get('sort'): table = ItemTable(f.qs, order_by='-timestamp') else: table = ItemTable(f.qs, order_by=request.GET.get('sort')) return render(request, 'itemlist/filteredlist.html', { 'itemtable': table, 'filter': f, }) I tried to slice the queryset before passing it to the table: table = PassTable(f.qs.order_by('-timestamp')[:20]) table = PassTable(f.qs.order_by(request.GET.get('sort'))[:20]) Resulting in: AssertionError: Cannot reorder a query once a slice has been taken. Because django-tables2 calls .order_by() again. Is there a way to configure django-tables2 or manipulate the queryset to limit the displayed rows? -
How to get dynamic HTML form fields name and value in Django?
some times 10 fields and more how to receive with request.POST.get(" ") or any method in django ex spec data id name 1 width 2 color {% for spec in spec %} <div class="form-group"> <label>{{spec.name}}</label> <input type="text" name="{{spec.id}}" class="form-control"> </div> {% endfor %} -
Django not storing data exactly as entered in form
I'm Django 3.1.4 with Postgres 13 Model: class Programme(models.Model): client = models.CharField(max_length=50, editable=True, blank=False, null=False) name = models.CharField(max_length=50, editable=True, blank=False, null=False) View: class ProgrammeCreateForm(ModelForm): class Meta: model = Programme fields = ('client', 'name') If the form input for 'client' is "ABC COMPANY" or "ABC Company", this data is being stored in the database as "Abc Company". Why is this and what should I be doing to ensure that the data is stored exactly as entered? Thanks. -
Can't change my Django model with migrations
I tried to implement many solutions that I found here, but nothing helps, so I'm looking for an answer. In my Django project I have Model.py with the following model: class Boat(models.Model): boatId = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) manufacturer = models.ForeignKey(Manufacturer, related_name='boatModels', on_delete=models.CASCADE, default=None) modelName = models.CharField(max_length=256, default=None) loa = models.FloatField(default=None) draftMin = models.FloatField(default=None) draftMax = models.FloatField(default=None) displacement = models.IntegerField(default=None) makerURL = models.CharField(max_length=1000, default=None) videoURL = models.CharField(max_length=1000, default=None) tags = TaggableManager() Initially I got this error with the latest added field videoURL: OperationalError at /boats/ no such column: boat_app_boat.videoURL Now it is this one: OverflowError at /admin/boat_app/boat/edc81b63-d8a5-4ab2-887d-97703554dc4e/change/ Python int too large to convert to SQLite INTEGER I did mess up with deleting old migrations as some advised, but I think it only made things worse. What is the best way to eventually migrate 'by the book' or if it is impoossible to say, I'd accept advice on how to start from fresh as I only have several items in my database. -
Separate Django user model from Wagtail user model
Is there a way to separate the general Django auth user model and the Wagtail auth user model? I'm including a wagtail blog app in my already existing Django project but I've been asked to create a separate user model for the blog app and I haven't found a way to do it. -
Dajngo class based view testing with django-bootstrap-modal-forms
I'm trying to test a class based view in Django where I'm implementing django-bootstrap-modal-forms. This is my view: class new_address_contact(BSModalCreateView): template_name = 'registry/address_contact.html' form_class = address_contact_Modal_Form csAddr = None # Aggiungo al contesto le mie variabili per poter utilizzare un solo template def get_context_data(self, **kwargs): # Al contesto standard/ aggiungo il modello address context = super().get_context_data(**kwargs) idAddress = self.kwargs['idAddress'] self.csAddr = CS_Address.objects.get(pk=idAddress) context['csAddr'] = self.csAddr context['title'] = 'INSERISCI NUOVO CONTATTO' context['function'] = 'INSERISCI' return context def post(self, request, *args, **kwargs): # Devo intercettare la chiamata per aggiungere il modello CS_Adresss al nuovo CS_Contact form = super().get_form() if form.is_valid(): if not self.request.is_ajax(): idAddress = self.kwargs['idAddress'] self.csAddr = CS_Address.objects.get(pk=idAddress) newContact = form.save(commit=False) newContact.address = self.csAddr newContact.save() messages.success(request, "Operazione effetuata correttamente!") return HttpResponseRedirect(self.get_success_url()) else: return super().post(request, *args, **kwargs) else: return super().post(request, *args, **kwargs) def get_success_url(self): idAddress = self.kwargs['idAddress'] self.csAddr = CS_Address.objects.get(pk=idAddress) return self.csAddr.get_absolute_url() for the test I tried to follow the django documentation: class Address_Contact(RegistryTest): def test_post_new_address_contact(self): post_data = { 'idAddress': self.cs_address.id, 'contact_type': 'cell', 'contact_value': '3339941768', 'note': 'qualche nota', } #todo finire test NB questa è una class based pop up view url = reverse('registry:new_address_contact', args=[self.cs_address.pk]) request = RequestFactory().post(url, data=post_data) response = new_address_contact(request=request) # view.setup(request) # response = view.post() self.assertEqual(response.status_code, 302) I'm playing … -
How to authenticate in Django with Azure AD via django-microsoft-auth
I'm trying to set up a local Django app which uses Azure Active Directory for authentication. I went through this quick start using the django_microsoft_auth library for backend authentication. I registered a new app on Azure and set the URI to http://localhost:8000/microsoft/auth-callback/. This is the same port which is used for the other pages like the admin page. When I try to login via Azure AD, I get the following error message: AADSTS50011: The reply URL specified in the request does not match the reply URLs configured for the application Only few other threads with this problem exist and there hasn't been a real solution yet using this library. Does anyone know a solution to this problem? -
django.core.exceptions.ImproperlyConfigured error all of a sudden
Worth mentioning: Everything was working fine with my django project until today. I tried to run some test from another session of coding to see if everything was alright then I saw this. Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. I tried: export DJANGO_SETTINGS_MODULE=<name_of_my_app>.settings then another error was raised: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. I tried putting this in settings.py: import django django.setup() Then something about SECRET_KEY can not be empty appeared even tough I had SECRET_KEY = '<my_secret_key>' in settings.py Never encountered this problem before and I don't know how to solve it or why it happened all of a sudden. -
View Other Users Profile Page in Django
I am creating a django application and i'm stuck at a point where i need to display other user's information about a product they will place an order for when that product is clicked but so far it is just displaying my own information. -
Can SELECT FOR UPDATE cause deadlocks?
I am using Django 2.2.12 as an ORM for MySQL 8.0, one of the queries is a concurrent SELECT FOR UPDATE, inside a transaction, where two or more threads may be targeting the same rows. Is not select for update atomic? Two transactions are allowed to lock and select the rows at same time? I am getting deadlock errors at random times. -
Trying to use add_notification() method on UserProfile object, ValueError: cannot assign UserProfile - Notification.user must be a User instance
I'm trying to use the default user model in my django application. I created UserProfile objects to have custom/additional fields for users. I'm trying to assign Notification objects to each UserProfile and I have the following code block allUsers = User.objects.all() for each in allUsers: uprof = UserProfile.objects.get_or_create(user=each) for u in allUsers: if u.userprofile: notif1 = u.userprofile.add_notification(title="Welcome to our site " + u.email, body="Your first notification") # error notif2 = u.userprofile.add_notification(title="Sample Notification" + u.email, body="Empty template for " + u.email) # also same error I was running this in a django shell plus. The first for loop iterates through all users and gives them a UserProfile object. The second tries to assign a notification to that user with a userprofile method called add_notification(). This fails and generates the error ValueError: Cannot assign "<UserProfile: devtest4@gmail.com>": "Notification.user" must be a "User" instance. I kinda don't really know what this error message means. And even so, I thought this would be the correct way of assigning a UserProfile to every existing User and then adding a notification to each user's respective userprofile. Am I going about this wrong? user_profile/models.py class UserProfile(models.Model): phone_number = models.CharField(max_length=15, verbose_name='Phone Number') user = models.OneToOneField(User, on_delete = models.CASCADE) api_key … -
Django model force capitalizing db_column names
I'm creating a Django model that reads from an Oracle SQL database. From the table that the model reads from, some columns have mixed cases and spaces, i.e. "Region" and "Foo Bar". So SELECT "Region", "Foo Bar" FROM some_table is perfectly valid on the db side of things. The Django model reads those columns explicitly using the db_column field, class SomeModel(models.Model): region = models.CharField(max_length=100, db_column="Region") foo_bar = models.CharField(max_length=100, db_column="Foo Bar") When Django goes to the database, however, I get the error ORA-00904: invalid identifier: "some_table"."FOO BAR" from column name being capitalized somewhere along the process. Is there some way that I can force Django to preserve the mixed case from the Django perspective, without modifying the column names on the db side? I have tried: db_column="'Foo Bar'", '"Foo Bar"', "\"Foo Bar\"", none of these seem to make the string interpreted literally and upper-cased. Thanks! Hacky workarounds welcomed. -
DRF Function Based View custom schema decorator for query parameters in swagger ui
I'd break my brain and loose/waste to much time to manage using Schema Decorator in DRF. I follow https://www.django-rest-framework.org/topics/documenting-your-api/ and manage it but on sagger-ui and redoc-ui. But GET method query parameters or POST body json string payload aren't documented. So i'm trying to deal with AutoSchema, ManualSchema and Custom classes to generate api documentation. https://www.django-rest-framework.org/api-guide/views/#view-schema-decorator But i never manage anything good. and yes i looking through [django-rest-framework] tag on stackoverflow too and yes i open a discussion on DRF google community (but no answers yet). So what i tried. Try to deal: import coreapi import coreschema from rest_framework.schemas import AutoSchema, ManualSchema log_file_delete_schema = AutoSchema( manual_fields=[ coreapi.Field( "file_path", required=True, location="query", type="string", description="path of the log to be delete", ) ] ) But it returns "AutoShema as no get_operation" error Try next: import coreapi import coreschema from rest_framework.schemas import AutoSchema, ManualSchema class CustomLogFileDeleteSchema(AutoSchema): def __init__(self): super(CustomLogFileDeleteSchema, self).__init__ def get_manual_fields(self, path, method): extra_fields = [ coreapi.Field( "file_path", required=True, location="query", description="log file path", type="string", example="/path/to/file/logfile.log", ) ] manual_fields = super().get_manual_fields(path, method) return manual_fields + extra_fields It returns to me 'CustomLogFileDeleteSchema' object has no attribute 'instance_schemas' I tried to use Django Rest Swagger but it's unmaintened project now so ==> next I'm using function … -
How to display a Custom Error Page in Django
I have a list of tables in my application, if a user book an available table it books it correctly without error but if a user books an unavailable table it displays an error page saying "Tables matching query does not exist". I have been trying some ways to get a custom error page or perhaps some nicer interface instead of the page error. error log Environment: Request Method: POST Request URL: http://localhost:8000/reserve/1/ Django Version: 3.1.4 Python Version: 3.7.3 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'core', 'dashboard', 'widget_tweaks', 'phonenumber_field'] Installed 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'] Traceback (most recent call last): File "C:\Users\Habib\Documents\django\FIVERR\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Habib\Documents\django\FIVERR\venv\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Habib\Documents\django\FIVERR\adam_mailk\core\views.py", line 30, in ReserveTable table_exists = Tables.objects.get(table_no=request.POST['table'], bar=bar) File "C:\Users\Habib\Documents\django\FIVERR\venv\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\Habib\Documents\django\FIVERR\venv\lib\site-packages\django\db\models\query.py", line 431, in get self.model._meta.object_name Exception Type: DoesNotExist at /reserve/1/ Exception Value: Tables matching query does not exist. views.py def ReserveTable(request, pk): bar = Bar.objects.get(id=pk) tables = Tables.objects.filter(bar=bar, status="available") form = ReservationForm() if request.method == "POST": if request.POST['table']: request.POST = request.POST.copy() table_exists = Tables.objects.get(table_no=request.POST['table'], bar=bar) if table_exists.DoesNotExist: return redirect(reverse('error-page', kwargs={'message': "This object does … -
django file upload progress bar with XMLHttpRequest
i created a normal django model.ModelForm and it is worked perfectly until i tried to add Progress bar for files uploading, i have an issue. i recieve the form information(request.POST and request.FILES) twice! but it is save the data only once in database, so also it is work, but i know i have a mistake in my code and i want to understand my mistake. this is my function for displaying the progress bar: function UploadFilesWithProgress(form, url) { const progressbarWrap = document.querySelector('.progress-bar-wrap'), label = progressbarWrap.querySelector('h6'), percentage = progressbarWrap.querySelector('span'), progressbarFill = progressbarWrap.querySelector('.progress > .progress-bar') let xhr = new XMLHttpRequest() xhr.open('POST', url, true); xhr.upload.onloadstart = function (e) { progressbarWrap.classList.remove('d-none') percentage.textContent = '0%' label.textContent = 'uploading...' }; xhr.upload.onprogress = function (e) { const percent = e.lengthComputable ? (e.loaded / e.total) * 100 : 0; progressbarFill.style.width = percent.toFixed(2) + '%'; progressbarFill.setAttribute('aria-valuenow', percent.toFixed(2)) percentage.textContent = percent.toFixed(2) + '%'; } xhr.upload.onloadend = function (e) { label.textContent = 'uplaod completed!' percentage.textContent = 'completed!' } xhr.send(new FormData(form)); } Form = document.getElementById('add-course-form') if (Form) { Form.onsubmit = function () { UploadFilesWithProgress(Form, Form.action); } } and this is my view: # I use CBV, so i share just the post method to not get missy. def post(self, *args, **kwargs): form … -
Tweet not creating in django twitter clone
I am just trying to build a simple twitter clone using django. To create a new tweet, a user has to choose an image and type some text. So i do just that, and when I click on the create tweet button, I get a form error that says "The image field is required". I don't understand why this happens. Here is a screenshot of that error: I don't even get ant error message. Here is my CreateTweet view function: class CreateTweetView(LoginRequiredMixin,CreateView): model = Tweet fields = ('image','tweet') template_name = 'twitter/create_tweet.html' def form_valid(self): new_tweet = form.save(commit=False) new_tweet.author = self.request.user new_tweet.save() return redirect('home') What is the problem here? EDIT: I have chosen an image, and upon form submission, I get this error In the media folder, I don't see the uploaded image -
How to pass data from ajax to django view?
I have the following script for ajax. this gets the public key and sends all other detail to Stripe server for payment but I need to send the dynamic value of price to item_line. fetch("/config/") .then((result) => { return result.json();}) .then((data) => { // Initialize Stripe.js var data1 = $('#priceId').html(); const stripe = Stripe(data.publicKey); // Event handler let submitBtn = document.querySelector("#submitBtn"); if (submitBtn !== null) { submitBtn.addEventListener("click", () => { var d = $('#priceId').html(); console.log(d) // this value need to send to my view... fetch("/create-checkout-session/") .then((result) => { return result.json(); }) .then((data) => { // Redirect to Stripe Checkout return stripe.redirectToCheckout({sessionId: data.sessionId}) }) .then((res) => { console.log(res); }); }); } }); how can I pass and how can I catch in a view file? my current view is: @csrf_exempt def create_checkout_session(request): if request.method == 'GET': domain_url = 'http://localhost:8000/' stripe.api_key = settings.STRIPE_SECRET_KEY try: checkout_session = stripe.checkout.Session.create( client_reference_id=request.user.id if request.user.is_authenticated else None, success_url=domain_url + 'success?session_id={CHECKOUT_SESSION_ID}', cancel_url=domain_url + 'cancel/', payment_method_types=['card'], mode='subscription', line_items=[ { 'price': settings.STRIPE_PRICE_ID, # here need dynamic selected value 'quantity': 1, } ] ) return JsonResponse({'sessionId': checkout_session['id']}) except Exception as e: return JsonResponse({'error': str(e)}) please help me. -
GeoDjango Get all records of a model that are within a given distance to any of the points of a given set of locations
I am trying to get the list of person(s) that are within a distance of 500m to a poi. I can achieve this goal in PostGIS as: SELECT DISTINCT public.dbconn_person.id, public.dbconn_person.name, public.dbconn_person.location, public.dbconn_poi.id, public.dbconn_poi.name, public.dbconn_poi.location FROM public.dbconn_person INNER JOIN public.dbconn_poi on st_dwithin(public.dbconn_person.location::geography, public.dbconn_poi.location::geography, 500); The point is that I am trying to use the same query in Django and I am facing some problems. models.py class Person(models.Model): name = models.CharField(max_length = 120) location = models.PointField() class Poi(models.Model): name = models.CharField(max_length = 120) location = models.PointField() view.py listpoi = Poi.objects.all() listperson = Person.objects.all() I expected that something like this would work, poi_filter = Person.objects.filter(location__dwithin=(Poi.objects.only('location'), 500)) As far as I have read, it seems that the location_dwithin function only accepts single points. Is this correct? Is there any way I can achieve my SQL result using Django? -
Debugger on Pycharm Macbook [closed]
Hello Fellow Developers. I am a junior in Django and Python. I wanted to set up the debugger in Pycharm but was not successful, As you know before running the server you have to enable the environment variables to be able to run the server because we are using shell file instead of .env file in my company's project. I cannot find any good source to follow so my last hope is StackOverflow. Any help is greatly appreciated 😊 -
Make executable file for django project to share with others
I have created a full running Django project and it's running fine locally. Now I have a requirement to share the project with others so that they can also use the web application running it on their local machine. I know Django is a web app and ideally should be deployed on a server instead of sharing the code but that's not a option for me now due to budget constraints. I was planning to share the entire folder with the team, but few of them are not from technical background so they are confused on how to activate the virtual environment and then run manage.py command. Questions: Is there a option to make the project executable i.e. one a click web app will open and users can start playing with it? If yes, how to implement it? I tried using pyinstaller, it did created the application but double clicking on it shows no result. Please help !! -
I installed uwsgi on ubuntu 20.04 but i keep getting errors when i run the command. How to i correct this error
sudo uwsgi --plugin=python3 --module=nebula.wsgi:application --env=DJANGO_SETTINGS_MODULE=nebula.settings.pro --master --pidfile=/tmp/project-master.pid --http=127.0.0.1:8000 --uid=1000 OUTPUT open("/usr/lib/uwsgi/plugins/python3_plugin.so"): No such file or directory [core/utils.c line 3724] !!! UNABLE to load uWSGI plugin: /usr/lib/uwsgi/plugins/python3_plugin.so: cannot open shared object file: No such file or directory !!! uwsgi: unrecognized option '--module=nebula.wsgi:application' getopt_long() error I also ran sudo uwsgi --module=nebula.wsgi:application --env=DJANGO_SETTINGS_MODULE=nebula.settings.pro --master --pidfile=/tmp/project-master.pid --http=127.0.0.1:8000 --uid=1000 Then i got this output: uwsgi: unrecognized option '--module=nebula.wsgi:application' getopt_long() error -
Django: Executing multiple commands with checkboxes
In my template I have two different tables. Table 1 shows every records with status "Yes". Table 2 shows records with status "No". Each row of table 1 has a button which changes the database status from "Yes"to "No". Meaning that if the user clicks the button, the record will move from table 1 to table 2. Table 2 has the same function, but then the other way around. I have now added a checkbox to do the same thing but then which multiple records. It all works, except in one scenario. When the first table is empty, I am unable to move items from table 2 to 1 with the checkbox function. The two tables <form action="{% url 'complete_multiple_tasks'%}" method="POST"> {% csrf_token %} <table class="trainers-table" id="myTable2"> <tr> <th> <button id = "deletion"class="btn_delete" type="submit" name="checkboxsubmit"> Uitvoeren</button></th> <th> Taak</th> <th> Check?</th> <th> Voltooien</th> </tr> {% for todo_nee in todo_nee%} <tr> <td> <input type="checkbox" name="instance" value={{todo_nee.id}} id="delete_selected"> </td> </form> <td> {{todo_nee.name}}</td> <td> <i id= "nocheck" class="fas fa-times-circle"></i></td> <td><form action="{% url 'todo_compleetmaken' todo_nee.id %}" method=POST> {% csrf_token %} <input type="hidden" name="returntopage" value="{{ request.path }}"> <button class="paginationformat2" type="submit">Uitvoeren</button> </form> </td> </tr> {%endfor%} </table> </div> <form action="{% url 'oncomplete_multiple_tasks'%}" method="POST"> {% csrf_token %} <table class="trainers-table" … -
Django GenericViews Context Data with Parameters
I have the following code views.py return HttpResponseRedirect(reverse('doc_aide:write_prescription', kwargs={'patient': patient.id})) And the Class in view.py fields = ("__all__") model = PrescriptionLine template_name = 'template.html' def __init__(self, *args, **kwargs): super(SinglePrescriptionCreateView, self).__init__(*args, **kwargs) print(kwargs) # this is {} def get_context_data(self, *args): context = super().get_context_data(*args) context['patient'] = Patient.objects.get(pk=1) # here needs to be the ID I need this Patient Id (where the 1 is), the print is {}, How please do I pass the patient ID into the class? -
Reverse for 'edit_post' with arguments '('',)' not found. 1 pattern(s) tried: ['(?P<slug>[^/]+)/edit_post$']
I am going through a Django tutorial and getting this error when trying to open post_detail view ( where i put the link of of edit_post ) for edit post in my blog app. I use Django==3.1.2. views.py def edit_post(request,id): context = {} user = request.user if not user.is_authenticated: return redirect('mains:posts') posts = get_object_or_404(Post,id=id) if request.POST: form = UpdatePost(request.POST or None, request.FILES or None ) if form.is_valid(): obj = form.save(commit=False) obj.save() context['success_message'] = "Updated" posts = obj form = UpdatePost( initial = { 'post_title' : posts.post_title, } ) context['form'] = form return render(request, 'mains/edit_post.html', context) forms.py class UpdatePost(forms.ModelForm): class Meta: model = Post fields = ['post_title'] def save(self,commit=True): post = self.instance post.post_title = self.cleaned_data['post_title'] if commit: posts.save() return posts urls.py path('<id>/edit_post', views.edit_post, name='edit_post'), models.py class Post(models.Model): post_owner = models.ForeignKey(User,default='',null=True,on_delete = models.CASCADE) post_title = models.CharField(max_length=500,default='') A template that causes the error in line 5 - post_detail_view.html. The error message highlights {% url 'edit_post' posts.id %} post_detail_view.html <br> <a>{{ post.post_title }}</a> <br> <a href="{% url 'mains:edit_post' post.id %}">Edit</a> The Problem When i open post_detail.html page in browser , i get this error :- Reverse for 'edit_post' with arguments '('',)' not found. 1 pattern(s) tried: ['(?P[^/]+)/edit_post$']. When i delete edit_post link from post_detail … -
cannot access a model field from filter queryset result
I have a model like this : class MeetingMember(models.Model): CHOICES = ( ("A", "Accepted"), ("R", "Rejected"), ) status = models.CharField(max_length=9,choices=CHOICES,default=None) meeting = models.ForeignKey(Meeting, on_delete=models.CASCADE, related_name="members2") user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, related_name="memberships") and in my views.py i have this code: if get_user_model().objects.get(email=email): member = MeetingMember.objects.filter(meeting=meeting).filter(user__email=email) if len(member)==0: print(member.user) print('not joined yet') elif member.status=="A": print('accepted') else: print('rejected') else: print('not found') but i get this error: 'QuerySet' object has no attribute 'user' any suggestion on how to fix it? note :MeetingMember model is used in my another model filed like this: joined_members = models.ManyToManyField(get_user_model(), blank=True, through='MeetingMember') Many thanks! enter code here