Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Select2 order of selected items after drag and drop
If you want to django select2 in with drag and drop then you need to add some JS in your code to save data as you selected in form. you need to first install django-select2 https://pypi.org/project/django-select2/ Models.py from django_select2 import forms as s2forms from django import forms from .models import Achievement, Industries class IndustriesWidget(s2forms.ModelSelect2MultipleWidget): search_fields = [ "name__icontains", ] class SkillsWidget(s2forms.ModelSelect2MultipleWidget): search_fields = [ "name__icontains", ] class AchievementForm(forms.ModelForm): class Meta: model =Achievement fields = ["title", 'skills', 'industries'] widgets = { "skills": SkillsWidget, "industries": IndustriesWidget } def __init__(self, *args, **kwargs): self.request = kwargs.pop('request', None) super(AchievementForm, self).__init__(*args, **kwargs) self.fields['skills'].widget.attrs.update({'class' : 'form-control custom-select select2-selection'}) self.fields['industries'].widget.attrs.update({'class' : 'form-control custom-select select2-selection'}) django form I have created three django model and i am using model into django forms. class IndustriesWidget(s2forms.ModelSelect2MultipleWidget): search_fields = [ "name__icontains", ] class SkillsWidget(s2forms.ModelSelect2MultipleWidget): search_fields = [ "name__icontains", ] class AchievementForm(forms.ModelForm): class Meta: model =Achievement fields = ["title", 'skills', 'industries'] widgets = { "skills": SkillsWidget, "industries": IndustriesWidget } def __init__(self, *args, **kwargs): self.request = kwargs.pop('request', None) super(AchievementForm, self).__init__(*args, **kwargs) self.fields['skills'].widget.attrs.update({'class' : 'form-control custom-select select2-selection'}) self.fields['industries'].widget.attrs.update({'class' : 'form-control custom-select select2-selection'}) JQuery $(document).ready(function () { function convertObjectToSelectOptions(obj) { var htmlTags = ''; for (var tag in obj) { for (const [key, value] of Object.entries(obj[tag])) { … -
How to convert relative path to full URL in Django?
I am trying to make the url shortener app like bit.ly with Django. It works when the {var} leads to absolute URL but I cannot figure out how to redirect links without "http//:www." prefix. So far I tried HttpResponseRedirect(link) and redirect(link) Example: link = "https://www.postgresql.org/docs/current/" => works as expected link = "postgresql.org/docs/current/" => redirects to "http://127.0.0.1:8000/{var}/postgresql.org/docs/current/" How to convert something like this "postgresql.org/docs/current/" to full URL? -
How do I translate this condition from SQL to Django
How does the following SQL query translate into the Django Queryset, assuming 'BP' and 'BS' being the models for the : SELECT SUM(case when BP.ERR in ('0') then 1 else 0 end) SUCCESS FROM BP,BS WHERE BP.TIME> sysdate-(60/1440) #Picking the data updated in the past 1hour AND BP.ID=BS.CODE AND BS.TYPE='3'; I tried this using a while loop along with sum+case+when() which returns no data. -
2 django serializers in 1 generic api view
I can't grasp the logic on how to do what I want. I do have 2 serializers: 1.CreateStudentProfileSerializer and 2.CreateStudentInfoSerializer serializer 1 looks like this: class CreateStudentProfileSerializer(serializers.ModelSerializer): user = CreateStudentUserSerializer(many= False) ... serializer 2: class CreateStudentInfoSerializer(serializers.ModelSerializer): student = serializers.StringRelatedField(many=False) adviser = serializers.StringRelatedField(many=False) profile = serializers.StringRelatedField(many=False) section = serializers.StringRelatedField(many=False) class Meta: Model = Student fields= [ 'id','student', 'period', 'adviser', 'profile', 'section' ] and I have a page that has a form that will take all required data for the 2 serializers, how do I save those 2 serializers at the same time in one view? Or should I do this in another way? -
Accessing dictionary inside Django template
I am customizing my item query result and marking these items as added in the cart based on DB values, i have succeeded in making this dictionary but the issue is how to access its values now inside the template my view menu_items =[] menus = MenuItem.objects.all().order_by('-date_added') for item in menus: print(item.id) menus_added['item']=item if item.id in cartitem: menus_added['is_added']=True else: menus_added['is_added']=False menu_items.append(menus_added) menus_added = {} print(menu_items) restaurants = Restaurants.objects.all() categories= Category.objects.all() return render(request,'store/store.html',context={ 'product':menu_items, <-- i want access this dictionary 'restaurants':restaurants, 'categories':categories }) this approach is not working template {% for item in product.item %} <div class="col-md-4"> <figure class="card card-product-grid"> <div class="img-wrap"> <img src="{{item.image_url}}"> </div> <!-- img-wrap.// --> <figcaption class="info-wrap"> <div class="fix-height"> <a href="{% url 'menus:item' item.id %}" class="title">{{item.item_name}}</a> <div class="price-wrap mt-2"> <span class="price">{{item.price}}</span> <del class="price-old">${{item.price}}</del> </div> <!-- price-wrap.// --> </div> {% if is_added %} <a href="#" class="btn btn-block btn-success">Added ! </a> {% else %} <a href="#" class="btn btn-block btn-primary">Add to cart </a> {% endif %} </figcaption> </figure> </div> <!-- col.// --> {% endfor %} -
Python finding the real availability comparing weekly based opening hour and booking
This is python problem, Let's say Jhon Doe is a tutor, and he has an appointment with student in following dates appointment = [ {'date': '2021-08-02','from_hour': '12:30', 'to_hour': '12:15' }, # monday {'date': '2021-08-04','from_hour': '02:30', 'to_hour': '03:15' }, # Wednesday ] and in the application, he choose his weekly based availability when weekday 1 is monday, 2 tueday, 3 wednesday, and so on available_based_on_weekday = [ { "weekday": 1, 'opening_hour_time': [ # monday {'from_hour': '12:30', 'to_hour': '12:15'}, {'from_hour': '12:30', 'to_hour': '12:15'}, {'from_hour': '12:30', 'to_hour': '12:15'} ] }, { "weekday": 7, 'opening_hour_time': [ # Saturday {'from_hour': '13:30', 'to_hour': '15:15'}, {'from_hour': '15:30', 'to_hour': '16:15'}, {'from_hour': '19:30', 'to_hour': '20:15'}, {'from_hour': '23:30', 'to_hour': '23:45'} ] }, { "weekday": 3, 'opening_hour_time': [ # Wednesday {'from_hour': '02:30', 'to_hour': '03:30'}, {'from_hour': '17:30', 'to_hour': '18:15'}, {'from_hour': '19:30', 'to_hour': '20:15'}, {'from_hour': '21:30', 'to_hour': '22:30'} ] } ] We want to know a tutor actual avaialability. coz, as there is already appointment booked in certain weekday time slot, that is mean the time slot no longer available. I am expecting this output based on month actual_availability = [ { 'date': '2021-08-01', 'available': [] }, { 'date': '2021-08-02', 'available': [ {'from_hour': '12:30', 'to_hour': '12:15'}, {'from_hour': '12:30', 'to_hour': '12:15'} ] }, { … -
how to set a field from another model to another with FK relation django
i've build a hotel management system , for pay methods for example in a booking room from 14-8-2021 to 20-8-2021 the price of rooms will be change depend on how long he/she remains in the hotel class BookingPayment(models.Model): admin = models.ForeignKey(User,on_delete=models.CASCADE) booking = models.ForeignKey(Booking,on_delete=models.CASCADE,related_name='bookings') start_date = models.DateTimeField(default=timezone.now) end_date = models.DateTimeField() price = models.DecimalField(max_digits=20,decimal_places=2) class Booking(models.Model): admin = models.ForeignKey(User,on_delete=models.CASCADE) room_no = models.ForeignKey(Room,on_delete=models.CASCADE,blank=True,related_name='rooms') takes_by = models.ManyToManyField('vistors.Vistor',through='BookingVisitor',related_name='vistors') check_in = models.DateTimeField(default=timezone.now) check_out = models.DateTimeField(blank=True,null=True) payment_status = models.BooleanField(default=False) if payment_status is False then it means the takers should still pay , whenever the takers paid full of the price then it will be True , but because the prices will change depend on how far he/she remains i cant depend on a specific price the change it using django signals is there another way to bring payment_status to BookingPayment Model Form please? class BookingPaymentForm(forms.ModelForm): class Meta: model = BookingPayment fields = ['start_date','end_date','price'] i want to add payment_status to the BookingPaymentForm without adding new field to BookingPayment model ?! is it possible please , then whenever it will be the last time to pay then the admin check it as True ?thank you for helping .. -
I am following a Django REST API tutorial and doing exactly as same a the instructor is doing. However, getting error
ImproperlyConfigured at /watch/stream/ Could not resolve URL for hyperlinked relationship using view name "streamplatform-detail". You may have failed to include the related model in your API, or incorrectly configured the lookup_field attribute on this field. Getting the Error mentioned above while hitting the URL(127.0.0.1:8000/watch/stream/) Models.py from django.db import models class StreamPlatform(models.Model): name = models.CharField(max_length=30) about = models.CharField(max_length=150) website = models.URLField(max_length=100) def __str__(self): return self.name class WatchList(models.Model): title = models.CharField(max_length=50) storyline = models.CharField(max_length=200) platform = models.ForeignKey(StreamPlatform, on_delete=models.CASCADE, related_name="watchlist") active = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title urls.py from django.urls import path, include from watchlist_app.api.views import WatchListAV, WatchDetailAV, StreamPlatformAV, StreamDetailAV urlpatterns = [ path('list/', WatchListAV.as_view(), name='movie-list'), path('<int:pk>/', WatchDetailAV.as_view(), name='movie-details'), path('stream/', StreamPlatformAV.as_view(), name='stream-list'), path('stream/<int:pk>/', StreamDetailAV.as_view(), name='stream-details'), ] views.py from rest_framework.response import Response from rest_framework.views import APIView from rest_framework import status from watchlist_app.models import WatchList, StreamPlatform from watchlist_app.api.serializers import WatchListSerializer, StreamPlatformSerializer class StreamPlatformAV(APIView): def get(self, request): platform = StreamPlatform.objects.all() Serializer = StreamPlatformSerializer(platform, many=True, context={'request': request}) return Response(Serializer.data) def post(self, request): serializer = StreamPlatformSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) else: return Response(serializer.errors) class StreamDetailAV(APIView): def get(self, request, pk): try: platform = StreamPlatform.objects.get(pk=pk) except StreamPlatform.DoesNotExist: return Response({'error': 'Not found'}, status=status.HTTP_404_NOT_FOUND) serializer = StreamPlatformSerializer(platform) return Response(serializer.data) def put(self, request, pk): platform = StreamPlatform.objects.get(pk=pk) serializer = … -
Annotate a queryset with successive values in a dictionary
How can we annotate a queryset with successive values in a dictionary? Something similar to the first object in the queryset will be annotated with the first value in the dictionary and so on... till the end of the queryset -
My form does not save item even from admin panel in django
i create a app name order in it a model name order but when i tried to save some data in that model from the user view it doesn't save it then i tried to save it doesn't even got save from there i don't understand what causing the problem class BuyOrder(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE,) address = models.ForeignKey(Address, default= True, on_delete=models.CASCADE ) status = models.IntegerField(choices = status_choices, default=1) method = models.CharField(max_length=50, blank=False,) total_price = models.FloatField(blank=False, default=0) payment_status = models.IntegerField(choices = payment_status_choices, default=3) order_id = models.CharField(unique=True, max_length=200, null=True, default=None) datetime_of_payment = models.DateTimeField(default=timezone.now) # related to razorpay razorpay_order_id = models.CharField(max_length=1000, null=True, blank=True) razorpay_payment_id = models.CharField(max_length=1000, null=True, blank=True) razorpay_signature = models.CharField(max_length=1000, null=True, blank=True) def save(self, *args, **kwargs): if self.order_id is None and self.datetime_of_payment and self.id: self.order_id = self.datetime_of_payment.strftime('COOLBUYORDER%Y%m%dODR') + str(self.id) return super().save(*args, **kwargs) else: pass def __str__(self): return self.user.username + " " + str(self.order_id) + " " + str(self.id) here is the screenshot of admin panel even from their i unable to save any data in that form -
NoReverseMatch at /home/category/doggo/
i am getting an error: Reverse for 'blog' with keyword arguments '{'_id': ''}' not found. 1 pattern(s) tried: ['home/category/(?P<id>[-a-zA-Z0-9]+)/$'] here is my views.py views.py def BlogDetailView(request,_id): try: navbar_list = Navbar.objects.exclude(name='default') category_list = Category.objects.exclude(name='default') dataset = BlogModel.newmanager.all() data = BlogModel.newmanager.get(slug =_id) comments = CommentModel.objects.filter(blog = data, status=True) except BlogModel.DoesNotExist: raise Http404('Data does not exist') if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): Comment = CommentModel(your_name= form.cleaned_data['your_name'], comment = form.cleaned_data['comment'], blog=data) Comment.save() return redirect(f'/home/category/{_id}') else: form = CommentForm() context = { 'data':data, 'form':form, 'comments':comments, 'dataset': dataset, "category_list": category_list, 'navbar_list': navbar_list, } return render(request,'layout/post-details-main.html',context) class CatListView(ListView): template_name = 'layout/category-main.html' context_object_name = 'catlist' def get_queryset(self): content = { 'cat' : self.kwargs['category'], 'posts' : BlogModel.objects.filter(category__name=self.kwargs['category']).filter(status='published') } return content def category_list(request): category_list = Category.objects.exclude(name='default') context = { "category_list": category_list, } return context class Navbar_view(ListView): template_name = 'layout/navbar_show_main.html' context_object_name = 'navbar' def get_queryset(self): content = { 'nav' : self.kwargs['navbar'], 'details' : BlogModel.objects.filter(category__name=self.kwargs['navbar']).filter(status='published') } return content def navbar_list(request): navbar_list = Navbar.objects.exclude(name='default') context = { "navbar_list": navbar_list, } return context i successfully render the CatListView and the category_list and the models of it, before i added the the Navbar_view and navbar_list and register it urls.py path('home/category/<navbar>/', views.Navbar_view.as_view(), name="navbar"), path('home/category/<category>/', views.CatListView.as_view(), name="category"), path('', views.BlogListView, name="blogs"), path('home/search/', views.searchposts, name= "searchposts"), … -
Syntax highlighting in Django using PrimJS
I'm working on a project using Django(3) in which I have blog posts and in these blog posts, I need to highlight code chunks in case we are writing a programming article. So, I decided to use PrismJS library. I have added the required CSS and JS files of the library: <link rel="stylesheet" href="{% static 'css/prism.css' %}" data-noprefix/> <link rel="stylesheet" href="{% static 'css/prism-synthwave84.css' %}"/> <link rel="stylesheet" href="{% static 'css/prism-line-numbers.css' %}"/> <script type="application/javascript" src="{% static 'js/prism.js' %}"></script> <script type="application/javascript" src="{% static 'js/prism-line-numbers.js' %}"></script> Now, inside the admin panel, I have integrated "ckEditor" for writing content. To highlight the code we need to place it inside the <pre><code> tags and add a css class as language-python to highlight python code. The problem is when we add this class and save the blog posts, this class disappears automatically. Don't know why it behaves like this? Sometimes it remains but if we update the blog posts, it disappears automaticly. -
while following a tutorial on youtube I encountered this while correcting the padding using Django. Error: TemplateDoesNotExist at /products/
The tutorial asked me to place the base.html module under the main project 'Pyshop' in templates directory. I have tried the following methods in the settings module of my app but still it doesn't solve my error, please help as I'm a beginner and learning how to code. Thanks import os from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, -
NLP: How to tell wether a text is talking about which topic
I am a noob in python I was just making a website for studying for children so, I wanted the student to enter their response to a question and then their text response is reviewed and then it checks whether the child has given a response on a particular topic and whether the answer talks about a few key points, so how do I make it and implement it using Django, btw I started web dev a week ago so I am very new to this. Please help me! thank you !! -
How to submit a form in base file in django?
my Views.py def subscribers(request): subscriber_email = request.POST.get('email') isuser = Subscriber.objects.filter(email = subscriber_email) if request.method == "POST": if isuser: Subscriber.objects.filter(is_user = True) subscriber = Subscriber.objects.create( email = subscriber_email ) subscriber.save() messages.success(request , "Thank You for subscribing") return HttpResponseRedirect('index') my base.html file form which <form action="{% url 'subscribers' %}" method="POST"> {% csrf_token %} <div class="form-group row" style="width: 100%"> <div class="col-lg-8 col-md-12"> <input name="email" placeholder="Enter Email" required="" type="email"> </div> <div class="col-lg-4 col-md-12"> <button class="nw-btn primary-btn" type="submit">Subscribe<span class="lnr lnr-arrow-right"></span></button> </div> </div> </form> my models.py class Subscriber(models.Model): email = models.EmailField(max_length=256) is_user = models.BooleanField(default=False) I can't understand what is my path for base file in urls.py file path('' , subscribers , name="subscribers") -
Cannot assign "['9', '10', '11']": "Element.value_code" must be a "Value" instance
I am a student who is learning Janggo. I am currently implementing a page where the selected option information, price, and quantity appear when I select the option. However, the error keeps appearing. I don't know if modelchoicefield is a problem or where I missed it, or if the format that I get from the getlist in the view conflicts with the form, so I can't get the value. I'm sure that in script, var checkValue = $("#optionSelect").Val(); /Get this value " <input name=\"value_code2\" id=\"value_code2\">" + I left it in the input box to save the selected option value, but I'm frustrated why they keep saying it's not value instance. How on earth can I solve the problem I've been through? ERROR : ValueError at /join/join_create/2/ Request Method: POST Request URL: http://127.0.0.1:8000/join/join_create/2/ Exception Type: ValueError Exception Value: Cannot assign "['9', '10', '11']": "Element.value_code" must be a "Value" instance. Models.py class Option(models.Model): option_code = models.AutoField(primary_key=True) name = models.CharField(max_length=32) product_code = models.ForeignKey(Product, on_delete=models.CASCADE, db_column='product_code') def __str__(self): return self.name class Meta: ordering = ['option_code'] class Value(models.Model): value_code = models.AutoField(primary_key=True) option_code = models.ForeignKey(Option, on_delete=models.CASCADE, db_column='option_code') product_code = models.ForeignKey(Product, on_delete=models.CASCADE, db_column='product_code') name = models.CharField(max_length=32) extra_cost = models.IntegerField() def __str__(self): return self.name class Meta: ordering = … -
Error: Invalid LatLng object: (undefined, -0.09) (When trying to get data from django rest api)
import React, { useRef, useEffect, useState } from 'react' import { gsap, Power3 } from 'gsap' import { MapContainer, TileLayer, Marker, Popup } from 'react-leaflet' import 'mapbox-gl/dist/mapbox-gl.css' const ResturentMapOpenDates = (props) => { //Close Map model const tl = gsap.globalTimeline var store_longitude = props.store_longitude var store_latitude = props.store_latitude var lon_lan = [store_longitude, store_latitude] const closemapmodel = () => { var full_map_box = document.querySelector('.map_box_open_full'); var map_box = document.querySelector('.map_open_date'); tl.to(full_map_box, .3, {visibility: 'hidden', opacity: 0}) .to(map_box, .2, {visibility: 'hidden', opacity: 0}) } return ( <> <div className="map_box_open_full" onClick={closemapmodel}></div> <div className="map_open_date"> <div id="res_location_map"> <div className="map-container"> <MapContainer center={[store_longitude, -0.09]} zoom={18} scrollWheelZoom={true} > <TileLayer attribution='&copy; <a href="http://osm.org/copyright"></a>' url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" /> <Marker position={[51.505, -0.09]}> <Popup>{props.returent_name}</Popup> </Marker> </MapContainer> </div> </div> </div> </> ) } export default ResturentMapOpenDates I cant use the store_longitude variable. It always gives undefined. Because it is undefined leaflet js cant render the map. I am studying react and I am a beginner in this, I am trying to make a map with the Leaflet tool of react. The fact is that when I select a particular country I want it to go to the selected country but it generates an error that is "Error: Invalid LatLng object: (54, undefined)", it would be helpful if … -
Why can't I fully get the value which is a list in python dictionary (Django request)?
I have a form inside of which is a select tag with options, it looks like this: <form method="POST"> {% csrf_token %} <div class="row"> <div class="col-sm-3"> <h4 class="mb-0 mt-2">Title:</h4> </div> <div class="col-sm-9"> <input type="text" name="title" class="form-control" placeholder="Blogpost Title"> </div> </div> <hr> <div class="row"> <div class="col-sm-3"> <h4 class="mb-0 mt-2">Tags:</h4> </div> <div class="col-sm-9"> <select class="form-select" name="tags" multiple aria-label="multiple select example" required> {% for tag in tags %} <option value="{{tag.name}}">{{tag.name}}</option> {% endfor %} </select> </div> </div> <hr> <div class="row"> <div class="col-sm-3"> <h4 class="mb-0 mt-2">Description:</h4> </div> <div class="col-sm-9"> <textarea name="desc" class="form-control" id="exampleFormControlTextarea1" rows="4" placeholder="Blogpost Description (HTML supported)"></textarea> </div> </div> <hr> <div class="text-center"> <button type="submit" class="btn btn-primary">Create</button> </div> </form> And this is my view, where I'm handling it: def create_blogpost(request, id): user = User.objects.get(id=id) tags = Tag.objects.all() if request.method == 'POST': title = request.POST['title'] blogpost_tags = request.POST['tags'] desc = request.POST['desc'] # BlogPost.objects.create( # title=title, # profile=user, # tags=tags, # desc=desc # ) else: pass context = { 'user': user, 'tags': tags } return render(request, 'main/create_blogpost.html', context) When I'm printing out request.POST it looks like this: request.POST <QueryDict: {'csrfmiddlewaretoken': ['TOKEN'], 'title': ['blogpost title'], 'tags': ['Python', 'C++'], 'desc': ['']}> Here I chose 2 tags: Python and C++, but when I'm printing out the variable blogpost_tags, it shows … -
How to query products under Brands individually
I am trying get Product name such as "stethoscope" which has a brand named "Beximco". I want to query all the data from 'm_Product' Table as above. My model: class m_Product(models.Model): name = models.CharField(max_length=200) Brand = models.CharField(max_length=200) quantity = models.IntegerField(default=0, null=True, blank=True) price = models.DecimalField(max_digits=7, decimal_places=2) digital = models.BooleanField(default=False, null=True, blank=True) image = models.ImageField(null=True, blank=True) description = models.CharField(max_length=2000) tags = models.CharField(max_length=20) def __str__(self): return f'{self.name} - {self.quantity} - {self.Brand} - {self.price}' My query: brandData = m_Product.objects.all().values("name").filter('Brand') Help! if you anyone understand this. Thank you! -
django rest framework api saving multiple data in db and using nested serializers
I have 3 serializers: UserCreationSerializer, StudentProfileSerializer, StudentInfoSerializer Now, I want to use my StudentProfileSerialzer as the "parent" which means I want to put UserCreationSerializer and StudentInfoSerialzer inside the StudentProfileSerialzer. I came up with this idea because I dont want to ruin the data integrity so might as well ask all information in one form and then just pop data and insert them into respective serializers Is this even Possible? If it is, someone please tell me how to do it right. And also I want to ask if the way how I create my StudentInfoSerializer is right or wrong, especially the serializers.RelatedField() part. I already worked on UserCreationSerializer and StudentProfileSerializer, and put UserCreationSerializer inside my StudentProfileSerializer, but I dont know how to put StudentInfoSerializer beacause all fields of StudentInfoSerializer are related on different models and some fields are going to be created on the fly when end-user input the data on my forms(example of this is the user). this is the StudentInfoSerializer I want to put in StudentProfileSerializer: class CreateStudentInfoSerializer(serializers.ModelSerializer): student = serializers.Related_Field(source='user',) period = serializers.Related_Field(souce="schoolperiod", read_only= True) adviser = serializers.Related_Field(source= "user", read_only= True) profile = serializers.Related_Field(source="studentprofile") section = serializers.Related_Field(source="Section", read_only= True) class Meta: Model = Student fields= [ 'id','student', … -
Django Widget : load CSS with Media class
I am creating a custom widget for forms, but CSS files are not loaded. Here is the widget: widgets.py from django.forms.widgets import Widget class MyCustomWidget(Widget): template_name = 'widgets/my_custom_widget.html' class Media: css = { 'all': ('css/my_custom_widget.css',) } Here is the call to the widget: models.py from django import forms from .widgets import CalendarWidget class MyForm(forms.Form): field = forms.CharField(widget=MyCustomWidget) The widget seems to be well constructed. The <link> I get from the shell using: >>> import MyCustomWidget() >>> w = MyCustomWidget() >>> print(w.media) <link href="/css/my_custom_widget.css" type="text/css" media="all" rel="stylesheet"> is correct because if I include it in my widget template the css is loaded. But I think the Media class should do this work automatically to make it included in the header (and I dont want to include the css in the main html form). Can you help me loading the CSS ? Thanks ! Django 3.2 documentation: Styling widgets , Media class -
Can I use Django truncatewords filter without image fields?
I upload a photo with ckeditor on my blog and show this photo in the content area. To show the summary of a blog on the home page, I limit the content area to truncatewords, but if there is an image within the word limits I specified, this image is shown in the blog summary. How do I prevent this situation? How can I prevent images from appearing when using the truncatewords filter? {{ blog.content|safe|truncatewords:50 }} -
Django images in static folder can not show on Heroku project
I deployed my app on Heroku. But the images in my static folder won't show up. In my local environment, here is the screenshot But on the project, the images fails to load Here are code in multiple related files. settings.py from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # additional django 'django.contrib.sites', 'django.contrib.sitemaps', 'article', 'taggit', 'crispy_forms', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', '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 = 'blog.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], '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', 'article.context_processors.common_context' ], }, }, ] WSGI_APPLICATION = 'blog.wsgi.application' # Password validation # https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/3.2/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'Asia/Taipei' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.2/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') … -
django REST api not receiving data from query param when getting request from java
I am calling a Django endpoint with the postman and passing some values in query param and its working fine but when i cal the same API from java code it doesn't getting data in params -
How to delete a row in a table using Django?
I want to delete a row from a table in the shell provided by Django. I am running the command Birthdays.objects.delete() but it's not working and gives a syntax error.