Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: can't load images but static files OK
I'm learning Django, and I've spent a week+ trying to display images in my app. I think that there's an issue with my settings but I'm perplexed since the static files are loading, though the images with similar settings are not. What confuses me so much is that my static files are loaded ok at MEDIA_ROOT/static, but that image files aren't found at MEDIA_ROOT/media. Based on settings.py, static seems like it would live at # C:\Users\...\final\static but it's clear that this isn't true. structure ├── final │ ├── dogtracks │ │ ├── static | │ │ ├── dogtracks │ ├── media | │ ├── images settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') ... MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') # C:\Users\...\final\media models.py class Animal(models.Model): ... photo = models.ImageField(upload_to='images', null=True, blank=True) ... class AnimalForm(ModelForm): class Meta: model = Animal fields = ['name', 'breed', 'species', 'birthday', 'photo'] html {% if pet.photo %} <img src="final{{ pet.photo.url }}" /> {% else %} <img src="{% static 'dogtracks/noun-pet.png' %}" /> {% endif %} I've read dozens of answers here on SO and gone through tutorials online. I've moved the location of my images folder to try to show these images. -
Python requests script with proxies does not work in Docker container on Windows
I have Docker installed on both Windows and Linux, and I have a dockerized Django app running on both operating systems. When I execute this script in the Django shell on Linux, it correctly returns the IP of the proxy server, as expected. However, when I run the same script on Windows, it returns my external IP address instead. import requests request = requests.get(url='https://httpbin.org/ip', proxies={ 'http': proxy_url, 'https': proxy_url, 'socks5': proxy_url }) print(request.text) Has anyone encountered a similar issue? -
Django ManifestFileStorage STATIC_ROOT misconfigured
I recently upgraded my project from Django 2.2.28 to 3.2 and am using Django-storage 1.14.2. As part of the upgrade, I replaced CachedFileMixin with ManifestFileStorage. Before the upgrade, everything was functioning correctly, and I haven't altered any other settings. However, I've run into an issue where self.location seems to cache a None value and it doesn't change. I found a temporary workaround by deleting the cache, which resolves the problem. Has anyone else experienced this or have any ideas on why this is happening? Code Snippet: class StaticFilesStorage(ManifestStaticFilesStorage, S3Boto3Storage): def __init__(self, *args, **kwargs): S3Boto3Storage.__init__(self, bucket_name=settings.STATIC_FILES_BUCKET, custom_domain=domain(settings.STATIC_URL), *args, **kwargs) ManifestStaticFilesStorage.__init__(self, *args, **kwargs) Error Message: Error output PDB Output: PDB output in ManifestStaticFilesStorage initializing After refreshing the cached value manually the error is resolved -
Django prefetch_related with multiple filters
Lets say this is my hypothetical codebase: class Address(models.Model): country = CountryField() ... class Location(models.Model): address = models.ForeignKey(Address, on_delete=models.CASCADE) class Zoo(models.Model): location = models.ForeignKey(Location, on_delete=models.CASCADE, related_name="zoos") class Animal(models.Model): name = CharField(max_length=200) animal_type = CharField(max_length=200) zoo = models.ForeignKey(Zoo, on_delete=models.CASCADE, related_name="animals") def animals_of_type_at_zoo(animal_type, zoo): return zoo.animals.filter(animal_type=animal_type) def generate_report(): report_data = {} animal_types = ["lion", "tiger", "bear", ...etc] locations = Location.objects.all() locations = locations.prefetch_related("zoos", "zoos__animals") for loc in locations.all(): for zoo in locations.zoos.all(): for animal in animal_types: report_data[loc.address.country][animal] += animals_of_type_at_zoo(animal, zoo).count() return report_data My goal is to make generate_report faster using prefetching. In this case I have added locations.prefetch_related("zoos", "zoos__animals"). However, since animals_of_type_at_zoo uses a filter, it triggers another query. My thought process was to prefetch each filter: locations = locations.prefetch_related("zoos", "zoos__animals") for animal in animal_types: locations = locations.prefetch_related(Prefetch("zoos_animals", queryset=Animals.objects.filter(animal_type=animal)) However zoos_animals can only be assigned once, I can't create multiple filters for this. My goal here is to prefetch everything needed with minimal impact to the animals_of_type_at_zoo function as it is used in other parts of the codebase and I want to minimize impact on the rest of the application (testing and performance). I had attempted to create custom object that override filter and would return the correct prefetch, but wasn't getting … -
RuntimeError: Failed to lock Pipfile.lock
I tried to install mysqlclient using the command Pipenv install mysqlclient. I get this error: RuntimeError: Failed to lock Pipfile.lock!. What does this mean, and how can I fix it? -
django-nose nose-py3 unit test shows the string None in the output even when successful
I have installed: django-nose==1.4.7 nose-py3==1.6.3 pinocchio==0.4.3 added django_nose to the INSTALLED_APPS added the lines: TEST_RUNNER = 'django_nose.NoseTestSuiteRunner' NOSE_ARGS = ['--with-spec', '--spec-color'] to the settings.py file in django created the following unit tests: def test_run_creation(self): """Test if the creation of runs creates instances of the Run model.""" self.assertIsInstance(self.run1, Run) self.assertIsInstance(self.run2, Run) self.assertIsInstance(self.run3, Run) def test_run_number_consistency(self): """Test if the number of runs in the project increases by 1 after run creation.""" self.assertEqual(self.final_no_of_runs_in_project, self.initial_no_of_runs_in_project + 1) the test run successfully and produce the following output: nosetests --with-spec --spec-color --with-xunit --verbosity=1 Creating test database for alias 'default'... None - Test if the creation of runs creates instances of the Run model. None - Test if the number of runs in the project increases by 1 after run creation. ---------------------------------------------------------------------- Ran 2 tests in 0.046s OK Destroying test database for alias 'default'... I would like to replace the String None in the output with something more descriptive but i have no idea what generate that text. Can anyone please help? Thank you -
I'm getting a "Connection unexpectedly closed" whenever I try to send an email with django hosted with Cloud Run. How do I diagnose this?
In my settings.py: EMAIL_BACKEND = django.core.mail.backends.smtp.EmailBackend EMAIL_HOST = smtp-relay.gmail.com EMAIL_HOST_USER = env('EMAIL_HOST_USER') EMAIL_HOST_PASSWORD = env('EMAIL_HOST_PASSWORD') EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_USE_SSL = False the line that actually sends the mail in one of the api end points is send_mail(subject, body, email_from, recipient_list) I can confirm with logs that the user and password is correct. I also can confirm that this works locally when I run it on my local environment. The issue is when I deploy this via Google Cloud Run I'm just getting Connection unexpectedly closed with no stacktrace and no information. From the Networking tab in cloud run I have allowed all ingress and have not set up any VPC network so I don't think it's that, however because of the nature of containerizing my app I don't know what else it could really be. What else would you try to diagnose and search? -
I have a django app running on a cpanel's subdomain. The challenge I am experiencing is I have ajax buttons that are not returning data
This is in my views.py ` def minuscreditcart(request): if request.method == 'GET': product_id = request.GET['prod_id'] print(product_id) print("GET MINUS {}", product_id) c = CreditCart.objects.get(Q(ordered=False) & Q(product=product_id) & Q(customer=Customer.objects.get(user_account=request.user))) if c.quantity <=1: pass else: c.quantity -= 1 c.save() cart = CreditCart.objects.filter(Q(customer=Customer.objects.get(user_account=request.user)) & Q(ordered=False)) creditApp = Credit_Facility_Application.objects.get(Q(disclaimer=False) &Q(customer=Customer.objects.get(user_account=request.user))) instal = Instalment.objects.get(application_form=creditApp) amount = 0 period = instal.period deposit = instal.deposit period = int(period) customer = Customer.objects.get(user_account=request.user) try: employment = Employment_detail.objects.get(customer=customer) employmentInfo = EmploymentForm(instance=employment) net_salary = employment.net_salary credit_limit = net_salary * 0.25 creditlimit = credit_limit except: credit_limit = False employmentInfo = EmploymentForm() admincharge = 0.03 ; mothlycharge = 0.08; ssbcharge = 0.05; for p in cart: value = p.quantity * p.product.discount_price amount = amount + value totalamount = amount balance = (1 + admincharge) * totalamount; depositlimit = int(balance * 0.3); balance = balance - deposit; totalmonthlycharges = mothlycharge * period; aftermonthlycharges = (1 + totalmonthlycharges) * balance; totalamount = ((1 + ssbcharge) * aftermonthlycharges) instalment = (totalamount / period) myinstalment = round(instalment, 2) data = { 'quantity':c.quantity, 'amount':amount, 'totalamount':totalamount, 'myinstalment':myinstalment, 'period':period, 'depositlimit':depositlimit, } return JsonResponse(data) This is the respective ajax code $('.minus-credit-cart').click(function(){ var id=$(this).attr("pid").toString(); var eml=this.parentNode.children[2]; $.ajax({ type:"GET", url:"/minus-credit-cart", data:{ prod_id:id }, success:function(data){ eml.innerText=data.quantity document.getElementById("amount").innerText=data.amount; document.getElementById("totalamount").innerText=data.myinstalment; document.getElementById("period").innerText=data.period; document.getElementById("depositamount").innerText = data.depositlimit; document.getElementById("depo").innerText = "Deposit … -
save() prohibited to prevent data loss due to unsaved related object 'classes'
Hello Help me please When I register the information, the first form saves the information, but when I register the second information, it gives an error and does not save the information. views.py class ClassesInline(): form_class = ClassesForm model = Classes template_name = "classes/classes_create_or_update.html" def form_valid(self, form): named_formsets = self.get_named_formsets() if not all((x.is_valid() for x in named_formsets.values())): return self.render_to_response(self.get_context_data(form=form)) kelas = form.save(commit=False) kelas.term = self.request.user.term kelas.branch = self.request.user.branch kelas.personnel_create = self.request.user self.object = kelas.save() for name, formset in named_formsets.items(): formset_save_func = getattr(self, 'formset_{0}_valid'.format(name), None) if formset_save_func is not None: formset_save_func(formset) else: formset.save() return redirect('kelas:classes_index') def formset_variants_valid(self, formset): reservs = formset.save(commit=False) # self.save_formset(formset, contact) # add this, if you have can_delete=True parameter set in inlineformset_factory func for obj in formset.deleted_objects: obj.delete() for reserv in reservs: reserv.classes = self.object reserv.save() class classesCreate(ClassesInline, CreateView): def get_form_kwargs(self): kwargs = super().get_form_kwargs() kwargs['request'] = self.request return kwargs def get_context_data(self, **kwargs): ctx = super(classesCreate, self).get_context_data(**kwargs) ctx['named_formsets'] = self.get_named_formsets() return ctx def get_named_formsets(self): if self.request.method == "GET": return { 'reservs': ReservationFormSet(prefix='reservs'), } else: return { 'reservs': ReservationFormSet(self.request.POST or None, prefix='reservs'), } The error that is observed and its reason -
AttributeError: Can't get attribute 'tokenizer' on <module '__main__'
I am trying to use y machine learning model in my Django but I have been getting so many error, and this is my first time of doing something like this. I need help the following is my view code # BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)) nltk.download('punkt') logger = logging.getLogger(__name__) # Load your AI model current_directory = os.path.dirname(os.path.abspath(__file__)) model_file_path = os.path.join(current_directory, 'ml_model/phishing_url_model.joblib') tfidf_vectorizer_path = os.path.join(current_directory, 'ml_model/tfidf_vectorizer.joblib') # tfidf_vectorizer = joblib.load(tfidf_vectorizer_path) # model = joblib.load(model_file_path) class UnregisteredScanCreate(generics.CreateAPIView): serializer_class = UnregisteredScanSerializer def tokenizer(self, url): # Your tokenizer code here """Separates feature words from the raw data Keyword arguments: url ---- The full URL :Returns -- The tokenized words; returned as a list """ tokens = re.split('[/-]', url) for i in tokens: if i.find(".") >= 0: dot_split = i.split('.') if "com" in dot_split: dot_split.remove("com") if "www" in dot_split: dot_split.remove("www") tokens += dot_split return tokens def create(self, request, *args, **kwargs): try: # Load the trained TF-IDF vectorizer tfidf_vectorizer = joblib.load(tfidf_vectorizer_path) # Load the trained model model = joblib.load(model_file_path) # Get the URL from the request data url = request.data.get("url", "") if not url: return Response({"error": "URL is required"}, status=status.HTTP_400_BAD_REQUEST) # Transform the URL into a numeric format using the fitted vectorizer url_features = tfidf_vectorizer.transform([url]) # Predict … -
Popen subprocess giving wrong ffmpeg process ID when trying to close
I'm trying to create a Video Management System application using React and Django, that displays live camera stream and do video recording. For this, I add cameras using POST request and everything works fine. But when I am required to update a camera's details, like IP address or password, then first I delete the camera and then create a new instance with same camera name. The problem I'm facing is that the process ID of the camera (ffmpeg instance here) is not updating, e.g. if initially the process ID was 10, then it remains 10 (in terminate() function in the code) even when I re-create the camera with new details but I do get new process ID in start() function. Below is the code: import subprocess from subprocess import Popen import os, sys import threading import time from datetime import datetime import pytz import os, signal """This class is used to create camera objects to display live stream and recordings, it is also used to manage recordings files by deleting them at the given time""" class CameraStream: def __init__(self, device_name, username, password, ip_address, storage_days): self.cam_name = device_name self.username = username self.password = password self.cam_ip = ip_address self.storage_days = storage_days self.p1 … -
How to Query If An Instance Exists Within A Many-To-Many Field On Django Queryset
Here are simplified model definitions class Resource(models.Model): name = models.CharField(max_length=100, unique=True) class Location(models.Model): name = models.CharField(max_length=100, unique=True) resources = models.ManyToManyField(Resource) And I want to know for one type of Resource, the existence on each Location. So the json data I want is like [ { "id": 1, "name": "loaction_A", "resource": true }, { "id": 2 "name": "location_B", "resource": false }, ... ] I tried following view function but obviously got wrong results. def resource_view(request, res_id): res = get_object_or_404(Resource, pk=res_id) locations = Location.objects.values('id', 'name')\ .annotate(resource=Q(resources=res)) return JsonResponce({'locations': list(locations)}) I know I need something like below (in SQL) select app_location.*, 1 in ( select resource_id from app_location_resources where location_id = app_location.id ) as resource from app_location How should I construct the queryset? -
Is the Use of Django Templates Common in Backend Python Jobs, or is it Typically Used Primarily for API and Business Logic Development?"
In the job market, I see many Python backend positions, and many of them require knowledge of the Django framework. However, as I started studying Django, I noticed that it uses templates as part of its architecture. In practice, are templates heavily used, or do companies typically have a frontend person using some JavaScript framework and a backend person using Django more for building APIs and implementing business logic? me as a Backend developer should focus in learn templates or learn build api in django with django rest? I'm new to Django and exploring backend Python job opportunities. I've noticed that Django uses templates in its architecture, but I'm curious about the practical use of templates in the industry. Have you encountered a situation where Django templates are widely used in backend development roles, or is it more common for companies to have a frontend specialist using JavaScript frameworks while Django is primarily utilized for API development and business logic implementation? -
Update an ImageField that is uploaded to S3 - REST API - FormData
I have created the following Django model: def upload_image(user, filename): ext = filename.split('.')[-1] return '%s/user_image.%s' % (user.image_path, ext) class CustomUser(AbstractUser): ... profile_picture = models.ImageField(default='default.png', upload_to=upload_image) @property def image_path(self): return f"{self.role}/{self.username}" And I have installed the storage package with which I upload the photos to a S3 bucket with the following configurations: if AWS_STORAGE_BUCKET_NAME' in os.environ: AWS_ACCESS_KEY_ID = os.environ['AWS_ACCESS_KEY_ID'] AWS_SECRET_ACCESS_KEY = os.environ['AWS_SECRET_ACCESS_KEY'] AWS_STORAGE_BUCKET_NAME = os.environ['AWS_STORAGE_BUCKET_NAME'] AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_S3_FILE_OVERWRITE = False STORAGES = { # Media file (image) management "default": { "BACKEND": "storages.backends.s3boto3.S3StaticStorage", }, # CSS and JS file management "staticfiles": { "BACKEND": "storages.backends.s3boto3.S3StaticStorage", }, } When I create a new custom user, the photo is uploaded correctly. if 'profile_picture' in self.validated_data: account.profile_picture = self.validated_data['profile_picture'] account.save() However, when I try to update the photo in the same way (with save), it does not work. How upload_image is only called the first time when initiating the model ? -
Django APIView returns “IndexError: list index out of range” in unit test but works in Postman
I have written an APIView in Django that returns a random line from a database table. When I test it using Postman, I get the response I want. However, when I call the URL of the endpoint in a unit test, I get an “IndexError: list index out of range” error. Here’s my code: Endpoint - def get(self, request, **kwargs): all_the_pickup_id = PickupData.objects.values_list('id', flat=True) # if not all_the_pickup_id: # return Response("No pickup lines found.") random_id = random.choice(all_the_pickup_id) random_pickup = PickupData.objects.get(id=random_id) random_line = random_pickup.text return Response(random_line) Unit Test Code - def test_text_response(self): client = APIClient() response = client.get('/getPickup/getUnitTest/') self.assertEqual(response['Content-Type'], 'application/json') print('Get Pickup',response.content) self.assertEqual(response.status_code, status.HTTP_200_OK) How can I fix this error and make my unit test work? -
Access to related model field in django_filters
I'm constructing Django-based 4-language website for a real estate agency. I'm using django-filter package to filter my objects (real estate properties) by certain parameters, such as type (house, apartment, etc.), city and some others. My 'type' field is a foreign key for the model 'Type'. On the html page this field is tendered as a field with options, which is good. But for some reason the options are rendered as slug names of my types ('house', 'apartment', etc., see the picture). It is the 'slug' field of my foreign key model Type. Instead of this, I want to print 'name' field in the options. This field is translated (django-modeltranslation package), so that in English version one should see options 'House', 'Apartment'..., and in Spanish version - 'Casa', 'Apartamento', etc. I tried modify this field in my PropertyFilter as using '__' symbol (type__name instead of type), but it doesn't seem to work. Please, help me, I'm stuck! -
which programming language should I choose? [closed]
I am a B.tech Information technology student , I am interested in both python and java but i have a doubt. which is best for software development python or java . which has the high scope for freshers? if any these language is best for software development the which frame work is suitable and which is trend today? -
How to manage serializers in Django Rest Framework?
I use the following serializer in my ViewSet to create some Instance: class InstanceCreateSerializer(ModelSerializer): class Meta: model = Instance fields = [ "id", "name", "description", "company", "err_msg", "is_valid", ] The fields author, company, is_valid and err_msg must be set by the service, not by the user. But if i use read_only_fields, as in the code below, then these fields cannot be changed by the service either. class InstanceCreateSerializer(ModelSerializer): class Meta: model = Instance fields = [ "id", "name", "description", "author", "company", "err_msg", "is_valid", ] read_only_fields = [ "author", "company", "err_msg", "is_valid", ] How can I manage serializers or prevent the user from submitting values for these fields? Additionally, these fields are available for input in the DRF Browsable API and Swagger, which is something I also want to fix. -
CKeditor not working on PythonAnywhere, working on localhost (Django)
I have simple blog project that I want to show on pythonanywhere. Unfortunatelly I cant seem to fix issue with CKeditor. It works on localhost, but on pythonanywhere it shows errors and only standard text editor window. Errors in console](https://i.stack.imgur.com/SCTnH.png) I did try solutions here on Stackoverflow. I did try to run collectstatics etc. Nothing helped so far. I found that someone said That Pythonanywhere wont ever be able to run CKeditor but I didnt find more about it. If CKeditor is not gonna work, do you know about any other rich text editor that will work? I need one with picture editing. Also here is the webppage on Pythonanywhere.com. Thank you for any advice. I will provide code if needed I just didnt know which part exactly would make this issue. -
Djoser UserViewSet, getting 401 Unauthorized `as_view("get": "list")`
When I test the endpoint using POSTMAN I am getting 401 Unauthorized. { "detail": "Authentication credentials were not provided." } enlighten me accounts.views.py from django.shortcuts import render from djoser.views import UserViewSet from .serializers import UserCreateSerializer, ResidentRegistrationSerializer from rest_framework import status from rest_framework.response import Response # Create your views here. class ResidentRegistrationView(UserViewSet): serializer_class = ResidentRegistrationSerializer # custom serializer # override the create method to enforce the required fields def create(self, request, *args, **kwargs): # check if address_info data is provided in the request if "address_info" not in request.data: return Response({"Error": "Address information is required."}, status=status.HTTP_400_BAD_REQUEST) # call the parent class's create method return super().create(request, *args, **kwargs) accounts.urls.py from django.urls import path from .views import ResidentRegistrationView urlpatterns = [ path("register/resident/", ResidentRegistrationView.as_view({"get": "list"}), name="resident-registration") ] accounts.serializers.py from djoser.serializers import UserCreateSerializer from django.contrib.auth import get_user_model from .models import ResidentProfile, AddressInformation User = get_user_model() class UserCreateSerializer(UserCreateSerializer): class Meta(UserCreateSerializer.Meta): model = User fields = ("id", "email", "password") class ResidentRegistrationSerializer(UserCreateSerializer): class Meta(UserCreateSerializer.Meta): model = ResidentProfile fields = ( "first_name", "middle_name", "last_name", "date_of_birth", "gender", "relationship_status", "phone_number", "address_info", ) -
Django ORM get record with latest date
This is the data I have: class RdpUserPasswordHash(models.Model): user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, related_name='password_hash') when = models.DateTimeField(auto_now_add=True, db_index=True) select id, "when", user_id from registry_rdpuserpasswordhash where user_id =3; 1 2023-07-29 10:55:41.193 +0200 3 2 2022-08-09 10:55:41.236 +0200 3 I need to filter getting for each user_id the latest record wrt "when" and I do not find a reliable way to do it with the ORM. (1) for r in RdpUserPasswordHash.objects.order_by('user_id', '-when').distinct('user_id'): if r.user_id==3: print(r) <RdpUserPasswordHash: RdpUserPasswordHash object (1)> RdpUserPasswordHash object (1) is the one with the latest date (2) RdpUserPasswordHash.objects.order_by('user_id', '-when').distinct('user_id').filter(when__lt=timezone.now() - td_expire_days) <QuerySet [<RdpUserPasswordHash: RdpUserPasswordHash object (2)>]> But I need to now, among the ones with the latest date which one is expired but with the above query I get the unexpected result. Unexpected because it is not in RdpUserPasswordHash.objects.order_by('user_id', '-when').distinct('user_id') So adding a filter actually changes the result of the initial queryset. QUERIES generated by the ORM: (1) SELECT DISTINCT ON ("registry_rdpuserpasswordhash"."user_id") "registry_rdpuserpasswordhash"."id", "registry_rdpuserpasswordhash"."user_id", "registry_rdpuserpasswordhash"."password_hash", "registry_rdpuserpasswordhash"."when" FROM "registry_rdpuserpasswordhash" INNER JOIN "registry_rdpuser" ON ("registry_rdpuserpasswordhash"."user_id" = "registry_rdpuser"."id") WHERE ("registry_rdpuser"."is_active" AND "registry_rdpuserpasswordhash"."when" < '2023-07-28T08:23:32.599017+00:00'::timestamptz) ORDER BY "registry_rdpuserpasswordhash"."user_id" ASC, "registry_rdpuserpasswordhash"."when" DESC LIMIT 21 (2) SELECT DISTINCT ON ("registry_rdpuserpasswordhash"."user_id") "registry_rdpuserpasswordhash"."id", "registry_rdpuserpasswordhash"."user_id", "registry_rdpuserpasswordhash"."password_hash", "registry_rdpuserpasswordhash"."when" FROM "registry_rdpuserpasswordhash" INNER JOIN "registry_rdpuser" ON ("registry_rdpuserpasswordhash"."user_id" = "registry_rdpuser"."id") WHERE ("registry_rdpuser"."is_active" AND … -
Trying to install Helios requirements
Building wheel for python-ldap (pyproject.toml) ...Error ERROR: Failed building wheel for python-ldap Failed to build python-ldap ERROR: Could not build wheels for python-ldap, which is required to install pyproject.toml-based projects -
Problem with user uploading images in django
I want to use the Django framework to design a user personal picture uploading system. The completed content includes a Django project name named SGV. The project inclue a name call Success app to handle various requests from users. After the user logs in, It will jump to a webpage named userhome.html. I want to upload pictures of the current webpage in this userhome without jumping to other pages. After the pictures are uploaded, they will be saved to the user_file/image folder in the root directory of the project. , the problem is that after I finished writing part of the code, I found that I could select the file, but nothing happened after clicking the upload image button, not even any error. Is there any kind person who can help me, a newbie in Django? The following is some code within the project, which may not be fully displayed. If you want to know more, please tell me. Userhome.html <!DOCTYPE html> <html> <head> {% load static %} <title>SGV UserHome</title> <base href="/"> <link rel="stylesheet" type="text/css" href="{% static 'css/system.css' %}"> </head> <body> <div class="nav"> <h1>Welcome to User Home</h1> <form method="post" enctype="multipart/form-data" id="upload-form"> {% csrf_token %} <input type="file" name="image" accept="image/*" id="image-input"> <button … -
Django Session, Login and Signup
This is my view module def home(request): return render(request, 'rescues_site/home_page.html') # @login_required def user_home(request): if request.method == 'POST': username = request.session.get('username') context = { 'username': username } return render(request, 'rescues_site/home_page.html', context) def login(request): if request.method == 'GET': return render(request, 'registration/login.html') if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username = username, password = password) if user is not None and user.is_active and user.is_authenticated: login(request, user) request.session['username'] = user.username return redirect('user_home') else: return render(request, 'registration/login.html') @transaction.atomic def sign_up(request): if request.method == 'GET': return render(request, 'registration/sign_up.html') if request.method == 'POST': error = [] first_name = request.POST.get('first_name') last_name = request.POST.get('last_name') address = request.POST.get('address') suburb = request.POST.get('suburb') postcode = request.POST.get('postcode') email = request.POST.get('email') phone_number = request.POST.get('phone_number', None) password = make_password(request.POST.get('password')) try: user = CustomUser.objects.create(username = email, first_name = first_name, last_name = last_name, address = address, suburb = suburb, postcode = postcode, phone_number = phone_number, password = password) request.session['username'] = user.username return redirect('user_home') I tried to login the user and redirect the user to the home page with their cresidentials but what I have is a POST request in the terminal and it take me nowhere. I'm still new to Django and Python. Thank you for your time! -
CSRF Error event after adding CORS_TRUSTED_ORIGINS Django
I am trying to implement feature for changing password but when I make a put request from react frontend to django backend I am getting CSRF error. I am not getting such an error for other put/post requests. Following are the code details: settings.py REST_FRAMEWORK = { # 'DEFAULT_PERMISSION_CLASSES': [ # 'rest_framework.permissions.IsAuthenticated', # ], # 'DEFAULT_AUTHENTICATION_CLASSES': [ # 'rest_framework_simplejwt.authentication.JWTAuthentication', # ], 'DEFAULT_PAGINATION_CLASS': 'main.paginations.CustomPagination', 'PAGE_SIZE': 12 } CORS_ORIGIN_ALLOW_ALL = False CORS_ALLOWED_ORIGINS = [ "http://127.0.0.1:8000", "http://127.0.0.1:3000", "http://localhost:3000", ] CORS_TRUSTED_ORIGINS = [ 'http://localhost:3000', ] views.py class ChangePasswordView(generics.UpdateAPIView): queryset = User.objects.all() serializer_class = serializers.ChangePasswordSerializer serializers.py class ChangePasswordSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True, required=True) password2 = serializers.CharField(write_only=True, required=True) old_password = serializers.CharField(write_only=True, required=True) class Meta: model = models.User fields = [ 'old_password', 'password', 'password2' ] def validate(self, attrs): if attrs['password'] != attrs['password2']: raise serializers.ValidationError({'password': 'Password fields did not match!'}) return attrs def validate_old_password(self, value): user = self.context['request'].user if not user.check_password(value): raise serializers.ValidationError({'old_password': 'Old password provided is incorrect!'}) return value def update(self, instance, validated_data): user = self.context['request'].user print(user) if user.pk != instance.pk: raise serializers.ValidationError({"authorize": "You don't have permission to change password!",}) instance.set_password(validated_data['password']) instance.save() return instance urls.py ... path('change_password/<int:pk>/', views.ChangePasswordView.as_view(), name='auth_change_password'), ... Frontend: const link = `${BASE_URL}${CHANGE_PASSWORD_URL}${customer_id}`; const formData = new FormData(); formData.append('old_password', oldPwdRef.current.value); formData.append('password', newPwdRef.current.value); formData.append('password2', confirmNewPwdRef.current.value); axios.put(link, formData, …