Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why are there so many ways in doing the same thing in Python Script Commands in calling dependencies?
Forgive me because I came from Laravel 8 (to be specific) I am still a newbie in Django and in Python in general because I want to learn both at the same time because I always see in social media sites that they're always marketing python hence a trending language nowadays and I like to be a web developer so I also want to learn Django like i did with php, javascript, css-pre-processors, vue and react alll inside of the Laravel Ecosystem Like for example I just discovered you can do this but on a different command call of dependency libraries and I am confuse both the py and python starting commands in calling and importing python scripts and is there going to be some slight sort of technical issues Example 1: Via Package Manager Installation of the Django Web Framework and additional Parameters @MINGW64 ~/backend Opt1: pip install django djangorestframework django-cors-headers Opt2: py -m pip install Django djangorestframework django-cors-headers Opt3: python -m pip install django gunicorn psycopg2-binary Opt4: py -3 -m pip install Django djangorestframework django-cors-headers Example 2: And in testing and running the server (venv)@MINGW64 ~/backend/djangoreactProj Opt1: py -m manage runserver 0.0.0.0:5000 Opt2: py -3 -m manage runserver … -
enable/disable password protection for website
I want to give my client the option to enable/disable password protection on their website through a admin panel kind of like how Shopify does it. first question would be is this option available in any existing headless cms. if not can this be done with my own custom cms using Django or a different backend framework? i'v looked around for resources but can't seem to find anything so any advice/resources would be appreciated note will be built in react -
“detail”: “Method \”GET\“ not allowed.” Django Rest Framework
I know this question was duplicate I am beginner in django I tried in all ways but not able to find solution I was trying to upload a file and get a json response as ok using django rest framework So far I tried is views.py: from rest_framework.views import APIView from rest_framework.parsers import MultiPartParser, FormParser from rest_framework.response import Response from rest_framework import status from .serializers import FileSerializer class FileView(APIView): parser_classes = (MultiPartParser, FormParser) def post(self, request, *args, **kwargs): file_serializer = FileSerializer(data=request.data) if file_serializer.is_valid(): file_serializer.save() return Response(file_serializer.data, status=status.HTTP_201_CREATED) else: return Response(file_serializer.errors, status=status.HTTP_400_BAD_REQUEST) urls.py: from django.conf.urls import url from .views import FileView urlpatterns = [ url(r'^upload/$', FileView.as_view(), name='file-upload'), url(r'^upload/<int:pk>/$', FileView.as_view(), name='file-upload'), ] The error is: Method /GET/ is not allowed please help me thanks in advance -
Code works locally but not on the server (Django, Opencv)
I'm trying to convert the image and save it in the static folder temporarily by using the cv2.imwrite function, but I'm getting an error that says No such file or directory: './static/images/0.png' (In order to convert the image, I had to save images temporarily). It works locally but not on the server. What am I supposed to do? class Article(models.Model): writer = models.ForeignKey(User, on_delete=models.SET_NULL, related_name='article', null=True) project = models.ForeignKey(Project, on_delete=models.SET_NULL, related_name='article', null=True) title = models.CharField(max_length=200, null =True) image = models.ImageField(upload_to='article/', null=True, blank=True) image_converted = models.ImageField(upload_to='article/converted/', null=True, blank=True) style = models.CharField(max_length = 50, blank = True, null=True, choices=ACTION_CHOICES) content = models.TextField(null=True) created_at = models.DateField(auto_now_add=True, null=True) like = models.IntegerField(default=0) def convert_image(self, *args, **kwargs): image_converted = convert_rbk(self.image, self.style) self.image_converted = InMemoryUploadedFile(file=image_converted, field_name="ImageField", name=self.image.name, content_type='image/png', size=sys.getsizeof(image_converted), charset=None) def convert_rbk(img, style): if style == "HAYAO": img = Image.open(img) img = img.convert('RGB') img = ImageOps.exif_transpose(img) img.save("./static/images/0.png") model = Transformer() model.load_state_dict(torch.load('pretrained_model/Hayao_net_G_float.pth')) model.eval() img_size = 450 img = cv2.imread('./static/images/0.png') T = transforms.Compose([ transforms.ToPILImage(), transforms.Resize(img_size, 2), transforms.ToTensor() ]) img_input = T(img).unsqueeze(0) img_input = -1 + 2 * img_input img_output = model(img_input) img_output = (img_output.squeeze().detach().numpy() + 1.) /2. img_output = img_output.transpose([1,2,0]) img_output = cv2.convertScaleAbs(img_output, alpha = (255.0)) cv2.imwrite('./static/images/1.png', img_output) result_image = "./static/images/2.png" cmd_rembg = "cat " + "./static/images/0.png" + " … -
How to add one to one unique relationship between multiple models in django?
class User(models.Model): # User's fields such as username, email etc class Agent(models.Model): user = models.OneToOneField(to=User, on_delete=models.CASCADE) # Other agent fields class Seller(models.Model): user = models.OneToOneField(to=User, on_delete=models.CASCADE) # Other agent fields class Buyer(models.Model): user = models.OneToOneField(to=User, on_delete=models.CASCADE) # Other agent fields Here I have one custom User model and 3 different models, Agent, Seller, Buyer, so the relationship must be one-directional from user to any of the 3 models. Suppose I have a user User1, he can be either an agent or a buyer or a seller, he cannot be both a buyer and seller. So for instance, User1 is a buyer, after creating an object of the Buyer model with User1, User1 cannot be used to create Seller object or ``Agent` object How can I do that? -
How to render html file in Django
In my views.py from django.shortcuts import render def home(request): return render(request, "app/base.html") In my urls.py from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.home, name="Home") ] I'm so confuse, it is not working -
To test a POST request for an authenticated route in Django Rest Framework
I want to test a post request for a route with authentication required(Knox from Django Rest Framework). Here the post request should object for a logged in user. Following is urls.py path('cards', addCard.as_view(), name="cards"), Following is addCard view class addCard(generics.ListCreateAPIView): serializer_class = CardSerializer permission_classes = [permissions.IsAuthenticated, IsOwnerOrNot] def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) card = serializer.save(owner=self.request.user) return Response({'card': CardSerializer(card, context=self.get_serializer_context()).data,}) def get_queryset(self): return self.request.user.cards.order_by('-id') Following is the test case, I used this answer, I got 401!=201 error, clearly Unauthorized user. class addCardAPIViewTestCase(APITestCase): url = reverse("cards") def setUp(self): self.username = "john" self.email = "john@snow.com" self.password = "you_know_nothing" self.user = get_user_model().objects.create_user(self.username, self.password) self.token = Token.objects.create(user=self.user) def test_create_cards(self): client = APIClient() client.login(username=self.username, password=self.password) client.credentials(HTTP_AUTHORIZATION='Token ' + self.token.key) response = client.post(self.url,{ "bank": "Citibank", "card_number": "5618073505538298", "owner_name": "c1", "cvv": "121", "expiry_date_month": "03", "expiry_date_year": "2023" },format='json') self.assertEqual(response.status_code, 201) -
Django allauth with custom fields in User Moel
I am trying to use Django All Auth for login and signup using custom User Model and Form. class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(_('username'), max_length=130, unique=True) full_name = models.CharField(_('full name'), max_length=130, blank=True) is_staff = models.BooleanField(_('is_staff'), default=False) is_active = models.BooleanField(_('is_active'), default=True) date_joined = models.DateField(_("date_joined"), default=date.today) phone_number_verified = models.BooleanField(default=False) change_pw = models.BooleanField(default=True) phone_number = models.BigIntegerField(unique=True,default=create_new_ref_number()) country_code = models.IntegerField(default='91') two_factor_auth = models.BooleanField(default=False) USER_TYPE_CHOICES = ( (1, 'student'), (2, 'teacher'), (3, 'unassigned'), (4, 'teacherAdmin'), (5, 'systemadmin'), ) user_type = models.PositiveSmallIntegerField(choices=USER_TYPE_CHOICES,default=3) objects = UserManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['full_name', 'phone_number', 'country_code'] I am not sure how or where should I get phone_number from users who are signing up. Since the field is required and unique, I am using random number to temporarily have some value. Please suggest. -
Django a simple query makes me crazy ''int' object is not iterable'
I have two Models: class MasterData(models.Model): ID = models.AutoField(primary_key=True) Companyname = models.CharField('Companyname', max_length=128, blank=True, null=True) UserID = models.IntegerField('UserID') class Prefixes(models.Model): ID = models.AutoField(primary_key=True) UserID = models.ForeignKey('MasterData', on_delete=models.CASCADE) InvoiceNoPrefix = models.CharField('InvoiceNoPrefix', max_length=5, blank=True, null=True) No I want in my view a make a simple objects.get_or_create if you visit the site the first time and no records exist should it create one. @login_required(login_url='/backend/') def edit_prefixes(request): user_id = request.user.id userfrommasterdata = MasterData.objects.filter(UserID__in=user_id) prefixes_data = Prefixes.objects.get_or_create(UserID=userfrommasterdata) And all what I get is a: 'int' object is not iterable What do I miss? On my MasterData view it's working perfectlit: @login_required(login_url='/backend/') def edit_masterdata(request): user_id = request.user.id # stamdata_data = get_object_or_404(Stamdata, pk=user_id) stamdata_data, _ = MasterData.objects.get_or_create(UserID__iexact=user_id, UserID=user_id) -
Managing post data from external API (callback URL)
I have a Django app in the MENA region and can't use Stripe as the payment gateway there, I'm relying on a payment page created on the site as a response to my payment request ( I'm not hosting the payment form on my own site ) this is the response I get when my server sends the payment page creation {'callback': 'https://example.com/mycallback', 'cart_amount': '{amount}', 'cart_currency': '{currency}', 'cart_description': 'Subscription 123', 'cart_id': '4244b9fd-c7e9', 'redirect_url': 'https://payment-gateway.com/payment/page/9B8E682', 'tran_ref': 'TST2109500134074', 'tran_type': 'Sale'} and when the user proceeds to the payment form gets redirected to my callback URL with a HTTP POST like this: acquirerMessage=&acquirerRRN=&cartId=4244b9fd-c7e9&customerEmail=user@email.com&respCode=G95839&respMessage=Authorised&respStatus=A&token=&tranRef=TST2109500134074&signature=c93f8f98c46e8bf972b8848f4a59f81583304f125bd7e4d136fd8b4432baf7b3 and based on this response my callback view will handle the user data. If you supplied a callback URL, then the Payment gateway will send the transaction results to that URL using a HTTP POST. This will be a purely server-to-server request, the customers browser will not be involved. Your systems should provide HTTP response with response codes 200 or 201. how should I handle this in the callback URL how can I grap this data ? -
why the Django rest framework ModelSerializer. create and ModelSerializer.validate not working properly?
I am developing an authentication system for User registration through Django rest framework. serializers.py from rest_framework import serializers from .models import NewEmployeeProfile class RegistrationSerializers(serializers.ModelSerializer): ''' We need to add the password2, as its not the part of the NewEmployeeProfile model. So, we need to make it manually. ''' password2 = serializers.CharField(style={'input_type: password'}, write_only=True) class Meta: model = NewEmployeeProfile fields = ('email', 'first_name', 'last_name', 'employee_code', 'contact', 'dob', 'password', 'password2') extra_kwargs = { 'password': {'write_only': True} } def create(self, validated_data): """ before we save the new user, we need to make sure that the password1, and password2 matches. In order to do that, we need to override the save() method. """ password = self.validated_data['password'] password2 = self.validated_data['password2'] if password != password2: raise serializers.ValidationError({'password': f'password must match..'}) return NewEmployeeProfile.objects.create(**validated_data) def validate(self, attrs): if attrs: account = NewEmployeeProfile( email=self.validated_data['email'], first_name=self.validated_data['first name'], last_name=self.validated_data['last name'], employee_code=self.validated_data['employee code'], contact=self.validated_data['contact'], dob=self.validated_data['dob'], ) account.save() return account views.py class UserRegisterView(ListCreateAPIView): create_queryset = NewEmployeeProfile.objects.all() serializer_class = RegistrationSerializers(create_queryset, many=True) permission_classes = [AllowAny] def post(self, request, *args, **kwargs): serializer = RegistrationSerializers(data=request.data) if serializer.is_valid(): newUser = serializer.save() serializer = RegistrationSerializers(newUser) return Response(data={"status": "OK", "message": serializer.data}, status=status.HTTP_201_CREATED) return Response(data={"status": "error"}, status=status.HTTP_400_BAD_REQUEST) models.py from django.db import models from django.contrib.auth.base_user import BaseUserManager from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, … -
Uploading and Retrieving Images to MongoDB Atlas using Django Rest (HELP)
I'm having trouble uploading images to Mongo and retrieving them using Django Rest. I am using GridFS and I'm simply trying to upload a profile picture of a user.This what my api looks like after uploading my image It does not show me a viable link to access it. It just points me back to the create view for some reason. I checked my Mongo Atlas page and it seems like the images are being stored. How can I properly retrieve my images? Here is the code I wrote: settings.py BASE_URL = 'http://127.0.0.1:8000/' models.py grid_fs_storage = GridFSStorage(collection='myfiles', base_url=''.join([settings.BASE_URL, 'myfiles/'])) class ProfilePic(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) profile_pic = models.ImageField(upload_to='users', default='avatar.png',storage=grid_fs_storage) serializers.py class ProfilePicSerializer(serializers.ModelSerializer): class Meta: model = models.ProfilePic fields = ('id', 'profile_pic') views.py class ProfilePicView(viewsets.ModelViewSet): authentication_classes = (authentication.TokenAuthentication,) permission_classes = (permissions.IsAuthenticated,) queryset = models.ProfilePic.objects.all() serializer_class = ProfilePicSerializer -
is there a better way of checking if multiple key exists in a dictionary and assigning multiple values to a variable based on the key found
is there a better way of checking if multiple key exists in a dictionary and assigning multiple values to a variable based on the key found in the dictionary. instead of multiple ifs?? name = None type_of_transaction = None customer = None transaction_id = None for key, value in data_value.items(): if "unique_element" in key: customer = value if "type" in key: type_of_transaction = value if "product_name" in key: name = value if "transactionId" in key: transaction_id = value -
A form submit returns {"error": "'action'"}
I have a form submit that crashes in production with the following error {"error": "'action'"}, but for some weird reason does not happen in local way. The input with id="btnEditar" is the one that push the error. The error is displayed in a white page. Nothing appears in the console of the browser and as far as the error doesnt ocurr in local no messages appears in the backend. I have tried to reload js in several browsers but with the same results... running on Django local dev server the form is submitted OK and the data is updated as well, but in pythonanywhere prod server the error mentionated error comes up. hope you can help me to figure it out!! Here is the template code: {% extends 'core/home.html' %} {% load static %} {% load bootstrap %} <!doctype html> <html lang="es"> <head> </head> <body class="text-center"> {% block content %} <form method="post"> {% csrf_token %} <div style="visibility: hidden;" id="HiddenId">{{ object.id }}</div> <div style="visibility: hidden;" id="HiddenFecAnt">{{ object.start_time }}</div> <div class="container mb-4" style="margin-top: 10px;"> <div class="row justify-content-center"> <div class="card w-24" style="height: 7rem; width: 14rem; margin: 2px"> <div class="card-header" style="height: 2.5rem;" > Fecha de Reprogramación </div> <div class="card-body"> <div class="row justify-content-center"> {{form.start_time|bootstrap}} </div> … -
Give access to my Google Drive to the users of my website
I am developing an application in django and I need that the users who enter my website have access to my Goolge Drive, I am trying to save the google accesses in the user's session, but it does not work SCOPES = ['https://www.googleapis.com/auth/drive'] credentials = Credentials.from_authorized_user_file('token.json', SCOPES) request.session['credentials'] = {'token': credentials.token, 'refresh_token': credentials.refresh_token, 'token_uri': credentials.token_uri, 'client_id': credentials.client_id, 'client_secret': credentials.client_secret, 'scopes': credentials.scopes } -
How do I force my heroku django project to use https?
I have a django site hosted by Heroku (tachlisgeredt.com), but I am having a weird problem. Basically, for anyone going to my site going to 'tachlisgeredt.com' doesn't work, only going to 'tachlis.herokuapp.com', and even that shows 'not secure'. However, going to 'https:/www.tachlisgeredt.com' works, and it shows 'secure'. So basically, how do I force my django site hosted by Heroku to use https? -
Django DRF create new object with primary key "id: null" after axios post method
Summary I'm using django and django rest framework as backend and vue3 as frontend to build a website. I also use axios to post data to the backend and it works fine except that every object created in the backend has a primary key "id: null" instead of auto increment id field. id: null Detail I know that django will automatically create auto increment primary key for you so I didn't declare this field in my models.py. And it works because I can get the primary key id and display it in the frontend when reading data from the backend. So I think I can post data without a id field and let django do the work to provide this new instance with an auto incremented id field. However, every time the object is created and every time "id: null". Here is my serializer for the model: class MaterialSerializer(serializers.ModelSerializer): class Meta: model = Material fields = "__all__" Here is the object list view code that receives the request: class MaterialList(generics.ListCreateAPIView): queryset = Material.objects.all() serializer_class = MaterialSerializer permission_classes = [permissions.IsAuthenticatedOrReadOnly] Here is my post request from vue3 using axios: const addNewMaterial = (payload) => { axios.post(store.state.backendAPIs.coreAPI, payload.data) .then(_ => console.log('...')) .catch(err … -
React rest-hooks how to Authentication
I am trying to build the authentication part of my frontend project so it can communicate with the DRF API. I decided also to use rest-hooks to fetch and send data from / to the API. I am reading rest-hooks auth documentation as a guide but I can't find the "proper way" to implement it in my project. Everything I have read so far is using resources to fetch and send data to the API. In the backend I have this /api-auth endpoint that after sending username & password parameters it returns a token to use as a header while fetching, I guess this is the "easy" part. Despite I am trying to understand the rest-hooks documentation I can't figure out how to bring this together using DRF API + rest-hooks. And plus, besides everything I have said above, I have tried this anyway, and is not working... Attempts I created this AuthResource to attach to the login form. With the fetch approach: import { Resource } from '@rest-hooks/rest'; import { API_URL } from '../utils/server'; export default class AuthResource extends Resource { static getFetchInit = (init: RequestInit) => ({ ...init, credentials: 'same-origin' }); } Error: Class static side 'typeof AuthResource' … -
How to fix UnboundLocalError in Django website
I am getting this error, "local variable 'stu_details' referenced before assignment". How can i fix it please. views.py def assignment_page(request): if request.method == "POST": get_course_name = request.POST.get('get_course_name') add_courses_get = add_courses.objects.get(Course_Name=get_course_name) stu_course_all_stu = add_courses.objects.filter(Course_Name=add_courses_get) for all_stu_details in stu_course_all_stu: for stu_details in all_stu_details.student.all(): id_ = stu_details.student_ID name = stu_details.student_name context3 = {"stu_details":stu_details, "id_":id_, "name": name, 'stu_course_all_stu':stu_course_all_stu} return render(request, 'assignment_page.html', context3) else: return redirect('/') -
can't load bundle.js using webpack-loader and Vue.js
I'm working on a small project using Django and Vue.js i have installed django-webpack-loader and everything works fine for me since i followed a udemy course, i have just one problem is Failed to load resource: net::ERR_ADDRESS_INVALID and exactly bundle.js This is my vue.config.js file : const BundleTracker = require("webpack-bundle-tracker"); module.exports = { // on Windows you might want to set publicPath: "http://127.0.0.1:8080/" otherwise http://0.0.0.0:8080/ publicPath: "http://0.0.0.0:8080/", outputDir: './dist/', chainWebpack: config => { config .plugin('BundleTracker') .use(BundleTracker, [{filename: './webpack-stats.json'}]) config.output .filename('bundle.js') config.optimization .splitChunks(false) config.resolve.alias .set('__STATIC__', 'static') config.devServer // the first 3 lines of the following code have been added to the configuration .public('http://127.0.0.1:8080') .host('127.0.0.1') .port(8080) .hotOnly(true) .watchOptions({poll: 1000}) .https(false) .disableHostCheck(true) .headers({"Access-Control-Allow-Origin": ["\*"]}) }, // uncomment before executing 'npm run build' // css: { // extract: { // filename: 'bundle.css', // chunkFilename: 'bundle.css', // }, // } }; By the way, I'm running my application on Ubuntu Server. -
Improving accuracy in Python Tesseract OCR
I am using pytesseract along with openCV in a simple django application in Python to extract text in Bengali language from image files. I have a form that lets you upload an image and on clicking the submit button sends it to the server side in an ajax call in jQuery to extract the text from the image to serve the purpose of OCR (Optical Character Recognition). Template part : <div style="text-align: center;"> <div id="result" class="text-center"></div> <form enctype="multipart/form-data" id="ocrForm" action="{% url 'process_image' %}" method="post"> <!-- Do not forget to add: enctype="multipart/form-data" --> {% csrf_token %} {{ form }} <button type="submit" class="btn btn-success">OCRzed</button> </form> <br><br><hr> <div id="content" style="width: 50%; margin: 0 auto;"> </div> </div> <script type="text/javascript"> $(document).ready(function(){ function submitFile(){ var fd = new FormData(); fd.append('file', getFile()) $("#result").html('<span class="wait">Please wait....</span>'); $('#content').html(''); $.ajax({ url: "{% url 'process_image' %}", type: "POST", data: fd, processData: false, contentType: false, success: function(data){ // console.log(data.content); $("#result").html(''); if(data.content){ $('#content').html( "<p>" + data.content + "</p>" ) } } }) } function getFile(){ var fp = $("#file_id") var item = fp[0].files return item[0] } // Submit the file for OCRization $("#ocrForm").on('submit', function(event){ event.preventDefault(); submitFile() }) }); </script> The urls.py file has: from django.urls import path, re_path from .views import * urlpatterns … -
Check if token exist
How can i check if the token i'm sending to django exist? does jango rest framework has a built-in function to check this? Currently i've the login and i'm creating the token each time a user logs in c86177ae21c1c0b83a5c0354e742334ef2f376f3 -
Django Mysql string convertion utf8 and unicode?
Well, I have a django model that stores the name of a music band. So new trouble arises when a band called '✝✝✝ (Crosses)' attempts to be stored in a TextField. This is the error: django.db.utils.OperationalError: (1366, "Incorrect string value: '\\xE2\\x9C\\x9D\\xE2\\x9C\\x9D...' for column 'album_name' at row 1") But this becomes weird because I have another table that stores a JsonField with the band info. The same name '✝✝✝ (Crosses)' is stored correctly. the JsonField was a TextField that stored json.dumps(dict_with_band_info) ... So in the database is stored something like { "name": "✝✝✝ (Crosses)" ...}. And repeat, this was a TextField before and works as expected. So why attempting to add "name": "✝✝✝ (Crosses)" to the db Textfield shows that error but not in the other table no? I'm using pdb.set_trace() to see what are the values before do the save(). I would like to mention again that that error doesn't appear even when the JsonField was TextField in my band info table, but the error appears in the TextField of the band_name and exactly in the instance.save(). with this, I can deduct that my text_fields are ready to receive unicode, because in the band info table, the jsonfield shows the … -
I raise two validationerror but if anyone of them is triggered it always gives me the same validation error output
I raised two validationerror messages but if anyone is triggered it gives me the same message of one of the the message is "User has already a current profile model try to update it not creating a new one" here is the code class CurrentProfileSerializer(serializers.ModelSerializer): class Meta: model = CurrentProfile fields = '__all__' read_only_fields = ('user', ) def create(self, validated_data): try: c_profile = CurrentProfile(**validated_data) if c_profile.profile.owner != c_profile.user: raise serializers.ValidationError('You can only use profiles that the user created') c_profile.save() return c_profile except: raise serializers.ValidationError('User has already a current profile model try to update it not creating a new one') the try and except block is made because i mad a OneToOne realtionship in my model CurrentProfile with the user model so it will trigger an error if i tried to add more than one instance of the CurrentProfile Model with same user. the validation error in the if block is made to ensure that the profile selected is created by the same user not just any random profile created by another user the weird thing is that if i remove the try and except block it works fine but when add it again in both cases it gives me the … -
How to use Ajax in Django to change image url
I'm using Django with Ajax ,I have already used Ajax to upload image successfully. Now I want to figure out how to use Ajax direct change the image url. Html: {% block content %} <div class="row"> {{user.username}} {{user.avatar.url}} <p id="error"></p> <div class="col-md-2"> <img class="avatar" src="{{user.avatar.url}}" width="60px" height="60px" /> </div> <div class="mb-2"></div> {% if request.user.username == profile_user.username %} <form enctype="multipart/form-data" class="form-horizontal" method="post"> {% csrf_token %} <label for="avatar" class="change-avatar" >更换头像/change avatar</label> <input type="file" id="avatar" style="visibility:hidden;"> <input type="button" class="btn" value="保持更改/save"> </form> <script> $(".btn").click( function(){ var formdata = new FormData(); formdata.append("avatar",$("#avatar")[0].files[0]); $.ajax({ url:"", type:"post", contentType:false, processData:false, data:formdata, beforeSend: function (xhr, settings) { xhr.setRequestHeader("X-CSRFToken", "{{ csrf_token }}"); }, success:function(data){ console.log(data) var error = data.error var avatar = data.avatar var s =`<div> ${error} </div>` var t = '${avatar}' var src = $(".avatar").attr('src').replace('avatar','avatar') $(".avatar").attr('src', src); $("#error").prepend(s); } }) } ) </script> {% endif %} </div> {% endblock content %} views: @login_required def user_detail(request, username): profile_user = get_object_or_404(User, username=username) form = UserAvatar(request.POST, request.FILES, instance=request.user) response = {} if request.is_ajax(): if form.is_valid(): form.save() response['avatar'] = request.FILES.get('avatar') else: response['error'] = '格式错误' return JsonResponse(response) return render(request, 'user/user_detail.html', { 'profile_user': profile_user, })