Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
When I try to add some data in database from admin, Iam getting NoReverseMatch error
Here I am not using any admin template. I am using the default admin template. How can I reverse this url? The error which I get: NoReverseMatch at /admin/machine/module/add/ Reverse for 'machine_module_change' with arguments '('',)' not found. 1 pattern(s) tried: ['admin/machine/module/(?P<object_id>.+)/change/$'] Request Method: POST Request URL: http://localhost:8080/admin/machine/module/add/ Django Version: 3.0.8 Exception Type: NoReverseMatch Exception Value: Reverse for 'machine_module_change' with arguments '('',)' not found. 1 pattern(s) tried: ['admin/machine/module/(?P<object_id>.+)/change/$'] Exception Location: C:\Users\Administrator\AppData\Local\Programs\Python\Python37\lib\site-packages\django\urls\resolvers.py in _reverse_with_prefix, line 677 Python Executable: C:\Users\Administrator\AppData\Local\Programs\Python\Python37\python.exe Python Version: 3.7.7 Python Path: ['C:\Users\Administrator\Documents\CheckMeOut\checkmeout', 'C:\Users\Administrator\AppData\Local\Programs\Python\Python37\python37.zip', 'C:\Users\Administrator\AppData\Local\Programs\Python\Python37\DLLs', 'C:\Users\Administrator\AppData\Local\Programs\Python\Python37\lib', 'C:\Users\Administrator\AppData\Local\Programs\Python\Python37', 'C:\Users\Administrator\AppData\Roaming\Python\Python37\site-packages', 'C:\Users\Administrator\AppData\Local\Programs\Python\Python37\lib\site-packages', 'C:/Users/Administrator/Documents/CheckMeOut/checkmeout', 'C:/Users/Administrator/Documents/CheckMeOut/checkmeout/checkmeout'] Server time: Tue, 2 Mar 2021 15:21:42 +0530 urls.py from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from django.urls import reverse urlpatterns = [ path('', include('main.urls')), path('equipment/', include('equipment.urls')), path('machine/', include('machine.urls')), path('admin/',admin.site.urls), ] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) -
Template Does Not Show Me Anything When I Use A For Loop In Django
I want to show some items in my cart template, but it doesn't show me anything. When I don't use a for loop, it works fine, but it shows me nothing when I use it for a loop. My guess is, maybe something on my Cart class is wrong, I am not sure, but it would be great if you check it out. View: from django.shortcuts import render, get_object_or_404, redirect from Products.models import Product from .forms import AddCartForm from django.views.decorators.http import require_POST from decimal import Decimal CART_SESSION_ID = 'cart' class Cart: def __init__(self, request): self.session = request.session cart_session = self.session.get(CART_SESSION_ID) if not cart_session: cart_session = self.session[CART_SESSION_ID] = {} self.cart = cart_session def add_product(self, product, quantity): product_id = str(product.id) if product_id not in self.cart: self.cart[product_id] = {'quantity': 0, 'price': str(product.price)} self.cart[product_id]['quantity'] += quantity self.save() def save(self): self.session.modified = True def __iter__(self): product_ids = self.cart.keys() products = Product.objects.filter(id__in=product_ids) cart = self.cart.copy() for product in products: cart[str(product.id)]['product'] = product for item in cart.values(): item['total_price'] = Decimal(item['price']) * item['quantity'] yield item @require_POST def add_product(request, product_id): cart = Cart(request) form = AddCartForm() if form.is_valid(): product = get_object_or_404(Product, pk=product_id) quantity = form.cleaned_data['quantity'] cart.add_product(product=product, quantity=quantity) return redirect('cart:cart_details') def cart_details(request): cart = Cart(request) context = {'cart': cart} return … -
Django Channels + WebSockets: concepts unclear
I have some experience with Django and am currently working on a project for live boardgaming (generally two-player abstract games). I am using Channels and am able to send moves to different tabs in the browser. Now I need to solve the issue of separating players from spectators, since they all go into the same "room" and even the third tab/user can make moves. I don't grasp all the concepts around Channels, layers, sockets, consumers, and so on, and am looking for some help or direction. Basically, I need some guidance on what the general structure of a project like this should look like. What should the consumers be? One for every user? One for every specific game between two players? One for every room? I've read that consumers are in a way equivalent to views, but it seems that one view can communicate with many consumers. I have tried to hold data in a consumer class, such that it is accessible to all instances of that consumer. It does not work, so I guess that's not the correct approach. Where do I store, say, the state of the board? Should I be writing every move and chat message to … -
Send Emails with html_message
I want to send HTML-email, using Django templates like this: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> Hello <strong>{{ message }}</strong> - your account is activated. </body> </html> Also I want to send data from the backend with the Email. In this example I want to send a message from the backend with the email template. Here is my View: def home(request): message_name = "NAME" message_email = "EMAIL" message = "USER" msg_html = render_to_string('email/email.html') send_mail( 'message from ' + message_name, # subject message, # message message_email, # from email ['myemail@outlook.de'], # To Email html_message=msg_html, ) context = {'message': message, 'message_name': message_name, 'message_email': message_email} return render(request, 'email/email.html', context) When I receive the Email I only get the text and not the {{ message }} which would be USER in this example. -
Is it possible to use FCM-Django with a python client?(Firebase Cloud Messaging)
I am new to django and I need to write a REST api that can handle a database includes users with multiple IoT devices(Jetson Nano) belongs to user. User can set configuration settings of IoT device from web or mobile apps and I want to send notifications to the device when a change occurs. Is it possible to implement with FCM-Django? I think using a python client with an event listener at the Jetson side will do the work but I just wanna make sure if this plan works. I hope my question is clear. -
Print data in pdf from Django Admin Console action
I have a Django app which allows customers to register for an event and sign a liability release agreement. I want to be able to pick certain release agreements for each specific event and create a pdf file which can then be downloaded and printed. I wan to do this in the Admin console, probably using admin actions ('With selected, print release Form'). Does anyone know how I can get an Admin action to access field data, populate a pdf file and then make it downloadable? In my models.py file the Release Form model is: class ReleaseForm(models.Model): FORMSTATUS = ( ('required', 'required'), ('submitted', 'submitted'), ) customer = models.ForeignKey(Customer, on_delete= models.CASCADE, null = True) i_agree = models.BooleanField(default = False) release_status= models.CharField(max_length=200, null=True, choices=FORMSTATUS,default='required') release_date_submitted = models.DateTimeField(null=True,blank=True) note = models.CharField(max_length=1000, null=True,blank=True) def str(self): return self.release_status In my admin.py file I have added: @admin.register(ReleaseForm) class ReleaseAdmin(admin.ModelAdmin): def participant(self, obj): return str(obj.customer.last_name) + ", " + str(obj.customer.first_name) def training(self, obj): return str(obj.order.training_registered.name) def print_release(self, request, queryset): #code to print out the release forms needs to go here # or a call to function which does it updated=queryset.count() self.message_user(request, ngettext( '%d Relase Form was successfully printed.', '%d Relase Forms were successfully printed.', updated, ) % … -
Django REST queryset.delete() doesn't delete records
DRF 3.12.2 I'm trying to create an endpoint which deletes all CategoryTargetGroups with the given category id "cat_id". The call works but doesn't delete any records. Example url, this should delete all CategoryTargetGroup objects with category=61: http://localhost:8000/api/ctg-delete/?cat_id=61 The model: class CategoryTargetGroup(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE, null=False) target_group = models.ForeignKey(TargetGroup, on_delete=models.CASCADE, null=False) The view: class CategoryTargetGroupDelete(viewsets.ModelViewSet): queryset = CategoryTargetGroup.objects.all() serializer_class = CategoryTargetGroupSerializer @action(detail=False, methods=['delete']) def delete(self, request): cat_id = request.query_params['cat_id'] queryset = CategoryTargetGroup.objects.filter(category=cat_id) queryset.delete() serializer = CategoryTargetGroupSerializer(queryset, many=True) return Response(serializer.data) Serializer: from rest_framework import serializers class CategoryTargetGroupSerializer(serializers.ModelSerializer): class Meta: model = CategoryTargetGroup fields = ( 'id', 'category', 'target_group', ) Front end axios call: axios .delete(AuthUrls.API_CTG_DELETE, { headers: { authorization: "Token " + getUserToken(), }, params: { cat_id: cat_id } }) -
Why does Django send different csrf tokens when using use_token function?
I have a ReactJS application deployed on one domain(abc.com) and a Django server is deployed on another domain(xyz.com). I have added a separate call to get the csrf token in Django as follows- def csrf(request): return JsonResponse({'csrfToken': get_token(request)}) When i call this API i get a Set-cookie response header which has a different csrftoken value as the json response from this API- Set-Cookie: csrftoken=0b6qbRmAyF8QITIHbvFT2gGFOB98Vzg7cCRWvFWn2zzRbLon4BduX3P0orRX5Afh; expires=Tue, 01 Mar 2022 10:33:18 GMT; Max-Age=31449600; Path=/; SameSite=None; Secure Whereas the response has the following csrf(which i save as cookie)- {"csrfToken": "mMPB6X86ZzsS6T2rg1AN0e8MhG9raEn6ydA7qLITttTTzLI7978oV1h7RwRgkFmg"} i need to send the csrftoken in the post call as well as a cookie and i cannot access the token sent in the cookie because it is of different domain (CORS) and neither can i overwrite that record. If i set credentials: 'include', in my fetch call and send the csrftoken in form data or as a request header(X-CSRFToken) then the call has the cookie sent to me as the cookie itself (0b6qbRmAyF8QITIHbvFT2gGFOB98Vzg7cCRWvFWn2zzRbLon4BduX3P0orRX5Afh) and the header/form data csrf as the one sent as json(mMPB6X86ZzsS6T2rg1AN0e8MhG9raEn6ydA7qLITttTTzLI7978oV1h7RwRgkFmg) and i get a 403 error with the message- CSRF verification failed. Request aborted. In my local system it works well because the cookie recieved from server is … -
"Multipart form parse error - Invalid boundary in multipart: None" Django and AJAX
I’m trying to build an web app using django and I want to upload a file (a pdf or word document) using ajax (the ajax module in jquery). I’m building my API using django rest framework. I’ve pretty much tried to do what every site says but can’t seem to get around it. Has anyone did this? My views: def contract_post(request): contract = Contract() if request.method == 'POST': serializer = ContractSerializer(contract, data=request.data) data = {} if serializer.is_valid(): serializer.create(validated_data=request.data) handle_uploaded_file(request.FILES['atasament']) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def handle_uploaded_file(f): with open(f.name, 'wb+') as destination: for chunk in f.chunks(): destination.write(chunk) My serializer (it's a nested serializer): class ContractSerializer(serializers.ModelSerializer): client = ClientSerializer(read_only=False) termen = serializers.DateField(format='%Y-%m-%d', default=datetime.date.today) atasament = serializers.FileField(max_length=None, allow_empty_file=True) class Meta: model = Contract fields = ( 'pk', 'tip', 'nr_data', 'obiectul', 'termen', 'atasament', 'client', ) def create(self, validated_data): client = validated_data.pop('client') client_instance, created = Client.objects.get_or_create(**client) contract_instance = Contract.objects.create(**validated_data, client=client_instance) return client_instance My model: class Contract(models.Model): TIPURI = ( ('P', 'Proiectare'), ('E', 'Executie'), ('D', 'Documentatie'), ) tip = models.CharField(max_length=300, choices=TIPURI) nr_data = models.CharField(max_length=50) obiectul = models.TextField() termen = models.DateField(default=datetime.date.today) atasament = models.FileField(upload_to='main/documents/', blank=True, null=True) client = models.ForeignKey(Client, on_delete=models.SET_NULL, null=True) def __str__(self): return self.nr_data class Meta: verbose_name_plural = "Contracte" My JS: $('#form_add').submit(function (event) { event.preventDefault(); … -
How to allow reversing to one of two matches in urls.py?
I want my users to access a specific location of my API using either the English word "series" or the French equivalent "séries" as an argument in the URL. The URL and subsequent extensions will be reversed to using the English word. Here is my first attempt: urlpatterns = [ path(r"series/", include("series.public_urls", namespace="series")), path(r"séries/", include("series.public_urls")), ] Despite the following warning, I have been able to reverse all my URLs so far: ?: (urls.W005) URL namespace 'series' isn't unique. You may not be able to reverse all URLs in this namespace However a warning is a foreboding of impending doom and I'm looking for another solution. I've tried using Regex paths: urlpatterns = [ re_path(r"s(e|é)ries/", include("series.public_urls", namespace="series")), ] This throws an ImproperlyConfigured error. I understand the reverser cannot handle the "or" matching control but needs to know which of e or é it should reverse to. How can I allow reversing to "series" solely within this very urls.py file? -
Exception...NoReverseMatch ...Reverse for 'venue' with arguments '('',)' not found. 1 pattern(s) tried: ['venue/(?P<pk>[0-9]+)$']
I'm trying to develop a Django app for a booking system. I know the problem is from the url link pk argument that was passed to the venues.html. I've tried everything possible to solve this problem and nothing has worked. In venues.html, I've tried <li><a href="{% url 'booking:venue' pk %}">v.venue</a></li> <li><a href="{% url 'booking:venue' pk=v.pk %}">v.venue</a></li> - This shows me a list of all my venues as v.venue and only the first integer works (I hope this makes sense). <li><a href="{% url 'booking:venue' 1 %}">v.venue</a></li>- This shows a result similar to the previous one I just mentioned. Every other argument I've tried has given me the same error... I've read the django documentation on class-based detailview and watched and read a number of tutorials but nothing has helped. From everything I've found, the code I've written is supposed to work... However, I keep getting this traceback error. Pls, I would really appreciate any help I can get. Thank you so much. Environment: Request Method: GET Request URL: http://127.0.0.1:8000/venues/ Django Version: 3.1.6 Python Version: 3.8.8 Installed Applications: ['booking', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template error: In template C:\Users\Ada Eloka\OneDrive\python_work\space_pau\booking\templates\booking\base.html, error at … -
django Show all options in the relationship that the current user has added like row id
i now the row id in admin awant show that in django forms this is two models: class class_student(models.Model): name = models.CharField(max_lenth=50) class student(models.Model): name = models.CharField(max_lenth=50) cl = models.ForeignKey(class_student, on_delete=models.CASCADE, related_name='myrelated') -
Generic updateview not saving the form
There's no error while submitting the form. The fields aren't getting updated. While submitting I get a "POST /RISK00005/update/ HTTP/1.1" 302 0 " but no changes in the fields of form. Here's my views.py, I'm using Generic Classes class PostUpdateView(LoginRequiredMixin, UpdateView): model = Risk #fields = "__all__" form_class = RISKForm def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def test_func(self): post = self.get_object() if self.request.user == post.requester: return True return False Models.py class Risk(models.Model): id = models.CharField(primary_key=True, editable=False, max_length=10) time = models.DateTimeField(default=timezone.now) header = models.CharField(max_length=15, null=True, blank=True) bu = models.CharField(max_length=50, choices=BU_CHOICES, null=True) function = models.CharField(max_length=50, choices=FNCT_CHOICES, null=True) task = models.CharField(max_length=50, choices=TASK_CHOICES, null=True) s_d = models.CharField(max_length=30, null=True, blank=True) title = models.CharField(max_length=50, null=True) #title = AutoSlugField(populate_from=lambda instance: instance.risk.get_full_title()) mp = models.CharField(max_length=50, choices=MP_CHOICES, null=True) requester = models.ForeignKey(User, on_delete=models.CASCADE, null=True) #Identified By a_o = models.CharField(max_length=50, null=True) requester_manager = models.TextField(null=True) #L4 Manager Reviewer qa_reviewer = models.TextField(blank=True, null=True) #QA STL Reviewer def save(self, **kwargs): if not self.id: try: max = Risk.objects.aggregate(id_max=Max('id'))['id_max'] max = int((max[4:]).lstrip("0"))+1 self.id = "{}{:05d}".format('RISK', max if max is not None else 1) except: self.id= "RISK00001" #self.title = self.header + self.task + self.s_d super().save(*kwargs) def __str__(self): return self.id def get_absolute_url(self): return reverse('detail', kwargs={'pk': self.pk}) urls.py urlpatterns = [ path('', PostListView.as_view(), name = 'blog-home'), path('<pk>/', … -
How can I connect the user to a post he created in Django
I am starting with Django, and I have a question about the connection between a post and the user who created it. For now, I managed to create the link, however, whenever I create a new post, the user id is always the default one, thus one. I want to make it in a way that the user id is the id of the person creating the post, and for some reason, it never works. The other option I tried is to put "user" into the form but the problem is that then the user can choose which user he is, which is risky. So is there any way to make it automatic? That when the post is created, the right user id is directly connected to it? Thank you for any help!! model.py """ class Post(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE, default=1) image = models.ImageField(default="man.jpg") titre = models.CharField(max_length=50) slug = models.SlugField(max_length=100) date_publication = models.DateTimeField(auto_now_add=True) """ view.py """ @login_required def post_create(request): if request.method == "POST": post_form = PostForm(request.POST) if post_form.is_valid(): post_form.save() messages.success(request, 'Your post was successfully created!') return redirect('seed:view_seed') else: messages.error(request, 'Please correct the error below.') else: post_form = PostForm(request.POST) return render(request, "post/create.html", context={"post_form": post_form}) """ forms.py """ class PostForm(ModelForm): class Meta: … -
How to solve user logout when updating the password?
I created a user profile update page. There are several fields like name, surname, email, profile picture and password. If you leave the password field blank, parts other than the password can be updated. If you If you want to change the password, you can fill in the password field. When a user updates their fields other than the password, the page redirects the user to the homepage, which is something we want. But when the user wants to change the password, the user gets logout and redirect to the logout page. How can I fix it and redirect the user to the homepage? views.py @login_required def update_user(request, id): user = get_object_or_404(UserProfile, id=id) form = SignUpChangeForm(request.POST or None, request.FILES or None, instance=user) if form.is_valid(): form.save() if form.cleaned_data['password1'] != "": user.set_password(form.cleaned_data['password1']) user.save() return redirect('home') context = { 'form': form, } return render(request, "update_user.html", context) forms.py class SignUpChangeForm(forms.ModelForm): password1 = forms.CharField(max_length=250, required=False, label="New Password (leave blank if you do not want to change it)", widget=forms.PasswordInput) password2 = forms.CharField(max_length=250, required=False, label="New Password Confirmation (leave blank if you do not want to change it)", widget=forms.PasswordInput) class Meta: model = UserProfile fields = ('username', 'first_name', 'last_name', 'email', 'image') widgets = { 'password1': forms.PasswordInput(), 'password2': forms.PasswordInput(), … -
Django multiple databases save manytomany field
I have 2 databases set up in my django project, "default" and "remote". I have 2 models, Product and Category, Product has a many to many relationship to Category. When i try to save my product with a category selected in the admin panel i get this error: Cannot add "<Category: Cat1>": instance is on database "remote", value is on database "default" Cat1 exists both in the default and remote databse. -
AttributeError at /api/test type object 'Product' has no attribute 'objects'
So I get AttributeError at /api/test type object 'Product' has no attribute 'objects' error when I try to load up the page via get request, I'm trying to make an API using django rest framework and it says Product has no objects attribute. views.py from django.shortcuts import render from rest_framework import viewsets from .serializers import ProductSerializer from .models import Product from rest_framework.views import APIView from rest_framework.response import Response class Product(APIView): def get(self, request, format=None): products = Product.objects.all() serializer = ProductSerializer(products) return Response(serializer) urls.py from django.contrib import admin from django.urls import path, include from rest_framework import routers from . import views # router = routers.DefaultRouter() # router.register('products', views.ProductViewSet) # router.register('test', views.Product) # urlpatterns = router.urls urlpatterns = [ path('test', views.Product.as_view()) ] serializers.py class ProductSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Product fields = ['name','price','description'] -
Multiple file upload FileField in Django Rest Framework
In my app I want to have a form which contains file uploading option Model is such as: class GrnItems(models.Model): item = models.ForeignKey(Product, on_delete=models.CASCADE) item_quantity = models.IntegerField(default=0) item_price = models.IntegerField(default=0) label_name = models.CharField(max_length=25, blank=True, null=True) class Grn(models.Model): items = models.ManyToManyField(GrnItems) remarks = models.CharField(max_length=500, default=0) reciever = models.CharField(max_length=500, default=0) document = models.FileField(upload_to='grn/', blank=True, null=True) How can I upload multiple files in this ? I know a way out is to create a ManytoMany Field and upload the files in a loop and set it via set but is there a way I can use the same model and do it? -
text having newlines not downloading perfectly in csv file
I have data in a database that needs to be exported to CSV. Some of the fields include newlines which MUST be preserved.I am using sed to export data and it is being exported like this (this is sample data of course): 38,"testing here" in csv file after download it is showing as: but it should download like: Is it possible to export newlines in CSV files? Please help me out. Thanks in advance. -
Version conflict django-oauth-toolkit>0.12.0 and idna==3.1
Why I have a problem with updating Django from version 1.11.29 to 2.0.13. When updating the library django-oauth-toolkit to version 1.2.0 - version support Django 2.0 I receive an error: version = pkg_resources.require("django-oauth-toolkit")[0].version needed = self.resolve(parse_requirements(requirements)) raise VersionConflict(dist, req).with_context(dependent_req) pkg_resources.ContextualVersionConflict: (idna 3.1 (/.virtualenvs/django-oauth-tookit-conflict/lib/python3.6/site-packages), Requirement.parse('idna<2.8,>=2.5'), {'requests'}) -
Can't change headers with DRF APIClient()
I use APIClient() for my tests. I use Token auth, so I need to use THIS If we dive into the source code we'll see next: # rest_framework/test.py class APIClient(APIRequestFactory, DjangoClient): def __init__(self, enforce_csrf_checks=False, **defaults): super().__init__(**defaults) self.handler = ForceAuthClientHandler(enforce_csrf_checks) self._credentials = {} def credentials(self, **kwargs): """ Sets headers that will be used on every outgoing request. """ self._credentials = kwarg Also I use APIClient() as a pytest fixture in my code: @pytest.fixture(scope="function") def _api(): """API factory for anonymous and auth requests""" def __api(token=None, field=None): api_client = APIClient() headers = {} if token: headers["HTTP_AUTHORIZATION"] = f"Token {token}" if field: headers["X-CUSTOM-HEADER"] = field api_client.credentials(**headers) return api_client return __api But if we create TestMiddleware to look for headers, we see next: lass TestMiddleware: def __init__(self, get_response): self._get_response = get_response def __call__(self, request): header = request.headers.get("X-CUSTOM-HEADER") # None header = request.META.get("X-CUSTOM-HEADER") # Works fine! ... # Response processing response = self._get_response(request) return response The question is: Have we any way to have access to the X-CUSTOM-HEADER with APIClient() ? Also if I use Postman it obviously works fine with request.headers.get() -
django html template can't find static css and js files
I have a django project that structure is like this: >vira >vira -__init.py -settings.py -urls.py -wsgi.py >vira_app >migrations >template -index.html >static >vira_app >assets >css >js >vendor >aos >bootstrap >bootstrap-icons >isotope-layout >swiper -__init__.py -admin.py -apps.py -models.py -tests.py -urls.py -views.py -db.sqlite3 -manage.py I have used bootstrap. index.html is like below: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> {% load static %} <link href="{% static 'vira_app/assets/vendor/aos/aos.css' %}" rel="stylesheet"> <link href="{% static 'vira_app/assets/vendor/bootstrap/css/bootstrap.min.css' %}" rel="stylesheet"> <link href="{% static 'vira_app/assets/vendor/bootstrap-icons/bootstrap-icons.css' %}" rel="stylesheet"> <link href="{% static 'vira_app/assets/vendor/swiper/swiper-bundle.min.css' %}" rel="stylesheet"> {% load static %} <link href="{% static 'vira_app/assets/css/style.css' %}" rel="stylesheet"> </head> <body> <main id="main"> <div id="portfolio-grid" class="row no-gutter" data-aos="fade-up" data-aos-delay="200"> {% if catalogue_list %} {% for Catalogue in catalogue_list %} <div class="item web col-sm-6 col-md-4 col-lg-4 mb-4"> <a href="{{ Catalogue.link }}" class="item-wrap fancybox"> <div class="work-info"> <h3>{{ Catalogue.title }}</h3> <span>{{ Catalogue.source }}</span> </div> <img class="img-fluid" src="{{ Catalogue.image }}"> </a> </div> {% endfor %} {% endif %} </div> </div> </main> <a href="#" class="back-to-top d-flex align-items-center justify-content-center"><i class="bi bi-arrow-up-short"></i></a> <script src="assets/vendor/aos/aos.js"></script> <script src="assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script> <script src="assets/vendor/isotope-layout/isotope.pkgd.min.js"></script> <script src="assets/vendor/php-email-form/validate.js"></script> <script src="assets/vendor/swiper/swiper-bundle.min.js"></script> <script src="assets/js/main.js"></script> </body> </html> When I run the server and go to index.html, data retrieved from db and show well, but without any style! I have tried some solution, check every … -
Image file not display in pdf format using xhtml2pdf with django
I am following a vdo and corresponding repo https://github.com/divanov11/django-html-2-pdf for my html to pdf requirement. The reportlab is working great with converting html to pdf except it do not include image files in my html to the pdf. I also tried adding a link_call back pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result, link_callback=link_callback) below is the settings.py extract STATIC_ROOT = os.path.join(BASE_DIR , 'static') STATIC_URL = "/static/" STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' django_heroku.settings(locals()) i also tried with the absolute path {{imgpath}} (jinga variable in html) but it is also giving error that the file path is outside the base path def ViewPDF(request): dr = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) data["imgpath"] = dr.replace('\\','/') ##Used imgpath with static in tempalte print('start') print(dr ) print('end') pdf = render_to_pdf('invoice.html', data) return HttpResponse(pdf, content_type='application/pdf') -
how to export multiple files by Django
Can I response multiple files from Django ? Normally , I see many web site have upload multiple picture. However, I've not seen response multiple picture or file. Now, I can export excel file from Django, but I want to export multiple excel files at the same time. this code below export single excel file from response from openpyxl import Workbook response = HttpResponse( content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', ) response['Content-Disposition'] = 'attachment; filename={date}-user.xlsx'.format( date=datetime.now().strftime('%Y-%m-%d'), ) workbook = Workbook() worksheet = workbook.active worksheet.title = 'Test' row_num = 1 columns = ["Username", "First_name", "Last_name", "Email"] for col_num, column_title in enumerate(columns, 1): cell = worksheet.cell(row=row_num, column=col_num) cell.value = column_title user_queryset = User.objects.all().values("username", "first_name", "last_name", "email") for user in user_queryset: row_num += 1 # Define the data for each cell in the row row = [ user['username'], user['first_name'], user['last_name'], user['email'], ] # Assign the data for each cell of the row for col_num, cell_value in enumerate(row, 1): cell = worksheet.cell(row=row_num, column=col_num) cell.value = cell_value workbook.save(response) return response -
How to get image at navbar in python django?
I am not getting images at my navbar although I am giving the source to it,please give the actual code. <img src="{% static 'AARTHA/images/logo.jpeg' %}"> Here is the folder structure in Pycharm :-