Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I annotate a queryset using RawSQL in Django
I need to annotate each message based on its labels. I have to use RawSQL because the real query performs aggregations on an aggregate annotation which Django does not allow. The stripped down models are as follows: class Message(models.Model): text = models.CharField(max_length=250) class Label(models.Model): message = models.ForeignKey(to=Message, on_delete=models.CASCADE) text = models.CharField(max_length=249, blank=False) I can get the query to annotate every message with the same result by removing F('id') and hardcoding an id where there %s is. How can I make this query operate on every message? Note that this is a simplified query from what I am doing. Also note that the query is messages = messages.annotate because there are ORM filters before and after this annotation. raw_sql = """ SELECT COUNT(DISTINCT labels_label.id) AS count FROM messages_message LEFT OUTER JOIN labels_label ON labels_label.message_id = messages_message.id WHERE messages_message.id = %s GROUP BY annotations_message.id """ messages = messages.annotate(count=RawSQL(raw_sql, F('id'))) -
Django storage.path does not get referenced in the Model
I am trying to save a file in a Model's file field. I do this specifying the field storage path and writing to that path. class Layer(models.Model): name = models.CharField(max_length=50, unique=True) file = models.FileField(upload_to='layers') My use case is writing a GDAL dataset to the path: instance = Layer.objects.get(pk=1) name = 'layers/test.tif' out = instance.file.storage.path(name=filename) # use this path dataset = gdal.Open("/path/to/dataset.tif") warp = gdal.Warp(out, dataset, dstSRS="EPSG:4326") # write to that path instance.save() The file gets written in the path. However the model does not reference to it: print('out', instance.file.path) Gets this error: ValueError: The 'file' attribute has no file associated with it. What Model FileField method or Save method should I call so I can reference it? -
How to create different header names for api calls in swagger?
I am using the django restfull framwework with swagger. And swagger works fine. But I try to create different headers for the api calls. Because the current situation is that it is just one long list with header name api. But I have these api call names: PUT /api/accounts/me/ PATCH /api/accounts/me/ POST /api/accounts/token/ GET /api/animals/ POST /api/animals/ GET /api/animals/{id}/ So api/accounts and api/animals. And I try to create for each api/... seperate header name. Like: Accounts: api/accounts/me api/accounts/token Animals: api/animals api/animals/{id}, etc So I the url.py file in the main app looks like: urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('DierenWelzijnAdmin.urls')), path('api-auth/', include('rest_framework.urls')), path('schema/', get_schema_view()), path('api/schema/', SpectacularAPIView.as_view(), name='api-schema'), path('api/docs', SpectacularSwaggerView.as_view(url_name='api-schema'), name='api-docs'), path('api/accounts/',include('accounts.urls') ) ] and I have two seperate apps: Accounts and DierenWelZijnAdmin: urls Accounts: urlpatterns = [ path('create/', views.CreateUserView.as_view(), name='create'), path('logout/',views.LogoutView.as_view(), name='logout'), path('token/', views.CreateTokenView.as_view(), name='token'), path('me/', views. ManageUserView.as_view(), name='me'), path('login/', obtain_auth_token, name='login' ) ] and urls DierenWelZijnAdmin: urlpatterns = [ path('', include(router.urls)) ] And serializer of DierenWelZijnAdmin looks: class AnimalViewSet(viewsets.ModelViewSet, permissions.BasePermission): queryset = Animal.objects.all().order_by('name') serializer_class = AnimalSerializer permission_classes = [IsAuthenticated] class CategoryViewSet(viewsets.ModelViewSet, permissions.BasePermission): def get_serializer_class(self): if hasattr(self, 'action') and self.action == 'main_groups': return MainGroupSerializer return CategorySerializer queryset1 = Category.objects.all().order_by('name') queryset = CategorySerializer.eager_load(queryset1) serializer_class = get_serializer_class(super) permission_classes = [IsAuthenticated] @action(methods=['get'], detail=False) … -
How can I access my Django website on my phone using a local IP and port?
I created a website with django using asgi protocol. and I would like to view this website via my phone. After opening a local server on my pc to share the site locally I searched for my local ip and used it with the port of the server I also created a new inbound rule in the windows fire wall advanced security which should let me access any site with any protocol when it is on my network. After all of that I tried connecting to the site from my phone using this url: http://10.0.0.6:8000/home/ (I also tried it without home, home is just the landing page for my site) and the site can't be reached... Is there anything that I am doing wrong lol? ---------_---- -
How to query multiple tables which are related by a column in another table using Django class based view
I created these models with are related by by a common column [band_id] in ModelC as shown in the model.py code below; class ModelA(models.Model): id = models.IntegerField(primary_key=True) date = models.DateTimeField('Date') band = models.ForeignKey(ModelC, related_name='band', on_delete=models.CASCADE) class ModelB(models.Model): id = models.IntegerField(primary_key=True) band = models.ForeignKey(ModelC, related_name='bandspends', on_delete=models.CASCADE) spending = models.FloatField(default=0.0) class ModelC(models.Model): id = models.IntegerField(primary_key=True) label = models.CharField(max_length=200) How do I query ModelA and ModelB such that I retrieve values from ModelA[date, band_id] and ModelB[band_id, spending] where band_id in ModelA = band_id in ModelB? I have already written my view.py like the one below but the problem is that I cannot do this on a QuerySet. class MyView(ListAPIView): serializer_class = MySerializer def get_queryset(self): queryset = Oas_Spend.objects.select_related('band').filter(band_id=F('ModelC__brand_id')).values( 'ModelC__band_id', 'ModelC__label', 'spending').join( ModelA.objects.select_related('band').filter('band__brand_id')).values('id', 'date') return queryset def get(self, request): queryset = self.get_queryset() # Serialize the data serializer = self.serializer_class(queryset, many=True) pagination_class = DataPagination # Return the serialized data in the response return Response(serializer.data) I expect to have a json like; [ { "band_id": 100, "band_label": "MLTR", "spending": 900.000, "id": 2212121, "date": "2018-02-01T00:00:00Z", }] -
How can I optimize email sending time in Django using Redis pub/sub and multithreading?
Django: Optimizing the sending time by using pub-sub with multiple threads dispatching emails in parallel. Repository link: EmailCampaignManager (Checkout the pub/sub branch) .campaigns/views.py from rest_framework.response import Response from rest_framework.views import APIView from rest_framework import status from campaigns.serializers import EmailCampaignSerializer import redis # Create your views here. class EmailCampaignView(APIView): red = redis.StrictRedis(host='localhost', port=49153, decode_responses=True, password="redispw") def post(self, request, *args, **kwargs): serializer = EmailCampaignSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response( {"data": serializer.data, "message": "Campaign Created Successfully"}, status=status.HTTP_201_CREATED) return Response({"error": serializer.errors}, status=status.HTTP_400_BAD_REQUEST) def publish_email_campaign(sender, instance, **kwargs): red = redis.StrictRedis(host='localhost', port=49153, decode_responses=True, password="redispw") red.publish('email_campaign', str(instance.id)) print(f"message published on email_campaign channel, message={str(instance.id)}") .campaigns/signals.py from django.db.models.signals import post_save, pre_save from django.dispatch import receiver from campaigns.models import EmailCampaign from campaigns.email_dispatcher import send_emails from campaigns.views import publish_email_campaign import redis import threading @receiver(post_save, sender=EmailCampaign, dispatch_uid="email_campaign_created") def send_email_campaigns(sender, instance, **kwargs): publish_email_campaign(sender, instance, **kwargs) red = redis.StrictRedis(host='localhost', port=49153, decode_responses=True, password="redispw") sub = red.pubsub() sub.subscribe('email_campaign') print("subscribed to email_campaign channel, listening for messages") for message in sub.listen(): campaign_id = message.get('data') print(f"message received on email_campaign channel, message={campaign_id}") if campaign_id == str(instance.id): campaign = EmailCampaign.objects.get(id=campaign_id) send_emails(campaign) ./campaigns/email_dispatcher.py from subscribers.models import Subscriber import threading from campaigns.utils import render_email_template, send_email def process_email(event, campaign, subscriber): email_content = render_email_template(campaign, subscriber) retries = 3 # Number of retries while retries > … -
object type date is not Json serializable [closed]
I had to make some changes in my Django model in order to store the shamsi(use in persian) date, but when fetching the data, Django cannot serialize this field and returns the error object type date is not json serializable. thank you for your solution. I tried different ways to avoid this error but it didn't work. Do you have a surefire way to do this? -
Django how to allow multiple selection without ctrl click
I have a listbox on a Django form forms.MultipleChoiceField(widget=forms.widgets.SelectMultiple()) How can I enable multiple choice with a simple click to select/unselect , without having to press the ctrl key ? -
Getting error when creating a tunnel in django application
I have a django application in which I am trying to access my database using a tunnel connection. The tunnel needs the username and a private key file to connect. I am able to connect the tunnel using 'putty' app. But for creating the connection in django application I am using 'sshtunnel' package provided by django. ` from sshtunnel import SSHTunnelForwarder ssh_tunnel = SSHTunnelForwarder(('myhost.host', 22), ssh_private_key=os.path.join(BASE_DIR, 'privateKey.ppk'), ssh_private_key_password='password@123', ssh_username='ssh-user', remote_bind_address=('localhost', 5432)) ssh_tunnel.start() ` But got the error - "sshtunnel.BaseSSHTunnelForwarderError: Could not establish session to SSH gateway" Can someone help me find out, what I am doing wromg? -
Django access context data with a forloop.counter
I'm trying to access context data via the forloop.counter. I have two loops and my data should be accesed by {{ data.[loop1xloop2].i_want_this}} in the html. Example context data: {'data': { '0x0' : { 'i_want_this' : 'value'}, '0x1' : {'i_want_this':...}, ...}} I'm trying to display this data in a table which is generated by two forloops anyway. I tried using djangos with tag to traverse the context structure but it seems that django doesn't recognize my created variable. I tried this: {% for day in days%} {% with daycounter=forloop.counter0|stringformat:"s" %} {% with daykey=daycounter|add:"x0"|stringformat:"s" %} #tried it for the first loop by hardcoding loop1x0 <tr> <td rowspan="6" >{{day}}</td> # value is the importend part <td ><input type="text" name="arbeit{{ forloop.counter0 }}0" value="{{data.daykey.i_want_this}}">{{data.0x0.i_want_this}} {{daykey}}</td> [...] {% for i in range %} <tr> <td class="border border-slate-950"><input class="w-full border-none" type="text" name="arbeit{{ forloop.parentloop.counter0 }}{{forloop.counter}}" id="arbeit{{ forloop.parentloop.counter0 }}{{forloop.counter}}"></td> </tr> [...] {% endfor %} {% endwith %} {% endwith %} {% endfor %} Directly addressing the value with {{data.0x0.i_want_this}} works and {{daykey}} also shows "0x0" but using {{data.daykey.i_want_this}} doesn't. Is there something I'm not seeing or does django simply not have this functionalety? -
ModelForm's cleaned_data returns None for FileField with empty string input
Consider a model with the nullable filefield. I'm encountering a puzzling behavior with Django's ModelForm when it comes to handling a FileField. I have noticed that when the FileField receives an empty string ('') as the file data, the cleaned_data dictionary of the ModelForm returns None for that field instead of ''. Additionally, I observed another related behavior: If i have 2 entries Model.objects.create() and Model.objects.create(file='') Model.objects.filter(file__isnull=True) will return empty queryset and Model.objects.filter(file='') will return both the entries -
does django-redis support retry on TimeOut Exception while doing CRUD operation on Redis?
I am using the django-redis package version (4.12.1), I am getting a TimeOut Exception(Intermittent issue) while reading data from the Redis cache, I would like to Retry for some N number of times to fetch the data I tried using these settings but retry is not happening "REDIS_CLIENT_KWARGS": {"retry_on_timeout": True} Please let me know if any other settings are available to retry while reading data from Redis using the django-redis package. Example Code: cache.get("mykey"), getting time out exception here cache settings in my project: CACHES = { 'default': { 'BACKEND': 'django_redis.cache.RedisCache', 'LOCATION': 'redis_server_url', 'OPTIONS': { 'CLIENT_CLASS': 'django_redis.client.DefaultClient', 'REDIS_CLIENT_KWARGS': {'ssl': True}, 'CONNECTION_POOL_KWARGS': {'ssl_cert_reqs': False}, 'SOCKET_TIMEOUT':4, 'SOCKET_CONNECT_TIMEOUT':4 } } } -
TypeError: create_superuser() got an unexpected keyword argument 'emails'
TypeError: create_superuser() got an unexpected keyword argument 'emails' I am using Django REST Framework for my REST API. I am creating a custom user model. Here is my code: from django.db import models from django.contrib.auth.models import AbstractBaseUser from django.contrib.auth.models import PermissionsMixin from django.contrib.auth.models import BaseUserManager # Create your models here. class UserProfileManager(BaseUserManager): """Manager for user profiles""" def create_user(self, email, name, password=None): """Create a new user profile""" if not email: raise ValueError('User must have an email address') email = self.normalize_email(email) user = self.model(email=email, name=name) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, name, password): """Create and save a new superuser with give details""" user = self.create_user(email, name, password) user.is_superuser = True user.is_staff = True user.save(using=self._db) return user class UserProfile (AbstractBaseUser, PermissionsMixin): """database model for users in the systems""" emails = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=255) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=True) objects = UserProfileManager() USERNAME_FIELD = 'emails' REQUIRED_FIELDS = ['name'] def get_full_name(self): """Retrieve full name of the user""" return self.name def get_short_name(self): """Retrieve short name of the user""" return self.name def __str__(self): """Return string representation of our user""" return self.email ` And I get the following error when I try to create a superuser: Instead of asking 'mail' it is asking 'emails'. … -
How to get a ValidationError for a UniqueConstraint in Django 4.1+
Since Django 4.1, constraints are supposedly checked during model validation*. I therefore expected a ValidationError for a UniqueConstraint on a model, when I try to create a new entry through a standard CreateView (not using a custom Form) that violates the constraint. I was hoping that the create form would be presented again, adorned with an error message, just like a violation of the unique=True setting of a model field does. However, I get an IntegrityError instead (resulting in a 500 Internal Server Error), implying that the validation never took place and the constraint was only found to be violated on database creation. Is there something I'm doing wrong? The model looks something like this: class Child(models.Model): name = models.CharField(max_length=100) parent = models.ForeignKey(Parent, on_delete=models.CASCADE) class Meta: indexes = [models.Index(fields=['name'])] constraints = [models.UniqueConstraint(fields=['name', 'parent'], name='unique_ChildName')] (* Older versions didn't do this, expect for the UniqueConstraint constraint under specific circumstances, and there are other StackOverflow questions for doing this yourself, e.g. Django unique constraint + form errors How to validate uniqueness constraint across foreign key (django) UniqueConstraint in django 2.2 don't raise ValidationError django: ValidationError with UniqueConstraint on Model.Forms, clean() . But that situation has changed since Django 4.1 and my question … -
When retrieving data to edit the select does not show the saved data by default
I'm doing a crud, one of the model's fields is a foreign key to another model and when I open a record saved in the form to edit instead of the select showing the data saved by default it shows empty. Here is my code: models.py class Cliente(models.Model): nome = models.CharField(max_length=200, blank=False, null=False) email = models.EmailField(max_length=200, blank=False, null=False) def __str__(self): return self.nome class Imovel(models.Model): numero = models.CharField(max_length=200, blank=False, null=False) cliente = models.ForeignKey("Cliente", null=True, on_delete=models.SET_NULL) def __str__(self): return self.numero forms.py from django import forms from imoveis.models import Imovel, Cliente class FormImovel(forms.ModelForm): class Meta: model = Imovel fields = [ 'numero', 'cliente', ] class FormCliente(forms.ModelForm): class Meta: model = Cliente fields = [ 'nome', 'email', ] views.py from django.shortcuts import render, get_object_or_404 from imoveis.forms import FormCliente, FormImovel from imoveis.models import Imovel, Cliente def imoveis(request): if request.method == 'POST': form = FormImovel(request.POST) if form.is_valid(): form.save() return render(request, 'imoveis.html') def clientes(request): if request.method == 'POST': form = FormCliente(request.POST) if form.is_valid(): form.save() return render(request, 'clientes.html') def insere_imovel(request): form = FormImovel() return render(request, 'imovel_form.html', {'form': form}) def edita_imovel(request, imovel_id): imovel = get_object_or_404(Imovel, pk=imovel_id) form = FormImovel(imovel.__dict__) return render(request, 'imovel_form.html', {'form': form, 'imovel_id': imovel_id}) def insere_cliente(request): form = FormCliente() return render(request, 'cliente_form.html', {'form': form}) urls.py from django.contrib … -
Why is Django looking for templates in the wrong directory?
Where does django look for Templates by default? I thought by default django looks for templates in myApp/templates/myApp/ folder but in my case django is looking for templates in myApp/templates/ folder. I am unable to force django to look cahnge the directory of templates. Here is the structure of my directory. Directory Structure I worked on other projects but those worked fine. I was wondering if the documentation has changed in django 4.2.1 Here are the codes: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'school' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'django_project.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] school/urls.py from django.urls import path from . import views urlpatterns = [ path('', views.home, name='home'), ] django_project/urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('school.urls')), ] -
Django single code, 2 configs/2customers (2 different databases)
I'd like to have a scenario: I've got django application for some purpose for example "restaurant app" I'd like to serve it to one customer (so have specific database and django settings) and then i'd like to use the same code (code+css+images etc) (not duplicate it in separate folder), and just use additional settings and database, to serve it to the second customer etc. Any ideas how to do it? (so , in case some code changes, I will not need to change code for all customers) -
What is the architectural pattern behind Django's 'Backend' classes (e.g., EmailBackend)? When and how should we utilize this design approach?
I'm currently exploring Django's "Backend" classes, such as EmailBackend, and I'm curious about the architectural pattern behind them. I would like to understand the architectural pattern or design principle that Django follows when implementing these Backend classes. What is the underlying concept or pattern that Django employs to separate and encapsulate these functionalities? Additionally, I'm interested in learning about the scenarios where it would be appropriate to design something similar to Django's Backend classes. In what situations should we consider implementing this type of modular and extensible design approach? Are there any best practices or guidelines to follow when creating Backend classes or similar architectural components? Any insights, explanations, or references to relevant resources would be greatly appreciated. Thank you! -
How do I make my image from my django model to show in my HTML?
Need some help here. I want the image to show in the "card_img"-class, but nothing is showing. I've got this HTML code: <section class="cards"> {% for recipe in recipes %} {% if recipe.category == 'drink' %} <article class="card card--1"> <div class="card__info-hover"> <svg class="card__like" viewBox="0 0 24 24"> <path fill="#000000" d="M12.1,18.55L12,18.65L11.89,18.55C7.14,14.24 4,11.39 4,8.5C4,6.5 5.5,5 7.5,5C9.04,5 10.54,6 11.07,7.36H12.93C13.46,6 14.96,5 16.5,5C18.5,5 20,6.5 20,8.5C20,11.39 16.86,14.24 12.1,18.55M16.5,3C14.76,3 13.09,3.81 12,5.08C10.91,3.81 9.24,3 7.5,3C4.42,3 2,5.41 2,8.5C2,12.27 5.4,15.36 10.55,20.03L12,21.35L13.45,20.03C18.6,15.36 22,12.27 22,8.5C22,5.41 19.58,3 16.5,3Z" /> </svg> </div> <div class="card__img"> <img src="{{recipe.image.url}}"> </div> <a href="{% url 'recipe_view' recipe.id %}" class="card_link"> <div class="card__img--hover"></div> </a> <div class="card__info"> <span class="card__category">{{ recipe.category }}</span> <h3 class="card__title">{{ recipe.title }}</h3> <span class="card__by">by <a href="#" class="card__author" title="author">{{ recipe.user }}</a></span> </div> </article> {% endif %} {% endfor %} </section> In the original design the image url was called from the CSS, like so: .card--1 .card__img, .card--1 .card__img--hover { background-image: url('https://images.pexels.com/photos/45202/brownie-dessert-cake-sweet-45202.jpeg?auto=compress&cs=tinysrgb&h=750&w=1260'); } In the browser's developer tools, the image is correctly linked. image of dev tool code Any ideas? Show the image from the recipe class -
Removing auth_groups and auth_permission table from DB.(Django Rest Framework)
I don't want auth_group and auth_permission table in my DB as I'm not using groups and permission but I can't remove django.contrib.auth from the INSTALLED_APPS in settings.py as I'm using login, authenticate modules of contrib.auth. I've unregistered Groups in admin.py so it doesn't appear in the admin panel. Is there a way to avoid only these two (auth_groups, auth_permission) tables from my DB. Also if I drop these two tables manually from DB will there be any effect on my project? I have already talked to some folks they are suggesting not to drop these tables. -
How can i validate the username and email in django default User model
model from django.contrib.auth.models import User I want to validate the username and email like the username contains only an a-z underscore and dot symbol and the email contains only an a-z,@ ow can I done this validation -
How to correctly serialize non-uniform data arrays in Django using DRF?
I am developing an api with DRF to receive data from a customer and write it into a database. I cannot change the format of the data so I have to adapt the API to it. The data contains a product which itself contains several sub-components in an array called let's say components. { "serial_number":"12345", "manufacturing_date":"2023-05-19", "components":[ { "serial_number":"12345", "type": "component_a", "manufacturer":"asdf" }, { "serial_number":"54321", "type": "component_b", "manufacturer":"fdsa" } ] } Now I can create models which reflect this easily: models.py class Product(models.Model): serial_number = models.CharField( primary_key=True, max_length=255, ) manufacturing_date = models.DateField() class Component(models.Model): serial_number = models.CharField(max_length=255, primary_key=True) type = models.CharField(max_length=255, null=False) product = models.ForeignKey( Product, on_delete=models.SET_NULL, null=True, blank=True, related_name="components", ) If the objects in "components" all have the same fields this can easily be serialized by adding e.g. a ComponentSerializer to the ProductSerializer with the many=True option. BUT it is possible that the objects in the array are different from each other and should be serialized into different models according to their "type": { "serial_number":"12345", "manufacturing_date":"2023-05-19", "components":[ { "serial_number":"12345", "type": "component_a", "manufacturer":"asdf", "comp_a_specific": 100, }, { "serial_number":"54321", "type": "component_b", "manufacturer":"fdsa" } ] } To achieve this I left out the "components" layer in the models and linked the components … -
Django file upload error 'files': [ErrorDetail(string='The submitted data was not a file. Check the encoding type on the form.', code='invalid')]
I'm writing unit tests to test serializer. One element in the request payload is a file. When I run the test, I'm seeing the following error. Please help me solve this. 'files': [ErrorDetail(string='The submitted data was not a file. Check the encoding type on the form.', code='invalid')] Unit test .... .... self.data = { "format": "xxxxx", "files": self._generate_file(), "url": "http://example.com/", "metadata_url": "http://example.com/meta.json", "size": 1024, } .... .... def test_serializer_with_valid_data(self): self.request = APIRequestFactory().get("./fake_path", format="multipart") serializer = DatasetSerializer(data=self.data, context={"request": self.request}) res = serializer.is_valid() print(serializer.errors) ok_(serializer.is_valid()) Output test_serializer_with_valid_data (apps.datasets.test.test_serializers.TestDatasetSerializer) ... {'files': [ErrorDetail(string='The submitted data was not a file. Check the encoding type on the form.', code='invalid')]} FAIL ====================================================================== FAIL: test_serializer_with_valid_data (apps.datasets.test.test_serializers.TestDatasetSerializer) ---------------------------------------------------------------------- Traceback (most recent call last): File "/usr/local/lib/python3.8/unittest/mock.py", line 1325, in patched return func(*newargs, **newkeywargs) File "/app/apps/datasets/test/test_serializers.py", line 71, in test_serializer_with_valid_data ok_(serializer.is_valid()) AssertionError: None -
cannot import name 'gaecontrib' from 'requests_toolbelt._compat'
I'm trying to set up django hosting, which I bought from turkticaret.net, but it gives an error when installing pyrebase4 and I can't run my project. enter image description here I tried "pip install requests-toolbelt","pip install requests-toolbelt==0.7.1" but it gave no results -
Why does my webpage refresh when I execute the "save" function in Django?
Why does my webpage refresh when I execute the "save" function in Django? This is my Django, HTML, and Vue code. I can't figure out the reason, but I know that the webpage refreshes after executing the save() function. I don't want the page to reset, as it would also cause a refresh for other users accessing the webpage simultaneously. The data is being successfully uploaded, but is there any specific reason causing the webpage to refresh? @csrf_exempt @api_view(['POST']) def upload_file(request): if request.method == "POST": file = request.FILES.get('file') if file: filename = file.name post = ModelWithFileField() post.upload = file post.OnlyForDatabase = file post.filename = filename post.upload_date = date.today() post.save() return Response(post.id, status=status.HTTP_201_CREATED) <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Performance Tuning Database</title> </head> <body> <div id="app"> <form method="post" onsubmit="return false"> <input type="file" ref="fileInput" /> <button type="submit" @click="upload">Upload</button> </form> </div> <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script> <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script> <script src="JS/welcome copy.js"></script> </body> </html> new Vue({ el: "#app", data: { APIip: sessionStorage.getItem('API_IP'), token: sessionStorage.getItem('token'), }, methods: { async upload(event) { event.preventDefault(); const fileInput = this.$refs.fileInput; const file = fileInput.files[0]; const formData = new FormData(); formData.append('file', file); console.log(formData) this.message = formData const response = await axios.post(this.APIip + "/api/file/upload", formData, { headers: { "Content-Type": "multipart/form-data", 'Authorization': 'token ' + …