Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django-taggit kwargs understanding
I'm using-django taggit and it works fine. But there are need to make some changes to extend DetailView url and after them TagListView chushed with 404 error. So i'm undestand that problem with kwargs in get_absolute_url function, but i can't understand how to fix it. So, work fine: models.py def get_absolute_url(self): return reverse("posts:detail", kwargs={"slug": self.slug}) urls.py: url(r'^(?P<slug>[\w-]+)/$', Detail.as_view(), name='detail'), url(r'^tag/(?P<slug>[\w-]+)/$', TagListView.as_view(), name='tagged'), views.py: class TagListView(ListView): template_name = "posts/postlist.html" paginate_by = "3" def get_queryset(self): return Post.objects.filter(tags__slug=self.kwargs.get("slug")).all() def get_context_data(self, **kwargs): context = super(TagListView, self).get_context_data(**kwargs) context["tag"] = self.kwargs.get("slug") return context And when I add "category": self.category to get_absolute_url and urls it crush: models.py: def get_absolute_url(self): return reverse("posts:detail", kwargs={"category": self.category, "slug": self.slug}) urls.py: url(r'^(?P<category>[\w-]+)/(?P<slug>[\w-]+)/$', Detail.as_view(), name='detail'), url(r'^tag/(?P<slug>[\w-]+)/$', TagListView.as_view(), name='tagged'), I suppose that there shoulb be changes in get_context_data func, but can't see what exactly. Any ideas or advices please? -
Django auth_view redirecting me in the admin panel instead to html file
I'am creating a login, registration and change password panel in Django. Everything is going ok, but I don't know why Django redirecting me in the Admin Panel when I click 'logout' and 'password change'. I've create the html files for this, and I don't want to use a admin panel. My code: urls.py from django.urls import path from django.contrib.auth import views as auth_views from konto.views import dashboard urlpatterns =[ path('login/', auth_views.login, name='login'), path('logout/', auth_views.logout, name='logout'), path('logout-then-login/', auth_views.logout_then_login, name='logout_then_login'), path('password-change/', auth_views.password_change, name='password_change'), path('password-change-done/', auth_views.password_change_done, name='password_change_done'), path('', dashboard, name='dashboard'), ] views.py from django.shortcuts import render from django.contrib.auth import authenticate, login from .forms import LoginForm from django.http import HttpResponse from django.contrib.auth.decorators import login_required def user_login(request): if request.method == 'POST': form = LoginForm(request.POST) if form.is_valid(): cd = form.cleaned_data user = authenticate(username=cd['username'], password=cd['password']) if user is not None: if user.is_active: login(request,user) return HttpResponse ('Uwierzytelnianie zakończyło się sukcesem') else: return HttpResponse ('Konto jest zablokowane') else: return HttpResponse('Podano nieprawidłowe dane logowania') else: form = LoginForm() return render(request, 'konto/login.html', {'form': form}) @login_required def dashboard(request): return render(request, 'konto/dashboard.html', {'section': dashboard}) dashboard.html <!DOCTYPE html> <html> <head> <title>Panel główny</title> </head> <body> <h1>Witaj</h1> {% if request.user.is_authenticated %} Witaj, {{ request.user.username}} <a href="{% url 'password_change' %}">Zmiana hasła</a> | <a href="{% url 'logout' %}">Wyloguj</a> … -
Python geocoding name 'latitude' is not defined
I'm a new in django. I want to bulid a webapp to search map by address.(Geocoding) My code shows it has name error at/map/. I dont know the reason. Thanks for kindly reply. from django.shortcuts import render import urllib from urllib.request import urlopen import json def searchMap(request): if request.method == "POST": global latitude global longitude city_name = request.POST.get('address') city_name_Url="https://maps.googleapis.com/maps/api/geocode/json? address"+city_name city_name_Url_Quote=urllib.parse.quote(city_name_Url,':?=/') response=urlopen(city_name_Url_Quote).read().decode('utf-8') response_json = json.loads(response) latitude = response_json.get('results')[0]['geometry']['location']['lat'] longitude = api_response_dict('results')[0]['geometry']['location']['lng'] return render(request,'WebPage1.html',{'Latitude':latitude,'Longitude':longitude}) -
Url pattern for retrieving object with hash as primary key
I have objects that contains metadata about a file. I want to implement a retrive based on the primary key, which is the md5 hash of the file. I am a little rusty on my regex, so how one could implement the urlpattern for this retrive? -
How to get filtered Django ORM query result in Django rest framework response
My question is about getting Django query result in Django-rest-framework api's response. I have the following models of Product, Attribute and Productoptions in my Django project: class Product(models.Model): productid = models.AutoField(db_column='productId', primary_key=True) productname = models.CharField(db_column='productName', max_length=200) class Attribute(models.Model): attributeid = models.AutoField(db_column='attributeId', primary_key=True) attributename = models.CharField(db_column='attributeName', max_length=200, blank=True, null=True) class Productoptions(models.Model): optionsid = models.AutoField(db_column='OptionsId', primary_key=True) optionproductid = models.ForeignKey(Product, models.DO_NOTHING, db_column='optionProductId', blank=True, null=True) optionattributeid = models.ForeignKey(Attribute, models.DO_NOTHING, db_column='optionAttributeId', blank=True, null=True) I have filled sample data in all three tables and when trying to get the products whose attribute name is nike, the following Django query perfectly worked in Python shell. Productoptions.objects.filter(optionattributeid__attributename='nike').values('optionproductid__productname') Get the result <QuerySet [{'optionproductid__productname': 'nike shirt'}, {'optionproductid__productname': 'nike tracksuit'}]> But the related model class query is not working in my view class ProductOptionsView(APIView): serializer_class = ProductOptionsSerializer def get(self,request): filteredproduct = Productoptions.objects.filter(optionattributeid__attributename='nike').values('optionproductid__productname') serializer = self.serializer_class(queryset, many=True) return Response(serializer.data) I am not getting the desired result from this view. Is there any way that all Django query will simply provide result with Django-rest-framework. All get and post queries are perfectly working in Python shell. Is there any other way or DRF has its own method for it to use nested models result in rest api. I have read Django Filter too but … -
django, how to mapping no other address, but just domain?
myproject/urls.py urlpatterns = [ url(r'^$', include('website-app.urls', namespace='website')), ] website-app/urls.py urlpatterns = [ url(r'^$', views.somedef, name='somename') ] I want to connect url domain.com/ to views.somedef which is not in myproject. What domain.com/ means is just domain and end of address with /. It is with No other parameters. domain.com/other/parameters/ has other parameters (other/parameters/), so it is not what I want. If I run django with that above code, django says ?: (urls.W001) Your URL pattern '^$' uses include with a regex ending with a '$'. Remove the dollar from the regex to avoid problems including URLs. Is there any good way to use url domain.com/ in website-app/urls.py , Not in myproject/urls.py? -
How to register a function in template tags in Django?
I want to keep a function without arguments in template tags in django and to be able to call it in a template. Example of the function: def my_count(): return models.MyModel.objects.count() Example of the template: Count: {{ my_count }} How should I define the function my_count in my template? -
Save OneToManyRelationship based on url input in Django
I have two database which are OneToManyRelationship as shown below. I am preparing interface for Data to be uploaded. I want to specify the project attribute in Data model by inputting the url of the Project path like http://project/13. Does anyone know how I can construct the relationship from url input of parent data? Models.py class Project(models.Model): project = models.CharField(max_length=50, blank=True) version = models.IntegerField(default=0) class Data(models.Model): project=models.ForeignKey(project) csv=models.FileField(upload_to=dir_path) -
Django copy instances bulk create
What is the best way to copy django objects for bulk creating, when multiple fields may vary between instances? for example i have: objects_to_create = [] for i in range(5): new_obj = obj new_obj.pk = None new_obj.foo = i objects_to_create.append(new_obj) M.objects.bulk_create(objects_to_create) However, for all of these newly created objects, foo will have value 4, because bulk create is saving 5 instances of new_obj as it is at the end of the loop. Is there a way to create copies that can then be modified before saving? Thanks. -
Spyne. How can i make service for one tag xml
Worked on python 2.7, django 1.6, spyne 2.11 I have this xml: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE inquiry_A2 SYSTEM "inquiry_A2.dtd"> <!-- Optional --> <inquiry_A2> <!-- Optional --> <Consignee> <AgencyCode>123123</AgencyCode> <PartyID>123123</PartyID> </Consignee> <SubstitutionIndicator>123123</SubstitutionIndicator> <Campaign>123123</Campaign> <DocumentID>1</DocumentID> </inquiry_A2> inquiry_A2 is a root element I want to make spyne proceed this request, but i can't figure out how to make this? The problem is that spyne rpc need both method name and param, for example: @rpc(RequestInquiry) def inquiry_A2(ctx, inquiry_A2): return True But with this example spyne generated xml is: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE inquiry_A2 SYSTEM "inquiry_A2.dtd"> <!-- Optional --> <inquiry_A2> <inquiry_A2> <!-- Optional --> <Consignee> <AgencyCode>123123</AgencyCode> <PartyID>123123</PartyID> </Consignee> <SubstitutionIndicator>123123</SubstitutionIndicator> <Campaign>123123</Campaign> <DocumentID>1</DocumentID> </inquiry_A2> </inquiry_A2> Is that possibile to do with spyne? I can't change incoming xml -
install Django 2.0.2 Could not find a version
Im trying to use pip install Django==2.0.2 but throw , No matching distribution found for Django==2.0.2 , and it´s weird cause im using the same command from Django, what can i do ? -
django error while installing
Getting error while installing Django C:\Users\Lenovo>pip install django Collecting django Retrying (Retry(total=4, connect=None, read=None, redirect=None)) after connection broken by 'ProxyError('Cannot connect to proxy.', NewConnectionError(': Failed to establish a new connection: [Errno 11001] getaddrinfo failed',))': /simple/django/ Retrying (Retry(total=3, connect=None, read=None, redirect=None)) after connection broken by 'ProxyError('Cannot connect to proxy.', NewConnectionError(': Failed to establish a new connection: [Errno 11001] getaddrinfo failed',))': /simple/django/ Retrying (Retry(total=2, connect=None, read=None, redirect=None)) after connection broken by 'ProxyError('Cannot connect to proxy.', NewConnectionError(': Failed to establish a new connection: [Errno 11001] getaddrinfo failed',))': /simple/django/ Retrying (Retry(total=1, connect=None, read=None, redirect=None)) after connection broken by 'ProxyError('Cannot connect to proxy.', NewConnectionError(': Failed to establish a new connection: [Errno 11001] getaddrinfo failed',))': /simple/django/ Retrying (Retry(total=0, connect=None, read=None, redirect=None)) after connection broken by 'ProxyError('Cannot connect to proxy.', NewConnectionError(': Failed to establish a new connection: [Errno 11001] getaddrinfo failed',))': /simple/django/ Could not find a version that satisfies the requirement django (from versions: ) No matching distribution found for django -
'image' attribute has no file associated with it - django
I have a blog project, and receive the above error when running the django dev server. I have uploaded an image via the admin panel, which then saves as expected in the posts/media folder. Please can anyone help? My project (shortened version) looks as follows: - blogproject - posts - media - static - templates - posts - base.html - getAllPosts.html - blog - urls.py - settings.py - models.py SETTINGS.PY BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates') STATIC_DIR = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [STATIC_DIR, ] STATIC_URL = '/static/' MEDIA_DIR = os.path.join(BASE_DIR, 'posts/media') MEDIA_ROOT = MEDIA_DIR MEDIA_URL = '/media/' URLS.PY [...] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) models.py class Post(models.Model): title = models.CharField(max_length=200) summary = models.CharField(max_length=500, default=True) body = models.TextField() pub_date = models.DateTimeField(default=timezone.now) category = models.ManyToManyField('Category') author = models.ForeignKey(User, default=True) titleSlug = models.SlugField(blank=True) authorSlug = models.SlugField(blank=True) image = models.ImageField(upload_to="images/%Y/%m/%d", null=True) def save(self, *args, **kwargs): self.titleSlug = slugify(self.title) self.authorSlug = slugify(self.author) super(Post, self).save(*args, **kwargs) def __str__(self): return self.title getAllPosts.html <!DOCTYPE html> {% extends "posts/base.html" %} {% load static %} {% load template_tags %} {% block content %} {% if latest_posts %} {% for post in latest_posts %} <a href="{% url 'getPost' slug=post.titleSlug %}"> <img src="{{ MEDIA.URL }} {{post.image.url}}" alt="image- {{post.title}}"/> … -
I want to built a multiple items search at a time like user can search for (rice, potato, eggs, etc) multiple items at once
This is my current search view.py. I am trying to split the whole search string by (, ) and then take each word to return each searched product. But that's not working.Can anyone give any idea on how should I approach this? from django.shortcuts import render from django.views.generic import ListView from products.models import Product class SearchProductView(ListView): template_name = "search/view.html" def get_context_data(self, *args, **kwargs): context = super(SearchProductView, self).get_context_data(*args, **kwargs) query = self.request.GET.get('q') context['query'] = query return context def get_queryset(self, *args, **kwargs): request = self.request method_dict = request.GET query = method_dict.get('q', None) que = query.split(', ') for query_item in que: if query_item is not None: return Product.objects.search(query_item) -
How to safely increment database using django rest framework?
I'm facing some troubles by trying to make a like/unlike system for my app. It's okay when i like/unlike in a normal timelapse, but when i click multiple times in a very short frequency (20 clicks in 10 seconds for example) then my counter is disturbed. Normally while i'm testing my counter should always have a value of 1 or 0 since i am the only one to do the operation. However when i click quickly and multiple times, my rest api cannot follow the rythm and i'm getting a counter that have 7 or 8 likes. I've tried multiple solutions. first by adding the model transaction included with django. As a decorator : @transaction.atomic Or manually : with transaction.atomic(): #do stuff I've also tried to increment directly from the database by using F() : votes=F("votes") + 1 Nothing seems to work. Any suggestion ? -
Django - CreateView fails, am redirected to empty create view
My CreateView seems to be failing but I am unsure as to why. I am being redirected to an empty CreateView with no errors or messages to tell me why its failing. I would of thought I would of been redirected to CreateView with the entered Data saved and an error. I've checked admin for the model and the record is not being created. the issue seems to be server side but I am not getting any output in console I just get 200s "POST /sites/site/add_subnet/7 HTTP/1.1" 200 41406 my forms.py: class AddSubnetForm(forms.ModelForm): class Meta: model = SiteSubnets fields = ['device_data','subnet', 'subnet_type', 'circuit', 'vlan_id', 'peer_desc'] def __init__(self, *args, **kwargs): site_id = kwargs.pop('site_id', None) super(AddSubnetForm, self).__init__(*args) self.fields['circuit'].queryset = Circuits.objects.filter(site_data=site_id) view.py: class AddSubnet(CreateView): form_class = AddSubnetForm template_name = "sites/edit_subnet.html" @method_decorator(user_passes_test(lambda u: u.has_perm('config.add_subnet'))) def dispatch(self, *args, **kwargs): self.site_id = self.kwargs['site_id'] self.site = get_object_or_404(SiteData, pk=self.site_id) return super(AddSubnet, self).dispatch(*args, **kwargs) def get_success_url(self, **kwargs): return reverse_lazy("sites:site_detail_subnets", args=(self.site_id,)) def form_valid(self, form): form.instance.site_data = self.site return super(AddSubnet, self).form_valid(form) def get_form_kwargs(self, *args, **kwargs): kwargs['site_id'] = self.site_id return kwargs def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['SiteID']=self.site_id context['SiteName']=self.site.location context['FormType']='Add' context['active_subnets']='class="active"' return context template: {% block content %} <div class="col-lg-3"> {{ result }} {{ form.errors }} {% if messages %} {% for … -
Contains or in filtering using DRF
I have a simple Blog app, which contains models Entry with ManyToManyField, called tags MODELS class Tag(models.Model): name = models.CharField(max_length=30) class Entry(models.Model): ... tags = models.ManyToManyFiled(Tag) ... I also have a filter class django_filters.rest_framework.FilterSet, which should be able to filter entries which contain the only tags that were passed to request or the tags + others. How do I implement this? -
Annotate each result with value indicating if minimum or maximum of field
I have two models, Author and Book: class Author(models.Model): name = models.CharField(max_length=256) class Book(models.Model): name = models.CharField(max_length=256) price = models.IntegerField() publication_date = models.DateField() author = models.ForeignKey(Author, related_name="books") Now when I get a set of authors and their books, I want to annotate each book with two values indicating if it is the cheapest or most expensive out of the filtered books from the same author. I got the correct results using Exists and annotations filtered_books = Book.objects.filter(publication_date__year=2010) lower_price = filtered_books.only('id').filter(price__lt=OuterRef('price'), author=OuterRef('author')) higher_price = filtered_books.only('id').filter(price__gt=OuterRef('price'), author=OuterRef('author')) filtered_books = filtered_books.annotate( lowest_price=~Exists(lower_price), highest_price=~Exists(higher_price), ) authors = Author.objects.annotate.prefetch_related(Prefetch('books', queryset=filtered_books)) It works but results in three (lower_price, higher_price and the prefetch) very similar subqueries being executed and is not that fast. How can I optimize it? -
How to create user permissions for my UserPost model.
I'm new to django, i want to know how to assign permissions to the model. My requirement is - i want to create 2 different category posts namely It-posts and Art-posts and need to select any one from the category by the user while signup, after the user login - he must be able to see only the posts that he selected from category, if he tries to select /view the other posts category - a error message should be displayed for the user. I created category while signup but failing in assining permissions for user to see particular posts. Can anyone please help me, how to overcome this issue with this issue.? enter image description here -
How to execute a shell script that prompts user at least 20 times using Python?
I have a shell script that connects to at least 20 remote servers internally using SSH. Therefore, it prompts user to enter password 20 times. I cannot use public authentication key as it can be a security violation. Neither, do I have permissions to install sshpass or any other plugins. I want to learn python and so I want to execute this shell scripts using python that can execute this script and also allow us for user prompts. Further, I want to use Django to make a UI out of the output provided by the shell script. Is that possible and how ? -
Django styling included templates
I have three files. My base.html: {% load static %} <head> <link href="{% static 'base/css/normalize.css' %}" rel="stylesheet" type="text/css" /> <link href="{% static 'base/css/base.css' %}" rel="stylesheet" type="text/css" /> {% block styling %} {% endblock %} </head> <body> {% block content %} {% endblock %} </body> Project.html: {% extends "base/base.html" %} {% load sass_tags %} {% load static %} {% block styling %} <title>Project</title> <link href="{% sass_src 'dashboard/scss/project.scss' %}" rel="stylesheet" type="text/css" /> {% endblock %} {% block content %} <div class="project-container"> {% include "dashboard/tree.html" %}... and tree.html: {% load sass_tags %} <link href="{% sass_src 'dashboard/scss/tree.scss' %}" rel="stylesheet" type="text/css" /> <section class="tree"> <ul class="tree__root">... To summarize above code; project.html extends from base.html, and project.html is also including tree.html. This works as intended and the styling is applied correctly as well. But I'm unhappy about the place of the styling. When I include the styling of tree.html it is put in the body of the DOM. I want it to be in the head. I have tried extending base.html in tree.html and using {% block styling %}, didn't work. Also I tried defining a head in tree.html which didn't work either (no surprise there). So as far as I can see I am left … -
Dynamically Chain Django Forms
In a Django 1.11 app I've created a large form for users to update a model instance, but based on what the users change there may be multiple other forms I'd like to redirect them to afterwards. What's the best practise for dynamically chaining multiple forms (dynamic workflow)? I can't find anything helpful in the Django docs or other questions on here. E.g. (extremely simplified) view for model update form: def asset_edit(request, pk): asset = get_object_or_404(Asset, pk=pk) current_location_concat = "{} {} {}".format(asset.location_building, asset.location_room, asset.location_area) if request.method == "POST": form = EditAsset(request.POST, request.FILES, instance=asset) if form.is_valid(): asset = form.save(commit=False) # setting some things... asset.save() new_location_concat = "{} {} {}".format(asset.location_building, asset.location_room, asset.location_area) if current_location_concat != new_location_concat: check_relatives = True # redirect to check_relatives form if asset.equipment_id: if Asset.objects.filter(equipment_id=asset.equipment_id).count() > 1: duplicate_assets = True # redirect to check_duplicates form # if check_relatives and duplicate_assets: # redirect to check_duplicates form and then on to check_relatives form return redirect("asset_detail", pk=asset.pk) I know I could just add a new URL for my check_duplicates form with a "Next" (or similar) parameter, pass the name of my check_relatives view or a value to map to it or something similar, but is this best practise? Especially given that the … -
cannot upload files to django rest framework using react js
I'm using react Js to upload an image to django restframework. here I'm sending post request using fetch API. Eapp.jsx import React, { Component } from 'react'; class Eapp extends Component { constructor(props){ super(props); this.state = { profilePic: null, }; this.inpuElement = null; this.handleChange = this.handleChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); } handleChange(e){ this.setState({profilePic: e.target.files[0]}); } handleSubmit(){ let formData = new FormData(); formData.append('profile_pic',this.state.profilePic); fetch('http://10.42.0.1:8000/auth/profile-pic/', { method: 'POST', headers: { Accept: 'application/json, text/plain, */*', 'content-type': 'multipart/form-data', }, body:formData, }).then(res => res.json()) .then((data) => { console.log(data); }) .catch(err => console.log(err)); } render(){ return( <div> <input type="file" multiple={false} ref={(input) => { this.inpuElement = input; }} accept=".jpg,.jpeg,.png" onChange={this.handleChange} /> <button onClick={this.handleSubmit}>submit</button> </div> ); } } export default Eapp; error msg Eapp.jsx:19 POST http://10.42.0.1:8000/auth/profile-pic/ 500 (Internal Server Error) handleSubmit @ Eapp.jsx:19 callCallback @ react-dom.development.js:542 invokeGuardedCallbackDev @ react-dom.development.js:581 invokeGuardedCallback @ react-dom.development.js:438 invokeGuardedCallbackAndCatchFirstError @ react-dom.development.js:452 executeDispatch @ react-dom.development.js:836 executeDispatchesInOrder @ react-dom.development.js:858 executeDispatchesAndRelease @ react-dom.development.js:956 executeDispatchesAndReleaseTopLevel @ react-dom.development.js:967 forEachAccumulated @ react-dom.development.js:935 processEventQueue @ react-dom.development.js:1112 runEventQueueInBatch @ react-dom.development.js:3607 handleTopLevel @ react-dom.development.js:3616 handleTopLevelImpl @ react-dom.development.js:3347 batchedUpdates @ react-dom.development.js:11082 batchedUpdates @ react-dom.development.js:2330 dispatchEvent @ react-dom.development.js:3421 example:1 Failed to load http://10.42.0.1:8000/auth/profile-pic/: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 500. … -
create several pdf files and compress them for download
I have one problem about download zip file with several pdf file, and in my case I have only links for these pdf files, and I don't know how to it, because in many links which I saw tell me that I just need to show directory, but for my case it doesn't work. I have function for generate pdf file and download it: def get_pdf_document(request, code): host = request.scheme + "://" + request.META["HTTP_HOST"] uri = reverse('documents:view_signed_document', kwargs={'code': code}) + "?is_pdf=true" obj = get_object_or_404(DownloadCode, code=code) options = { 'page-size': 'A4', 'encoding': "UTF-8", 'no-outline': None, 'margin-bottom': '17', 'margin-left': '10', 'margin-right': '10', 'margin-top': '10', 'footer-html': host + reverse('api:pdf-footer', kwargs={'code': code}), } if obj.doc_type == ACTS_TYPE or obj.doc_type == LISTS_TYPE: options['orientation'] = 'Landscape' result = pdfkit.from_url(host + uri, False, options=options) response = HttpResponse(result, content_type='application/pdf') if obj.doc_type == INVOICE_TYPE: doc = proxy.get_invoice_by_id(invoice_id=obj.doc_id, tin=obj.tin) if doc.status.code != pb.ResponseStatus.OK: doc = proxy.get_invoice_draft_by_id( invoice_draft_id=obj.doc_id, tin=obj.tin) doc_num = u"#{}".format(doc.invoice.num) doc_create_date = doc.invoice.turnover_date else: ref = perm.document_type_proxy[obj.doc_type] doc = ref['get'](doc_id=obj.doc_id, tin=obj.tin) if doc.status.code != pb.ResponseStatus.OK: return render(request, 'documents/doc_not_found.html', {'code': code}) doc_num = ("" if obj.doc_type == RECONS_TYPE else u"#{}".format(doc.document.act_num) if obj.doc_type == ACTS_TYPE else u"#{}".format(doc.document.num)) doc_create_date = doc.document.create_date response['Content-Disposition'] = ( "attachment; filename*=utf-8''" + urllib.quote((u'{} - OT {} - … -
Using both the project level and the app level static files in django
I have some static files that will remain common through all the application and I also have some static files that are specific to some particular apps only. Now in one of my apps, i want to use both the project level and the app level static files but that doesn't seem to work. Following code section is from settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "homepage","static"), os.path.join(BASE_DIR, "landing_page","static"), os.path.join(BASE_DIR, "static"), ] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') I have used python manage.py collectstatic and it returns with a warning which goes like Found another file with the destination path 'homepage\css\style.css'. It will be ignored since only the first encountered file is collected. If this is not what you want, make sure every static file has a unique path. Despite the above warning, I still get both the project level and the app level static files in the staticfiles folder in my root directory. When I use it in a template, the project level static file gets loaded while the app level static file (which is just a single CSS file) doesn't get loaded. Following is how I am trying to load the CSS file. {% load static %} <link rel="stylesheet" …