Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
JSONDecodeError while working with websockets
I'm learning to work with WebSockets. I'm using Django as server-side and react at the client-side. I'm able to connect and send an object to the backend but unable to receive massage on the frontend side. I'm sharing my code. Please me my flaws and a perfect way to do the basic setup of sockets on the frontend and backend. Thank You. django-python import json from channels.generic.websocket import WebsocketConsumer class ProjectConsumer(WebsocketConsumer): def connect(self): print("HEY HEY HEY HEY") self.accept() def disconnect(self, close_code): pass def receive(self, text_data): print("Reciasha",text_data) text_data_json = json.loads(text_data) # message = text_data_json['message'] message =text_data print("Hey",message) self.send(text_data=json.dumps({ 'message': message })) React-js export const WebSocketTest = () => { var ws = new WebSocket("ws://localhost:8000/ws/projects/"); ws.onopen = function() { // Web Socket is connected, send data using send() const msg = { "firstName": "Jane", "lastName": "Doe", } ws.send(msg); alert("Message is sent..."); }; ws.onmessage = function (evt) { const data = JSON.parse(evt.data); // var received_msg = evt.data; console.log(evt) console.log("data",data) console.log("received_msg",data["message"]) alert("Message is received..."); }; ws.onclose = function() { // websocket is closed. alert("Connection is closed..."); }; } Right now I'm facing the below error: WebSocket HANDSHAKING /ws/projects/ [127.0.0.1:43012] HEY HEY HEY HEY WebSocket CONNECT /ws/projects/ [127.0.0.1:43012] HTTP GET /api/project-viewset/ 200 [0.11, 127.0.0.1:43008] Reciasha … -
Cannot insert an entity along with it's foreign key in django/djangorestframework
I have the following models in my application: class User(models.Model): name = models.CharField(max_length=100) birth_date = models.DateField() address = models.CharField(max_length=200) class Device(models.Model): description = models.CharField(max_length=200) location = models.CharField(max_length=200) max_energy_consumption = models.FloatField() avg_energy_consuumption = models.FloatField() user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) A user can have multiple devices, hence the foreign key user in the Device class. These are my serializers: class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = '__all__' class DeviceSerializer(serializers.ModelSerializer): user = UserSerializer(read_only=True) class Meta: model = Device fields = '__all__' I am using a default ModelViewSet for CRUD operations: class UserViewSet(ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer class DeviceViewSet(ModelViewSet): queryset = Device.objects.all() serializer_class = DeviceSerializer In my database, the devices table has a user_id column, like it should. When I open the Django API in the browser, I see this: In the POST form, there is no field for user_id. Shouldn't it be one? How am I supposed to add a device through a request and specify which user it belonges to? Like this it just puts null in the user field, which is not what I want. I want to specify to a device which user it belonges to at creation. -
Include React app inside MPA Django Website
How do you integrate a React application into Django MPA website? The website has multiple pages. One of the pages is where changes intensive react app should be placed in. The rest pages use vanilla js. React app and rest pages would share same database, but the functionality of the react app is mostly seperate from the rest webpage. It is like if you had a game/player/some tool inside a website that you can load. My most fears is about js and react conflicts. -
How do I use a postgresql function result in a Django template?
I'm quite new to Django so I suspect I'm missing something simple. I've used Django to build a website that features "regular" pages as well as a data-entry, display, update and delete pages in a back-end section of the website that requires a login to access. All of that was easy. I've also used Django's template inclusion feature and, for what I've needed so far, it seems to work fine. I now have a requirement to use a postgresql function to dynamically generate a central portion of a webpage and include that in the template. Basically, if a page is called "abc" then I need to do something like textfield = myfunction('abc') where myfunction would generate the equivalent of a static template stored in a folder. I understand (I think) that the template inclusion content can be contained in a variable. What I'm missing is how to get the results of the postgresql function into that variable in the template. I'm assuming that I need to put this logic in the model but I haven't been able figure out how to do that. Any help or advice would be greatly appreciated. Thanks!