Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ajax GET 403 (Forbidden)
I have a page of articles and a Load More button with ajax call in my Django app. The problem is that the Load More button works just when the user logged in to the site. If an anonymous user clicks on the button, it doesn't work, and sees the error below in the chrome console: In the network tab in chrome console I see this error: But I don't want to identify the user who clicked the button and want to show more posts to everyone! The ajax call is : // Load more posts in the main page $('.load-more').click(function () { var card_count = $(".card-count").length; $.ajax({ url: 'load-more', method: 'GET', data: { "card_count": card_count, }, success: function (data) { // Append more articles to the article List }, error: function (data) { } }); }); I do some search and tried some ways to pass the csrf_token or skip it: This link & This link But still stuck on this. How can I get rid of this error? Thanks for your help. -
Django CSRF cookie sending images with axios client
Good day. I need to send an image by the post method of a client with axios to a Django server but I get the following message on the server. Forbidden (CSRF cookie not set.): And the client gives me the following answer xhr.js:177 POST http://127.0.0.1:8000/xxxx/ 403 (Forbidden) How is it possible to solve this problem? It is possible to disable the CSRF cookie= This is the client code: var formData = new FormData(); formData.append("imagen", await fetch(`${filepath}`).then((e) => { return e.blob() }) .then((blob) => { let b: any = blob b.lastModifiedDate = new Date() b.name = '' return b as File }) ); const axios = require('axios'); axios({ url:url, method:'POST', data:formData }).then(function(res: any){ console.log(res) }).catch((error: any) =>{ console.log(error) //Network error comes in }); And this is the server view function (It just check the info to debug) def completeInfo (request): print(request) return HttpResponse("Bad Response") -
Django Wagtail [Errno 111] Connection refused form submission
I have a site that I made using Wagtail (Django) and set up a contact form with a landing page. When using this contact form on localhost, I can successfully add information on the contact form and submit it, which takes me to the landing page. However, I have hosted this on heroku, and now have a problem with submitting the contact form. When I have submitted the contact form, it gives me an error that the connection was refused [Errno 111]: Traceback (most recent call last): File "/app/.heroku/python/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/app/.heroku/python/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/app/.heroku/python/lib/python3.8/site-packages/wagtail/core/views.py", line 24, in serve return page.serve(request, *args, **kwargs) File "/app/.heroku/python/lib/python3.8/site-packages/wagtail/contrib/forms/models.py", line 300, in serve form_submission = self.process_form_submission(form) File "/app/.heroku/python/lib/python3.8/site-packages/wagtail/contrib/forms/models.py", line 341, in process_form_submission self.send_mail(form) File "/app/.heroku/python/lib/python3.8/site-packages/wagtail/contrib/forms/models.py", line 346, in send_mail send_mail(self.subject, self.render_email(form), addresses, self.from_address,) File "/app/.heroku/python/lib/python3.8/site-packages/wagtail/admin/mail.py", line 62, in send_mail return mail.send() File "/app/.heroku/python/lib/python3.8/site-packages/django/core/mail/message.py", line 284, in send return self.get_connection(fail_silently).send_messages([self]) File "/app/.heroku/python/lib/python3.8/site-packages/django/core/mail/backends/smtp.py", line 102, in send_messages new_conn_created = self.open() File "/app/.heroku/python/lib/python3.8/site-packages/django/core/mail/backends/smtp.py", line 62, in open self.connection = self.connection_class(self.host, self.port, **connection_params) File "/app/.heroku/python/lib/python3.8/smtplib.py", line 253, in __init__ (code, msg) = self.connect(host, port) File "/app/.heroku/python/lib/python3.8/smtplib.py", line 339, in connect self.sock = self._get_socket(host, port, … -
How to customize UserCreationForm validation in django
I'm currently trying to build user registration form using UserCreationForm but it doesn't suit my needs. First of all, Username field accepts not only alphabet symbols and digits but also @ . + - _. I want to make it accept only latin and cyrillic leterrs and digits but I could not find any information. Also i want to change it's other properties like maximum length. Also after we make these changes will both client and server sides validation process deny banned symbols? Here is some code I already have in forms.py: class CreateUserForm(UserCreationForm): class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] and views.py: def register(request): form = CreateUserForm() if request.method == 'POST': form = CreateUserForm(request.POST) if form.is_valid(): form.save() context = {'form': form} return render(request, 'register.html', context) -
Error Django Pillow : profiles.Profile.photo: (fields.E210) Cannot use ImageField because Pillow is not installed
Hi, I want to install Pillow + Django in Docker but Not works. ERRORS: profiles.Profile.photo: (fields.E210) Cannot use ImageField because Pillow is not installed. HINT: Get Pillow at https://pypi.org/project/Pillow/ or run command "python -m pip install Pillow". Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/local/lib/python3.8/threading.py", line 932, in _bootstrap_inner self.run() File "/usr/local/lib/python3.8/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/usr/local/lib/python3.8/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "/usr/local/lib/python3.8/site-packages/django/core/management/base.py", line 442, in check raise SystemCheckError(msg) django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: profiles.Profile.photo: (fields.E210) Cannot use ImageField because Pillow is not installed. My Stack Python 3.8 Django 3.1 Environtment: Docker : python:3.8.3-alpine Thanks so much -
Hello, I'm a. beginner at Django API and http GET Method doesn't work. It prints an error
In urls.py, which is in 'users' folder, which is containing migrations folder, localhost: 8000 /users is scripted. Then I typed http GET localhost:8000 on the command line after which Virtual environment had been activated. But It prints this error. http: error: ConnectionError: HTTPConnectionPool(host='localhost', port=8000): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x10172bd60>: Failed to establish a new connection: [Errno 61] Connection refused')) while doing a GET request to URL: http://localhost:8000/ What's the problem? I've been stuck into this step so I couldn't go forward anymore. Please give me some help! -
What are the most important features in django?
I know this is off topic but i think a lot of people learning a lot of code and most companies require something more specific always. For example most of the websites out there have the same features. Ex Login,Register,API services etc. But in general, what are the most important Django features-skills a developer need to have? -
How to query the total number of "interest= Pending" object for any of my post added together?
In my project, anyone can submit any interest to any post, limited to 1 interest per post. Right now, i am trying to query the TOTAL number of interests (that is not accepted yet, meaning the status is still pending) that has been sent to any of my post, like all of them added up together, and I want that to be displayed in my account page. Is that possible to query it from the template based on the current code i have, and how can i do it? I have been trying the past hour but it hasn't be successful :( All help is appreciated thank you! models.py class Account(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) class BlogPost(models.Model): title = models.CharField(max_length=50, null=False, blank=False, unique=True) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) body = models.TextField(max_length=5000, null=False, blank=False) class Interest(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) blog_post = models.ForeignKey(BlogPost, on_delete=models.CASCADE) my_interest = models.TextField(max_length=5000, null=False, blank=False) class InterestInvite(models.Model): ACCEPT = "ACCEPT" DECLINE = "DECLINE" PENDING = "PENDING" STATUS_CHOICES = [ (ACCEPT, "accept"), (DECLINE, "decline"), (PENDING, "pending"), ] interest = models.OneToOneField(Interest, on_delete=models.CASCADE, related_name="interest_invite") status = models.CharField(max_length=25, choices=STATUS_CHOICES, default=PENDING) views.py def account_view(request, *args, **kwargs): context = {} user_id = kwargs.get("user_id") account = Account.objects.get(pk=user_id) context['account'] = account … -
How can I filter a intersection of manytomany field in django?
i want to filter query , and one of field is manytomany . how to filter intersection in manytomany fields my model is: class Event(models.Model): category = models.ManyToManyField(Category, blank=True) title = models.CharField(max_length=400) views: search_subcategory = Q() if subcategory != 'null': total_filter.append('subcategory') subcategory = subcategory.split(",") for i in range(0, len(subcategory)): subcategory[i] = int(subcategory[i]) for x in subcategory: search_subcategory &= Q(subcategory=x) search_title = Q() if title != '': total_filter.append('title') search_title = Q(title__icontains=title) filter_query = Event.objects.filter(search_category & search_title).distinct() -
why 502 error in google app engine flexible environment django?
I want to deploy Django + CloudSQL (Postgresql) + app engine flexible environment in google cloud. My app.yaml setting runtime: python #gunicorn env : flex entrypoint : gunicorn -b 127.0.0.1 -p 8000 config.wsgi --timeout 120 #instance_class : F4 beta_settings: cloud_sql_instances: icandoit-2021start:asia-northeast3:test-pybo=tcp:5434 runtime_config: python_version: 3 gcloud app logs tail result 2021-02-03 11:02:17 default[20210203t195827] [2021-02-03 11:02:17 +0000] [1] [INFO] Starting gunicorn 19.7.1 2021-02-03 11:02:17 default[20210203t195827] [2021-02-03 11:02:17 +0000] [1] [INFO] Listening at: http://127.0.0.1:8000 (1) 2021-02-03 11:02:17 default[20210203t195827] [2021-02-03 11:02:17 +0000] [1] [INFO] Using worker: sync 2021-02-03 11:02:17 default[20210203t195827] [2021-02-03 11:02:17 +0000] [8] [INFO] Booting worker with pid: 8 2021-02-03 11:09:18 default[20210203t170353] [2021-02-03 11:09:18 +0000] [1] [INFO] Handling signal: term 2021-02-03 11:09:18 default[20210203t170353] [2021-02-03 11:09:18 +0000] [8] [INFO] Worker exiting (pid: 8) 2021-02-03 11:09:19 default[20210203t170353] [2021-02-03 11:09:19 +0000] [1] [INFO] Shutting down: Master 2021-02-03 11:09:19 default[20210203t170353] [2021-02-03 11:09:19 +0000] [1] [INFO] Handling signal: term 2021-02-03 11:09:19 default[20210203t170353] [2021-02-03 11:09:19 +0000] [8] [INFO] Worker exiting (pid: 8) 2021-02-03 11:09:20 default[20210203t170353] [2021-02-03 11:09:20 +0000] [1] [INFO] Shutting down: Master 2021-02-03 11:14:25 default[20210203t195827] "GET /" 502 django and gunicon works normally. Why Do I Have 502 Errors? -
Elastic Apm python agent connection problem
I have a very basic django apm agent setup: ELASTIC_APM = { # Set required service name. Allowed characters: # a-z, A-Z, 0-9, -, _, and space 'SERVICE_NAME': 'bourse', # Set custom APM Server URL (default: http://localhost:8200) 'SERVER_URL': '127.0.0.1:8200', 'LOG_LEVEL': "debug", 'LOG_FILE': "/home/hamed/Desktop/log.txt",} my apm server is up and running on localhost:8200. But it seems my apm agent can't make a connection to the apm server.Here is a part of my log file that I think cause the problem: Skipping instrumentation of urllib3. Module botocore.vendored.requests.packages.urllib3.connectionpool not found HTTP error while fetching remote config: HTTPConnectionPool(host='config', port=80): Max retries exceeded with url: /v1/agents (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7fe2625ed610>: Failed to establish a new connection: [Errno -3] Temporary failure in name resolution')) this is my apm agent log file. ps: On my apm server I'm not receiving any request from my agent. I checked the apm server log files. Please help me. I'm stuck. -
NoReverseMatch at /products/update/6/ Reverse for 'product_update' with arguments '('',)' not found
I want to go to the product update method through the URL with the product ID by clicking on the product list but this error is coming. I don't understand what I did wrong here. The following codes are given. Product list: {% for product in products %} <tr> <td> <img width="55px" height="55px" src="{{ product.photo.url }}" /> </td> <td><input class="groupCheck" type="checkbox" value="{{product.id}}" id="{{product.id}}"/></td> <td> <a class="btn product-update" href="{% url 'accpack:product_update' pk=product.id %}">{{product.product_code}}</a> </td> <td>{{product}}</td> <td> <a class="far fa-plus-square fa-1x js-create-product_attribute" data-url="{% url 'accpack:products_attributes_create' pk=product.id %}" data-toggle="modal" data-target="#modal-product_attribute"></a> &nbsp <a class="far fa-edit fa-1x js-create-product_attribute" data-url="{% url 'accpack:products_attributes_update' pk=product.id %}" data-toggle="modal" data-target="#modal-product_attribute"></a> </td> <td>{{product.cost_price}}</td> <td>{{product.sale_price}}</td> <td>{{product.quantity_per_unit}}</td> <td>{{product.brand}}</td> </tr> {% endfor %} url: # Product url url('products/$', views.product_index, name="products"), url('products/create/$', views.product_create, name="product_create"), url('products/update/(?P<pk>\d+)/$', views.product_update, name="product_update"), view: def product_update(request, pk): product = get_object_or_404(Product, pk=pk) if request.method == 'POST': form = ProductForm(request.POST, instance=product) else: form = ProductForm(instance=product) return save_product_form(request, form, 'products/partial_product_update.html') partial_product_update.html: <form id="Form" method="post" action="{% url 'accpack:product_update' pk %}" class="col s12" enctype="multipart/form-data"> {% csrf_token %} <br> {% crispy form form.helper %} <br> </form> Traceback: Traceback (most recent call last): File "C:\Users\Dell\anaconda3\envs\webapp\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Dell\anaconda3\envs\webapp\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\MEGA\djangoprojects\myprojects\accpack\views\products.py", line 52, in … -
Conditional Counter in Django template for loops
I want my for loop to end after the if-condition is satisfied thrice while rendering my "products" details in my eCommerce website. category.html {% for item in subcategory %} {% with counter="0" %} <div> <h5 class="my-0" style="font-weight: 700;">{{ item.title }}</h3> </div> <div class="row"> {% for i in products %} {% if i.category.id == item.id %} {{ counter|add:"1" }} {% if counter == "3" %} {{ break}} {% endif %} <div class="col-3 p-0 px-1 my-3"> <a href="{% url 'product_detail' i.id i.slug %}"> <img class="w-100" id="catbox" src="{{ i.image.url }}" alt=""> </a> </div> {% endif %} {% endfor %} <div class="col-3 p-0 my-3 text-center" style="border-radius: 10px;background: url({% static 'images/temp.jpeg' %}); background-size: cover;"> <div class="h-100 w-100 m-0 p-0" style="background: rgba(0, 0, 0, 0.61);border-radius: 10px;"> <div style="position: relative;top: 50%;transform: translateY(-50%);"> <a href="{% url 'category_product' item.id item.slug %}" class="text-white " href="#"><strong>SEE ALL</strong></a> </div> </div> </div> </div> {% endwith %} {% endfor %} I want the second for loop, i.e., {% for i in products %} to break once the if condition, i.e., {% if i.category.id == item.id %} inside it is satisfied thrice. But the counter I set to 0 is incremented to 1 repeatedly instead of being incremented recurrently with the for loop. Since there … -
Make Django db optional, but still functional if needed
So in my django project i have my databse set up like this : DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': env("DEFAULTDB_NAME"), 'USER': env("DEFAULTDB_USER"), 'PASSWORD': env("DEFAULTDB_PASS"), 'HOST': env("DEFAULTDB_HOST") }, "remote": { 'ENGINE': 'django.db.backends.postgresql', 'NAME': env("REMOTEDB_NAME"), 'USER': env("REMOTEDB_USER"), 'PASSWORD': env("REMOTEDB_PASS"), 'HOST': env("REMOTEDB_HOST") } } What i want is for the remote database to be optional, so if i run my server it works even if the connection to remote databse fails. I have tried the solution mentioned here, But with this if the connection is lost when i start the server i can't use my remote database until i restart my server -
Access all content from a post in Django
I apologize in advance if the question is poorly written. tried my best to explain my problem as good as i could :). Thanks for helping! I have currently made a django web server. i am trying to access all the content from all my different posts and display them by eachother within "ul" and "li" HTML tags. I am currently only able to display the Main Posts title, and not the rest of the content. The result i am currently getting is this. My Book List: * The Hunger Games and the result i am wanting to get is this. My Book List: * Title: The hunger games * Author: Suzanne Collins * Publisher: Scholastic Press * Published: 2008-09-14 I've tried multiple solutions to try and make it work. But i cant find any solution on youtube or any related social media website, so i resorted to here. models.py file from django.db import models # Create your models here. class Books(models.Model): title = models.CharField(max_length=50) author = models.CharField(max_length=50) publisher = models.CharField(max_length=50) pulished = models.DateField() def __str__(self): return self.title Views.py file from django.shortcuts import render from .models import Books # Create your views here. def book_list(request): books = Books.objects.all() context = … -
django: taking user input from html, processing it and showing output in the same page
I am quite new in Django and stuck at specific point. I want to take user input from html that goes into database, process it with specific python script and return result to the same html page. I want Users to enter score in "exam_score" line, then process that input with specific python script and then to output result to "uni_name_1_result". For now, python script that just prints 'Hello world' is enough, just want to understand the mythology of how it can be done. Would appreciate any help. models.py from django.db import models from django.core.validators import MaxValueValidator, MinValueValidator # Create your models here. class User(models.Model): first_name = models.CharField(max_length=128) last_name = models.CharField(max_length=128) email = models.EmailField(max_length=254,unique=True) exam_score = models.FloatField(null=True, validators=[MinValueValidator(0.0),MaxValueValidator(700)]) uni_name_1 = models.CharField(max_length=254) uni_name_1_result = models.CharField(max_length=254) forms.py from django import forms from django.core import validators from ielts_app.models import User class NewUserForm(forms.ModelForm): # validations can be set here class Meta(): model = User fields = '__all__' views.py from django.shortcuts import render # from ielts_app import forms from ielts_app.forms import NewUserForm # from django.http import HttpResponseRedirect def index(request): return render(request,'ielts_app/index.html') def users(request): form = NewUserForm() if request.method == 'POST': form = NewUserForm(request.POST) if form.is_valid(): variable:form.cleaned_data form.save(commit=True) # to save forum data (user data), commit=True … -
DRF: access serializer fields outside meta
So, i need to get the "like" status on posts, and need my serialzier to return attr "liked" bool. I am trying to get the current post being serialized, pass it into a query which will either return true or false. -
Saving data from different forms to different table using one view Django
I have five different Models and each model have different fields.I have created five form for the respective models.Please refer the below code.I am getting used_for from url and I am using used_for for identifying which form has been triggered to save the data.Its working for me I just wanted to know is this a good way to this or is there any another way.I dont want to create fie different views to save the data views.py def contract_details(request,used_for): if request.method == "POST": if used_for == "contractmanager": form = ContractForm(request.POST) elif used_for == "contractlineitem": form = ContractLineItemForm(request.POST) elif used_for == "billingtype": form = BillingTypeForm(request.POST) else: messages.info(request,"Invalid Form") return redirect("useradmin:revenue_manager") if form.is_valid(): form.save() messages.success(request,"Contract Saved Successfully.") return redirect("useradmin:revenue_manager") urls.py urlpatterns = [ path("add",views.add_admin,name = "add_admin"), path("view",views.view_admin,name = "view_admin"), path("timezone/", views.add_timezone, name = "timezone"), path("timezone/delete/<int:id>/", views.delete_timezone, name = "deletetime"), path("language/", views.add_language, name = "language"), path("language/delete/<int:id>/", views.delete_language, name = "deletelanguage"), path("organization/", views.add_organization, name = "organization"), path("organization/delete/<int:id>/", views.delete_organization, name = "deleteorganization"), path("revenue-manager/", views.revenue_manager, name = "revenue_manager"), path("revenue-manager/bulk-add/<str:data>", views.data_upload, name = "bulk_add"), path("revenue-manager/export-data/", views.export, name = "export_data"), path("add-contract/<str:used_for>/", views.contract_manager, name = "add_contract"), ] -
DJANGO: Group by two fields and aggregate a method's return value
How to group records by two fields, and then take the sum of a method's return value? I have the following model: class Invoice(models.Model): client = models.ForeignKey(Client, on_delete=models.DO_NOTHING) date = models.DateField() quantity = models.IntegerField() price = models.DecimalField(max_digits=18, default=2) def total_amount(self): return self.quantity * self.price I want to group records of Invoice by year of date, and client, and take the sum of total_amount for each year for each client. The output should look something like this: top_companies = {"2021": {"Company 1": 22000.0, "Company 2": 20000.0}, "2020": {"Company 2": 40000.0, "Company 1": 10000.0}} -
save() takes 1 positional argument but 2 were given
I am trying to register as a seller ( is_seller=True). But I am getting this issue of save() function cant take two positional arguments. I tried passing *args and **kwargs as well, but it is still not working. My models: class CustomUser(AbstractUser): # username = models.CharField(max_length=255,) first_name = models.CharField(max_length=255, verbose_name="First name") last_name = models.CharField(max_length=255, verbose_name="Last name") email = models.EmailField(unique=True) is_seller = models.BooleanField(default=False) is_customer = models.BooleanField(default=False) USERNAME_FIELD = "email" REQUIRED_FIELDS = ["first_name", "last_name"] objects = CustomUserManager() def __str__(self): return self.email My serializers: class SellerRegisterSerializer(serializers.ModelSerializer): seller = serializers.PrimaryKeyRelatedField(read_only=True,) phone_num = serializers.CharField(required=False) class Meta: model = User fields = ['seller','email', 'phone_num', 'first_name', 'last_name', 'password'] def get_cleaned_data(self): data = super(SellerRegisterSerializer, self).get_cleaned_data() extra_data = { 'phone_num': self.validated_data.get('phone_num', ''), } data.update(extra_data) return data def save(self, request,*args, **kwargs): user = super(SellerRegisterSerializer, self).save(request) user.is_seller = True user.save() seller = Seller(seller=user, phone_num=self.cleaned_data.get('phone_num')) seller.save(*args, **kwargs) return user My view: class SellerRegisterView(RegisterView): serializer_class = SellerRegisterSerializer My urls: path("api/seller/register/",SellerRegisterView.as_view(), name='api-registerseller'), -
how to apply serial number in model.py in python django
we have a table that contains row and column we need one more column that will show serial number of row. It mean when user will update the table the serial number will update automatically. -
django reduce number of database queries on bulk-update
so I have functions like this in my reusable manager class. @query_debugger def update_object_positions(self, data: list, overwrite_objects): """ Updates object positions for the given array of overwrite objects. Removes unchanged data from the current list of objects and puts it back in after sorting the list. Expects a list of serialized object-data, consisting of the id and the changed-position of the respective objects. """ if overwrite_objects.count() < 2: # we don't update positional values for objects if none or # only one of the same is found, because it doesn't make # any sense to do the same. Objects only change their positions to be # shifted among each other. model_name_plural = self.model._meta.verbose_name_plural.title() raise exceptions.ValidationError(detail=f'less than two {model_name_plural} found') collected_data = {obj['id']: obj['position'] for obj in data} changed_objects = overwrite_objects.filter(id__in=collected_data.keys()) for obj in changed_objects: obj.position = collected_data[obj.id] rotated = self.perform_rotate(changed_objects, overwrite_objects) self.overwrite_object_positions(rotated) @query_debugger def overwrite_object_positions(self, data: list): """ Overwrites object-positions, enclosed within a transaction. Rolls-back if any error arises. We need a transaction here because all of our positional objects have a deferring unique constraint over their positions. """ cleaned = [obj for obj in data if not hasattr(obj, 'is_default') or not obj.is_default] self.model.objects.bulk_update(cleaned, ['position']) for instance in cleaned: # … -
can a django login api be created without using django auth model
Can a django login rest api be created completely from scratch, build with custom model and not inbuilt. I've been trying but cannot understand how to create it. -
Django Rest Framework: Send full foreign key objects in GET response but accept only foreign ids in POST payload, without two serializers?
Say I've two models: class Singer((models.Model): name = models.CharField(max_length=200) class Song(models.Model): title = models.CharField(max_length=200) singer = models.ForeignKey(Singer) And two serializers like: class SingerSerializer(serializers.ModelSerializer): class Meta: model = Singer fields = '__all__' class SongSerializer(serializers.ModelSerializer): singer = SingerSerializer() class Meta: model = Singer fields = '__all__' I've defined the serializers as above because I need the full foreign key object in the GET response for songs: { "singer": { "id": 1, "name": "foo" }, "id": 1, "title": "foo la la" } Is there a way to allow POST/PATCH payloads to only send in the id of the foreign object and not the entire object, without writing a different serializer? I'd like the PATCH payload to be so: { "singer": 1, "id": 1, "title": "foo la la" } -
TypeError: cannot serialize '_io.BufferedRandom' object While trying to upload file in Django
I am trying to upload some files in Django but sometimes when the file size increases it gives the following error: TypeError: cannot serialize '_io.BufferedRandom' object In the current case I am trying to upload a file(size ~3Mb) but it's still showing the error. I tried to check in the network that if the file has been uploaded or not but it shows: I am unable to understand what changes I need to make in order to resolve this