Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Upload file on Django REST framework default view
I am using Django REST framework. It makes UI easily api_view like this @api_view(['POST', 'GET']) def uploadFile(request): data = {'meta':'upload','status':1} return Response(response) There appears form automatically. Is it possible to add file upload form on this?? I have found samples of Django REST framework and some frontend, however couldn't find the form using default view. -
DRF Serializer doesn't recieve value from request for ManyToMany field
My Model is class ChatRoom(models.Model): name = models.CharField(max_length=55, verbose_name='Имя чата', unique=True) users = models.ManyToManyField( CustomUser, verbose_name='Пользователи', related_name='user_chatrooms', null=True ) My Serializer for this model class ChatRoomSerializer(serializers.ModelSerializer): users = UserInfoSerializer(many=True, read_only=False) class Meta: model = ChatRoom fields = [ 'name', 'users' ] View looks @api_view(['POST']) @permission_classes([IsAuthenticated]) def api_create_chat(request): if request.method == 'POST': serializer = ChatRoomSerializer(data=request.data) 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) I do request (here is body) <QueryDict: {'name': ['benny'], 'users': ['11,1']}> In this case I recieve Error {'users': [ErrorDetail(string='This field is required.', code='required')]} And I can't understand what is wrong here. When I change parameter to read_only=True in UserInfoSerializer it works, but it doesn't add user to new Chat object. { "name": "benny", "users": [] } -
Unable to execute .sh file from docker container in Windows
I am using Windows 10, and working on a Django Project with Docker. If I run a python command from inside docker container, it runs perfectly. E:\path>docker exec -it my_docker_container bash root@701z00f607ae:/app# python manage.py makemigrations authentication No changes detected in app 'authentication'enter code here But when I try to run same command using a .sh file, it gives different output. root@701z00f607ae:/app# cat ./migration_script.sh python manage.py makemigrations authentication root@701z00f607ae:/app# ./migration_script.sh '. installed app with label 'authentication Note: Executing ./migration_script.sh works perfectly on Linux based system. -
Django "NotImplementedError: `to_internal_value()` must be implemented" when sending a patch request
I'm trying to get an updated normalized resource when I update a resource using patch. (Using APIRequestFactory in my TestCase tests e.g self.factory.patch) LoadBaseSerializer inherits BaseSerializer and using to_representation. I'm doing this to return a customized serializer. However, I keep getting that annoying error. The patch request contains {'carrier' : 2 }. I expect to return the whole serialized resource, but I guess this only works for GET requests. How am I able to get this work for PATCH/POST methods? View: class LoadUDView(RetrieveUpdateDestroyAPIView): serializer_class = NormalizedLoadSerializer queryset = Load.objects.all() My serializer looks like this: # custom serializer class NormalizedLoadSerializer(LoadBaseSerializer): # not working, still get error def to_internal_value(self, data): load_data = data['carrier'] return super().to_internal_value(load_data) def to_representation(self, instance): # dict values serialized using ModelSerializer data = dict( contacts=self.get_driver_contacts(instance.carrier), drivers=self.get_drivers(instance.carrier), income = IncomeSerializer(instance.income, read_only=True).data, expense = ExpenseSerializer(instance.expense, read_only=True).data, stops = StopSerializer(instance.stops, many=True, read_only=True).data, load=LoadSerializer(instance, read_only=True).data, income_line_items= self.get_income_line_items(instance), expense_line_items= self.get_expense_line_items(instance), addresses=self.get_addresses(instance) ) return data LoadBaseSerializer: # inherit BaseSerializer and added helper functions class LoadBaseSerializer(serializers.BaseSerializer): def get_income_line_items(self, instance): income = instance.income.income_line_items.all() return IncomeLineItemSerializer(income, many=True).data def get_expense_line_items(self, instance): expense = instance.expense.expense_line_items.all() return ExpenseLineItemSerializer(expense, many=True).data def get_addresses(self, instance): data = [stop.address for stop in instance.stops.all()] return AddressSerializer(data, many=True).data def get_driver_contacts(self, carrier): data = [driver.contact for driver in … -
why isn't django creating my media directory through my update form ,but works fine when is use admin panel?
im trying to upload a profile picture and it works fine when using the admin panel but when is use my template form it give the wrong path(i know this because i displayed it to check the url) like so... <p>{{user.userprofile.profile_image.url}}</p> output on html page: /media/check.png when it should instead be: /media/images/check.png Note: everything else works fine on my form and it even shows that the image url was update in the admin panel but only shows the image name and not (images/img_name.png) as it should form: <form method="post" action="{%url 'profile-view' username=user.username%}" enctype="multipart/form-data" class="myOverlayForm"> {%csrf_token%} <label for="id_profile_image">Profile Image: <i class="fa fa-upload" style="font-size: 30px;"></i></label> <input type="file" name="profile_image" accept="image/*" id="id_profile_image"> <div class="form-group"> <label for="bioInput">Bio: </label> {%if form.errors%} <div class="alert alert-warning alert-dismissible fade show my_error" role="alert"> <strong>{{form.errors.bio}}</strong> <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> {%endif%} <div class="form-group"> </div> <input type="text" class="form-control" name="bio" maxlength="150" minlength="25" id="id_bio"> <small id="bioHelp" class="form-text text-muted">Please avoid to putting out very personal information.</small> </div> <div class="form-group"> <label for="bioInput">Age:</label> <input type="number" class="form-control" name="age" placeholder="Enter Age"> <small id="ageHelp" class="form-text text-muted">Note that this has nothing to do with age restriction, CLASSY is available to everyone☺.</small> </div> <button type="submit" name="update_profile_details" class="btn btn-block btn_update">Update</button> </form> view function: views.py def profile_view(request,username): try: profileForm = … -
In a project in drf, I have endpoint "api/v1/invoice/#id/" so I want to give access to view to only author of this invoice
I have an endpoint /api/v1/invoice/#id/ I want that only author of this invoice should be able to view invoice Or staff should be able to view this invoice And superuser should be able to view, update, delete invoice I tried creating permissions.py file in my app: permissions.py from rest_framework.permissions import BasePermission class AuthorGetStaffGetAdminAll(BasePermission): edit_methods = ("PUT", "PATCH", "DELETE") def has_permission(self, request, view): if request.user.is_authenticated: return True return False def has_object_permission(self, request, view, obj): if request.user.is_superuser: return True if obj.author == request.user and request.method not in self.edit_methods: return True if request.user.is_staff and request.method not in self.edit_methods: return True return False -
Django: m2m's .count() and .order_by() with annotate values are very slow
The Video has about 300k data and there are about 2k Tags. If you do .annotate(count=Count('video')) and then do .order_by('-count') with that value as shown below, it will take It takes about 500ms. Also, since we are using DRF pagination, the .count() is being done behind the scenes, and the speed of the .count() is about 500ms. I have no idea what causes these things, even though I have researched them. How can I remedy this? # models.py class Tag(models.Model): name = models.CharField(unique=True, max_length=100) is_actress = models.BooleanField(default=False, db_index=True) created_at = models.DateTimeField(default=timezone.now) class Meta: ordering = ["-is_actress"] def __str__(self): return self.name class Video(models.Model): tags = models.ManyToManyField(Tag, blank=True, db_index=True) # serializers.py class TagSerializer(serializers.ModelSerializer): count = serializers.IntegerField() class Meta: model = Tag fields = ("pk", "name", "is_actress", "count") # views.py class TagListPagination(PageNumberPagination): page_size = 100 class TagListView(generics.ListAPIView): serializer_class = TagSerializer pagination_class = TagListPagination def get_queryset(self): return Tag.objects.annotate(count=Count("video")).order_by("-count") -
Django Custom SQL to Feed into a Model
I have done some Google search and find the following: Use custom query result as source for Django model (MySQL database) Also, I have found similar stuff in the Django document site. However, I am still struggling after doing some searching. Original Working Scripts cName = models.CharField(max_length=20, null=False) cSex = models.CharField(max_length=2, default='M', null=False) cBirthday = models.DateField(null=False) cEmail = models.EmailField(max_length=100, blank=True, default='') cPhone = models.CharField(max_length=50, blank=True, default='') cAddr = models.CharField(max_length=255,blank=True, default='') def __str__(self): return self.cName Then, I try to change the above to custom SQL. The following is not working. for p in student.objects.raw('SELECT cName, cSex, cBirthday, cEmail, cPhone, cAddr FROM TUTORIAL.STUDENTSAPP_STUDENT'): print(p.cName,p.cSex,p.cBirthday,p.cEmail,p.cPhone,p.cAddr ) it returns NameError: name 'student' is not defined Please suggest what is missing. Thanks in advance. -
How to create datefield in django models in the format (mm-dd-yyyy)
I am scraping the dates from different websites and it is in the format of mm-dd-yyyy ie. 10-28-2021 . Right now, I'm storing it as a string. In django models, I have created the field as: issued = models.CharField(max_length=16) This stores the data as string. But I want to convert into a datefield. When I tried, issued = models.DateField() I cannot store the data in this field. How to add the date in the particular format in the above field? -
How to create a relation to intermediate table using Model in Django?
Could anyone help me create this database using the ORM model in Django? I'm stuck at creating table CHITIETLOPHOC, DINHDANHKHUONMAT, DINHDANHTHUCONG ERD -
Get multipe images urls on Django RestFramework
I'm using Django RestFramework to create a simple eCommerce API where one product could have many images and I would like to get the URLs of all these images on a json field. For now, I got the first image url using "imagembicicleta_set.all.first.image.url" on the serializer, but I need all URLs list: { "count": 7, "next": null, "previous": null, "results": [ { "id": 1, "nome": "Specialized Roubaix", "marca__nome": "Specialized", "categoria": "Bicicletas de Estrada", "atividades": [ 1 ], "terrenos": [ "Asfalto" ], "preco": "16999.00", "ano": 1, "absolute_url": "/bicicletas/Specialized/specialized-roubaix-2020/", "img_url": "/media/images/bicicletas/roubaix1.jpeg" }, { "id": 2, "nome": "Specialized Roubaix Sport", "marca__nome": "Specialized", Following how is my setup: Models.py class Bicicleta(models.Model): id = models.AutoField(primary_key=True) nome = models.CharField(max_length=200, blank=False, null=False) slug = models.SlugField(unique=True) status = models.IntegerField(choices=STATUS_CHOICES, default=1, blank=False, null=False) descricao = RichTextField(blank=True, null=True) marca = models.ForeignKey(MarcaBicicleta, blank=True, null=True, on_delete=models.SET_NULL) ... class ImagemBicicleta (models.Model): bicicleta = models.ForeignKey(Bicicleta, default=None, on_delete=models.CASCADE) image = models.ImageField(upload_to='images/bicicletas') Serializer.py class BicicletasSerializer(serializers.ModelSerializer): marca__nome = serializers.CharField(source='marca.nome') categoria = serializers.CharField(source='categoria.nome') terrenos = serializers.StringRelatedField(many=True) absolute_url = serializers.URLField(source='get_absolute_url', read_only=True) img_url = serializers.URLField(source='imagembicicleta_set.all.first.image.url', read_only=True) #I could get the first image using this class Meta: model = Bicicleta fields = ['id', 'nome', 'marca__nome', 'categoria', 'atividades', 'terrenos', 'preco', 'ano', 'absolute_url', 'img_url'] views.py class BicicletasView(generics.ListAPIView): serializer_class = BicicletasSerializer queryset = Bicicleta.objects.all() … -
Why my button doesn't return "POST" django?
When I click the button I always get the method GET instead of post: Any Ideas? Thanks! <body> <form action="/reset" type="POST"> {% csrf_token %} <h3>Random Word (attempt # {{request.session.counter}})</h3> <div> <h1>{{request.session.rword}}</h1> </div> <label for="title">Title</label> <input type="text" name="title" id=""> <button type="submit">Generate</button> </form> -
Django Overriden Admin Template not importing JS
I have a Django template I am trying to run with my own JS code. So I extended the admin template login in my /templates folder of my app. However, I can confirm the script is there if I go to: http://localhost:8000/static/admin.js But in the source and console log never appear. I don't ever see my script tag either. This is my dir structure: [![directory structure ][1]][1] Here's my template code: {% extends "admin/login.html" %} {% load static %} {% block content %} <h2> hello world! </h2> <p>{% static 'admin.js' %}<p> {% endblock %} <script src="{% static 'admin.js' %}"></script> My settings do have APP_DIRS set to true as well so it should see the template and it does but doesn't put in my script tag. -
How do I write a Django query that matches only the minute field of a DateTime column?
I'm using Django 3.2 and PostGres 9.6. I have this model with a "created" DateTime field ... class PriceQuote(models.Model): ... created = models.DateTimeField(null=False, default=datetime.now) How do I write a Django filter query that includes a clause to match the minute field of the created column? So in the below class PriceQuoteManager(): def get_prices_per_hour(self, item): now = datetime.datetime.now() end_time = now.replace(second = 0, microsecond = 0) start_time = end_time - timedelta(days=1) return PriceQuote.objects.filter( item=item, created__range=[start_time, end_time], xxx=end_time.minute ) I want to replace "xxx" with a clause that says match the minute field of "created" with the minute field of the "end_time" variable. -
add bearer token with post in unit tests Django - ValueError: invalid literal for int() with base 10
I am trying to add a bearer token via posting in the unit tests, the access_token is well generated, but when I pass it i the post request and error is thrown as below : ValueError: invalid literal for int() with base 10: '<bound method TestCase.id of <customers.tests.CustomerProfileTestCase testMethod=test_validate_founder_cant_add_owp>>' Below is my test : def setUp(): user = User.objects.create_user(username='john', email='js@js.com', password='js.sj') client = APIClient() @property def bearer_token(self): """Generate token with bearer""" refresh = RefreshToken.for_user(self) return str(refresh.access_token) def test_create_customer_profile(self, data): """ Create a new customer profile. :param self: Reference to the current instance of the class. :param data: customer profile data. """ token = self.bearer_token self.client.credentials( HTTP_AUTHORIZATION='Bearer ' + token) response = self.client.post( reverse('api:customers:customer-profile-list'), data) assert(response.status, 200) -
DRF Annotate all stores that an author have a book seeling
Currently I'm trying to annotate an information in my Author API: All Stores where that author have a book. I have the following models: class Author(models.Model): name = models.CharField(max_length=100) age = models.IntegerField() class Book(models.Model): name = models.CharField(max_length=300) authors = models.ManyToManyField(Author, related_name='books') class Store(models.Model): name = models.CharField(max_length=300) books = models.ManyToManyField(Book) In my get_queryset method i've tried to do something like: def get_queryset(self): qs = Author.objects.all().annotate( stores=F('books__stores__name') ) return qs but stores return just one name of a store, and not a list of stores. can someone tell me what I'm done wrong ? Edit: my current Serializer: class AuthorSerializer(ModelSerializer): stores = serializers.CharField(max_length=300) class Meta: model = Author fields = ['name', 'age', 'books', 'stores'] -
How do you update user info with an api call to a django/djoser backend?
The djoser endpoint for the user data is /users/ and then the id number of the user. https://djoser.readthedocs.io/en/latest/getting_started.html#available-endpoints But I'm not sure how to get the id number of the user that's currently logged in so the api call can have that id number at the end. I'm able to get their token but not their actual id number. Any ideas on how to do that? I took a screenshot of the code below screenshot -
Django - AttributeError: module 'environ' has no attribute 'ENV'
Installed Python 3.9 on Windows 10. Also installed Django 3.2 Django-environ 0.8. But I don't know why this raise an error when I tried to run python manage.py runserver My code: import environ from pathlib import Path env = environ.ENV(DEBUG=(bool, False)) The error: AttributeError: module 'environ' has no attribute 'ENV' -
Recreating bootstrap cards row layout with tailwind in django
ASK I'm trying to recreate bootstrap cards row layout with Tailwind within django framework BLOCKER However the tailwind attempt results in below index.html -- bootstrap {% extends 'base.html' %} {% block title %}Home{% endblock title %} {% block content %} <div class="py-2"> <div class="row"> {% for t in object_list %} <div class="col-md-3"> <div class="card mb-4 box-shadow bg-green-500"> <div class="card-body"> <h2 style="font-size:18px;font-weight:bold;min-height:42px;"><a class="text-dark" href="#"> {{t.currency|truncatechars:50}}</a></h2> <div class="d-flex justify-content-between align-items-center"> <small class="text-muted">{{t.country|truncatechars:25}}</small> </div> </div> </div> </a> </div> {% endfor %} </div> {% endblock content %} index.html -- tailwind {% extends 'base.html' %} {% block title %}Home{% endblock title %} {% block content %} <div class="p-10 "> <div class="max-w-sm rounded overflow-hidden shadow-lg"> {% for t in object_list %} <div class="px-6 py-4"> <div class="font-bold text-xl mb-2">{{t.country}}</div> <p class="text-gray-700 text-base"> {{ t.currency }} </p> </div> {% endfor %} </div> </div> {% endblock content %} -
JavaScript help for responsive webapp
I know I might get some flack for this, but I'm basically looking for someone to spoon feed me with some javascript instructions for a web app I'm working on. I have no prior JS knowledge. I'm using Jinja2 template to render the webapp. The index page rengers out a list of divs which contain information about particular events. Users can join these events. This is done by sending a post request to the Django Server with the users name and the event ID. Can someone help me out with the JS code creates a pop-up display when a user clicks "join" button on a particular event. <div class="container" id="container"> {% for event in data %} <div class="event"> <div class="sport"> <h2>{{ event.description }}</h2> </div> <div class="venue"> <p> <span class="title">Creator:</span> {{ event.creator }}</p> </div> <div class="time"> <p> <span class="title">Date and Time:</span> {{ event.time }}</p> </div> <div class="venue"> <p> <span class="title">Venue:</span> {{ event.venue }}</p> </div> <div class="participants"> <p> <span class="title">Participants:</span> {{ event.participants }}</p> </div> <div class="join-now"> <a><h3 id="{{ event.id }}" class="join-now-button">Join</h3></a> </div> <div class="see-participants"> <a> <h3>See Participants</h3> </a> </div> </div> <div class="join-form"> <form action=""> <label for="">{{ event.id }}</label> <p><span class="title">Your Name:</span></p><input type="Name"> <br><br> <div class="join-now"> <a href=""> <button> <h3>Join</h3> </button> </a> </div> … -
stripe integration on Django project TypeError
I am new to Django and Stripe API. I am following the Stripe document and I copied the code from the document to my view.py file: this is my views.py file from django.shortcuts import render,redirect from django.conf import settings from django.urls import reverse from django.views import View import stripe stripe.api_key = settings.STRIPE_SECRET_KEY class Create_checkout_session (View): def post(self, request, *args, **kwargs): DOMAIN = "http://127.0.0.1:8000" checkout_session = stripe.checkout.Session.create( line_items=[ { # Provide the exact Price ID (e.g. pr_1234) of the product you want to sell 'price': 'price_id', 'quantity': 1, }, ], payment_method_types=[ 'card', ], # mode can be subscription, setup, payment mode='payment', success_url=DOMAIN+'/success/', cancel_url=DOMAIN+'/cancel/', ) return redirect(checkout_session.url, code=303) This is my urls.py in payment app: from django.urls import path, include #import views.py from . import views app_name ='payment' #set urls for the app urlpatterns = [ path('create-checkout-session/',views.Create_checkout_session, name='create-checkout-session') ] The error message I have is when I render this page, I have: TypeError at /create-checkout-session/ init() takes 1 positional argument but 2 were given Request Method: GET Request URL: http://127.0.0.1:8000/create-checkout-session/ Django Version: 3.2.8 Exception Type: TypeError Exception Value: init() takes 1 positional argument but 2 were given Exception Location: /Users/hannah/Desktop/TDMock/venv/lib/python3.9/site-packages/django/core/handlers/base.py, line 181, in _get_response Python Executable: /Users/hannah/Desktop/TDMock/venv/bin/python I put the stripe secret … -
Django Rest Framework Forbidden when i send post request
I am making a website with django rest framework backend and a react frontend but when i use axios to send a post request to /products it sends a 403 forbidden error this is the views file @api_view(['GET', 'POST']) def products(request): if request.method == 'GET': products = Product.objects.all() serializer = ProductSerializer(products, many=True) return Response(serializer.data) elif request.method == 'POST': serializer = ProductSerializer(data=request.data) print(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) this is how i send the request in react: const handleSave = () => ( axios.post('/products', getInputData()).then((response) => (console.log(response))) ); this is my settings file in django: ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', 'rest_framework', 'API', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ORIGIN_ALLOW_ALL = False CORS_ORIGIN_WHITELIST = ( 'http://localhost:3000', ) -
How to add a custom action for the same route as default one in a ViewSet
Suppose, we have a ViewSet class: class SomeViewSet(viewsets.ViewSet): def create(self, request): pass def custom_action(self, request): pass and we register SomeViewSet as follows: some_router = DefaultRouter() some_router.register(r'some-route', AuthenticationViewSet, basename='some-name') So, now we have the SomeViewSet with the standard action create, that will be accesible with the route some-route/ using POST HTTP method. The question is how to configure the custom_action action to be accesible by the same route as a standard create action (some-route/) with PUT HTTP method. -
Why the 'and' operator isn't working in the Django template?
What's supposed to be wrong in the following if-else statement in my template? {% if rp.package.patient_type != "CASH" and rp.realization.cash == True %} N/A {% else %} {{rp.realization.deficit_or_surplus_amount}} {% endif %} Even when the patient type is Cash, it displays N/A. Where am I going wrong here? -
Fullcalendar v5 only renders one event tip
I´m trying to render some events in v5 fullcalendar. This is my code: document.addEventListener('DOMContentLoaded',function(){ var cUI= document.getElementById('calendar'); var c= new FullCalendar.Calendar(cUI,{ themeSystem: 'bootstrap', headerToolbar:{ left:'prev,next today', center:'title', right:'', }, events:[ {% for v in vacation %} { {% if v.id_cause.cause_name == 'Vacations' %} backgroundColor : 'blue', borderColor : 'blue', {% else %} backgroundColor : 'darkgreen', borderColor : 'darkgreen', {% endif %} textColor : 'gray', title:"{{ v.startT }} - {{ v.endT }}", start: "{{ v.startD | date:'Y-m-d' }}", end: "{{ v.endD | date:'Y-m-d' }}", description:"{{v.id_cause.cause_name}} {{v.cause_text}}", }, {% endfor %} ], {% comment %} eventDidMount: function(info) { var tooltip = tippy('.fc-event-title-container',{ content: info.event.extendedProps.description, placement: 'top', interactive: true, }); }, {% endcomment %} }); c.render(); c.setOption('locale','en'); }); It renders the calendar and tips, however it repeats the same tip for all events, but colors for different cause_names shows different, so I don´t get the point it renders all events with their data correctly but tips fails. I´m on django 3 btw. Maybe rollback to previous fullcalendar version with eventRender, instead eventDidMount? Thanks for the help