Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
raise ValueError('Filename must be a string') ValueError: Filename must be a string when upload file to AWS S3 in Django
I have used Django to develop a web app. In the frontend, the user is supposed to upload an image by upload button to AWS S3. But I got the error at s3_client.upload_file: raise ValueError('Filename must be a string') ValueError: Filename must be a string view.py def save_pic(request): print("save_pic") if request.method == 'POST': image = request.FILES.get('image') print(image) img_name = image.name ext = os.path.splitext(img_name)[1] img_path = os.path.join(settings.IMG_UPLOAD, img_name) with open(img_path, 'ab') as fp: for chunk in image.chunks(): fp.write(chunk) import boto3 from botocore.exceptions import ClientError s3_client = boto3.client('s3', aws_access_key_id='XXX', aws_secret_access_key='XXX', region_name='XXX') try: with open(img_path, 'rb') as fp: response = s3_client.upload_file(fp, 'etp-tms', 'image_0.jpg') except ClientError as e: print(e) try: data = {'state': 1} except: data = {'state': 0} return JsonResponse(data) return JsonResponse(data="fail", safe=False) HTML: function renderCover(value, row) { return '<input id="image-input" accept="image/*" type="file" />\n' + '<img id="image-img" /> ' } function upload() { //alert("upload"); var formdata = new FormData(); formdata.append("image", $("#image-input")[0].files[0]); formdata.append("csrfmiddlewaretoken",$("[name='csrfmiddlewaretoken']").val()); $.ajax({ processData:false, contentType:false, url:'/save_pic/', type:'post', data:formdata, dataType:"json", success:function (arg) { if (arg.state == 1){ alert('success') }else { alert('fail') } },error: function () { alert("error") } }) } when I upload the img, the error occurs at response = s3_client.upload_file(fp, 'etp-tms', 'image_0.jpg').: raise ValueError('Filename must be a string') ValueError: Filename must be … -
putting fields labels in django table in first row
I want to: print the label in the first row set with of each field to 45px put the first column where C will enumerate 1,2,3,... according to the rows. it should be something like this: V x1 x2 direct RHS C1 field field field field C2 field field field field C3 field field field field in the body of page.html: <table> {% for form in formset %} <tr> {{ form.label }} {% for item in form %} <td style="width:10px; text-align: center">{{ item }}</td> {% if not item.label_tag = 'direction' %} ...do something... {% endif %} {% endfor %} </tr> {% endfor %} </table> in forms.py: class linprog_vars(forms.Form): x1 = forms.FloatField(label='x1') x2 = forms.FloatField(label='x2') direct = forms.CharField(label='direct') rhs = forms.FloatField(label='rhs') En views.py def linprog(request): extra_lines = 3 formset = formset_factory(linprog_vars, extra=extra_lines) context = {'formset': formset} return render(request, 'linprog/linprog.html', context) -
Django Models Data is not shown in Bootstrap Modal
I have faced a problem to pass the model data to Bootstrap modal. The information is not displayed in Bootstrap modal but when I try to pass data to a normal template, the information is shown. Can you guys please help me to find out where is the problem. I will be very appreciated for your help! Here is the code. catalog.html <div class="row"> {% for getdata in furniture %} <div class="col-md-4"> <a class="" href="{{ getdata.update_view_count_url }}" data-toggle="modal" data-target="#product_modal"> <div class="card text-center mb-5"> <img src="{{baseUrl}}/{{getdata.furnitureImg}}" alt="" class="card-img-top mt-3 px-2"> <div class="card-body"> <h3 class="card__fName text-uppercase">{{getdata.furnitureName}}</h3> <h2 class="card__fPrice">${{getdata.unitPrice}}</h2> <a href="{{ getdata.add_to_cart_url }}" class="card__button text-uppercase"> <i class="uil uil-shopping-cart"></i> Add To Cart </a> </div> </div> </a> </div> {% endfor %} {% include 'user/product.html' %} </div> models.py def update_view_count_url(self): return reverse("ecommerce:view", kwargs={ 'slug': self.slug }) urls.py from django.urls import path from . import views from . import recommendation from .views import ItemDetailView, CartDetailView, OrderSummaryView app_name = 'ecommerce' urlpatterns = [ path('view/<slug>/', views.updateViewToItem, name='view'), path('product/<slug>/', ItemDetailView.as_view(), name='product'), ] views.py class ItemDetailView(DetailView): model = Furniture template_name = "user/product.html" # View the item after clicking def updateViewToItem(request, slug): item = get_object_or_404(Furniture, slug=slug) viewed_item = User_Views.objects.filter(userId=request.user, furnitureId=item) if viewed_item.exists(): get_viewed_item = User_Views.objects.get(userId=request.user, furnitureId=item) get_viewed_item.viewCount += 1 get_viewed_item.save() else: view … -
Why can't I get Axios to set CSRF token headers?
I have an HTTP only cookie that was set by Django for session based authentication. When I try to make a POST request in my Next.Js app I get detail: "CSRF Failed: CSRF token missing or incorrect.". I know I need the X-CSRFToken header but Axios won't set it for me. The cookies are being sent in the request just not as a header. My post request looks like: axios .post(`${process.env.NEXT_PUBLIC_API_URL}/shops`, createShopFormData, { xsrfHeaderName: 'X-CSRFToken', xsrfCookieName: 'csrftoken', withCredentials: true, }) .then((response: AxiosResponse) => { console.log(response); }) .catch((error: AxiosError) => { console.log(error.response?.data.message); }); }; -
Django and nginx: How to add url prefix to all the django urls
I have the following nginx config: I am running two servers Nodejs(port:3000) and django(port:8000) http { server { listen 80; server_name localhost; location / { proxy_pass http://127.0.0.1:3000; <-- NODEJS APP } location /api { proxy_pass http://127.0.0.1:8000; <-- DJANGO APP } } } I want to access Django at {domain_name}/api and anything other than that will be fetched from Nodejs I want to access all the /admin and whatever urls mentioned in the Django at /api Is there any way to do that. I know i can add /api infornt of all the urls in the urls.py. But this can be dynamic. So I dont want to disturb the urls. -
Inspect response when i use a view Class-based views - Django
I need to inspect the response for know the params of pagination. I try used Pdb but the application stops. I think to overwrite some method like def dispatch(self, request, *args, **kwargs): but i don't know if the best way, someone could guide me ? class PostsFeedView(LoginRequiredMixin, ListView): template_name = 'posts.html' model = Post ordering = ('-created',) paginate_by = 10 context_object_name = 'posts' # import pdb; pdb.set_trace() -
find the total time a user spent in python
How to read text file line by line than filter time details and sum the time. Basically I need to find the total time a user spent in hours.for example: TL:1 2/23/12: 9:10pm - 11:40pm getting familiar with Flash 2/29/12: 12:50pm - 2:00pm getting familiar with Flash 3/1/12: 6:00pm - 11:40pm getting familiar with Flash 3/3/12: 3:00pm - 7:00pm step-debug Energy Game code 3/4/12: 8:00pm - 11:40pm start carbon game 3/5/12: 2:00pm - 3:00pm 4:00pm - 4:30pm carbon game 3/6/12: 11:30am - 1:30pm carbon game data structures and classes for the first action 3/7/12: 11:00am - 5:00pm tested basic concept 3/8/12: 1:00am - 1:30am changed vector calling, 10:30am - 2:30pm 4:00pm - 5:00pm wrote code to draw points indicator and marshal the data -
Django: Is there a way to play local video in VLC or something else when the django view is requested on click event from html?
I am building python django application where I need to play a video when request is made from web browser. Scenerio: When I click a button from webapp then I should be directed to next page, and video should play on either mediaplayer such as VLC or something else(pop-up). I tired python openCV and VLC library, but had a very little luck because It wait for video to finish playing, so it doesn't render the page and kills the django server. Here is the code I was trying: play_video() opens the openCV frame and start playing the video, but django view doen't render def index(request): person = person.objects.all() context = {'donors': donors} play_video() return render(request, 'index.html', context) -
File arrangement different in Ubuntu server
I have a problem retrieving the last file from some files with these filenames: On Windows localhost: On Ubuntu server: Its all arranged by year and by quarter. I need the last file for 1 of my scripts, and the way I access it is by doing: filenames = os.listdir(edgar_path) last_file = filenames[-1] It works fine on my localhost on my Windows PC, but it's working unexpectedly on the Ubuntu server. When I try to print the last file being retrieved, it's different on the server. logger.debug('last_file') logger.debug(last_file) Windows localhost result: Ubuntu Server result: It's the same script, with the same files but for some reason, it's returning the wrong file in the servers script. Any idea what might cause this? Any help is appreciated. -
how to solve CORS error using react and django on aws
I have my application in production where www.foo.com is the frontend on s3 built with reactjs and api.foo.com is the backend built with django. Both the front end and backend are on cloudfront. now whenever i try to hit the endpoint create i get the following result in the console. Access to XMLHttpRequest at 'https ://api.foo.com/create/' from origin 'https ://www.foo.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. xhr.js:177 POST https ://api.foo.com/create/ net::ERR_FAILED react create.js ... const options = { headers: { 'Content-Type': 'application/json', "Access-Control-Allow-Origin": "*", // I have tried to comment this before... } }; const handleSubmit = (e) => { e.preventDefault(); console.log("form submitted", fields.name); axios.post("https ://api.foo.com/create/", fields, options) .then(response => { console.log("Status", response.status); console.log("Data", response.data); }).catch((error => { console.log("error", error); })); }; ... django settings.py ... ALLOWED_HOSTS = ["*"] # for the sake of testing CORS_ORIGIN_WHITELIST = ( "https ://www.foo.xyz", ) CORS_ALLOWED_ORIGINS = [ "https ://www.foo.xyz", ] ... django views.py ... @api_view(["POST"]) @parser_classes([JSONParser]) def create(request): if request.method == "POST": serializer = PersonSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) The configuration seem right to me, not sure what i am getting wrong here Any help would be much appreciated -
Simple Background Image, Django unable to find image
Just wanting to make a simple multiple page website and I cant seem to get the background image to show on local host, Django just keeps saying Image not found. Can anyone help with this?? I want to drop vue in and do some fun stuff, but If I can't even get the images to show its going to be no fun at all. The HTML File. <body> <section id="hero" class="d-flex align-items-center"> <div id="bg"> <div class="bg"> <img src="{% static "media/ocean.jpg" %}" class="bg1" alt="" /> My View File from django.shortcuts import render # Create your views here. def homepage(request): return render(request, '/Users/mossboss/Dev/SimpleWS/apps/core/templates/core/base.html') My Settings STATIC_URL = '/static/' STATICFILES_DIRS = [ BASE_DIR / 'static' ] MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR / 'media' -
Transfer the QuerySet in Django AdminModel
I'm trying to make a reference to another model with my sorting. query = Cars.objects.filter(task_id__exact=obj.task_id, engine__isnull=False).values_list('engine', flat=True) engines_ids_list=list(query) link = reverse("admin:auto_engines_changelist") + f"?id={engines_ids_list}" ^ Not work, it's example ?engine_id=1&engine_id=2 display object with the last parameter (engine_id=2), not 2 objects.. work only Engines.objects.filter(pk__in=engines_ids_list) How can I send this filter to the engine changelist page? -
Django using multiple form with rich editor
I am creating comment area and reply to comment area for users. And I using django-ckeditor for this but there is a problem. When I add "reply form" just showing once in the page. Not showing other forms. The reply system its works just its not showing ckeditor(Rich editor). I am add some photos for better understanding: secon image: inspect: my Models: class UserMessages(models.Model): postMessages = RichTextUploadingField(null=True, verbose_name="Message") post = models.ForeignKey( serPosts, on_delete=models.CASCADE, verbose_name="Linked Post", null=True) username = models.ForeignKey( User, on_delete=models.CASCADE, verbose_name="Username", null=True) replies = models.ForeignKey("self", blank=True, null=True, on_delete=models.CASCADE) my Forms: class MessageForm(forms.ModelForm): class Meta: model = UserMessages fields = ("postMessages",) widgets = { "postMessages": forms.TextInput(attrs={"class":"form-control"}), #And I tried this but not works.. class ReplyFormMessage(forms.ModelForm): class Meta: model = UserMessages fields = ("replies",) my HTML: <form method="POST" > {% csrf_token %} {{form.media}} {{ form }} <input type="hidden" name="replies_id" value="{{ message.id }}"> <input type="submit" value="Reply" class="btn btn-default"> </form> as for me, ckeditor just using one id for all form in page. So, do you have an idea? -
Handle requests that demand high RAM in Django
I have developed a geospatial app using Django. Users have the potential to draw a polygon and to get data analysis for the pixels included in the polygon. In order to get this data analysis, each request demands several GB and a couple of minutes to show the result. What if many users make a response at the same time? There will be a problem regarding the RAM. What I need is to put the requests into a queue, inform the user with a message about the waiting and execute one by one the requests. Any idea how to make this happen? Thanks in advance. Best, Thanassis -
Django - keyerror in form when running test
I have a CustomUser model, using django's auth for authentication, and a custom signup view. In the signup form I have some validation to check that the email_suffix (domain of the email) matches with the district that they select in the form. I also check that the email is unique. When running a test on this, I get an error on the form: value_district = self.cleaned_data['district'] KeyError: 'district' Model class CustomUser(AbstractUser): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) is_student = models.BooleanField('student status', default=False) is_teacher = models.BooleanField('teacher status', default=False) SD23 = 'SD23' SD39 = 'SD39' SD67 = 'SD67' SDISTRICT = [ (SD23, 'Kelowna SD23'), (SD39, 'Vancouver SD39'), (SD67, 'Summerland SD67'), ] district = models.CharField( max_length=4, choices=SDISTRICT, blank=True, default='SD39') paper = models.BooleanField(default=False) def __str__(self): return self.username View def signup(request): if request.method == 'POST': form = CustomUserCreationForm(request.POST) if form.is_valid(): user = form.save(commit=False) to_email = form.cleaned_data.get('email') # make the username the same as the email user.username = str(to_email) user.is_teacher = True user.is_staff = True user.is_active = False user.save() group = Group.objects.get(name='teacher') user.groups.add(group) current_site = get_current_site(request) print(urlsafe_base64_encode(force_bytes(user.pk))) sendgrid_client = SendGridAPIClient( api_key=os.environ.get('SENDGRID_API_KEY')) from_email = From("doug@smartmark.ca") to_email = To(to_email) subject = "Activate your SmartMark Account" active_link = render_to_string('account/acc_active_email_link.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) html_text … -
how to define subdomain with ip address django tenant app
im trying to deploy my django project using django-tenants i deploy it through linux ubuntu server 20.4 LTS version , my ip address 255.255.255.255(not correct) it works fine for the public schemas but when i try to creating a new tenant for example blog1 with domain name blog1.255.255.255.255 it doesnt work , and shows nothing but it create a new schemas , but i cant access it through my browser ! is there any solution if i dont use domain name ?! my ALLOWED_HOSTS = ['*'] i use dedicated server in linode thank you django version == 3.2 i use postgres DB version 12 -
Django ValueError: ModelForm has no model class specified. Where am I going wrong?
from django.db import models class Topic(models.Model): """Um assunto sobre o qual o usuário está aprendendo.""" text = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): """Devolve uma representação em string do modelo.""" return self.text class Entry(models.Model): """Algo específico aprendido sobre um assunto.""" topic = models.ForeignKey(Topic, on_delete=models.PROTECT) text = models.TextField() date_added = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural = 'entries' def __str__(self): """Devolva uma representação em sring do modelo.""" return self.text[:50] + "..." This error persists. Can anyone point me where I'm wrong? -
Direct assignment to the forward side of a many-to-many set is prohibited. User exercise.set() instead
I have two models, Exercise and Workouts. I want to create a workout with a set of exercise. I have already able to send the array of exercise and workout details using POST and ajax, but I keep getting this error. I have read all other questions with this error, but my problem is two things: 1-the exercise item is already created, 2-I want to add more than one exercise item to the workout table. Any idea on how to do this? models.py: class Exercise(models.Model): BODYPART_CHOICES = ( ('Abs', 'Abs'), ('Ankle', 'Ankle'), ('Back', 'Back'), ('Biceps', 'Biceps'), ('Cervical', 'Cervical'), ('Chest', 'Chest'), ('Combo', 'Combo'), ('Forearms', 'Forearms'), ('Full Body', 'Full Body'), ('Hip', 'Hip'), ('Knee', 'Knee'), ('Legs', 'Legs'), ('Lower Back', 'Lower Back'), ('Lumbar', 'Lumbar'), ('Neck', 'Neck'), ('Shoulders', 'Shoulders'), ('Thoracic', 'Thoracic'), ('Triceps', 'Triceps'), ('Wrist', 'Wrist'), ) CATEGORY_CHOICES = ( ('Cardio', 'Cardio'), ('Stability', 'Stability'), ('Flexibility', 'Flexibility'), ('Hotel', 'Hotel'), ('Pilates', 'Pilates'), ('Power', 'Power'), ('Strength', 'Strength'), ('Yoga', 'Yoga'), ('Goals & More', 'Goals & More'), ('Activities', 'Activities'), ('Rehabilitation', 'Rehabilitation'), ) EQUIPMENT_CHOICES = ( ('Airex', 'Airex'), ('BOSU', 'BOSU'), ('Barbell', 'Barbell'), ('Battle Rope', 'Battle Rope'), ('Bodyweight', 'Bodyweight'), ('Cables', 'Cables'), ('Cones', 'Cones'), ('Dumbbells', 'Dumbbells'), ('Dyna Disk', 'Dyna Disk'), ('Foam Roller', 'Foam Roller'), ('Kettlebells', 'Kettlebells'), ('Leg Weights', 'Leg Weights'), ('Machine', 'Machine'), ('Medicine Ball', … -
Django allauth with custom redirect Adapter ignoring "?next" parameter
I am using Django 3.2 and django-allauth 0.44 I have a custom adapter that redirects a user to their profile page upon login - however, I also want to be able to use a ?next=/some/url/ so that a user is redirected to that url if there is a next parameter in the GET arguments. This is my custom Adapter: class MyAccountAdapter(DefaultAccountAdapter): def get_login_redirect_url(self, request): print(f"GET request dict is {request.GET}") return reverse('profile', kwargs={'username': request.user.username}) I suspect that I have to modify my custom adapter, so that it checks for a 'next' GET parameter BEFORE going to the profile page. However, I found to my surprise that it seems: I can't set a breakpoint in the adaptor (it is ignored) If I deliberately introduce an error in the adaptor (e.g. print(request.GET['hello']) ) the code runs fines and redirects to the profile page without throwing an exception How can I use ?next=/some/url with django-allauth whilst also using a custom adaptor? -
The google-one-tap does't work on Django latest version
In my project, the google-one-tap does work fine in Django<=3.0 version, but it doesn't work in Django>=3.1. It gives me this error. [GSI_LOGGER]: The given origin is not allowed for the given client ID. I need it does work on Django==3.2.7. I need your help urgently. Thank you. -
Using HTML and Python together
I need some general python/web development help. Me and my friend know some Python and HTML and want to make a simple test website to practice with some text and buttons, but we don't how to make python detect the button press and run code then display text. I don't even know where to start with this? -
Register form in Django
I am noob to django programming.I want to create register form.I get error NoReverseMatch at / Reverse for 'register' with no arguments not found. 1 pattern(s) tried: ['(?P<register_id>[^/]+)/$'].Please help me. views.py def register(request): if request.method == "POST": user_form = UserRegistrationForm(request.POST) if user_form.is_valid(): new_user = user_form.save(commit=False) new_user.set_pasword =(user_form.cleaned_data['Password']) new_user.save() return render(request, 'main/account/register_done.html', {'new_user': new_user}) else: user_form = UserRegistrationForm() return render(request, "main/account/register.html", {'user_form': user_form}) url.py path("<int:register>/",views.register, name='register'), forms.py from django.contrib.auth.models import User from django import forms from django.forms import widgets class UserRegistrationForm(forms.ModelForm): password = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField(label='Repeat password', widget=forms.PasswordInput) class Meta(): model = User fields = {"Username", "email", "Name", "SurName"} def clean_password2(self): cd =self.cleaned_data if cd['password'] != ["password2"]: raise forms.ValidationError("Password dont match") return cd["password2"] base.html <a class="me-3 py-2 text-dark text-decoration-none" method="POST" href="{% url 'register' %}">Регистрация</a> -
Invalid section header '[Socket]ListenStream=/run/gunicorn.sock'
I am trying to deploy, a Django app on production mode using Nginx and Gunicorn, on an ec2 linux instance. I created a gunicorn.socket file in the path /etc/systemd/system/gunicorn.socket: It's contents are: [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target Furthermore I created a service file , in the path /etc/systemd/system/gunicorn.service Its contents are: [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=ec2-user Group=www-data WorkingDirectory=/home/ec2-user/buisness ExecStart=/home/ec2-user/.local/bin/gunicorn --access-logfile - --workers 3 --bind unix:/run/gunicorn.sock buisness.wsgi:application [Install] WantedBy=multi-user.target I then tried to start and enable gunicorn socket: sudo systemctl start gunicorn.socket but I got the error, Failed to start gunicorn.socket: Unit is not loaded properly: Bad message. When I checked the error logs, using, systemctl status gunicorn.socket , this is wat I got: ● gunicorn.socket - gunicorn socket Loaded: error (Reason: Bad message) Active: inactive (dead) Sep 06 19:13:52 ip.compute.internal systemd[1]: [/etc/systemd/system/gunicorn.socket:3] Invalid section header '[Socket]ListenStream=/run/gunicorn.sock' Sep 06 19:13:52 ip.compute.internal systemd[1]: [/etc/systemd/system/gunicorn.socket:3] Invalid section header '[Socket]ListenStream=/run/gunicorn.sock' Sep 06 19:14:15 ip.compute.internal systemd[1]: [/etc/systemd/system/gunicorn.socket:3] Invalid section header '[Socket]ListenStream=/run/gunicorn.sock' Sep 06 19:14:27 ip.compute.internal systemd[1]: [/etc/systemd/system/gunicorn.socket:3] Invalid section header '[Socket]ListenStream=/run/gunicorn.sock' Sep 06 19:26:15 ip.compute.internal systemd[1]: [/etc/systemd/system/gunicorn.socket:3] Invalid section header '[Socket]ListenStream=/run/gunicorn.sock' Sep 06 19:26:26 ip.compute.internal systemd[1]: [/etc/systemd/system/gunicorn.socket:3] Invalid section header '[Socket]ListenStream=/run/gunicorn.sock' Sep 06 19:56:22 ip.compute.internal systemd[1]: [/etc/systemd/system/gunicorn.socket:3] Invalid section header '[Socket]ListenStream=/run/gunicorn.sock' … -
Abstract User django create different table but it is not show in db
1st Problem : i have already running django-oscar app ,now i have to convert it into restapi app so i just create User using from oscar.apps.customer.abstract_models import AbstractUser then it was giving me .0001 initial migrations error ,then i deleted all migrations folder from oscar sitepackage and use python ./manage.py makemigrations and the migrate command ,every thing was ok until i found that when i open from my local server it show user table inside the Authentication(my custom app) but when same app use though from server it wad inside authentication and autherization table and work normally,then i search my authentication table in side my db it was not showing ,i am confuse if there is no authentication table then how i get user inside authentication table and if it is created why it is not showing inside db. 2nd : in my case i have already existing and live application based on django-oscar ,now i want to use jwt token for authentication ,what should i do ? thanks in advance and all above things happen on my testing server but if it will success than it will replicate on production server. -
how to use django related_name
I have to models named Meeting and MeetingMembers like this : class Meeting(models.Model): title = models.CharField(max_length=255) description = models.TextField() class MeetingMember(models.Model): CHOICES = ( ("A", "Accepted"), ("R", "Rejected"), ("I", "Invited" ), ("H", "Host")) status = models.CharField(max_length=9, choices=CHOICES, default="I") meeting = models.ForeignKey(Meeting, on_delete=models.CASCADE, related_name="members") email = models.EmailField(blank=True) i need to write a query that first gets all the records in MeetingMeember models which belongs to current logged in user like this : meetingmembers = MeetingMember.objects.filter(email = requets.user.email) then i need to the get all the info from the meetings belongs to the meetingmember(the second queryset should be Meeting object) i have studied about related_name but still can't figure out how can i write this.