Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to using two parameters in delete method of class GenericViewSet in Django
I'm newbie Django How can use 2 params on my url with delete method on django 3 My url config: API_VERSION = os.getenv('API_VERSION') API_ROOT = "grpz/" router = routers.DefaultRouter(trailing_slash=False) router.register(r'^groups/(?P<group_id>.)/users/(?P<user_id>.)', group_views.DeleteGroupViewSet) schema_view = get_schema_view( title='next_blog', renderer_classes=[OpenAPIRenderer, SwaggerUIRenderer]) urlpatterns = [ path('admin', admin.site.urls), path('api_auth', include( 'rest_framework.urls', namespace='rest_framework')), path('docs', schema_view, name='docs'), path(API_ROOT, include(router.urls)), ] My class viewsets: class DeleteGroupViewSet(viewsets.GenericViewSet): queryset = Groups.objects.all() serializer_class = GroupSerializer permission_classes = (AllowAny,) def destroy(self, request, group_id, user_id): try: # user_id = self.kwargs['user_id'] # group_id = self.kwargs['group_id'] user = Users.objects.filter(user_id=user_id).first() if user is None: return Response({ 'msg': 'User is not exist', }, status=status.HTTP_500_INTERNAL_SERVER_ERROR) else: user_owner_role_in_group = GroupHasUsers.objects.filter( group_id=group_id, user_id=user_id, role__name='owner' ) if user_owner_role_in_group.count() == 0: return Response({ 'msg': 'User is not a owner role' }, status=status.HTTP_500_INTERNAL_SERVER_ERROR) else: Groups.objects.filter(id=group_id).delete() return Response({'msg': 'success'}, status=status.HTTP_200_OK) except Exception as e: return Response({ 'msg': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) Thanks all ! -
Accessing os files with django inside an electron application
I have a web application built with Django/React. I want to convert it to an electron app and am unsure if I need to refactor some of the backend code to node.js. Here is the relevant information: User needs to create a file with their own API token received from 3rd party. I would like to avoid sending their personal token to my server and want to keep it on their operating system. Django uses the token to query data from the 3rd party api. Django sends data back to front end. My question is, once the application is bundled as an electron app, can django access their api token and query the 3rd party api without hitting my server? Will the django code be run on the localhost (or can it) is I guess what I mean. Thanks, hope this is a valid SO question. -
Django modelformset not saving data. Returns empty list after calling cleaned_data
I have a problem with formset, its doesnt save. Console returns no errors but after calling print(formset.cleaned_data) it returns empty list. Standard form saves normally. This formset is for adding a service made to a car object. I couldnt find the answer online, maybe someone will help or find a better solution. models.py class Car(models.Model): FUEL = ( ('', '---------'), ('1', 'Gasoline'), ('2', 'Diesel'), ('3', 'Electric'), ('4', 'Hybrid'), ) client = models.ForeignKey(Client,on_delete=models.CASCADE, null=True, blank=True) car_make = models.ForeignKey(CarMake, on_delete=models.CASCADE) car_model = models.ForeignKey(CarModel, on_delete=CASCADE) fuel_type = models.CharField(max_length=15, choices=FUEL, default=None) engine = models.CharField(max_length=15) extra_info = models.TextField(max_length=300, verbose_name='Remarks', null=True, blank=True) date_added = models.DateTimeField(auto_now_add=True) date_updated = models.DateTimeField(auto_now=True) def __str__(self): return f"{self.client} | {self.car_make} {self.car_model}" class Meta: ordering = ('-date_updated',) class Service(models.Model): car_relation = models.ForeignKey(Car, on_delete=models.CASCADE) service_name = models.CharField(max_length=200, verbose_name='Service') service_price = models.CharField(verbose_name='Price', blank=True, null=True, max_length=20) def __str__(self): return self.service_name forms.py class AddServiceForm(forms.ModelForm): class Meta: model = models.Service fields = ['service_name'] class CarForm(forms.ModelForm): class Meta: model = models.Car fields = '__all__' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['car_model'].queryset = models.CarModel.objects.none() # returns no value till "Make" field is chosen, will be negated in elif statement if 'car_make' in self.data: try: car_make_id = int(self.data.get('car_make')) self.fields['car_model'].queryset = models.CarModel.objects.filter(make_id=car_make_id).order_by('model_name') except (ValueError, TypeError): pass elif self.instance.pk: self.fields['car_model'].queryset = self.instance.car_make.carmodel_set.order_by('model_name') # … -
how to to check if a value exists in a multiselectfield with django templat language
I am using multiselectfield in the models so that a user can select multiple values and store in a column called sub_law_type. The values are gettting stored correctly in that column. Now in the html I have some conditions that are to be met for the judgement data to be displayed. All the other condtions are being checked correctly but I am confused as to how to check if a value exists in the sub_law_type. here I want to check if the sub_law_type has the value 'ipc' in it then only display the judgement the code below is the way I wrote initially to check if the condition is true but this was not displaying any result {% if data.law_type == 'criminal' and data.sub_law_type.ipc and data.law_category == 'limitations' and data.court_type == 'The Supreme Court of India' %} then i tried writing it as below but even that was not displaying the correct result {% if data.law_type == 'criminal' and data.sub_law_type== 'ipc' and data.law_category == 'limitations' and data.court_type == 'The Supreme Court of India' %} Since both of them are not working I am confused how I should write it so tat i can get the result. models.py sub_type_of_law = ( … -
django model ImageFile upload through code/manually
I am writing a populate script in python to register users and registeration asks them to upload a picture. Now, to achieve it through code, I read various threads of stackoverflow and came up with the 'picture.save' code below to save an image to the ImageField where actually user uploads a image. Below is the snippet of code in my populate_dogpark.py file from django.core.files import File created, __ = Dog.objects.get_or_create(owner=dog['owner'], breed=dog['breed'], breedname=dog['breedname'], name=dog['name'], age=dog['age'], gender=dog['gender']) created.picture.save(dog['path'], File().read(), True) created.save() But, upon attempting to execute this command I get the following error: File "populate_dogpark.py", line 80, in create_dog created.picture.save(dog['path'], File().read(), True) TypeError: __init__() missing 1 required positional argument: 'file' (socialapp) What I want to achieve is that for the following field in my model, picture = models.ImageField(upload_to="dog_profile_picture", blank=True) I want the ImageField to automatically upload picture from the path to file from the static/images directory I will provide in dog['path']. I need help to resolve this error. Stack trace provided above. -
django user authenticate only returns None
i'm trying to create a simple API on Django, and this is my first. The class User get the AbstractUser, like this: from django.db import models from django.contrib.auth.models import AbstractUser class Usuario(AbstractUser): nome = models.CharField(max_length = 255) username = models.CharField(max_length=150, unique=True, blank=False, null=False, default="") nascimento = models.DateField() password = models.CharField(max_length=128, blank=False, null=False, default="") But when I try to authenticate, the method allways returns None. Why? I checked, on DataBase, and the Users are already there. from django.shortcuts import render, redirect from conta.models import Usuario import secrets from django.contrib.auth import authenticate, login def login_view(request): if request.method == "POST": user = request.POST.get("user") senha = request.POST.get("password") autenticador = authenticate(request, username=user, password=senha) if autenticador is None: context = {"error" : "Invalid username or password"} return render(request, "conta/tela_de_login.html", context) login(request, autenticador) redirect('/admin') return render(request, "conta/tela_de_login.html", {}) -
OpenCV camera issue with Django and Azure
I am new to using azure and django. During my project I'm having issues with the camera on my laptop. When running the code on my local system, it works completely fine (the camera opens, detects everything and does what it needs to). So after that I uploaded my code on azure using a virtual machine to get it up and running. The code is uploaded fine and everything works fine but the camera doesn't switch on (a broken image box appears) when I go to the page where the camera is supposed to run. What can I do to fix this? I uploaded the code using azure web app to look at the error logs, errors like this appear too- [ERROR] import gi [ERROR] ModuleNotFoundError: No module named 'gi' [ERROR] [ WARN:0] global /tmp/pip-req-build-khv2fx3p/opencv/modules/videoio/src/cap_v4l.cpp (890) open VIDEOIO(V4L2:/dev/video0): can't open camera by index [ERROR] INFO: Created TensorFlow Lite XNNPACK delegate for CPU. [ERROR] cv2.error: OpenCV(4.5.4) /tmp/pip-req-build-khv2fx3p/opencv/modules/imgproc/src/color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function 'cvtColor' (I do not get these errors on my local system, only when I upload it) (Also the audio clip that is supposed to play doesn't work either, does that have something to do with server configuration?) I … -
How to get model-objects using other models in django
I need if user requests to get the following page the response of the request would be the page containing specific posts made by the users who is followed by the user who requests. I thought to do some actions to do this: Get the requester Get the users who are followed by the requester Get the posts created by the users the who are being followed In my models.py: class User(AbstractUser): image_url = models.CharField(max_length=5000, null=True) class Follow(models.Model): follower = models.ForeignKey( User, on_delete=models.PROTECT, related_name="follower") following = models.ForeignKey( User, on_delete=models.PROTECT, related_name='following') class Post(models.Model): content = models.CharField(max_length=140) date_created = models.DateTimeField(auto_now_add=True) poster = models.ForeignKey(User, on_delete=models.CASCADE) In my views.py: def following_page(request, username): user = User.objects.get(username=username) f = user.following.all() posts = Post.objects.filter(poster=f.following) posts = posts.order_by("-date_created").all() return render(request, 'network/index.html', { "posts": posts }) It says AttributeError 'QuerySet' object has no attribute 'following' Should I have to change the model? How to solve the problem? -
Djongo ArrayReferenceField in Django Admin Issue
I have used the below models class ProductVariation(Trackable): """Product Variation""" variation_name = models.TextField() storage = models.CharField(max_length=127) color = models.CharField(max_length=255) ram = models.CharField(max_length=255) price = models.CharField(max_length=31) variation_images = models.ArrayReferenceField(to=GenericImages, null=True, on_delete=models.CASCADE) objects = models.DjongoManager() class Product(Trackable): """Product master""" product_model = models.CharField(max_length=255) processor = models.CharField(max_length=127) screen_size = models.CharField(max_length=127) variation = models.ArrayReferenceField(to=ProductVariation, on_delete=models.CASCADE, related_name='variants') product_metadata = models.JSONField(blank=True) ##Foreignkey category = models.ManyToManyField('Category') # sub_category = models.ManyToManyField('SubCategory') brand = models.ForeignKey(Brand, on_delete=models.CASCADE, null=True, blank=True) def __str__(self): return self.long_name and this is my admin.py for product model class ProductAdmin(admin.ModelAdmin): list_display = ('product_model', 'created_at',) I'm not able to add the variations in the django admin for Product form(i.e there is no add symbol like for categories in front of variations field)Refer the Image Versions: Python: 3.7 Django: 3.2.6 djongo: 1.3.6 Please help me with this. Thanks! -
How to convert UIImage to data that Django understands
It may seem like a stupid question, but I have a problem with UIImage. My app communicates with my Django server, and for that, I'm using Alamofire. I need to pass an image, but I don't know how to convert UIImage to appropriate data so that the server can understand. My code currently looks like this: let param = ["image": image] // <- 'image' is a UIImage AF.request(method: .post, parameters: param) // and so on The server says the form is invalid. For my server, I'm using a form looks like this: class UploadImageForScanForm(forms.Form): image = forms.ImageField() How can I convert a UIImage to an appropriate data format so that my Django server can understand it and do its work with it? -
How to filter users first name from related model in Django filter form
I want to filter users first name from my profile model using Django filter this is my profile model in models.py. from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) total_members = models.CharField(max_length=500, blank=True) ...other fields and this is my filters.py import django_filters from .models import Profile class ProfileFilter(django_filters.FilterSet): class Meta: model = Profile fields = '__all__' in this when I add my form to template it gives me select tag with all users username and I don't want that because if user want to filter user by it's name than they can search by their name instead of looking in drop down.Please help me (: -
django changing a value of databe field using variable in view
Is there any way to update the by-hand value of a particular field in the model instance using variables? For example. models.py class ExampleModel(models.Model): name=models.CharField(max_length=10) a=models.CharField(max_length=10) b=models.CharField(max_length=10) c=models.CharField(max_length=10) views.py list=[a,b,c] fruits=[orange,apple,banana] values def ExampleView(request): model_instsnce=ExampleModel.objects.last() for i in list: instance_model.i=fruits[i] model_instance.save() In my project, I tried to use something like the above but it doesn't work. 'i' from loop doesn't behave like a variable. 'i' is treated as a new field in the model. Any idea how to use variables to designate fields from model to change? -
How to avoid data being stored in database using django rest framework
I have create a django rest framework api. For that i have created model, then create a serialize. It is working fine. I want to know is there a way that my input would not store in database. Currently, my inputs are stored in sqlite3 database. The reason why i want to do that the user input value via php form. I have to take 1 value from that form and do some modifications on it and return the value. Thats why i dont think i need a db for my django project, Here is code models.py class MyModel(models.Model): value=models.IntegerField() serializers.py class MySerializer(serializers.ModelSerializer): class Meta: model=MyModel fields='__all__' views.py class MyViews(APIView): def post(self, request): serializer = MySerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response({"status": "success", "data": serializer.data}, status=status.HTTP_200_OK) else: return Response({"status": "error", "data": serializer.errors}, status=status.HTTP_400_BAD_REQUEST) urls.py urlpatterns = [ path('api', VideoUploadViews.as_view()) ] -
Sorl-thumbnail only working with DEBUG=True
I'm using Python 3.6.9, Django 3.2.8, sorl-thumbnail 12.7.0 with memcached my thumbnails completely disappear and give a 404 when settings.py variable DEBUG is set to False. I also have to say, that I don't get any errors displayed at all from setting THUMBNAIL_DEBUG = True as I understand it depends on the aforementioned variable which I have to set to False for pictures to disappear, if it does not depend on it I'm not getting any error displayed either. I'm just loading them inside templates like this: {% load thumbnail %} {% thumbnail ann.obj.fotografia_professionista "460x310" as thumb %}<img src="{{ thumb.url }}" data-src="{{ thumb.url }}" class="img-fluid lazy">{% endthumbnail %} and it works fine as long as DEBUG = True. I restarted apache2 and memcached, I also used python manage.py thumbnail clear or cleanup but it just doesn't work at all. I'm delivering the thumbnails at SETTINGS.MEDIA_URL, which is just set to "/media" and that I'm enabling in urls.py like this: urlpatterns = [ # my paths ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I did read this thread and I set up my urlpatterns the same exact way as it was suggested, but it doesn't solve my problem -
I have a problem with making random backgorund image usign js inside my django project?
the images don't appear even though I add the correct directory but djaong post give this massage in console: GET http://127.0.0.1:8000/%7B%%20static%20bc-3.jpg%20%%7D 404 (Not Found) script.js:24 my problem is I wanna add a random background image in my project I set this in CSS property "background-image" and it's work the URL but js code doesn't work my code: index.html {% extends "kidedu/layout.html" %} {% load static %} {% block body %} <div class="random_images_container"> <div class="main_head"> <h1>Join Our Big Community, To Educate Kids.</h1> <h5>Get Start, By sing-in for a new account or log in.</h5> <a class="head_btn btn" href="{% url 'sign_up' %}">Join Us</a> </div> <div class="arrows"> <i class="fas fa-chevron-left le"></i> <i class="fas fa-chevron-right ri"></i> </div> <ul class="bullets"> <li></li> <li class="active"></li> <li></li> </ul> </div> {% endblock %} js file // Image slider const imageSlider = document.querySelector(".random_images_container") const imagesArr = ['bc-1.jpg', 'bc-2.jpg', 'bc-3.jpg'] setInterval(() => { let randomNumber = Math.floor(Math.random() * imagesArr.length) console.log(randomNumber); imageSlider.style.backgroundImage = 'url("{% static '+imagesArr[randomNumber]+' %}")' }, 1000) url.py from django.urls import path from django.urls.resolvers import URLPattern from . import views urlpatterns = [ path("", views.index, name="index"), # User path("log_in/", views.log_in, name="log_in"), path("sign_up/", views.register, name="sign_up"), path("log_out/", views.log_out, name="log_out"), ] style.css .random_images_container { height: 515px; background-size: cover; background-image: url("{% static 'images/bc-1.jpg' %}"); width: … -
How to send Django GraphQL Auth mails with Celery?
I am using Django GraphQL Auth for authentication purposes. It has this feature to automatically send emails after creating an account or during a password reset etc. I want to use this feature with Celery and thankfully it provides that too here. It's just that I am not sure how to use that feature. Can you tell me how? -
Django - Pass PK as initial value in Form(CreateForm)
-Objective- I want to set an object PK as initial value in the Create Form. Version Python 3.9.2 - Django 3.2 - (Crispy-Forms) Context: I created a list from where I create objects(each with pk). Once I select one I can add several lines from a Detail page(Detailview)that redirects to create/update forms (like add/edit informations related to that specific object). I need to have it related (1 to many). -Issue and Error- I'm unable to get the object PK -as initial value- in the 1st field of the Creation form(based on Createview+ Forms.py + Class in Models.py). Errors such as: "object can't be null" - value does not appear in the form, but the space/widget does - many, many others. I tried plenty of variations of code(get pk from url, from cache, dict., def in forms.py)...but haven't found one way to make it work. Please, any help on the matter would be kindly appreciated. Thanks in advance, Below my code: Forms.py ----------------------------CREATION FORM IN THE ENDPAGE-------------------------- from django import forms from django.forms import ModelForm from django.contrib.auth.models import User from django.db.models.fields import BooleanField, CharField, DateField from django.forms import ModelForm, widgets from django.forms.fields import ChoiceField from django.forms.models import ModelChoiceField from django.http.response import … -
Example of usage Subquery in django orm
What is the difference between two queries? Because I see identical queries through queryset.query. categories = Category.objects.filter(is_active=True).values_list("pk", flat=True) Post.objects.filter(category_id__in=Subquery(categories)) vs Post.objects.filter(category_id__in=Category.objects.filter(is_active=True).values_list("pk", flat=True)) And how to use Subquery properly? In what cases? Can anyone explain with examples Subquery, Outref etc? -
I am creating a blog site. I want to create a list field in the user model , or the profile model to store all the posts created by the user
** Help me to create a list field in the models or extend the user model to have the lists of posts created by the user. ** from django.db import models from django.contrib.auth.models import User from PIL import Image from blog.models import Post # This is my Profile Model class Profile(models.Model) : user = models.OneToOneField(User , on_delete = models.CASCADE) image = models.ImageField(default= 'default.png' , upload_to = "profile_pics") """ i want to create list field to store the posts user create . This is the Profile model . whenever a post is created by the user. the list in here saves the post created by the user. """ def __str__(self): return "{} Profile".format(self.user.username) def save(self, *args, **kwargs): super().save(*args, **kwargs) img = Image.open(self.image.path) if img.height > 125 or img.width >125 : output_size = (150 , 150) img.thumbnail(output_size) img.save(self.image.path) This is my Post model . How and where should i create the list so that i can have the track of the posts created by the user. from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse class Post(models.Model) : title = models.CharField(max_length = 100) content = models.TextField() date_posted = models.DateTimeField(default = timezone.now) author = models.ForeignKey(User, on_delete … -
Django Sessions not Working on remote server
I am trying to use a session variable in my django app view.py def get(self, request): room_name = request.session.get('room_name', str(uuid.uuid4().hex)) context = app.get_context(room_name) context['room_name_create'] = room_name context['room_name_check'] = request.session.get('room_name') return render(request, self.template, context) js console.log('a', context.room_name_create) console.log('b', context.room_name_check) This works perfectly on my local server. On the remote server context.room_name_create shows a value, but context.room_name_check shows as null in the browser. This is only a small app and I have copied all of the source files to the remote server and so all of the source is identical. I have tested this on different browsers Can anyone suggest what I can check to resolve this? -
What is the entry point of a Django app similar to main.py? Where do I set up parameters?
I want to set up some parameters and initialize the Injector object, because I want to use a dependency injection and singletons in my Django app. Usually I do that in the main.py of my app but with Django I don't see where the first entry point of the application is when it runs. Where shoud I initialize the injector and pass it my views and services? I have a view like this: from uuid import UUID from django.shortcuts import render from django.http.response import JsonResponse from django.http.request import HttpRequest from rest_framework import viewsets, status from rest_framework.parsers import JSONParser from rest_framework.response import Response from Instruments.services import InstrumentsService from rest_framework.decorators import api_view from Instruments.services import InstrumentsService from injector import singleton, inject # Application views live here @singleton class InstrumentViewSet(viewsets.ModelViewSet): @inject def __init__(self, instrument_service: InstrumentsService, **kwargs): self.instrument_service = instrument_service super().__init__(**kwargs) def list(self, request: HttpRequest): data = {} try: data = self.instrument_service.get_instruments() return JsonResponse(data, status=status.HTTP_200_OK, safe=False) except Exception as exc: return JsonResponse( {"Status": f"Error: {exc}"}, status=status.HTTP_400_BAD_REQUEST, safe=False, ) def create(self, request): instrument_data = JSONParser().parse(request) data = {} try: data = self.instrument_service.add_instrument(instrument_data) return JsonResponse(data, status=status.HTTP_201_CREATED, safe=False) except Exception as exc: return JsonResponse(data, status=status.HTTP_400_BAD_REQUEST, safe=False) def retrieve(self, request, pk: UUID = None): data = {} try: … -
Why isn't assertContains working properly in django tests?
I wrote a test that is supposed to create a flight, then pass appropriate arguments to the client.get function and receive a response that will contain results of 'search' - in this case it should be only the flight created before as a direct flight from Airport to AirportSeceond(names or airport and airport2). However, it seems that there are no results in the response (the first assertion works properly). My test (TestCase): def test_no_errors_html_direct_flights(self): country, city, airport, city2, airport2, airport3 = create_set() flight = SingleFlight.objects.create(departure_airport=airport, arrival_airport=airport2, departure_time_utc=(tz.now()+datetime.timedelta(days=5)), duration_in_hours=2, duration_in_minutes=10, price=200) print("\n\n\n") print(flight) date = (tz.now() + datetime.timedelta(days=5)).date().strftime("%Y-%m-%d") print(date) kwargs = {'dep': 'Airport', 'arr': 'AirportSecond', 'date': date} response = self.client.get(reverse('app1:flight-search-result'), kwargs) self.assertContains(response, 'No options for your search') self.assertContains(response, 'Direct connection') My template: {% block content2 %} {% if not direct_flights %} {% if not indirect_flights %} <p><strong>No options for your search</strong></p> {% endif %} {% endif %} {% for flight in direct_flights %} <p>{{ flight.departure_airport }}</p> <p>{{ flight.departure_time_local }}</p> <p> </p> <p>{{ flight.arrival_airport }}</p> <p>{{ flight.arrival_time_local }}</p> <p>Direct connection</p> <---- this should be in the response <a href="{% url 'app1:flight-search-detail-passenger-form' flight.id_flight %}">Here! ;)</a> {% endfor %} {% for connection in indirect_flights %} {{ connection.price }} {% for flight in connection.all_info %} … -
Access to ForeingKey's model data in Django
I need to access to a ForeignKey's model data, but I don't know how. I wrote this as a simple example of what I want to do: class Model1(models.Model): name = models.CharField(max_length=100) phone_number = models.BigIntegerField() class Model2(models.Model): model1 = models.ForeignKey(Model1, on_delete=models.CASCADE) name = model1.name phone_number = model1.phone_number It gives me the following error message: AttributeError: 'ForeignKey' object has no attribute 'name' -
How to customize a look of crispy forms?
I have to edit an upload form created with crispy forms. I have provided a code that I have been used, and how it looks right now and how I would like to look. I tried to do it with helper attributes, but I failed, can you help me to get wanted outcome? This is how it looks now! I'm looking for something like this! This is upload_document.html {% extends "base.html" %} {% load static %} {% load crispy_forms_tags %} {% block content %} <h1>Upload</h1> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form|crispy }} <button type="submit" class="btn btn-primary">Upload</button> </form> {% endblock content %} models.py from django.db import models class UploadFile(models.Model): excel = models.FileField(upload_to="excel/", max_length=250) def __str__(self): return self.title forms.py from .models import UploadFile class GlForm(forms.ModelForm): class Meta: model = UploadFile fields = ('excel',) settings.py CRISPY_TEMPLATE_PACK = 'bootstrap4' INSTALLED_APPS = [ 'bootstrap4', 'crispy_forms', '...', ] Thanks in advance! -
Django Swagger won't allow me to use POST method (no parameters shown)
I'm using djangorestframework together with drf-spectacular modules for a Django project, and I'm trying to build some basic API methods for my Project model. Its structure looks like this: from django.db import models # Create your models here. class Project(models.Model): title = models.CharField(max_length = 128) description = models.TextField() image = models.URLField() date = models.DateTimeField(auto_now_add=True) I also have a serializer for the model, looking like this: from rest_framework import serializers from api.models.Project import Project class ProjectSerializer(serializers.ModelSerializer): class Meta: model = Project fields = ['title', 'description', 'image', 'date'] Then, in views.py, I created two functions: project_list_view, which either lets you to GET all the Project objects from the database, or lets you POST a new object. And finally, project_detail_view, which lets you GET a Project object by typing in its pk (integer id). These are my two functions: @api_view(['GET', 'POST']) def project_list_view(request): if request.method == 'GET': projects = Project.objects.all() serializer = ProjectSerializer(projects, many=True) return Response(serializer.data) elif request.method == "POST": serializer = ProjectSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) @api_view(['GET']) def project_detail_view(request, pk): if request.method == "GET": try: project = Project.objects.get(pk = pk) serializer = ProjectSerializer(project, many = False) return Response(serializer.data, status = status.HTTP_200_OK) except: return Response(status=status.HTTP_404_NOT_FOUND) The GET from …