Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to display a list of children objects on detail view for Django Admin?
I have two models: Setting and SettingsGroup. When someone clicks on a specific SettingsGroup in the Django Admin and the edit/detail page appears I'd like for the child Setting objects to be displayed but as a list not a form. I know that Django has InlineModelAdmin but this displays the children as editable forms. My concern isn't with the child objects being editable from the parent object but rather the amount of space it consumes. I'd rather have a list with either a link to the appropriate child record or that changes a particular object to be inline editable. Here is my Setting model: class Setting(models.Model): key = models.CharField(max_length=255, blank=False) value = models.TextField(blank=True) group = models.ForeignKey('SettingsGroup', blank=True, on_delete=models.SET_NULL, null=True) def __str__(self): return str(self.key) And the SettingsGroup model: class SettingsGroup(models.Model): name = models.CharField(max_length=255) description = models.TextField(blank=True) def __str__(self): return str(self.name) The method I don't want to use (or need to find a different way to use) is InlineModelAdmin which appears in my admin.py currently as: class SettingsGroupInline(admin.StackedInlin): model = Setting fk_name = 'group' @admin.register(SettingsGroup) class SettingsGroupAdmin(admin.ModelAdmin): inlines = [ SettingGroupsInline, ] Here is an example of how I'd like it to work: There is a MySettings object, an instance of the … -
Docker nginx service can't communicate with Django service and returning Bad Request 400
My nginx Docker container can't seem to communicate with my Django WSGI app container. It works locally but when I deploy it to Linode I get Bad Request (400) Project Structure Project ─ Dockerfile ─ docker-compose.yml ─ entrypoint.sh └── app ── wsgi.py ── settings.py ── urls.py ── <other django apps> └── nginx ── Dockerfile ── nginx.conf docker-compose.yml: version: '3.3' services: web: build: context: . dockerfile: Dockerfile command: gunicorn app.wsgi:application --bind 0.0.0.0:8000 expose: - 8000 env_file: - ./.env depends_on: - db db: image: postgres:12.0-alpine volumes: - postgres_data:/var/lib/postgresql/data/ env_file: - ./.env.db nginx: build: ./nginx volumes: - static_volume:/var/www/app/staticfiles - media_volume:/var/www/app/mediafiles ports: - 80:80 depends_on: - web volumes: postgres_data: nginx/Dockerfile FROM nginx:1.17.4-alpine RUN rm /etc/nginx/conf.d/default.conf COPY nginx.conf /etc/nginx/conf.d nginx/nginx.conf upstream polls_django { server web:8000; } server { listen 80; location / { proxy_pass http://polls_django; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } } Clues: Locally: I can visit my app at localhost just fine. However, I noticed that I will get Bad Request (400) when trying to visit 0.0.0.0. Linode: When I visit the IP address of my Linode I get Bad Request (400). Looking at my nginx container's error logs, something I noticed is this entry: 2022/11/28 01:08:51 [info] 7#7: *2 client … -
Query unique values inside django forloop
I have a query where I should avoid double entry of the same question. In fact, I would like to get only unique values but, I am using the distinct() django function which isn't working. I have these models: class QuestionTopic(models.Model): name = models.CharField(max_length=255) question_subject = models.ForeignKey( QuestionSubject, on_delete=models.CASCADE) exam_questions_num = models.IntegerField(null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name class Meta: ordering = ('created_at',) class Question(models.Model): id = models.CharField(max_length=7, unique=True, primary_key=True, editable=False) question_subject = models.ForeignKey( QuestionSubject, on_delete=models.CASCADE) text = tinymce_models.HTMLField() mark = models.IntegerField(default=1) is_published = models.BooleanField(default=True) question_bank_id = models.CharField(max_length=255, blank=True, null=True) question_topic = models.ForeignKey( QuestionTopic, on_delete=models.CASCADE, null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) and the query is: subject = QuestionSubject.objects.get(id=request.POST.get('subject')) question_topics = QuestionTopic.objects.filter( question_subject=subject) questions_list = [] for topic in question_topics: for q in range(topic.exam_questions_num): question = Question.objects.filter( question_subject=subject, question_topic=topic).values_list( 'id', flat=True).order_by('?').distinct().first() questions_list.append(question) What I would like to achieve is to have all different questions for each different topic inside questions_list. Which I am not achieving at the moment being the distinct used inside a loop. -
Hubspot api client does not work for existing django project but works for new Django project
In my existing Django project I added a function called test as following: ... import hubspot from hubspot.crm.contacts import ApiException, PublicObjectSearchRequest, SimplePublicObjectInput ... ... def test(email): client = hubspot.Client.create(access_token=<access_token>) public_object_search_request = PublicObjectSearchRequest(filter_groups=[{"filters": [{ "value": email, "propertyName": "email", "operator": "EQ" }]}]) try: api_response = client.crm.contacts.search_api.do_search( public_object_search_request=public_object_search_request) pprint(api_response) except ApiException as e: print("Exception when calling search_api->do_search: %s\n" % e Running sudo python3 manage.py runserver gives me error saying no such module 'hubspot.crm'. So I commented everything in test except client line as following: ... import hubspot ... ... def test(email): client = hubspot.Client.create(access_token=<access_token>) This time I get error module 'hubspot' has no attribute 'Client'. I then created new Django project (on same system) and had same test function (the first snippet) and ran django server, this time it worked without errors. Why is Django not seeing hubspot module for existing project? I have also tried to do this using venv and same results were seen. I am using: Python 3.10.6 hubspot-api-client=7.0.0 https://pypi.org/project/hubspot-api-client/ -
Django - Sending post request using a nested serializer with many to many relationship. Getting a [400 error code] "This field may not be null] error"
I'm fairly new to Django and I'm trying to make a POST request with nested objects. This is the data that I'm sending: { "id":null, "deleted":false, "publishedOn":2022-11-28, "decoratedThumbnail":"https"://i.ytimg.com/vi/a2lC4V479hQ/maxresdefault.jpg, "rawThumbnail":"https"://i.ytimg.com/vi/a2lC4V479hQ/maxresdefault.jpg, "videoUrl":"https"://www.youtube.com/watch?v=cl60ToTvG8w, "title":"Video with tags", "duration":120, "visibility":1, "tags":[ { "id":null, "videoId":null, "videoTagId":42 } ] } Here's a brief diagram of the relationship of these objects on the database I want to create a video and pass in an array of nested data so that I can create multiple tags that can be associated to a video in a many to many relationship. Because of that, the 'id' field of the video will be null and the 'videoId' inside of the tag object will also be null when the data is being sent. However I keep getting a 400 (Bad request) error saying {tags: [{videoId: [This field may not be null.]}]} I'm trying to override the create method inside VideoManageSerializer so that I can extract the tags and after creating the video I can use that video to create those tags. I don't think I'm even getting to the create method part inside VideoManageSerializer as the video is not created on the database. I've been stuck on this issue for a few days. … -
AttributeError at /social-auth/complete/google-oauth2/ 'Request' object has no attribute 'login'
I had written a REST API service on python using django rest framework to which I wanted to attach authentication from authorizations using OAuth2 (Google). I used to social django lib, however when I was starting my service locally and putting my credentials in google form to auth I keep getting this error (look at image)... The point where the error began auth = request.login in /messenger/venv/lib/python3.8/site-packages/requests/sessions.py, line 479, in prepare_request. It was weird, but I solved my problem! -
How to write a correct test (pytest) for RegisterView is failing (the View is working correctly)
I managed to create a View for registering user in django. And it works. The user added manually through form (post) is showing in the database. I am currently trying to write test for this view and it's failing. I keep getting; AttributeError: 'User' object has no attribute 'items' tests.py # test for Register View @pytest.mark.django_db def test_012_register_view_post(client, new_user): url = reverse('register') response = client.post(url, new_user) assert response.status_code == 302 assert response.url == reverse('login') User.objects.get(**new_user) conftest.py (tested 2 different fixtures) - both return the same result (AttributeError) @pytest.fixture def users(): lst = [] for user in range(10): user_name = 'User_' + str(user) lst.append(User.objects.create(username=user_name)) return lst @pytest.fixture def new_user(): username = 'User@test.pl' email = 'User@test.pl' first_name = 'User' last_name = 'Test' x = User.objects.create(username=username, email=email, first_name=first_name, last_name=last_name) x.save() return x view.py class RegisterView(View): def get(self, request): form = RegisterForm() return render(request, 'register.html', {'form': form}) def post(self, request): form = RegisterForm(request.POST) if form.is_valid(): email = form.cleaned_data['email'] password = form.cleaned_data['password1'] first_name = form.cleaned_data['first_name'] last_name = form.cleaned_data['last_name'] u = User() u.username = email u.email = email u.first_name = first_name u.last_name = last_name u.set_password(password) u.save() return redirect('/login') return render(request, 'form.html', {'form': form}) form.py class RegisterForm(forms.ModelForm): first_name = forms.CharField(max_length=128, widget=forms.TextInput(attrs={'class': 'form-group', 'placeholder': 'Imię'}), label='') last_name = … -
Python Django: deleting an object
I'm looking to delete an object in Django, but none of the other Stack Overflow questions fix mine. I looked at this one, but it doesn't seem to be working. My delete object code (in the views file) looks like this: @login_required def delete_entry(request, entry_id): """Delete an existing entry.""" if request.method != 'POST': # No data submitted; create a blank form. form = TopicForm() else: # POST data submitted; process data. form = TopicForm(data=request.POST) if form.is_valid(): new_topic = form.delete(commit=False) ### code to delete object new_topic.owner = request.user new_topic.save() return redirect('learning_logs:topics') # Display a blank or invalid form. context = {'topic': topic, 'form': form} return render(request, 'learning_logs/new_entry.html', context) And in URLs.py: path('delete_entry/<int:entry_id>', views.delete_entry, name='delete_entry'), I would like to use a Bootstrap4 button (inside a modal) to delete the entry, (so without any redirects to another confirmation page). Image. Unfortunately, this isn't working. I'm just getting a server error saying that NoReverseMatch at /delete_entry/6. Could someone tell me what this means? Thanks, Ben -
How to whitelist only specific domain in Google OAuth2
I was making a registration portal using in Django 4 using Google OAuth2 and need to register people only with a specific domain like abc@akgec.ac.in but I'm not able to figure out how to do it. I'm using social-auth-app-django for setting up Google OAuth Authentication. Can anyone help me? I have tried using SOCIAL_AUTH_GoogleOAuth2_WHITELISTED_DOMAINS = ['akgec.ac.in'] but it's not working too. -
how to do less than django queryset with column parameter
I want to count my stock as this sql code SELECT COUNT(*) FROM management_stock WHERE stockCount < minStock how to do that query in django queryset? i got error in my this query Stock.objects.all().filter(stockCount__lt=minStock).count() my table is like this class Stock(models.Model): product = models.OneToOneField(Product, on_delete=models.CASCADE) bengkel = models.OneToOneField(Bengkel, on_delete=models.CASCADE) stockCount = models.PositiveIntegerField() minStock = models.PositiveIntegerField() thanks i tried that code then my eror is : NameError: name 'minStock' is not defined -
Login Issue "POST" 200 3689 (Python, Django)
I am quite new to Django and followed a tutorial to create a website. I'm not able to log in to an account. When I log in with any details (correct or incorrect), my 'login' page just reloads and nothing else happens (The expected result is that I go into a different page when I log in correctly) I am getting "POST /login/ HTTP/1.1" 200 3689 in the terminal. Here's part of the code: (views.py) def loginpage(request): error = "" page = "" if request.method == 'POST': u = request.POST['email'] p = request.POST['password'] user = authenticate(request,username=u,password=p) try: if user is not None: login(request,user) error = "no" g = request.user.groups.all()[0].name if g == 'Doctor': page = 'doctor' d = {'error': error, 'page':page} return render(request,'doctorhome.html',d) elif g == 'Receptionist': page = 'reception' d = {'error': error, 'page':page} return render(request,'receptionhome.html',d) elif g == 'Patient': page = 'patient' d = {'error': error, 'page':page} return render(request,'patienthome.html',d) else: error = "yes" except Exception as e: error = "yes" #print(e) #raise e return render(request,'login.html') Creating an account: def createaccountpage(request): error = "" user="none" if request.method == 'POST': name = request.POST['name'] email = request.POST['email'] password = request.POST['password'] repeatpassword = request.POST['repeatpassword'] gender = request.POST['gender'] phonenumber = request.POST['phonenumber'] address = … -
Is there a way to send query params for tests?
I am trying to make some tests in which asks for ads of a particular type for instance: http://127.0.0.1:8000/ads/?type=normal should return the normal ads and http://127.0.0.1:8000/ads/?type=premium should return the premium ads the tests ask for the ads like this response = self.client.get(reverse("ads")) self.client is for the site. Reverse() was the function i have been using for the other tests so i thought it would work as fine. i was looking for a way i could send the parameters but there is nothing on the internet as far as i'm concerned and i have been struggling with this for hours. ┻━┻ ︵ヽ(`Д´)ノ︵ ┻━┻ If you need any more info i could bring you i tried using: reverse("ads", kwargs={"type": "normal"}) reverse("ads", QUERY_PARAMS={"type": "normal"}) reverse("ads", QUERY_KWARGS={"type": "normal"}) reverse("ads", {"type": "normal"}) these are all things i found online However, nothing worked thanks for reading -
How to render a Django Serializer Template with React Js?
I've set up my api for a basic model in my Django project. I've defined my post and get methods and everything is working correctly. Now, I'm wondering how I can render my Django model using react js. Essentially, I'm wondering how I can use react js to assign my django model values that were inserted using reactjs instead of django. For example, if my django model's fields are "name" and "id", how can I assign these fields using reactjs instead of the basic Django page(I've inserted my current page below)? Do we need to use axios or jquery to make these transitions? Thanks. -
How can I register model created by django-simple-history on admin site?
So, I got a model Question that has a history saved in the model HistoricalQuestion by the django-simple-history package, how do I register it to django admin site? Other model registering is straightforward admin.site.register(models.Event) But I am not sure how to get it for that package models. -
React + Django communication
I'm working on a data mining web app, you should be able to upload a csv file, apply an algorithm and get results in the browser and a pdf with information (graphs and models for prediction principally) this is my first time using React and Django, so my question is, how to send the csv file from react to django, handle the data and return it to react? Thanks!! I've seen a lot of tutorials, but every tutorial use the sqlite data base and the POST method for store data and I only want to process the data inside the csv, because the files will never be the same. -
Django dumpdata/loaddata – Key is not present in table
I'm trying to dump my postgres data and load it locally, but I'm ending up with an error These are my two models: class User(AbstractUser): pass class Profile(models.Model): user = models.OneToOneField( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, primary_key=True ) dob = models.DateField(null=True, blank=True) This is the code I'm executing for the data dump: call_command('dumpdata', indent=4, exclude=['contenttypes', 'auth.Permission', 'sessions', 'admin.logentry']) However, when trying to load it, I get the following error: django.db.utils.IntegrityError: Problem installing fixtures: insert or update on table "profiles_profile" violates foreign key constraint "profiles_profile_user_id_a3e81f91_fk_accounts_user_id" DETAIL: Key (user_id)=(1) is not present in table "accounts_user". What I noticed when trying to read the fixture is that there are no pks for the user, and no references from the profile: { "model": "accounts.user", "fields": { "password": "xyz", "last_login": "2022-11-27T17:28:45.854Z", "is_superuser": true, "username": "JohnDoe", "first_name": "John", "last_name": "Doe", "is_staff": true, "is_active": true, "date_joined": "2020-09-02T16:28:13.329Z", "groups": [], "user_permissions": [] } }, { "model": "profiles.profile", "pk": 1, "fields": { "dob": "1980-06-20", } }, Is that normal? Note that I also tried using natural-foreign and natural-primary-keys like this: call_command('dumpdata', indent=4, exclude=['contenttypes', 'auth.Permission', 'sessions', 'admin.logentry']) but without any effect. What am I doing wrong? Thanks! -
how to group by category in Django
I have a list of project tasks that show on a Django site. But how in the template can I force it to split the projects this way? What I want to do is have section headings: **PROJECT 1** Task 1 Task 2 Task 3 **PROJECT 2** Task 1 Task 2 -
How can I change URL for upladed files?
I have a problem with a path for opening files. I files are saved on s3 amazon, and url for it is https://certsstorenordic.s3.eu-west-3.amazonaws.com/certificate/2022/11/28/Coffee_Maker_64753-001-003_SN_13-09-4222.pdf. However when i am trying to open it from my website it opens as http://127.0.0.1:8000/certificate/2022/11/28/Ceiling_Light_PN_4041-70_SN_31907.pdf. How to change the beginning of url for uploaded files? My MEDIA_URL in settings.py doesn't work. My urls.py: urlpatterns = [] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Settings.py: WS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.eu-west-3.amazonaws.com' STATIC_URL = '/static/' STATIC_ROOT = BASE_DIR / 'static' MEDIA_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/' MEDIA_ROOT = BASE_DIR / 'media' models.py: certificate = models. FileField(upload_to='certificate/%Y/%m/%d/', blank=True, null=True) html: {% for i in response %} <tr> <td>{{i.component.description}}</td> <td><a href="{{ i.certificate }}">Download</a></td> </tr> {% endfor %} -
Calling a DRF View from another View
I have a User Model Viewset that adds users to my Django Rest Framework application (VueJS -> DRF -> PostGres). I have another ModelViewSet for an activity log that has entries when users get credit for doing training, etc. I ran into an issue where I realized that a user that has done nothing, skews the metrics. To combat this, I just want to insert an Activity into the ActivityLog upon user creation. How can I call a ModelViewSet to post a new activity from the the new user post? I read several questions that seemed similar but I am not understanding well enough to translate to my issue. I just want to take the ID created from the new user creation and pass that with some data to the ActivityLogViewset. If I override perform_create() in the UserViewset, how would I call and pass the data to the other endpoint? Thanks. BCBB -
how to fix error UNIQUE constraint failed: auth_user.username
i was trying to use sending email modual from django in order to send sign up email for each user when sign up im facing this error :UNIQUE constraint failed: auth_user.username ` i was trying to use sending email modual from django in order to send sign up email for each user when sign up im facing this error :UNIQUE constraint failed: auth_user.username` # this is my views.py from django.shortcuts import render ,redirect from django.contrib.auth import login from django.contrib.auth.decorators import login_required from . import forms # Create your views here. def home(request): return render(request,'home.html') @login_required def customer_page(request): return render(request,'home.html') @login_required def courier_page(request): return render(request,'home.html') def sign_up(request): form = forms.SignUPForm() if request.method=='POST': form=forms.SignUPForm(request.POST) if form.is_valid(): email=form.cleaned_data.get('email').lower() user= form.save(commit=False) user.useranme = email user.save() login(request,user,backend='django.contrib.auth.backends.ModelBackend') return redirect('/') return render(request,'sign_up.html',{ 'form':form }) ` now i have created signals.py to use email forms ` # my signals.py file from email.base64mime import body_decode from django.db.models.signals import post_save from django.dispatch import receiver from django.core.mail import send_mail from django.conf import settings from django.contrib.auth.models import User from django.template.loader import render_to_string from django.core import mail connection = mail.get_connection() @receiver(post_save,sender=User) def send_welcome_email(sender,instance,created,**kwarg): if created and instance.email: connection.open() body=render_to_string( 'welcome_email_template.html', { 'name':instance.get_full_name() } ) email2 = mail.EmailMessage( 'Welcome to fast Parcle', body, … -
Django RestFramework POST nested request
I'm having a little problem right now with Django Rest Framework. I'm trying to post an object with nested objects in it. This is my models.py file. class Supplier(models.Model): name = models.CharField(max_length=255, blank=True, null=True) def __str__(self): return self.name class Transaction(models.Model): date = models.CharField(max_length=255, blank=True, null=True) income = models.IntegerField(blank=True,null=True) expense = models.IntegerField(blank=True,null=True) card = models.CharField(max_length=255, blank=True, null=True) currency = models.CharField(max_length=255, blank=True, null=True) supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE) category = models.CharField(max_length=255, blank=True, null=True) def __str__(self): return self.date + ' ' + str(self.expense) + ' ' + self.card + ' ' + str(self.supplier) This is my serializers.py file class SupplierSerializer(serializers.ModelSerializer): class Meta: model = Supplier fields = ['id', 'name'] class TransactionSerializer(serializers.ModelSerializer): supplier = SupplierSerializer() class Meta: model = Transaction fields = ['id', 'date', 'income', 'expense', 'card', 'currency', 'supplier', 'category'] read_only_fields = ['id'] def create(self, validated_data): supplier_data = validated_data.pop('supplier') supplier = Supplier.objects.create(**supplier_data) transaction = Transaction.objects.create(supplier=supplier, **validated_data) return transaction This is my views.py file @api_view(['POST', 'GET']) def transaction(request): if request.method == 'POST': transaction_serializer = TransactionSerializer(data=request.data) print(transaction_serializer) if transaction_serializer.is_valid(): transaction_serializer.save() return Response(transaction_serializer.data, status=status.HTTP_201_CREATED) if request.method == 'GET': transactions = Transaction.objects.all() serializer = TransactionSerializer(transactions, many = True) return JsonResponse(serializer.data, safe=False) I'm trying to make this POST Request: { "date": "12/10/2022", "income": 41241, "expense": null, "card": "Credit card", "currency": … -
Serving static HTML etc and Django from root '/' using nginx
I have nginx set up to successfully serve a Django website. I'd like to have it also serve a directory of HTML files, images, etc. If a URL doesn't match a file in there, the request should go to Django. Currently I have this (with irrelevant settings removed, e.g. SSL, logging, etc): upstream myproject_server { server unix:/webapps/myproject/run/gunicorn.sock fail_timeout=0; } server { server_name example.com; rewrite ^/favicon.ico$ /static/myproject/favicons/favicon.ico last; rewrite ^/robots.txt$ /static/myproject/robots.txt last; location /static/ { # Django's static files alias /webapps/myproject/code/myproject/static_collected/; } location / { if (!-f $request_filename) { proxy_pass http://myproject_server; break; } } } If I have a directory of miscellaneous files like this at /webapps/myproject/code/myproject/static_html/: static_html/ test.html directory/ foo.html bar.png another/ hello.pdf etc... What do I need to add to my nginx.conf so that those files are efficiently served at /test.html, /directory/foo.html, etc? -
How do I get the client IP address of a websocket connection in Django Channels?
I need to get the client IP address of a websocket connection for some extra functionality I would like to implement. I have an existing deployed Django server running an Nginx-Gunicorn-Uvicorn Worker-Redis configuration. As one might expect, during development, whilst running a local server, everything works as expected. However, when deployed, I receive the error NoneType object is not subscriptable when attempting to access the client IP address of the websocket via self.scope["client"][0]. Here are the configurations and code: NGINX Config: upstream uvicorn { server unix:/run/gunicorn.sock; } server { listen 80; server_name <ip address> <hostname>; location = /favicon.ico { access_log off; log_not_found off; } location / { include proxy_params; proxy_set_header Connection ""; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass http://uvicorn; proxy_headers_hash_max_size 512; proxy_headers_hash_bucket_size 128; } location /ws/ { proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "Upgrade"; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_redirect off; proxy_pass http://uvicorn; } location /static/ { root /var/www/serverfiles/; autoindex off; } location /media { alias /mnt/apps; } } Gunicorn Config: NOTE: ExecStart has been formatted for readability, it is one line in the actual config [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=django Group=www-data WorkingDirectory=/srv/server Environment=DJANGO_SECRET_KEY= Environment=GITEA_SECRET_KEY= Environment=MSSQL_DATABASE_PASSWORD= ExecStart=/bin/bash -c " source venv/bin/activate; exec /srv/server/venv/bin/gunicorn --workers 3 --bind unix:/run/gunicorn.sock … -
Django view in array
I have 2 tables (posts, upvoted) that I am working within and am looking to see if a post has been upvoted already and if it has, replace the upvote arrow with a filled arrow. In my view, I am already sending over the Upvote object to my template and am trying to check if the post.id exists within the upvoted table. I tried the code below but it didn't work. How would I do it? {% if post.id in upvote.post_id.all %} -
Upload multiple images to a post in Django View Error(Cannot resolve keyword 'post' into field.)
My Model : class Gallary (models.Model): ProgramTitle = models.CharField(max_length=200, blank = False) Thum = models.ImageField(upload_to='Gallary/Thumb/',default = "", blank = False, null=False) VideoLink = models.CharField(max_length=200, blank = True,default = "") updated_on = models.DateTimeField(auto_now = True) created_on = models.DateTimeField(auto_now_add =True) status = models.IntegerField(choices=STATUS, default = 1) total_views=models.IntegerField(default=0) class Meta: verbose_name = 'Add Gallary Content' verbose_name_plural = 'Add Gallary Content' #for compress images if Thum.blank == False : def save(self, *args, **kwargs): # call the compress function new_image = compress(self.Thum) # set self.image to new_image self.Thum = new_image # save super().save(*args, **kwargs) def __str__(self): return self.ProgramTitle class GallaryDetails (models.Model): Gallary = models.ForeignKey(Gallary, default = None, on_delete = models.CASCADE) G_Images = models.ImageField(upload_to='Gallary/Images/',default = "", blank = False, null=False) #for compress images if G_Images.blank == False : def save(self, *args, **kwargs): # call the compress function new_image = compress(self.G_Images) # set self.image to new_image self.G_Images = new_image # save super().save(*args, **kwargs) def __str__(self): return self.Gallary.ProgramTitle My View def gallery(request): gallary = Gallary.objects.all() context = { 'gallary': gallary.order_by('-created_on') } return render(request, 'gallery.html',context) def album_details(request, post_id): post = get_object_or_404(Gallary,pk=post_id) photos = GallaryDetails.objects.filter(post=post) context = { 'post':post, 'photos': photos } return render(request, 'album_details.html',context) Gallary View <div class="our_gallery pt-60 ptb-80"> <div class="container"> <div class="row"> {% for post in gallary …