Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Faile to load resource: the server responded with a status of 500 (Internal Server Error)
my web page runs normally, until i do a javascript AJAX snippet, it starts showing error 500 in cart function at the plus sign, when I click add it just increases the amount in the data and has to reload the page to see the number quantity, the user side won't see it script in html <script src="https://code.jquery.com/jquery-3.6.4.min.js" integrity="" crossorigin="anonymous"></script> Views.py def add_to_cart(request): user = request.user product_id = request.GET.get('prod_id') product = Product.objects.get(id=product_id) Cart(user=user, product=product).save() return redirect('/cart') def show_cart(request): if request.user.is_authenticated: user = request.user cart = Cart.objects.filter(user=user) amount = 0.0 shipping_amount = 10.0 total_amount = 0.0 cart_product = [p for p in Cart.objects.all() if p.user == user] if cart_product: for p in cart_product: tempamount= (p.quantity * p.product.final_price) amount += tempamount total_amount = amount+ shipping_amount context = {'cart':cart, 'total_amount':total_amount, 'amount':amount,'shipping_amount':shipping_amount} return render(request, 'general/addtocart.html', context) else: return redirect('login') def plus_cart(request): if request.method == 'GET': prod_id = request.GET['prod_id'] c= Cart.objects.get(Q(product=prod_id) & Q(user = request.user)) c.quantity+=1 c.save() amount = 0.0 shipping_amount = 10.0 cart_product = [p for p in Cart.objects.all() if p.user == request.user] for p in cart_product: tempamount= (p.quantity * p.product.final_price) amount += tempamount total_amount = amount+ shipping_amount data={ 'quantity':c.quantity, 'amount': amount, 'total_amount': total_amount }, return JsonResponse(data) Javascript.js $('.plus-cart').click(function () { //console.log("Click") var id … -
"[" was not closed what can i do to fix this
i keep getting this error but the bracket is actually closed i checked the entire work but to no avail. -
docker web container not finding the database from mysql container
i'm using docker and docker-compose for the local development host as we're working in a team of frontend developers and backend developer, using django as the backend with mysql as the sgbd, so the project was running well in docker( only the backend is dockerized), after the last commit everything crashed , so i'm getting the following logs from the web container : File "/usr/local/lib/python3.10/threading.py", line 953, in run 2023-04-25 23:13:25 self._target(*self._args, **self._kwargs) 2023-04-25 23:13:25 File "/usr/local/lib/python3.10/site-packages/django/utils/autoreload.py", line 64, in wrapper 2023-04-25 23:13:25 fn(*args, **kwargs) 2023-04-25 23:13:25 File "/usr/local/lib/python3.10/site-packages/django/core/management/commands/runserver.py", line 121, in inner_run 2023-04-25 23:13:25 self.check_migrations() 2023-04-25 23:13:25 File "/usr/local/lib/python3.10/site-packages/django/core/management/base.py", line 486, in check_migrations 2023-04-25 23:13:25 executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) 2023-04-25 23:13:25 File "/usr/local/lib/python3.10/site-packages/django/db/migrations/executor.py", line 18, in __init__ 2023-04-25 23:13:25 self.loader = MigrationLoader(self.connection) 2023-04-25 23:13:25 File "/usr/local/lib/python3.10/site-packages/django/db/migrations/loader.py", line 53, in __init__ 2023-04-25 23:13:25 self.build_graph() 2023-04-25 23:13:25 File "/usr/local/lib/python3.10/site-packages/django/db/migrations/loader.py", line 220, in build_graph 2023-04-25 23:13:25 self.applied_migrations = recorder.applied_migrations() 2023-04-25 23:13:25 File "/usr/local/lib/python3.10/site-packages/django/db/migrations/recorder.py", line 77, in applied_migrations 2023-04-25 23:13:25 if self.has_table(): 2023-04-25 23:13:25 File "/usr/local/lib/python3.10/site-packages/django/db/migrations/recorder.py", line 55, in has_table 2023-04-25 23:13:25 with self.connection.cursor() as cursor: 2023-04-25 23:13:25 File "/usr/local/lib/python3.10/site-packages/django/utils/asyncio.py", line 33, in inner 2023-04-25 23:13:25 return func(*args, **kwargs) 2023-04-25 23:13:25 File "/usr/local/lib/python3.10/site-packages/django/db/backends/base/base.py", line 259, in cursor 2023-04-25 23:13:25 return self._cursor() 2023-04-25 23:13:25 File … -
Using a pivot table to create a tree-like structure and how to create efficient queries?
In our codebase we have a set of models that represent AI models and their training data. When people train new models they are usually trained off an existing AI model in the database, and we wanted to track a sort of "versioning" of these models, so that people can use prior versions, and create branching revisions. our models look like so: class TrainingRun(models.Model): from_model = models.ForeignKey('api.AIModel', related_name='subsequent_runs') to_model = models.OneToOneField('api.AIModel', related_name='prior_run') hyperparameters = models.JSONField(default={}) # etc. class AIModel(models.Model): save_path = models.URLField(max_length=200, null=True) bookmarked_by = models.ManyToManyField('auth.User', related_name='bookmarks') # etc. we're expecting this data to come out looking something "linked-list"y so that users can create branching revisions to prior models, bookmark ones that they like etc. the data structure might come out to look something like a git revision history, without merge functionality but I'm wondering is this is a good idea inside a relational database with foreign keys etc. Also I am wondering if there is an efficient way to traverse the list of objects in a way where I could, say, get a list of any users inside the tree that have subscribed to a bookmark? It seems like no matter which way you slice it you'll be doing … -
How can I aggregate averages from two models for use in one model's field?
I have two models: class Review(models.Model): artist = models.CharField(max_length=100) album = models.CharField(max_length=200) rating = models.IntegerField( validators=[MinValueValidator(0), MaxValueValidator(10)], default=10, ) content = models.TextField(null=True, blank=True) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) ... class AddedReview(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) review = models.ForeignKey(Review, on_delete=models.CASCADE) rating = models.IntegerField(default=10) body = models.TextField() updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(default=timezone.now) ... The Review model is an initial review posted by a user. The AddedReview model is additional reviews users will be able to post on an initial Review The initial Review will have a rating added by the original user, and additional ratings will be added by other users. I want to be able to aggregate all the ratings from both models into an avg_rating field for use in the Review model. I know how to perform this in a Python shell but I'm not very knowledgable about how to create a model method to do this. -
You cannot access body after reading from request's data stream
I keep getting the following error when trying to post to PayPal: shippingData = json.loads(request.body) django.http.request.RawPostDataException: You cannot access body after reading from request's data stream I have tried removing the request.headers, this does nothing. I tried removing CRSF Token altogether and still the same error. I have also tried renaming request.body into a different variable, this also does not remove the error. Replacing with request.data just gives a different error also. This is my view: def create_order(request): customer = Customer.objects.get(user=request.user) shippingData = json.loads(request.body) first_name = customer.first_name last_name = customer.last_name ShippingAddress.objects.create( customer=customer, house=shippingData['shipping']['house'], street=shippingData['shipping']['street'], city=shippingData['shipping']['city'], postcode=shippingData['shipping']['postcode'], ) # assuming you have retrieved the ShippingAddress object for the given customer shipping_address_queryset = ShippingAddress.objects.filter(customer=customer) if shipping_address_queryset.exists(): shipping_address = shipping_address_queryset.first() # extract the necessary fields from the shipping_address object house = shipping_address.house street = shipping_address.street city = shipping_address.city postcode = shipping_address.postcode user_cart = Cart.objects.filter(user=request.user).first() if user_cart: # get cart items and total cart_items = user_cart.items.all() cart_total = user_cart.get_cart_total() # create the items list items = [] for item in cart_items: items.append({ "name": item.product.title, "description": "", "quantity": str(item.quantity), "unit_amount": { "currency_code": "GBP", "value": "{:.2f}".format(item.product.price) }, "tax": { "currency_code": "GBP", "value": "0.00" } }) # calculate the breakdown for the purchase unit item_total = sum(float(item["unit_amount"]["value"]) … -
Django: populate ID field with initial data in an upload image form
I want to create a form to upload ecography images for a specific "consulutation". when I click on add images buuton, the form should show with the field "Consultation_id" already filled with the ID of this consultation.the problem is that i Can't do that using views.py here is my code : models.py class Echographie(models.Model): created_at = models.DateField(auto_now_add=True) consultation_id=models.ForeignKey(Consultation,on_delete=models.CASCADE,) image=models.ImageField(blank=True, null=True,upload_to="images/echo/") @property def nom_patient(self): return self.consultation_id.nom_patient form.py: class NewEchographieForm(forms.ModelForm): image=forms.ImageField(required=False) class Meta: model = Echographie fields = ['consultation_id','image'] views.py: def echographie(request,pk): current_consultation = Consultation.objects.get(id=pk) form = NewEchographieForm(request.POST or None,request.FILES,initial={'consultation_id':[current_consultation.id]} ) if request.user.is_authenticated: if request.method == "POST": if form.is_valid(): add_image = form.save() messages.success(request, "Image added successfully....") return redirect('home') return render(request, 'echographie.html', {'form': form, 'current_consultation': current_consultation}) else: messages.success(request, "You should login in....") return redirect('home') Can you help me? -
I want to implement django-polaris deposit and withdrawal integration
I'm building an anchor with django-polaris on the stellar network using the readthedocs tutorial. I'm stuck at the Enable Hosted deposit and withdrawals. Here is the code for the deposit integration; from decimal import Decimal from django import forms from rest_framework.request import Request from polaris.models import Transaction from polaris.templates import Template from polaris.integrations import ( DepositIntegration, WithdrawIntegration, TransactionForm ) from .users import user_for_account, create_user class AnchorDeposit(DepositIntegration): def form_for_transaction( self, request: Request, transaction: Transaction, post_data: dict = None, amount: Decimal = None, *args, **kwargs ): # if we haven't collected amount, collect it if not transaction.amount_in: if post_data: return TransactionForm(transaction, post_data) else: return TransactionForm(transaction, initial={"amount": amount}) # if a user doesn't exist for this Stellar account, # collect their contact info user = user_for_account( transaction.muxed_account or transaction.stellar_account ) if not user: if post_data: return ContactForm(post_data) else: return ContactForm() # if we haven't gotten the user's full address, colelct it elif not user.full_address: if post_data: return AddressForm(post_data) else: return AddressForm() # we don't have anything more to collect else: return None def after_form_validation( self, request: Request, form: forms.Form, transaction: Transaction, *args, **kwargs, ): if isinstance(form, TransactionForm): # Polaris automatically assigns amount to Transaction.amount_in return if isinstance(form, ContactForm): # creates the user to … -
How can I deal with data creation that depends on response of a microservice?
I have two microservices: one is responsible for manage players and the other is responsible for manage authentication/authorization. When I create a new player inside the player microservice I make a call to create the auth data like: auth_data = create_auth_object(data) # This will make a post in auth microservice and after it I use the ID return from auth microservice to create players infos like: data_example = { auth_id: auth_data.get("id"), #sometimes auth_data is empty (explained below) name: "example", real: "example2" } create_player(data_example) but sometimes the auth microservice return a timeout error (some GCP problem) and I cant create the player without the ID from auth microservice, but the auth data has been created in the database even I got the timeout error. So, if I try to create the player again I will receive an error that show the player already exists, but only the auth data exists, the player data was not created. How is the proper way to deal with It? Tell me if you need more details. -
How would you implement a front end file editor? [closed]
As title suggests, I want to implement a file editor for users, so that they can upload their own .txt, .py, .md files and edit them directly on front end. I already have the upload part, but I can't seem to figure out how to implement the file editor, I've been thinking on CKeditor but I do not know how to provide it with the file so it displays it's contents. The best guess I have while researching online is to parse the file and the provide ckeditor with it as context, but how would you do it? -
I want to send excel file with post API with a body of form-data in python/Django
this is the format Here is the code (https://i.stack.imgur.com/Yv60u.png) I've tested it with (https://i.stack.imgur.com/6boPz.png) I've checked the url. I got JSON response content-404 and status code-500 when I run that but if I send from postman it works. Do I have to contact API team or what is the problem? -
DRF return errors from model validation
I have models and serializers. Errors that are returned from the serializer are helpful because I can send them as a response to API and user can correct invalid data. However, errors that are from models are useless for me. They return 500 error and they don't have a body that I can send back to the user. Should I overide validate method even more to give me some usable errors or there is a method for that? models class School(models.Model): SUBJECT = ( ('Math', 'Mathematic'), ('Eng', 'English'), ('Cesolved', 'Chemistry'), ) name = models.CharField(blank=False, max_length=50) subject = models.CharField(choices=SUBJECT, max_length=15, blank=False) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return str(f'{self.name} is {self.subject}') serializers class SchoolSerializer(serializers.ModelSerializer): subject = serializers.ChoiceField(choices=School.SUBJECT) def validate(self, data): name = data["name"] if (5 > len(name)): raise serializers.ValidationError({"IError": "Invalid name"}) return data class Meta: model = School fields = "__all__" views class SchoolViewSet(viewsets.ModelViewSet): queryset = School.objects.all() serializer_class = SchoolSerializer def create(self, request): serializer = SchoolSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) for example, if name is shorter than 5 i return a kinda helpful error but when name is to long and I let the django models return the error only thing that I … -
Attribute error str object has no attribute get while submitting form
This is the ObjectCreateMixin class which from which my TagCreate class inherits from django.shortcuts import redirect, render class ObjectCreateMixin: form_class = None template_name = '' def get(self, request): return render( request, self.template_name, {'form': self.form_class()}) def post(self, request): bound_form = self.form_class(request.POST) if bound_form.is_valid(): new_object = bound_form.save() return redirect(new_object) else: return render( request, self.template_name, {'form': bound_form} ) Here is My TagCreate class class TagCreate(ObjectCreateMixin, View): form_class = TagForm template_name = 'organizer/tag_form.html' I am trying to create Tag object by passing the name and slug in form but whenever i submit form it gives error ATTRIBUTE error 'str' has no attribute 'get' -
I am trying to communicate between a r307 finger print sensor and a Django website using arduino and esp32
I am creating a Django website which reads finger prints and replies in true or false using the r307 finger print sensor, arduino and Esp32. Can anyone guide me how to do that. I have connected the finger print sensor with the arduino IDE and it enrolls and verifies finger prints successfully but I can not figure out how to connect it with my website. I am making a Django project. All I want it it read the fingerprint and respond in true or false. -
Combining Django Rest Framework with Python Azure Functions for bulk data retrieval - better alternatives?
I developed a Django Rest Framework application, which serves as the backend to my website. The app can retrieve data from an external API in bulk, for a given Django queryset that is retrieved from the request parameters. I have created a Django APIView that first retrieves the Django queryset from my Postgres database, using the standard DjangoFilterBackend and then makes a separate HTTP call for each unique ID in the queryset. Since the queryset can be quite big (1000+ records), implementing this in a 'standard' synchronous Django view was very slow. Hence I have decided to implemented the external API datea retrieval part as a (Python) Azure Function. This takes all the unique IDs from the retrieved Django Queryset as input in one JSON and then makes async calls in parallel for each ID using the asyncio and aiohttp modules. Below is a snippet of my Python code within the Azure Function that calls the external API: import asyncio import aiohttp async def call_external_api(session, unique_id) -> dict: ## Set params for request params = {'id': unique_id, 'apiKey': API_KEY} async with session.get(EXTERNAL_API_ENDPOINT, params=params) as resp: response_json = await resp.json() response_status_code = resp.status The communications within my current set-uplook somewhat like … -
Django file sharing system
Inspired by a idea of wetransfer.com, i decided to create a similar app with the same functionality. This is a one page app. And i got stuck a bit. The question itself is about system design rather than writting a code. On the high level the following is happening: A user selects files Once a file list is formed and an user presses a button to get a link, ajax-request is being initialized with files upload Once files upload ended, an unique link is being formed and a client gets it Easy, but i'm really confused how to make it well from design viewpoint Let's start from the beginning. How i see that (without too detailed things): Let's say there will be a temporary folder for forming a final user hierarchy and a final folder for storing a ready-download archive like this: TEMP_USER_FILES = os.path.join( BASE_DIR, "tmp") FINISHED_USER_FILES = os.path.join( BASE_DIR, "files") Technically i've done something like this: There are two inputs (in index.html): for files and folders respectively. JS creates a new empty FormData If it gets a file: a file is beeing added into FormData as key: value, where key is a file name and key is a … -
Django form in templatags
I need to place my form diffrent pages. How can I render form in my html? templatetags.py(https://i.stack.imgur.com/um4GL.png) -
How do I retrieve every row that is at least `interval` apart with Django's ORM?
Suppose I have the following model: class MyModel(Model): timestamp = models.DateTimeField(auto_now=True) ... I'd like to retrieve every row for MyModel that is at least some interval (in seconds) from the previous row. Rows are typically added every 30s, but I'd like to get those that are 30s or more apart. I've tried a variety of different solutions with the following getting me the closest. queryset = MyModel.objects.annotate( time_diff=F("timestamp") - Window( expression=Lag("timestamp"), order_by=(F("timestamp"),) ) ) Obviously, it doesn't really do anything, but, unlike below, this doesn't immediately error out. The field time_diff exists when I try to use it (i.e. queryset.last().time_diff outputs a timedelta). However, when I try to .filter on time_diff, I get an error like NotSupportError: Window is disallowed in the filter clause. Some of the other, non-working, attempts I've tried are below (note that I'm also trying to limit the records to a specific date range, but that's working fine): start_date = datetime(...) end_date = datetime(...) time_interval = ... # total seconds time_diff_window = Window( expression=Lag('timestamp'), order_by=F('timestamp').asc(), ) queryset = MyModel.objects.filter( timestamp__range=(start_date, end_date), ).annotate( time_diff=Extract('timestamp', 'epoch') - Extract('lagged_timestamp', 'epoch'), lagged_timestamp=Lag('timestamp', default=start_date, over=time_diff_window), ).filter( time_diff__gte=time_interval, ).order_by('timestamp') window = Window(expression=Lag("timestamp"), order_by=F('timestamp').asc()) lagged_timestamp = Lag("timestamp", default=Value(timedelta(seconds=0), output_field=DurationField()), over=window,) # Compute the … -
Css is working fine in Firefox but will not load in Microsoft edge or Chrome
While coding in Django i was trying to customize my website with some css but while testing multiple webbrowsers i found out that the css is not being applied in Microsoft or Chrome. But its working in firefox. The css file is loading correctly in all browsers but is not being applied. My HTML: <!DOCTYPE html> <html> <head> {% load static %} <meta charset="UTF-8"> <link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}"/> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Roboto+Condensed&family=Roboto:wght@300&display=swap" rel="stylesheet"> <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@48,400,0,0" /> </head> <body> <label for="label1" id="label1">eeee</label> {% for card in cards %} <div class="card"> <img class="card_img" src="{{card.img.url}}" alt=""> <div class="card-content"> <h2 class="card_name" >{{card.name}}</h2> <p class="card_desc" >{{card.desc}}</p> </div> </div> {% endfor %} </body> </html> My css: *{ margin: 0; padding: 0; } /* Colors */ $color-primary-white: rgb(1, 240, 240); /* Colors */ #label1{ color: red; } body { display: flex; flex-direction: column; justify-content: center; align-items: center; padding: 50px; font-family: 'Roboto', sans-serif; } .card { width: 24rem; height: 36rem; border-radius: 10px; overflow: hidden; cursor: pointer; position: relative; color: #fff; box-shadow: 0 10px 30px 5px rgba(0, 0, 0, 0.2); } .card_img { position: absolute; object-fit: cover; width: 100%; height: 100%; top: 0; left: 0; opacity: 0.9; transition: opacity .2s … -
Zoho Oauth flow returning invalid client
I am trying to build a Oauth flow using python Django. The goal is to get the access token for zoho and save it to DB. but at the step where we exchange access token by sending authorization_code, I am getting invalid-client error. I couldn't figure out what's wrong. I have tried changing to .in domain in token url but that too didn't worked. -
Cannot run celery worker while importing playwright library
I'm trying to run a simple playwright code with celery as you can see below: @shared_task def get_title(): with sync_playwright() as playwright: browser = playwright.chromium.launch() page = browser.new_page() page.goto('https://github.com') print(page.title()) browser.close() When I start the celery worker I get this error immediately from command line. I've tried every possible way with playwright using sync/async methods bot none of them worked. When I remove playwright imports and code belong to it celery worker starts without any issues. I think the main issue is with the import order. I import playwright or select library before celery get imported but i got the similar error from command line like this 'select' has no attribute 'epoll' without the full traceback. # celery.py import os from celery import Celery os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.local") app = Celery("celery_app") app.config_from_object("django.conf:settings", namespace="CELERY") app.autodiscover_tasks() The code is running on python:3.9.6-slim-buster Full traceback code: Traceback (most recent call last): File "/usr/local/bin/celery", line 8, in <module> sys.exit(main()) File "/usr/local/lib/python3.9/site-packages/celery/__main__.py", line 15, in main sys.exit(_main()) File "/usr/local/lib/python3.9/site-packages/celery/bin/celery.py", line 217, in main return celery(auto_envvar_prefix="CELERY") File "/usr/local/lib/python3.9/site-packages/click/core.py", line 1130, in __call__ return self.main(*args, **kwargs) File "/usr/local/lib/python3.9/site-packages/click/core.py", line 1055, in main rv = self.invoke(ctx) File "/usr/local/lib/python3.9/site-packages/click/core.py", line 1657, in invoke return _process_result(sub_ctx.command.invoke(sub_ctx)) File "/usr/local/lib/python3.9/site-packages/click/core.py", line 1404, in invoke … -
How to use Django REST Framework to pass data from one app to another, and in different Docker containers?
My current university assignment consists of us making a cinema website. One of the requirements is that the payment system (I am using Stripe) needs to be a seperate application that runs on a seperate container, and we need to use the Django REST Framework to pass info between them. My trouble at the moment is that I don't understand how to go through the process of: Customer selects all the tickets they want for a viewing Pass that information to the Stripe Payment App and redirect the customer to the checkout page Process the customers payment, and redirect them back to the main cinema apps index page I've placed comments in the below code to point out exactly where and how I intend to do this, but I just don't understand how to implement it using REST Framework. Any help would be greatly appreciated. My code in the views.py file to process the ticket and showing selection the customer has made is: def make_booking(request, pk=None): form = ReservationForm() if pk: form.fields['showing'].initial = Showing.objects.get(id = pk) # If the submit button is pressed if request.method == 'POST': ............. # Code to handle extracting information from the customers form ............. if … -
Error in uploading image from a react form into django model using django rest framework
I am building a website using Django and React I want to create a form that enters data into a model containing image field. I have followed many tutorials to make this but I have failed to upload image into the Image field models.py: class entry(models.Model): title = models.CharField(max_length=600) body = models.TextField() entryCover = models.ImageField(upload_to='entrycover', blank=True, null=True) def __str__ (self): return self.title serializers.py: class EntryFormSerializer(serializers.ModelSerializer): entryCover = serializers.ImageField(required=False) class Meta: model = entry fields = ['title', 'body', 'entryCover'] views.py: class EntryFormViewSet(viewsets.ModelViewSet): queryset = entry.objects.all() serializer_class = EntryFormSerializer parser_classes = (MultiPartParser, FormParser) def post(self, serializer): serializer.save(creator=self.request.user) urls.py: urlpatterns = [ path('entryForm/', views.EntryFormViewSet) ] in Form.js: import React from "react"; import Select from 'react-select' import axios from 'axios'; import { AxiosInstance } from "axios"; export default function Form(){ const [inputs, setInputs] = React.useState({}); const handleImageChange = (e) => { console.log(e.target.files[0]) let image = e.target.files[0] setInputs(values => ({...values,'entryCover' : image})) }; const handleChange = (event) => { const name = event.target.name; const value = event.target.value; setInputs(values => ({...values, [name]: value})) } const handleSubmit = (event) => { event.preventDefault() let form_data = new FormData(); form_data.append('entryCover', inputs.entryCover, inputs.entryCover.name); form_data.append('title', inputs.title); form_data.append('body', inputs.body); axios.post('/entryForm/', form_data, { headers: { 'Content-Type': 'multipart/form-data' } }).then(res => { console.log(res); }).catch(err … -
Prevent the user from going to the URL manually
I am writing a website on the Django framework I have a user application in which authorization, registration, password change, user password reset are configured I have a url: auth/password_change/ that processes a view of the PasswordChangeView class embedded in Django with a form for changing the user's password and, if successful, redirects to the url: auth/password_change_done/ auth/password_change_done/ handles the representation of the PasswordChangeDoneView class built into Django, which handles a template that says: you have successfully changed your password But any authorized user, even without changing the password, can manually go to the URL auth/password_change_done/ and get the page to which the redirect should go only if the password is successfully changed Tell me how to make it so that no one can manually get to the URL auth/password_change_done/, but only if the password has been successfully changed I tried to use re_path, but it has nothing to do with it at all I need some other way I will be grateful to everyone -
Django admin page formatting is messed up
Picture of formatting I made some updates to my django backend that is running on an azure app service and suddenly the formatting is all broken, see above. I tested it on a local server and the formatting is perfectly normal so I'm very confused, has anybody experienced a similar issue before or have any ideas on what could cause this? EDIT: Wanted to add that I checked the web browsers inspector logs and found errors saying that "the resource from [url] was blocked due to MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff)." I assume thats the issue but I'm unsure how to fix that through azure