Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can't UPGRADE django from macOS terminal
I'm trying to upgrade django old version 2.2.5 so I can install the new one 4.0.2 I have both python Python 2.7.17 and Python 3.7.4 installed on my MacBook Air (macOS 12.2.1). When I try to uninstall django through 'pip3 uninstall django' i get a traceback error. I was trying to uninstall django so I can install the new version since is really outdated. *ERROR: Exception: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/shutil.py", line 566, in move os.rename(src, real_dst) PermissionError: [Errno 13] Permission denied: '/Library/Frameworks/Python.framework/Versions/3.7/bin/pycache/' -> '/private/var/folders/s7/p9l82rrs71g8df756700_4rh0000gn/T/pip-uninstall-labg_6ws' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/ABA/Library/Python/3.7/lib/python/site-packages/pip/_internal/cli/base_command.py", line 167, in exc_logging_wrapper status = run_func(args) File "/Users/ABA/Library/Python/3.7/lib/python/site-packages/pip/_internal/commands/uninstall.py", line 99, in run verbose=self.verbosity > 0, File "/Users/ABA/Library/Python/3.7/lib/python/site-packages/pip/_internal/req/req_install.py", line 638, in uninstall uninstalled_pathset.remove(auto_confirm, verbose) File "/Users/ABA/Library/Python/3.7/lib/python/site-packages/pip/_internal/req/req_uninstall.py", line 369, in remove moved.stash(path) File "/Users/ABA/Library/Python/3.7/lib/python/site-packages/pip/_internal/req/req_uninstall.py", line 267, in stash renames(path, new_path) File "/Users/ABA/Library/Python/3.7/lib/python/site-packages/pip/_internal/utils/misc.py", line 305, in renames shutil.move(old, new) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/shutil.py", line 578, in move rmtree(src) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/shutil.py", line 516, in rmtree return _rmtree_unsafe(path, onerror) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/shutil.py", line 400, in _rmtree_unsafe onerror(os.unlink, fullname, sys.exc_info()) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/shutil.py", line 398, in _rmtree_unsafe os.unlink(fullname) PermissionError: [Errno 13] Permission denied: '/Library/Frameworks/Python.framework/Versions/3.7/bin/pycache/django-admin.cpython-37.pyc' Can anyone help me? Thanks! -
Can't install django project dependencies using pipenv install
I want to install Django project in fresh ubuntu 20.04. The project requires python3.9, so I installed python3.9 using sudo apt install python3.9 python3-pip then I installed django using pip. Now I want to install the project dependencies using pipenv install here is the error I get: mahdi@mahdi-Latitude-E6430:~/Desktop/Project1$ pipenv install Creating a virtualenv for this project… Using /usr/bin/python3.9 (3.9.5) to create virtualenv… ⠋created virtual environment CPython3.9.5.final.0-64 in 429ms creator CPython3Posix(dest=/home/mahdi/.local/share/virtualenvs/Project1-UUOFIsQX, clear=False, global=False) seeder FromAppData(download=False, pip=latest, setuptools=latest, wheel=latest, pkg_resources=latest, via=copy, app_data_dir=/home/mahdi/.local/share/virtualenv/seed-app-data/v1.0.1.debian.1) activators BashActivator,CShellActivator,FishActivator,PowerShellActivator,PythonActivator,XonshActivator Virtualenv location: /home/mahdi/.local/share/virtualenvs/Project1-UUOFIsQX Pipfile.lock (6ab9a1) out of date, updating to (5b3760)… Locking [dev-packages] dependencies… Locking [packages] dependencies… 1] File "/usr/lib/python3/dist-packages/pipenv/patched/piptools/resolver.py", line 72, in resolve_hashes return {ireq: self.repository.get_hashes(ireq) for ireq in ireqs} File "/usr/lib/python3/dist-packages/pipenv/patched/piptools/resolver.py", line 72, in <dictcomp> return {ireq: self.repository.get_hashes(ireq) for ireq in ireqs} File "/usr/lib/python3/dist-packages/pipenv/patched/piptools/repositories/pypi.py", line 274, in get_hashes return { File "/usr/lib/python3/dist-packages/pipenv/patched/piptools/repositories/pypi.py", line 275, in <setcomp> self._get_file_hash(candidate.location) File "/usr/lib/python3/dist-packages/pipenv/patched/piptools/repositories/pypi.py", line 282, in _get_file_hash for chunk in iter(lambda: fp.read(8096), b""): File "/usr/lib/python3/dist-packages/pipenv/patched/piptools/repositories/pypi.py", line 282, in <lambda> for chunk in iter(lambda: fp.read(8096), b""): File "/usr/lib/python3/dist-packages/pipenv/vendor/pip9/_vendor/requests/packages/urllib3/response.py", line 324, in read flush_decoder = True File "/usr/lib/python3.9/contextlib.py", line 135, in __exit__ self.gen.throw(type, value, traceback) File "/usr/lib/python3/dist-packages/pipenv/vendor/pip9/_vendor/requests/packages/urllib3/response.py", line 237, in _error_catcher raise ReadTimeoutError(self._pool, None, 'Read timed out.') pip9._vendor.requests.packages.urllib3.exceptions.ReadTimeoutError: HTTPSConnectionPool(host='files.pythonhosted.org', port=443): Read timed … -
Django Rest Framework communicating with mobile app instances
I would like to build a REST Service which exchanges JSON messages with instances of a mobile app for registering patron traffic in physical locations of (public and academic) libraries. I plan on using Django Rest Framework, and using Django and DRF for the first time, have some questions (rather, recommendation requests). I have read the tutorials and followed some of them, and it looks very promising indeed. As I am quite confident with Object oriented coding in Python, I will be using class based views. Any reason not to? The intended usage of the system will include many different libraries with their own ids, users and properties. The data model behind is thus fairly complex, and implemented with MySQL. I feel I will have better control on the data exchange, updates inserts and selects, with custom SQL queries, and would like the DRF to handle mostly authentication and the routing of messages to and from the instances of the mobile app. Is this a misconception on my part, and would it be better to let DRF handle all database-involved aspects? Given that I follow the custom SQL approach: As (authenticated) user IDs are interwoven with the rest of the … -
Django PostModel request.user isLiked. How can I do that for Every Post?
For each of my posts, I want to send the data whether the logged in user likes it or not. My Post Model: class ModelPost(models.Model): user = models.ForeignKey(ModelUser,on_delete=models.CASCADE) title = models.CharField(max_length=100) Its my View: class ViewHomePage(View): http_method_names = ["get"] def get(self,request): posts = ModelPost.objects.all() # I want For each article I want to post whether that user liked it or not return render(request,"homepage.html",{"posts":posts}) I want to use it like this in template {% for post in posts %} {% if post.isLiked %} <h1>YES IT'S LIKED FROM REQUEST.USER (LOGGED USER) {% else %} <h1>NO IT'S NOT LIKED FROM REQUEST.USER (LOGGED USER) {% endif %} {% endfor %} How can I do that for EVERY POST -
Limit Choices for Charfield
I have a model for all choices in program. Instead of Choices Tuple , i wanna use this table for showing options and validate from table when it's gonna save. So it's not gonna be static as tuple choices in model. class FIELD_CHOICES(models.Model): groupName = models.CharField(max_length=120, null=True, blank=True) value = models.CharField(max_length=120, null=True, blank=True) key = models.CharField(max_length=120, null=True, blank=True) active = models.BooleanField(default=True, blank=True) Main problem is , i'm using charfield for choices right now and it should stay as charfield for other reasons. So i can't use Foreing key model type and limit_choices_to option. There are Also a lot of choices field in program so overriding save method is not best practice in this situation. Is there any option to keep it as charfield and validate from another table ? A custom model field or anything else ? -
TypeError: 'Answer' object is not iterable
class AnswerListFilterForUserView(APIView): def get(self, request, pk): user = request.query_params.get('user') data = Answer.objects.filter(question = pk).filter(username = user).order_by('created_at').last() serializer= AnswerFilterSerializer(data, many=True) return Response(serializer.data) How can i get last data from my Answer Model When i am use last() then error occurs That "TypeError: 'Answer' object is not iterable" Help me out of this -
How to add Scrapy project in Django project?
I want to use scrapy in my Django projects. Does anyone tell me what the structure will be? How can I save the scraped data saved in Django models and display it in Template View? -
Django admin query sum quantity for each type for each request.user
the issue is that i have 3 users levels 1-superuser 2-jihawi 3-mahali, I would like to separate the veiw from the "Quantite" function by request.user models.py class typestock(models.Model): Type = models.CharField(max_length=50, blank=True, null=True) def __str__(self): return self.Type class stock(models.Model): Jihawi = models.ForeignKey(User, on_delete=models.CASCADE, related_name="stockjihawi", editable=True, blank=True, null=True) Mahali = models.ForeignKey(User, on_delete=models.CASCADE, related_name="stockmahali", editable=True, blank=True, null=True) Date = models.DateField(blank=True, null=True) TypeStock = models.ForeignKey(typestock, on_delete=models.CASCADE, editable=True, blank=True, null=True) Quantite = models.IntegerField() def save(self, *args, **kwargs): super(stock, self).save(*args, **kwargs) return self.TypeStock admin.py class TypeStockAdmin(nested_admin.NestedModelAdmin, ImportExportModelAdmin): inlines = [InlineStock] list_display = ('Type', 'Quantite') list_display_links = ('Type',) list_filter = ('Type',) search_fields = ('Type',) def Quantite(self, obj): result = stock.objects.filter(TypeStock_id=obj).aggregate(Sum("Quantite")) return result["Quantite__sum"] Quantite.short_description = "Quantité" how to add this code in the Quantite function: if request.user.is_superuser: stock.objects.filter(StockType_id=obj).aggregate(Sum("Quantity")) ###must view all quantity from stock models### elif request.user.is_jihawi: stock.objects.filter(TypeStock_id=obj).aggregate(Sum("Quantity")) ###how to add filter Jihawi=request.user (Jihawi from stock models)### elif request.user.is_mahali: stock.objects.filter(StockType_id=obj).aggregate(Sum("Quantity")) ###how to add filter Mahali=request.user (Mahali from stock models)### -
Django: Difference between blank=True and default=""
When declaring a model, there are many questions about null vs blank arguemnts. But what is the difference between if I mark a django.db.models.CharField with default="" vs blank=True ? To me it seems like the same concept? -
DjangoListField() vs graphene.List() in Graphene Django
I used both "DjangoListField()" and "graphene.List()". "DjangoListField()" in schema.py: import graphene from graphene_django import DjangoObjectType from graphene_django import DjangoListField from .models import Category class CategoryType(DjangoObjectType): class Meta: model = Category fields = ("id","name") class Query(graphene.ObjectType): all_categories = DjangoListField(CategoryType) # Here def resolve_all_categories(root, info): return Category.objects.all() "graphene.List()" in schema.py: import graphene from graphene_django import DjangoObjectType from .models import Category class CategoryType(DjangoObjectType): class Meta: model = Category fields = ("id","name") class Query(graphene.ObjectType): all_categories = graphene.List(CategoryType) # Here def resolve_all_categories(root, info): return Category.objects.all() Then, I queried "allCategories": query { allCategories { id name } } But the result is the same: { "data": { "allCategories": [ { "id": "1", "name": "category1" }, { "id": "2", "name": "category2" } ] } } What is the difference between "DjangoListField()" and "graphene.List()"? -
creating a dynamic range slider in django and javascript but it's not working
I'm trying to make a dynamic range slider, but it's not work. I know basic Javascript. I want to make a slider like that If I change the price of the servers by changing the number in the slider, it would indicate the servers whose price is the same. Django template <div class="form-group numeric-slider"> <div class="numeric-slider-range ui-slider ui-slider-horizontal ui-slider-range"></div> <span class="numeric-slider-range_text" id='st_text'> </span> <input type="range"> </div> {% for i in page_obj %} ... {% endfor %} <script> $(function () { $(".numeric-slider-range").slider({ range: true, min: 0, max: "{{ page_obj.paginator.count }}", slide: function (event, ui) { $("#" + $(this).parent().attr("id") + "_min").val(ui.values[0]); $("#" + $(this).parent().attr("id") + "_max").val(ui.values[1]); $("#" + $(this).parent().attr("id") + "_text").text(ui.values[0] + ' - ' + ui.values[1]); }, create: function (event, ui) { $(this).slider("option", 'min', $(this).parent().data("range_min")); $(this).slider("option", 'max', $(this).parent().data("range_max")); $(this).slider("option", 'values', [$(this).parent().data("cur_min"), $(this).parent().data("cur_max")]); } }); $("#" + $(".numeric-slider").attr("id") + "_min").val($(".numeric-slider").data("cur_min")); $("#" + $(".numeric-slider").attr("id") + "_max").val($(".numeric-slider").data("cur_max")); $("#" + $(".numeric-slider").attr("id") + "_text").text(ui.values[0] + ' - ' + ui.values[1]); }); </script> def index(request): headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 Safari/537.36", "Accept-Encoding": "*", "Connection": "keep-alive" } url = "https://www.hetzner.com/a_hz_serverboerse/live_data.json" response = requests.get(url, headers=headers) data = response.json()['server'] p = Paginator(data, 20) pn = request.GET.get('page') page_obj = p.get_page(pn) context … -
How to have a array inside an object in django rest framework api
I want to create this kind of API Django: { question_no: "1", question: "How many sides are equal in a scalene triangle?", options: [ { answer_options: "3", selected: false, isCorrect: true }, { answer_options: "2", selected: false, isCorrect: true }, { answer_options: "0", selected: false, isCorrect: true }, { answer_options: "1", selected: false, isCorrect: true }, ], }, but I don't know how can I add the options array in my API in the Django rest framework. this is the model that I have created so far but it only contains question_no and question: class quiz(models.Model): question_no = models.IntegerField() question = models.CharField(max_length=400) how can I add the options array in my model? -
How can I prevent Wagtail richtext editor from creating autolists?
Is there a way to prevent Wagtail's richtext editor from creating autolists when a line starts with 1.? In some languages dates are written in this format: 1. february 2022. If you write a date in this format in the beginning of a line the richtext's autolist feature formats this as a numbered list. What would be a good way to disable this behaviour? -
Azure shared image gallery using python SDK "GalleriesOperations"
I am trying to create shared image gallery and add existing image to it using "GalleriesOperations" in python SDK, but not sure of what argument to pass for "serializer" and "deserializer" and "config" parameter for GalleriesOperations(client, config, serializer, deserializer) I need some reference code example as I am new to azure. GalleriesOperations(client, config, serializer, deserializer) begin_create_or_update(resource_group_name: str, gallery_name: str, gallery: "_models.Gallery", **kwargs: Any) -> LROPoller['_models.Gallery'] Here is what i was trying , but for compute_client var, its not showing any "compute_client.config" to pass as an argument. compute_client = azure.mgmt.compute.ComputeManagementClient(credential, subscription_id) resource_group_name="xxxx",gallery_name='xxxxx', gallery='_models.Gallery', location='xxxx', tags=None, description=None, identifier="xxxx") -
Django constraint that IS NULL conditions of two columns must match
Consider the following model. class MyModel(models.Model): a = models.DateField(blank=True, default=None, null=True) b = models.DateField(blank=True, default=None, null=True) I'd like to require that both a and b are NULL, or both are NOT NULL. I can express this in raw DDL: ALTER TABLE "app_mymodel" ADD CONSTRAINT "both_or_none_null" CHECK ((a IS NULL) = (b IS NULL)); To get this through Django, I tried class Meta: constraints = [ models.CheckConstraint( check=Q(a__isnull=F('b__isnull')), name='both_or_none_null' ) ] Alas, this produces django.core.exceptions.FieldError: Joined field references are not permitted in this query when I try to apply the resulting migration. I have therefore resorted to the less succinct check=(Q(a__isnull=True) & Q(b__isnull=True)) | (Q(a__isnull=False) & Q(b__isnull=False)) which generates a correspondingly clunky DDL constraint. But my Django-foo is limited, so is there a way to express the original constraint correctly? -
'QuerySet' object has no attribute 'x'
I want to go to a users page and see the their photos, so I was trying to get the objects assigned to a foreign key, but I keep getting the error above AttributeError at /user/30/ 'QuerySet' object has no attribute 'file'. I feel like the problem is in my syntax, but I really have no clue why it can't read my Uploads file model object, but it's able to read my profile objects. views.py def profile_view(request, *args, **kwargs,): #users_id = kwargs.get("users_id") #img = Uploads.objects.filter(profile = users_id).order_by("-id") context = {} user_id = kwargs.get("user_id") try: profile = Profile.objects.get(user=user_id) img = profile.uploads_set.all() except: return HttpResponse("Something went wrong.") if profile and img: context['id'] = profile.id context['user'] = profile.user context['email'] = profile.email context['profile_picture'] = profile.profile_picture.url context['file'] = img.file.url return render(request, "main/profile_visit.html", context) models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE, null = False, blank = True) first_name = models.CharField(max_length = 50, null = True, blank = True) last_name = models.CharField(max_length = 50, null = True, blank = True) phone = models.CharField(max_length = 50, null = True, blank = True) email = models.EmailField(max_length = 50, null = True, blank = True) bio = models.TextField(max_length = 300, null = True, blank = True) profile_picture = … -
django charfield not showing in admin panel
i create a model in django and register it in admin.py when i go to admin panel it shows the model but when i want to create object it doesn't show the charfields and i can just create the oject without any details this is my codes below view.py from django.shortcuts import render from django.http import HttpResponse from .models import Feature # Create your views here. def index(request): features = Feature.objects.all() return render(request, 'index.html', {'features' : features}) model.py from django.db import models # Create your models here. class Feature(models.Model): name: models.CharField(max_length=100) details: models.CharField(max_length=200) stting.py """ Django settings for myproject project. Generated by 'django-admin startproject' using Django 3.2.12. For more information on this file, see For the full list of settings and their values, see """ from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-dubzu2qq@tk9lk%d05a*@j1rd1hkr$v72eiga+*u7%v2d)19_5' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'livesync', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myapp' ] MIDDLEWARE … -
How can I call different Fields from one Django models to another fields of another Django Field?
I want to call MemberRegistration Model's 'fname' and 'regino' fields to TypeCharge Model (in 'serial' field), and 'fname' and 'presentaddress' fields to BankAccount Model (in 'accholder' field). I tried Foreign Key but it can only return one combination at a time due to def str(self). Thank You..! Here are my models: `class MemberRegistration(models.Model): regino = models.PositiveIntegerField(default=user_id) fname = models.CharField(max_length=200) presentaddress = models.CharField(max_length=500) def __str__(self): return str(self.regino) + " - " + self.fname class TypeCharge(models.Model): serial = models.ForeignKey(MemberRegistration, on_delete=models.CASCADE) chargename = models.CharField(max_length=200) class BankAccount(models.Model): accholder = models.ForeignKey(MemberRegistration, on_delete=models.CASCADE)` ``` -
How can I receive a list of dictionaries in djano?
Hello I am working on a djago project and I want to recieve a list of dictionaries just like this: [{1: 20}, {2:30}, {3: 50}, ......] here the key is the id of the productand value is price And the code below is just receiving a single dictionary like this {"id": 1, "price" : 20} I want to change it to something look like I mentioned above list_of_objects = [] try: id = int(request.payload.get("id")) price = int(request.payload.get("price")) list_of_objects.append({ "id" : id, "price" : price }) except ValueError: return response.bad_request("Invalid price, %s, should be in whole dollars" % price) I don't know how to do it Thanks -
Активировал venv, но все пакеты устанавливаются в общий питон [closed]
Установил venv, но при попытке установки пакетов, пишет, что они установлены. Проверяю через pip list, пишет все пакеты, которые установлены на стандартном pip. https://i.stack.imgur.com/pnGKv.png Скрин интерпретатора https://i.stack.imgur.com/ks6LP.png https://i.stack.imgur.com/hwp0C.png И скрин терминала https://i.stack.imgur.com/J0GEd.png Больше двух часов не могу решить проблему, помогите пожалуйста. -
'NoneType' object has no attribute 'json'
**Question ** 'NoneType' object has no attribute 'json' how to solve this error views.py from django.shortcuts import render from django.http import HttpResponse #from django.shortcuts import render import json import dotenv #from . models import Contect from flask import Flask, render_template, Response from rest_framework.response import Response # Create your views here. def home1(request): # get the list of todos response1 = request.GET.get('https://jsonplaceholder.typicode.com/todos/') # transfor the response to json objects todos = response1.json() return render(request, "main_app/home.html", {"todos": todos}) -
Make single CharField display as textarea inside a fieldset
I have a user model: class User(AbstractBaseUser): username = models.CharField(max_length=64, unique=True) email = models.EmailField(unique=True) about_me = models.CharField(max_length=140, blank=True) last_login = models.DateTimeField(auto_now_add=True) last_message_read_time = models.DateTimeField(auto_now_add=True) following = models.ManyToManyField("self",symmetrical=False) def save(self, *args, **kwargs): self.full_clean() return super().save(*args, **kwargs) def clean(self): obj = self parents = set() while obj is not None: if obj in parents: raise ValidationError('Cannot follow self', code='self_follow') parents.add(obj) obj = obj.parent and this admin form: class BlogUserAdmin(admin.ModelAdmin): fieldsets = [ (None, { 'fields': ['username', 'email', 'password'] }), ('Biography', { 'classes': ['collapse'], 'fields': ['about_me'] }), ('Follows', { 'classes': ['collapse'], 'fields': ['following'] }), ] admin.site.register(User, BlogUserAdmin) and it displays like this: imgur I want to make the "about me" a text area. I have viewed methods where you define the text area in forms.py but it seems that fieldsets do not support forms from that. I'm assuming this is not possible and that I will have to define my own form from scratch but perhaps there is some setting or method or class I have overlooked? -
Elasticsearch dsl
I need an multi match and suggestions in elasticsearch-dsl search1 = search.filter( 'nested', path='item_id', query=Q('match', item_id__code=categoryField.code) ) I tried multi_phrase and multi_phrase_prefix but not working ! -
update api not working in django rest framework
I have a simple update api which is not working properly. I tested the API in postman by sending only the key and data that needs to be updated but my frontend is sending whole formdata along with the data that are updated. It is working in my postman when I send only the key and the data that needs to be updated but when I send all the data with certain fields as empty string (""), it does not get updated. My models: class Lead(models.Model): title = models.CharField(max_length=5, choices=TITLES, blank=True) first_name = models.CharField(max_length=30) middle_name = models.CharField(max_length=30, blank=True) last_name = models.CharField(max_length=30) address = models.CharField(max_length=100, blank=True) city = models.CharField(max_length=50, blank=True) state = models.CharField(max_length=50, blank=True) country = models.CharField(max_length=30, default="nepal") phone = models.CharField(max_length=50, ) /........other fields................................/ My views: class LeadsView(APIView): permission_classes = [AllowAny] def put(self, request, pk=None, *args, **kwargs): print("iam put") id = pk abc = Lead.objects.get(id=id) serializer = LeadSerializer(abc,data=request.data) if serializer.is_valid(): serializer.save() return Response({ "message": " Leads has been updated", "data": serializer.data }, status=status.HTTP_200_OK) return Response(serializer.data) My serializers: class LeadSerializer(serializers.ModelSerializer): email= serializers.EmailField(required=False) phone = serializers.CharField(required=False) first_name = serializers.CharField(required=False) last_name = serializers.CharField(required=False) title = serializers.CharField(required=False) address = serializers.CharField(required=False) company_name = serializers.CharField(required=False) /.................same in other fields............../ class Meta: model = Lead fields = ['id','title','first_name','last_name','address','company_name', … -
How to upload images with AJAX in DJANGO
I have been using AJAX recently with DJANGO to send text data. It has been working smoothly and feels an easy method. But I cant understand and there no proper resource to learn to send images with AJAX and save to Django Database. HTML: <input type="file" id="fileInput-single" class="drop-zoon__file-input" accept="image/*"> JS: $(".add-prop").click(function() { var data = new FormData(); data.append("image", $("#fileInput-single")[0].files[0]) data.append("csrfmiddlewaretoken", $("input[name=csrfmiddlewaretoken]").val()) $.ajax({ method: "POST", url: "{% url 'upload-prop-images' %}", processData: false, contentType: false, mimeType: "multipart/form-data", data: data, success: function(data) { if (data.status == "Upload Done") { console.log("Uploading Done successfully") } } }) }); models.py class Property(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, related_name='property_user') prop_images = models.ImageField(upload_to="prop_images") views.py def uploadPropImages(request): image = request.POST['image'] property_new = Property(user_id=request.user.id, prop_images=image) property_new.save() return JsonResponse({'status': 'Upload Done'}) urls.py urlpatterns = [ path('upload-prop-images/', views.uploadPropImages, name='upload-prop-images') ] There is one tutorial using the forms.py file but I don't want to create a forms.py file.