Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get the file object from request
I send file with javascript like this, fetch png from server and send to the python fetch(fileUrl,{headers: headers}) .then(response => response.blob()) .then(blob => new File([blob], "image.png")) .then(file => { var formData = new FormData(); formData.append("metadata",JSON.stringify(metadata)); formData.append("file",file); axios.post( ai_api,formData,{} ).then(function (response) { console.log("sent success"); } then in django @api_view(["POST"]) def jobs(request): metadata = request.POST.get("metadata") file = request.POST.get("file") print(metadata) # I can get the metadata here!! print(file) # None why this file is None? How can I get the file itself? -
i cannot create a column aws rds database using django
when i add code at models.py file to make a new column like below, partnerId = models.IntegerField(null=True, blank=True, default=None) # added and do "python manage.py makemigrations" and "python manage.py migrate", and migration is done successfully, but the 'partnerId' column' is created only in local mysql database, not in aws rds mysql database. how can i deal with this problem? -
ImproperlyConfigured: Specifying a namespace in include() without providing an app_name is not supported
I am working on a django project, it was working fine untill I added "namespace="polls" in the code below(urls.py) and connected it to "index.html" in 2nd code. 1st- urls.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('polls/', include('polls.urls', namespace="polls")), ] 2nd: index.html: {% extends 'polls/base.html' %} {% block main_content %} {% if latest_questions %} <ul> {% for question in latest_questions %} <li><a href={% url "polls:detail" question.id %}><b>{{question.question_text}}</b</a></li> {% endfor %} </ul> {% else %} <p> You don't have any questions. Please add some.</p> {% endif %} {% endblock %} Now when I renserver it shows following error: ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Specifying a namespace in include() without providing an app_name is not supported. Set the app_name attribute in the included module, or pass a 2-tuple containing the list of patterns and app_name instead. Please help, where I am wrong, it could be some missing package/s too as it is recently installed pycharm. Thank you. -
django and stripe subscription payments issues
I'm trying to create a subscription based saas in django. There are three subscription tiers with both monthly and annual payment options. I have setup the stripe customer id to be created when a new user signs up. I have somehow managed to put together the forms so that they redirect to Stripe's checkout, but I can't save the subscription id and the subscription end date in the database. I get an error as well "An error occurred while creating the new subscription: Request req_8TXfavfNXo1P0A: This customer has no attached payment source or default payment method. Please consider adding a default payment method. For more information, visit https://stripe.com/docs/billing/subscriptions/payment-methods-setting#payment-method-priority." I want to be able to save the subscription id and subscription end date after a successful payment. My models.py from django.conf import settings from django.contrib.auth import get_user_model from django.db import models from django.db.models.signals import post_save import stripe stripe.api_key = settings.STRIPE_SECRET_KEY User = get_user_model() MEMBERSHIP_CHOICES = ( ('Free', 'free'), ('Basic', 'basic'), ('Premium', 'premium') ) class Membership(models.Model): membership_type = models.CharField( choices=MEMBERSHIP_CHOICES, default='Free', max_length=30) stripe_monthly_plan_id = models.CharField(max_length=40, blank=True, null=True) stripe_yearly_plan_id = models.CharField(max_length=40, blank=True, null=True) price_monthly = models.IntegerField(default=0) price_yearly = models.IntegerField(default=0) ordering = models.PositiveIntegerField(default=0) def __str__(self): return self.membership_type class UserMembership(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) stripe_customer_id … -
Nginx container don't see static from Django container
I launch containers through docker-compose, and when I go to url I see site without static. Where is the problem? git link to project - https://github.com/NNKapustin/docker-compose result I have tried different settings for Nginx and docker-compose.yml, but steel have same problem -
Docker-compose up starts Django server, but after changing index.html in templates folder, server doesn't reflect changes
My Dockerfile FROM python:3.6-slim ENV PYTHONUNBUFFERED 1 RUN mkdir /demo WORKDIR /demo ADD . /demo COPY requirements.txt . RUN pip3 install -r requirements.txt EXPOSE 8000 CMD python manage.py runserver 0:8000 my docker-compose file version: "3" services: web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/app ports: - "8000:8000" i tried all solution which provided by chatgpt but none of them is working for me -
Django html dependencies
I'm new to Django, I'm trying to load bootstrap5 and js to my project. To achieve this, I created a 'base.html' under templates and extend it in my other html file. For example: {% extends 'base.html' %} {% block content %} <div class="mt-4"> <h2>Log In</h2> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Log In</button> </form> </div> {% endblock %} This method works but I think it might make the maintenance harder if I include those tags in all of my html files, so is it possible to remove those tags and the dependencies still works? {% extends 'base.html' %} {% block content %} ... {% endblock %} I've tried to use a document_processors to load the CDN, I can confirm that this method is executed but the style is still not loaded if I remove the tags. # document.processor.py def base_template_variables(request): return { 'title': 'Default Title', 'bootstrap_css_cdn': 'https://cdn.jsdelivr.net/npm/bootstrap@5.3.1/dist/css/bootstrap.min.css', 'bootstrap_js_cdn': 'https://cdn.jsdelivr.net/npm/bootstrap@5.3.1/dist/js/bootstrap.bundle.min.js', } -
How to use the free domain given by ngrok?
In their release of ngrok https://ngrok.com/blog-post/new-ngrok-domains, they now provide free domains to free users as of April 2023. I can see my one free domain at https://dashboard.ngrok.com/cloud-edge/domains. However, I don't know how to use it. I have tried ngrok http -subdomain=xxx.ngrok-free.app 80 and ngrok http -subdomain=xxx 80 But it will give me an error Custom subdomains are a feature on ngrok's paid plans. Failed to bind the custom subdomain 'xxx.ngrok-free.app' for the account 'James Arnold'. This account is on the 'Free' plan. Is there a documentation on how to use this free domain by ngrok? -
How to Create different user/Member types in Python Django?
I need to create a paid memebership website with django.There are three types of members to be registered. these registration form/model will have different form fields appart from common authentication fields. In the admin panel these member/users should be listed separately from the super user/ admin/staff users. how can I achive this? models.py from datetime import timedelta, date, datetime from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin from django.db import models from django.conf import settings from .constants import GENDER_CHOICES, RADIO_CHOICES, INDIAN_STATES,COUNTRIES, DISTRICTS_IN_KERALA class MemberType(models.Model): title = models.CharField(max_length=100, blank=True,null=True) slug = models.SlugField(blank=True, null=True) description = models.CharField(max_length=250, blank=True,null=True) price = models.FloatField() def __str__(self): return self.title class NurseMemberManager(BaseUserManager): def create_user(self, email, password=None, **extra_fields): if not email: raise ValueError('The Email field must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) return self.create_user(email, password, **extra_fields) class NurseMember(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) # Add other fields as needed is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) gender = models.CharField(max_length=1, choices=GENDER_CHOICES) date_of_birth = models.DateField(null=True) mobile_no = models.CharField(max_length=15) whatsapp_no = models.CharField(max_length=15) address_lene_1 = models.CharField(max_length=150) address_lene_2 = models.CharField(max_length=150) pin_code = models.CharField(max_length=10) nursing_reg_no = models.CharField(max_length=50) employed = models.BooleanField(choices=RADIO_CHOICES,default=True,) country = models.CharField(max_length=100, choices=COUNTRIES, blank=True, null=True) … -
How can I query my API in React in a way that has dynamically defined queries?
I'm using Django Rest Framework and React, but this is more of a conceptual question. I've noticed that when querying data from an API, especially on a React-esque frontend, I always run into the same issues. API responses are not intrinsically typed I cannot specific exactly what fields I'd like to get back from the API I can't specify dynamic type-safe filtering and sorting. In an ideal world, I'd like to be able to do something like this: // Using a user model as an example. export function UserComponent(props: ...){ // `data` is inferred to be of type Pick<User, "email", "lastActive"> const data = myCustomAPIFetch<User>({ model: User fields: [User.email, User.lastActive], filters: { [User.firstName]: "Linus" } // Similar syntax for sorting }) return (...) } This solves all three issues - it returns the proper type object, filtering/sorting is type-safe, and the exact fields that I want back can be specified. The solutions that I've researched here solve some of the problems, but not all. Graphql - solves #2 and can solve #1, but from what I understand I have to make a new query/resolver for each filter or sort I want to do. Not ideal. Protobuf - types are cross-language … -
Django App fails to upload file to quickbooks
Hello all I am encountering a problem while trying to upload a file to quickbooks using the api. Below is the code, I get a success but the file is not sent or cannot be found in the bill itself. Any help would be appreciated. Inside my app views.py def handle_file_uploads(request): auth_client = AuthClient( settings.CLIENT_ID, settings.CLIENT_SECRET, settings.REDIRECT_URI, settings.ENVIRONMENT, access_token=request.session.get('access_token', None), refresh_token=request.session.get('refresh_token', None), realm_id=request.session.get('realm_id', None), ) if auth_client.access_token is None: return JsonResponse({'status': 'failure', 'message': 'Access token not available.'}) if auth_client.realm_id is None: raise ValueError('Realm id not specified.') if request.method == 'POST': # Get the file input names for each bill ID bill_ids = [key.replace('bill_', '') for key in request.FILES.keys()] for bill_id in bill_ids: uploaded_file = request.FILES.get(f'bill_{bill_id}') if uploaded_file: # Prepare the API endpoint URL to upload the attachment url = f"https://sandbox-quickbooks.api.intuit.com/v3/company/{auth_client.realm_id}/upload" # Prepare the request headers headers = { 'Authorization': f'Bearer {auth_client.access_token}', } # Prepare the file data to be sent as multipart form data files = { 'file_content': (uploaded_file.name, uploaded_file.read(), uploaded_file.content_type), } # Make the API call to upload the attachment response = requests.post(url, files=files, headers=headers) print(response.json) # Check the response status and handle the error case if necessary if response.status_code != 200: error_message = 'API call failed with status … -
ValueError at /store/place_order/ Cannot assign "<SimpleLazyObject: <User: user>>": "Order.user" must be a "User" instance
I am very new with django, i am trying to build a e-commerce store in django in my django project i have two applications accounts and store i my accounts application my form.py looks like this:- from django.contrib.auth import get_user_model from django.contrib.auth.forms import UserCreationForm from django import forms class UserCreateForm(UserCreationForm): mobile_number = forms.CharField(max_length=15, required=True) date_of_birth = forms.DateField(widget=forms.DateInput(attrs={'type': 'date'})) gender = forms.ChoiceField(choices=[('M', 'Male'), ('F', 'Female'), ('O', 'Other')], required=True) class Meta(): fields = ('username', 'email', 'date_of_birth', 'gender', 'mobile_number', 'password1', 'password2',) model = get_user_model() def __init__(self,*args,**kwargs): super().__init__(*args,**kwargs) self.fields['username'].label = 'Display Name' self.fields['email'].label = 'Email Address' self.fields['mobile_number'].label = 'Mobile Number' self.fields['date_of_birth'].label = 'Date of Birth' self.fields['gender'].label = 'Gender' in accounts/views.py:- from django.shortcuts import render, get_object_or_404 from django.urls import reverse_lazy from . import forms from django.views.generic import CreateView from .forms import UserCreateForm from django.contrib.auth import get_user_model from django.contrib.auth.models import User from django.views.generic import TemplateView class SignUp(CreateView): form_class = forms.UserCreateForm success_url = reverse_lazy('index') template_name = 'accounts/signup.html' def profile(request): return render(request,'accounts/profile.html',{'username':request.user, 'email':request.user.email, 'first_name':request.user.first_name, 'last_name':request.user.last_name}) class UserCreateView(CreateView): form_class = UserCreateForm success_url = reverse_lazy('index') template_name = 'accounts/signup.html' def form_valid(self, form): response = super().form_valid(form) self.success_url = reverse_lazy('profile', args=[self.object.pk]) return response in my store application models.py looks like this: - from django.db import models import datetime from accounts.models import User import … -
How to implement reuse of a discount code used for a canceled order?
I have a Django project to implement discount codes. The models are as follows: class CouponCode(models.Model): max_usage = models.PositiveSmallIntegerField() max_usage_per_user = models.PositiveSmallIntegerField(default=1) code = CharField(max_length=10, unique=True) discount_percent = models.PositiveSmallIntegerField(default=0, validators=MaxValueValidator(100)]) max_discount_amount = models.PositiveIntegerField(default=0) is_active = models.BooleanField(default=True) start_date = models.DateTimeField(null=True, blank=True) end_date = models.DateTimeField(null=True, blank=True) minimum_price = models.PositiveBigIntegerField(default=0) class UsedCode(models.Model): customer = models.PositiveBigIntegerField(verbose_name='customer id') coupon = models.ForeignKey(CouponCode, on_delete=models.PROTECT) order_id = models.PositiveIntegerField() @classmethod def has_reached_max_usage_for_user(cls, coupon, user): usages = cls.objects.filter(coupon=coupon, customer=user).count() if usages < coupon.max_usage_per_user: return False return True @classmethod def has_reached_max_usage(cls, coupon): usages = cls.objects.filter(coupon=coupon).count() if usages < coupon.max_usage: return False return True Every time an order is created with a coupon code, a UsedCode object is created. I want to implement a feature where the coupon code can be reused if the order is cancelled. I prefer not to delete the objects so I can track the data. -
Save file (not in MEDIA_ROOT) to Django FileField from fastapi UploadFile
I need to save a fastapi UploadFile object directly to a Django model defined below: class MyFile(models): file = models.FileField(upload_to="files/") In the API, I managed to obtain file object from the SpooledTemporaryFile using the read and write methods like in the block below: async def file_upload(file: UploadFile = File(...)): async with aiofiles.open(f"path/{file.filename}", "wb") as media: cont = await file.read() await media.write(cont) Then I try to convert the new file to FieldFile type in Django to be able to save it in the MyFile.file field but it kept returning a TypeError with the description: write() argument must be str, not generator from django.core.files import File as DjangoFile async def file_upload(file: UploadFile = File(...)): ... async with aiofiles.open(f"path/{file.filename}") as media: d_file = DjangoFile(media) file_model = MyFile() file_model.file.save(file.filename, d_file) file_model.save() return {"ok": True} The stack trace revealed file_model.file.save(file.filename, d_file) as the offending line. >>> type(file.filename) str >>> type(d_file) <class 'django.core.files.base.File'> Could you point me in the right direction? Thanks. -
Running django test, migrations with django.conf import settings are not using DJANGO_SETTINGS_MODULE or --settings override settings
I have a migration which does a check on settings.DEBUG, I've imported settings using from django.conf import settings and if it's False I'm expecting that this is a production(or production-ish) environment so I'm importing a secrets manager secret to use in a createsuperuser migration function, otherwise it's local hosting or local dev and I'm just using a hard coded string. My problem is that in my settings.py I've set DEBUG to false as a safe default, similar to how I set my SECRET_KEY to None so that if for some reason the settings override fails I get an error not the generated SECRET_KEY. Anyway, back from that aside, I'm trying to run ./manage.py test --settings=myproject.test (I have also tried using an export of DJANGO_SETTINGS_MODULE='myproject.test') to load my test.py settings file, at the top of which it does a from .settings import * import and then further down the page I overwrite the setting with DEBUG = True. So in my migration I from django.conf import settings and I'm expecting that to load my DJANGO_SETTINGS_MODULE settings, when I run my tests and it runs my migrations, I'm expecting that from django.conf import settings is going to use my DJANGO_SETTINGS_MODULE settings I … -
"WebSocket connection to 'ws://localhost:8000/ws/chat/cujncvifd/' failed"
I am getting a "WebSocket connection to 'ws://localhost:8000/ws/chat/cujncvifd/' failed" error in my django application. I am also getting a "Not Found: /ws/chat/cujncvifd/" statement in the terminal. The following are the relevant pieces of code from the mentioned files: settings.py: INSTALLED_APPS = [ 'channels', 'common_anime_chat.apps.CommonAnimeChatConfig', 'users.apps.UsersConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] ASGI_APPLICATION = 'anime_chat_app.routing.application' CHANNEL_LAYERS = { 'default':{ "BACKEND":"channels.layers.InMemoryChannelLayer" } } asgi.py: import os from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter, URLRouter import common_anime_chat.routing os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'anime_chat_app.settings') #the new code about the application you told me to write routing.py (main project directory): from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from django.core.asgi import get_asgi_application from channels.security.websocket import AllowedHostsOriginValidator import common_anime_chat.routing application = ProtocolTypeRouter({ 'websocket':AuthMiddlewareStack( URLRouter( common_anime_chat.routing.websocket_urlpatterns ) ), "http":get_asgi_application(), }) routings.py (from common_anime_chat which is an app): from django.urls import re_path from . import consumers websocket_urlpatterns = [ re_path(r'^ws/chat/(?P<room_name>\w+)/$', consumers.ChatRoomConsumer.as_asgi()) ] consumers.py: from channels.generic.websocket import AsyncWebsocketConsumer import json class ChatRoomConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() await self.channel_layer.group_send( self.room_group_name, { 'type':'tester_message', 'tester':'hello world' } ) async def tester_message(self, event): tester = event['tester'] await self.send(text_data=json.dumps({ 'tester':tester, })) async def disconnect(self, close_code): await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) common_anime_chat/urls.py: … -
How to get uncleaned CharField data from a form in a django formset?
I would like to get a charField from a form in a django formset without cleaning the data first. Cleaning the data removes the white space and for a particular Charfield I would like to keep the exact input. I have a form inside a formset and get most of the data fields by for form in formset: cd = form.cleaned_data name = cd.get('name') however I do not want to get the CharField by cleaning the data for a particular field. I was attempting to get the field like this for form in formset: name = form['name_of_field'] but it does not work -
How to use pop-up notifications in Django with Bulma?
I am making an app using Django, and I want to implement Bulma alerts, like this: But, I can't figure out how. I need them to inform the user if they filled out a form correctly. Does anyone know how to implement this? -
Cannot display a comment on a blog page - django
I have been trying to create a comment section for a blog site. Comments should only be made by the site's users. I am able to make comments and display them in the comment section from the admin panel, but when the users submit comments they don't display in the webpage. Here are my models.py: class Sight(models.Model): CATEGORY_MAX_LEN = 25 NAME_MAX_LEN = 30 LOCATION_MAX_LEN = 100 IMAGE_UPLOAD_TO_DIR = 'destinations/' name_of_sight = models.CharField( verbose_name='Name of Sight', max_length=NAME_MAX_LEN, unique=True, ) location = models.CharField( verbose_name='Location', max_length=LOCATION_MAX_LEN, ) category = models.ForeignKey( Category, on_delete=models.CASCADE, # choices=CATEGORIES ) description = models.TextField( verbose_name='Description', ) post_date = models.DateTimeField( auto_now_add=True, ) pros = models.TextField( verbose_name='Pros', null=True, blank=True, ) cons = models.TextField( verbose_name='Cons', null=True, blank=True, ) image = models.ImageField( upload_to=IMAGE_UPLOAD_TO_DIR, verbose_name='Image', ) user = models.ForeignKey( UserModel, on_delete=models.CASCADE, ) def __str__(self): return '%s - %s' % (self.name_of_sight, self.user) class SightComment(models.Model): MAX_BODY_LENGTH = 500 sight = models.ForeignKey( Sight, related_name='sight_comments', on_delete=models.CASCADE, blank=True, null=False, ) body = models.TextField() publication_date_and_time = models.DateTimeField( auto_now_add=True, blank=True, null=False, ) user = models.ForeignKey( UserModel, on_delete=models.CASCADE, ) def __str__(self): return '%s - %s' % (self.sight.name_of_sight, self.user) My form.py: class SightCommentForm(forms.ModelForm): class Meta: model = SightComment fields = ('body',) widgets = {'body': forms.Textarea(attrs={'class': 'form-control', 'cols': 30, 'rows': 4})} labels = { … -
ImportError: cannot import name 'Ingredient' from 'inventory.models' (C:\Users\mcarl\OneDrive\Desktop\VirtualEnvs\djangodelights\inventory\models.py)
So I am at a point in my project where I need to create instances of my models inside of the python shell. The problem is when I go to import my Ingredient model (which I've checked probably a hundred times now to find out if it was correct), I get this message - ImportError: cannot import name 'Ingredient' from 'inventory.models' (C:\Users\mcarl\OneDrive\Desktop\VirtualEnvs\djangodelights\inventory\models.py) The file structure is correct and everything.. How are they saying there is no Ingredient when there is a model called Ingredient inside the file..? Any idea how to fix.? Thanks My models.py file: from django.db import models import datetime class Ingredient(models.Model): name = models.CharField(max_length=100) available_quantity = models.DecimalField(max_digits=10, decimal_places=2) price_per_unit = models.DecimalField(max_digits=10, decimal_place=2) class MenuItem(models.Model): name = models.CharField(max_length=100) price = models.DecimalField(max_digits=10, decimal_places=2) class RecipeRequirement(models.Model): menu_item = models.ForeignKey(MenuItem, on_delete=models.CASCADE) ingredient = models.ForeignKey(Ingredient, on_delete=models.CASCADE) quantity_required = models.DecimalField(max_digits=10, decimal_places=2) class Purchase(models.Model): menu_item = models.ForeignKey(MenuItem, on_delete=models.CASCADE) purchase_date = models.DateTimeField(auto_now_add=True) quantity_purchased = models.DecimalField(max_digits=10, decimal_places=2) total_cost = models.DecimalField(max_digits=10, decimal_place=2) File structure, fixing typos, clearing python cache.. -
Connect django-server which are hosted by railway.app to react-server, also hosted by railway.app
I'm trying to connect my running Django-server to my running react-"server", but I don't know how... I have done the task with my apache-server, but can't manage to do it in railways.app. Any helpful minds out there who can guide me to my goal? -
Using JS to update profile photo
I'm trying to write a Django application where there is a button to change the profile photo and when clicked, a file selection screen appears. After selecting the file, I see the upload successful message, but the new image I selected is not written to the database. I can't pass this step for days. template js code: <script> // JavaScript document.addEventListener("DOMContentLoaded", function () { const uploadButton = document.getElementById("uploadButton"); const fileInput = document.getElementById("fileInput"); uploadButton.addEventListener("click", function () { fileInput.click(); }); fileInput.addEventListener("change", function () { const formData = new FormData(document.getElementById("profileForm")); fetch("{% url 'update_profil_photo' %}", { method: "POST", body: formData, headers: { "X-CSRFToken": '{{ csrf_token }}' } }) .then(response => response.json()) .then(data => { if (data.success) { alert("Sucessfully updated!"); } else { alert("An error occured, please try again."); } }) .catch(error => { alert("an error occured, please try again."); }); }); }); </script> template html: <form method="post" enctype="multipart/form-data" action='{% url "update" %}' id="profileForm"> {% csrf_token %} <button class="btn btn-info" type="button" id="uploadButton"> <i class="fa fa-fw fa-camera"></i> <span>Change Photo</span> </button><input id="fileInput" type="file" style="display: none;"> </div> </div> view: @login_required def update_profil_photo(request): user_profile = get_object_or_404(UserProfile, user=request.user) user = request.user if request.method == 'POST': profile_form = UserProfilePictureUpdateForm(request.POST, request.FILES, instance=user_profile) if profile_form.is_valid(): profile_form.save() messages.success(request, 'Update is successful') return JsonResponse({'success': True}) … -
NGINX not serving django static files after ssl certificate was installed
After building my django app, I got it to work over http. The issue started after installing ssl certificate using certbot. Now, static files are no longer being served. This is my nginx configuration server { server_name pythonyard.com www.pythonyard.com *.pythonyard.com; location /static/ { alias /home/kenechukwu_webapp/allpython/backend/; } location / { proxy_pass http://localhost:8000; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/pythonyard.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/pythonyard.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host = www.pythonyard.com) { return 301 https://$host$request_uri; } # managed by Certbot if ($host = pythonyard.com) { return 301 https://$host$request_uri; } # managed by Certbot listen 80; server_name pythonyard.com www.pythonyard.com *.pythonyard.com; return 404; # managed by Certbot } I have read through lots of similar problems here on stackoverflow but none has worked for me. Please what could be wrong? This is my first time using it -
how to Filter two models values in query sets
hi I'm Django rest framework in my I want to search filter 2 models at once class SearchViewSet(generics.ListAPIView): queryset = Profile.objects.all() serializer_class = SearchSerializer authentication_classes = [TokenAuthentication] filter_backends = [SearchFilter] search_fields = ["user__username", "caption", "post_text"] def get_queryset(self): search_query = self.request.GET.get("search") queryset = super().get_queryset() if search_query: # Filter the queryset based on the search query queryset = queryset.filter(user__username__icontains=search_query) # Get the related Post objects that match the search query post_queryset = Post.objects.filter( caption__icontains=search_query) | Post.objects.filter( post_text__icontains=search_query) # Get the distinct Profile objects that have related matching Post objects queryset = queryset.filter(posts__in=post_queryset).distinct() return queryset this is my serilizers. py class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = "__all__" depth = 1 class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = "__all__" class SearchSerializer(serializers.Serializer): profile = ProfileSerializer() posts = PostSerializer(many=True) I want to filter results by username as well as post description and post caption but the username belongs to ProfileSerilizers and the post description and post caption belongs to Post Sterilizers how can I achieve this I'm getting this error raise FieldError( django.core.exceptions.FieldError: Cannot resolve keyword 'posts' into field. Choices are: bio, id, id_user, location, profileimg, user, user_id -
S3 image URL to a python string and swap the backslashes
In my Django web app I use a function that takes the web request and goes to get the image URL from an S3 bucket and stores it into a variable. So I have a 2 part question I need to take that variable (which is holding the string) and turn forward slashes into back slashes Ultimately I am trying to verify that AWS has a path that exists, because right now it keeps telling me its false. def testPage(request, pk): photo = Photo.objects.get(id=pk) photo_url = str(photo.image.url) photo_path = str(request.build_absolute_uri()) print(photo_url) # "https://myBucketname.s3.amazonaws.com/Profile_pic_-_Copy.jpg" path_exists = os.path.exists(photo_url) # FALSE print(photo_path) # http://localhost:8000/prediction/68/ path_exists = os.path.exists(photo_path) # FALSE I have tried getting the raw string of the variable. I have tried to apply os.path.normpath() but it removes the double slash from the beginning of the URL. Any help on this would be great