Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Serializing Many To Many intermediate table in Django Rest Framework
I would like to learn how to get many to many intermediate table's serializer data by whole model , not only by id. #this is my model class class ProductMaterial(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) material = models.ForeignKey(Hammadde, on_delete=models.CASCADE) material_rate = models.FloatField(blank=True, null=True) material_price = models.FloatField(blank=True, null=True) #serializer class ProductMaterialSerializer(serializers.ModelSerializer): class Meta: model = ProductMaterial fields = '__all__' This returns: { "id": 1, "material_rate": 0.3, "material_price": 6.7, "product": 186, "material": 7 }, { "id": 2, "material_rate": 0.7, "material_price": 1.7, "product": 186, "material": 8 }, Problems: First problem is it duplicates data because of many to many table I want to see my product and material model fields too. My target: { "id": 1, "product": { "name" : "abcd", "date" : "01.01.2018" }, "material": [ { "id" : 7, "material_rate" : 0.3, "material_price" : 6.7, }, { "id" : 8, "material_rate" : 0.7, "material_price" : 1.7, }, ] }, -
Incorrect URL to file in Django admin
I'm getting the wrong URL to files that have been uploaded to the media-folder in the Django admin. The URL for the file is: /media/Users/hammer/Dev/*****/media/attachments/2018/09/12/pdf-test.pdf But the correct URL to the file is: /media/attachments/2018/09/12/pdf-test.pdf It seems like MEDIA_ROOT (/Users/hammer/Dev/*****/media/) is (incorrectly, I guess) added after the first /media/ in the URL. Any ideas on how to fix this? -
Django; adapt same validator with multiple fileds
I want to override first_name and last_name AbstractUser model has. I want to create validator that tells if either first_name or last_name is filled. So I want to adapt the same validator with the two paramters. How can I create? Anyone who could give me tip? -
Updating Django version to 1.10
I'm taking over an old project under Django for which I don't know the basic version to use, on my server I have 1.9.9, I tried to build it via docker, but without success... So I try to migrate Django 1.x to 1.10, but I currently have a problem with model dependency. when I launch the application I get an error message : stack trace web_1 | Traceback (most recent call last): web_1 | File "./manage.py", line 9, in <module> web_1 | execute_from_command_line(sys.argv) web_1 | File "/usr/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line web_1 | utility.execute() web_1 | File "/usr/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 341, in execute web_1 | django.setup() web_1 | File "/usr/local/lib/python2.7/site-packages/django/__init__.py", line 27, in setup web_1 | apps.populate(settings.INSTALLED_APPS) web_1 | File "/usr/local/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate web_1 | app_config.import_models(all_models) web_1 | File "/usr/local/lib/python2.7/site-packages/django/apps/config.py", line 199, in import_models web_1 | self.models_module = import_module(models_module_name) web_1 | File "/usr/local/lib/python2.7/importlib/__init__.py", line 37, in import_module web_1 | __import__(name) web_1 | File "/usr/src/app/ots/geo/models.py", line 19, in <module> web_1 | from ots.otsapi.models import RPCForeignKey web_1 | File "/usr/src/app/ots/otsapi/models.py", line 4, in <module> web_1 | from .fields import * web_1 | File "/usr/src/app/ots/otsapi/fields.py", line 7, in <module> web_1 | from django.db.models.fields.subclassing import Creator web_1 | ImportError: No module named subclassing … -
djcelery periodic poll data store in redis db?
I am having Django-celery implemented a Django project, and getting poll data from external API inside celery periodic task. I wanted to keep this data for other tasks of celery. using Redis how can achieve?? please give me brief explanation?? I am new to celery and Redis thank you in advance. -
Keras hanging during training when paired with celery
I have code that trains a neural network using Keras. First, I run it through a grid search-like algorithm to get the best parameters and then I use the best parameters to do the real predictions. The code works completely fine on its own; it's only after I run it with celery (Django backend) that I start to have the problem stated in the title. To clarify, training works completely fine during the grid search, but when it's done and runs again on the best parameters, it just hangs on 'Epoch 1/1'. Upon research, I read that I need to keep the keras imports to one area, as it doesn't work with multiprocessing. However, I made sure that was the case and even tried putting the keras imports inside the function that trains it, and still having the same problem. My question is: how do I get Keras to work properly with celery? -
Using JavaScript Onclick Event to pass Data to views.py in Django?
I Have a bit of idea about this to use ajax with the JavaScript to send data to views.py but I am not able to do that. So what I am trying to do is I have put onclick event on the image so by clicking on that image I should be able to send some value to views.py. This is Hello.html file. <img src="" onclick="change()"> JavaScript function: function change(){ // Do something here to send data to views.py } Now in views.py def SomeFunction(): //To get data here -
Django: Foreign Key to a partitioned table
I have used architect to partition an existing table. @architect.install('partition', type='range', subtype='integer', constraint='100', column='id') class Project(models.Model): name = models.CharField(max_length=150) The project model was used as a foreign key to another model. class ProjectChangeLog(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) After partitioning, I could not add any ProjectChangeLog objects. It says: IntegrityError: insert or update on table "logging_projectchangelog" violates foreign key constraint DETAIL: Key (project_id)=(231) is not present in table "project_project" -
umap-project can't find vendor libraries
I am trying to extend umap (), I used git clone to get the latest version of umap code and imported it into eclipse. I have PyDev Django environment set up. According to the installation guide I created configuration file (/etc/umap/umap.conf), created database, run manage.py migrate and collectstatic. Everything went ok. Home page is displayed also ok, but when I try to do anything (login, create map) I get stack of errors. Please find below log from eclipse console. I am looking at github repo and also cannot find this folder /static/umap/vendors. I just started to work with umap so maybe I am missing something. Loaded local config from /etc/umap/umap.conf /home/svranic/.local/lib/python3.6/site-packages/psycopg2/__init__.py:144: UserWarning: The psycopg2 wheel package will be renamed from release 2.8; in order to keep installing from binary please use "pip install psycopg2-binary" instead. For details see: <http://initd.org/psycopg/docs/install.html#binary-install-from-pypi>. """) Loaded local config from /etc/umap/umap.conf /home/svranic/.local/lib/python3.6/site-packages/psycopg2/__init__.py:144: UserWarning: The psycopg2 wheel package will be renamed from release 2.8; in order to keep installing from binary please use "pip install psycopg2-binary" instead. For details see: <http://initd.org/psycopg/docs/install.html#binary-install-from-pypi>. """) Performing system checks... System check identified no issues (0 silenced). September 12, 2018 - 11:32:32 Django version 2.1.1, using settings 'umap.settings' Starting development server at … -
Django Admin Login 403 Forbidden (CSRF cookie not set.)
I am trying to login admin panel but I am getting 403 Forbidden error. Last week, there was not error. I did not change anything. I almost tried all solution of same problems in StackOverFlow. Please help me! Thanks for reading. I apologize for my poor English. System: Ubuntu Python 3.5 Django 2.0 Gunicorn Nginx iRedMail django debug.log Exception while resolving variable 'is_popup' in template 'admin/login.html'. Traceback (most recent call last): File "/home/xxx/xxx/xxx/lib/python3.5/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/xxx/xxx/xxx/lib/python3.5/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'is_popup' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/xxx/xxx/xxx/lib/python3.5/site-packages/django/template/base.py", line 835, in _resolve_lookup if isinstance(current, BaseContext) and getattr(type(current), bit): AttributeError: type object 'RequestContext' has no attribute 'is_popup' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/xxx/xxx/xxx/lib/python3.5/site-packages/django/template/base.py", line 843, in _resolve_lookup current = current[int(bit)] ValueError: invalid literal for int() with base 10: 'is_popup' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/xxx/xxx/xxx/lib/python3.5/site-packages/django/template/base.py", line 850, in _resolve_lookup (bit, current)) # missing attribute django.template.base.VariableDoesNotExist: Failed lookup for key [is_popup] in [{'False': False, 'None': None, 'True': True}, {'base_url': 'domain.com', 'DEFAULT_MESSAGE_LEVELS': {'DEBUG': 10, 'SUCCESS': … -
Sending mail whenever POST request in API
I am using django and django-rest-framework to serve some API's. Vue.js is used to interact those API's as an frontend framework. I am able to send POST request data with the help of "Axios" and data is saving in django. I want to send mail whenever a POST request occurs. Initially when I was using django-forms, sending mail was easy because I would send_mail just before form.save(). But now I am little bit confused views.py class StudentQueryViewSet(viewsets.ModelViewSet): queryset = StudentQuery.objects.all() serializer_class = StudentQuerySerializer def create(self, request, *args, **kwargs): query=self.get_object() serializer = StudentQuerySerializer(data=request.DATA) if serializer.is_valid(): serializer.save() msg = "A new query has been added in Category" + str(query.category) msg += "\n Name: " + query.name msg += "\n Contact: " + str(query.contact) msg += "\n Subject: " + str(query.subjects) msg += "\n Standard: " + str(query.standard) msg += "\n Address: " + str(query.address) send_mail(emailSubject, message, emailFrom, emailList, fail_silently=False) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) When I used this create method I got hit by Assertion error. Here is the traceback Internal Server Error: /api/student-query/ Traceback (most recent call last): File "/home/f1uk3r/.virtualenvs/edhusk-project/lib/python3.5/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/f1uk3r/.virtualenvs/edhusk-project/lib/python3.5/site-packages/django/core/handlers/base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/f1uk3r/.virtualenvs/edhusk-project/lib/python3.5/site-packages/django/core/handlers/base.py", line … -
Django-tables2 add a dropdown column using model charfield with choices
I am making a webpage which has one table in it using Django-tables2. In this table I have a checkbox column, which I use to select specific row(-s). I also have a submit button, which submits checked row(-s) values. Basically, I am trying to add a column to my table, which has a dropdown menu with two choices. What I did was in my models.py I wrote a model class, which includes charfield with choices and other fields for the table: class Mymodel(models.Model): CHOICES = ( ('yes', 'Yes'), ('no', 'No'), ) choice = models.CharField(max_length=5, choices=CHOICES, default='no',verbose_name='Something') ... #other fields In my tables.py I have a table class: import django_tables2 as tables from .models import mymodel class myTable(tables.Table): class Meta: model = mymodel template_name = 'django_tables2/semantic.html' fields = ('field1', 'field2', 'field3','choice') attrs = {'class': 'table table-bordered table-hover', 'id': 'TableName'} orderable = False empty_text = ' ' The problem that I am having is that the table works, but the choice column, which has the 2 choices does not display the dropdown menu, but only shows the default choice. In Django admin page, where I can edit these fields it shows the dropdown menu and I can choose between them and save … -
Best way to associate pre-existing model instances to a new parent model?
Let's say I've created a few BoxModels, and every model has one field with a ForeignKey to a DeliveryRouteModel. At the time of creation, the FK field is empty. Now, in a DeliveryRouteModel form, I want to create a new Delivery Route and, besides of its own fields, I want to add a number of BoxModels that I load via Ajax into the model (by adding the ID of the newly created DeliveryRouteModel to the BoxModel) . What's the proper way to do it? Should I create a BoxFormSet and add it to the form? Or should I pass every Box ID as arguments without any Formset? P.S: Remember I just want to add the new ID to the BoxModel ForeignKey -
How to show API response in django template?
I am trying to use an api to link it with front end login form.I have written python requests post method to submit data from front end input fields and trying to get response back. Problem is whatever is the response my ajax doesnt behave accordingly.So how can i show error when api responds with an error and how to show success when api says so? urls.py path('login',ApiLoginView.as_view(),name = 'login') views.py class ApiLoginView(TemplateView): template_name = 'index.html' def post(self,request): email = request.POST.get('email') password = request.POST.get('password') API_KEY = 'XXXXXXXXXXXXXXXXXXXXXXXX' API_URL = 'http://dev.com/rest/storeLogin' parameter = { 'authToken':API_KEY, 'email':email, 'password':password, } r = requests.post(url = API_URL, params=parameter) return render(request,'index.html') template <script> $(document).ready(function(){ var myForm = $('.my-login-form') myForm.submit(function(e){ e.preventDefault() console.log('hi') var formData = $(this).serialize() $.ajax({ method: "POST", url: '/login', data: formData, success: handleFormSuccess, error: handleFormError, }) }) function handleFormError(jqXHR, textStatus, errorThrown){ console.log(jqXHR) console.log(textStatus) console.log(errorThrown) alert(errorThrown) } function handleFormSuccess(data, textStatus, jqXHR){ console.log(data) console.log(textStatus) console.log(jqXHR) myForm[0].reset(); } }) </script> <form class="my-login-form" action="/login" method="post"> {% csrf_token %} <div class="field-wrap"> <input type="email" name="email" required autocomplete="off" placeholder="Email Id"/> </div> <div class="field-wrap"> <input type="password" name="password" required autocomplete="off" placeholder="Password"> </div> <button class="button button-block"/>Login</button> <div class="forgot"><a class="user-form-toggle" href="#forgot">Forgot Password?</a></div> </form> -
NoReverseMatch at /accounts/password_reset/
I'm working on authentication for a Django project I'm working on. For some reasons, I'm getting the error Reverse for 'password_reset_done' not found. 'password_reset_done' is not a valid view function or pattern name. I put everything authentication in an accounts app. Here's the content of the base urls.py file: from django.contrib import admin from django.urls import path, include from accounts import urls as accounts_urls from core import urls as core_urls from core import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.home, name='home'), path('accounts/', include(accounts_urls, namespace='accounts')), path('core/', include(core_urls, namespace='core')), ] Here's the content of the urls.py file (in the accounts app): from django.urls import path, reverse_lazy from django.contrib.auth import views as auth_views from . import views as accounts_views app_name = 'accounts' urlpatterns = [ path('signup/', accounts_views.signup, name='signup'), path('login/', auth_views.LoginView.as_view(template_name='accounts/login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(), name='logout'), path('account_activation_sent/', accounts_views.account_activation_sent, name='account_activation_sent'), path('activate/<uidb64>/<token>/', accounts_views.activate, name='activate'), path('password_reset/', auth_views.PasswordResetView.as_view( template_name='accounts/password_reset.html', email_template_name='accounts/password_reset_email.html', subject_template_name='accounts/password_reset_subject.txt' ), name='password_reset'), path('password_reset/done/', auth_views.PasswordResetDoneView.as_view( template_name='accounts/password_reset_done.html' ), name='password_reset_done'), path('password_reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view( template_name='accounts/password_reset_confirm.html' ), name='password_reset_confirm'), path('password_reset/complete/', auth_views.PasswordResetCompleteView.as_view( template_name='accounts/password_reset_complete.html' ), name='password_reset_complete'), ] Here's the accounts/templates directory structure: templates/ accounts/ password_reset.html password_reset_email.html password_reset_done.html password_reset_confirm.html password_reset_complete.html I don't see anything wrong with what I have done so far. Any eye opener would be greatly appreciated, thanks! -
django force query aliases
I am writing a custom Oracle json field for Django, and for it to work the backend Requires table names to be aliased. i.e. This will work: select t.col1.x from table_name t where t.col1.y >2 This won't: select col1.x from table_name where col1.y >2 Nor will this: select table_name.col1.x from table_name where table_name.col1.y >2 Is there a flag, etc that can be set on the field, or the backend to force tables to be aliased? My current workaround is to join the table to itself, which then forces an alias, but it's a bit of a hack. class CustomQueryManager(models.Manager): def filter_special(self, *args, **kwargs): base_q = super().filter(*args, **kwargs) return self.filter(id__in=base_q.values_list('id', flat=True)) Ideally I would just like to use the standard MyModel.objects.filter method without having to force a self join, and without the custom filter_special method on the manager. -
Elastic Search Nested Query Matching All Documents
While I am Querying a nested field using elastic Search, It returns me all the nested field even if one field matches.If no of them match then it returns empty..I need help in restricting the field which only matches { "nested": { "path": "rooms", "query": { "bool": { "must": [ { "range": { "rooms.single_occupancy_rate":{ "lte" : budget } } }, { "range": { "rooms.guest_count": { "gte": 3 } } } ] } } -
Invalid template library specified. ImportError raised when trying to load
I'm trying to upgrade a Django project, now I'm working on django 1.10 I've already fixed all errors and all the deprecation warnings. But now I have this error which I cannot solve it or even understand why! Traceback (most recent call last): File "/home/basha/UpgradeMloss/venv1.10/local/lib/python2.7/site-packages/django/core/handlers/exception.py", line 39, in inner response = get_response(request) File "/home/basha/UpgradeMloss/venv1.10/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 249, in _legacy_get_response response = self._get_response(request) File "/home/basha/UpgradeMloss/venv1.10/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 217, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/basha/UpgradeMloss/venv1.10/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 215, in _get_response response = response.render() File "/home/basha/UpgradeMloss/venv1.10/local/lib/python2.7/site-packages/django/template/response.py", line 109, in render self.content = self.rendered_content File "/home/basha/UpgradeMloss/venv1.10/local/lib/python2.7/site-packages/django/template/response.py", line 84, in rendered_content template = self.resolve_template(self.template_name) File "/home/basha/UpgradeMloss/venv1.10/local/lib/python2.7/site-packages/django/template/response.py", line 68, in resolve_template return get_template(template, using=self.using) File "/home/basha/UpgradeMloss/venv1.10/local/lib/python2.7/site-packages/django/template/loader.py", line 18, in get_template engines = _engine_list(using) File "/home/basha/UpgradeMloss/venv1.10/local/lib/python2.7/site-packages/django/template/loader.py", line 72, in _engine_list return engines.all() if using is None else [engines[using]] File "/home/basha/UpgradeMloss/venv1.10/local/lib/python2.7/site-packages/django/template/utils.py", line 89, in all return [self[alias] for alias in self] File "/home/basha/UpgradeMloss/venv1.10/local/lib/python2.7/site-packages/django/template/utils.py", line 80, in __getitem__ engine = engine_cls(params) File "/home/basha/UpgradeMloss/venv1.10/local/lib/python2.7/site-packages/django/template/backends/django.py", line 30, in __init__ options['libraries'] = self.get_templatetag_libraries(libraries) File "/home/basha/UpgradeMloss/venv1.10/local/lib/python2.7/site-packages/django/template/backends/django.py", line 48, in get_templatetag_libraries libraries = get_installed_libraries() File "/home/basha/UpgradeMloss/venv1.10/local/lib/python2.7/site-packages/django/template/backends/django.py", line 113, in get_installed_libraries for name in get_package_libraries(pkg): File "/home/basha/UpgradeMloss/venv1.10/local/lib/python2.7/site-packages/django/template/backends/django.py", line 130, in get_package_libraries "trying to load '%s': %s" % (entry[1], e) InvalidTemplateLibrary: Invalid template library specified. ImportError raised … -
Modify prefetched objects
Is it possible to modify prefetched objects without using save()? class First(models.Model): field = models.IntegerField() class Second(models.Model): first = models.ForeignKey(First, related_name='seconds') some = models.IntegerField() f = First.objects.filter(field=12).prefetch_related('seconds') f.seconds.all()[0].some = 999 f.seconds.all()[0] == 999 # should be True -
Django - how to pass a value from <a href> to a view
I have a category dropdown list in a template. I don't want to hard code it and write separate list views for each category. So is there a way to pass a value from <a href=""> to a view? I guess self.request.GET.get('category search') never works because there is no <form method="get"> tag. Therefor it always returns None. home.html: <div class="dropdown-menu" aria-labelledby="navbarDropdown"> {% if all_categories %} {% for category in all_categories %} <a name="category search" href="{% url 'book:category_search' category.id %}"> {{ category }} </a> {% endfor %} {% endif %} </div> book.urls.py: urlpatterns = [ ......... path('categories/<int:pk>', views.CategorySearchView.as_view(), name='category_search'), ] book.views.py: class CategorySearchView(generic.ListView): template_name = 'book/search.html' model = Book context_object_name = 'book_list' paginate_by = 100 def get_queryset(self): queryset = super().get_queryset() search = self.request.GET.get('category search') if search: queryset = Book.objects.filter(categories__id=search) return queryset else: return queryset.none() -
how to load media from another app django
I have two apps accounts and home in tutorial project. A user can create a post in home app and I'm able to render post(i.e images and post data) in home app. In accounts app I want to create a search page where not logged in user can search and view the posts. settings.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'tutorial/media/') search.html {% load static %} {% if re %} {% for q in re %} <a href="{% url 'home:Post_detail' pk=q.id %}">{{q.id}}.{{ q.post }} <br> <img src="{{ q.image.url}}" width="240" height="auto"> <p>Posted by {{ q.user.get_full_name }} on {{ q.created }}</p> {%endfor%} {% endif %} I use the above code in both home app and accounts app. It works fine for home app but not for accounts app when I see view source page I get perfect url in accounts app (search.html) but, the images are not loading properly screenshot project urls.py from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('accounts/', include('accounts.urls' , namespace='accounts') ), path('home/', include('home.urls' , namespace='home') ), path('admin/', admin.site.urls), path('',login_redirect , name = 'login_redirect'), ] if settings.DEBUG is True: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) tutorial project structure tutorial |_accounts |_home |_tutorial |_media |_profile_images |_all … -
Will I reach Heroku's Postgres Connection Limit?
I want to sanity check my understanding of Heroku's Postgres Connection Limit. I currently use the Postgres Standard 0 addon which has a Connection Limit of 120. I am also running a Django application in two Standard 1x dynos. Each dyno runs the application using gunicorn with two workers. So firstly am I correct in assuming my application can handle four concurrent requests at any one time? Second will I ever reach the Postgres Connection Limit? I assuming not as there will only ever be four connections to Postgres at any one time. -
Cannot seem able to modify cache value from celery task
Description: I want to have a cached value (let's call it a flag) to know when a celery task finishes execution. I have a view for the frontend to poll this flag until it turns to False. Code: settings.py: ... MEMCACHED_URL = os.getenv('MEMCACHED_URL', None) # Cache of devel or production if MEMCACHED_URL: CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': MEMCACHED_URL, } } else: CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': 'unique-snowflake', } } api/views.py: def a_view(request): # Do some stuff cache.add(generated_flag_key, True) tasks.my_celery_task.apply_async([argument_1, ..., generated_flag_key]) # Checking here with cache.get(generated_flag_key), the value is True. # Do other stuff. tasks.py: @shared_task def my_celery_task(argument_1, ..., flag_cache_key): # Do stuff cache.set(flag_cache_key, False) # Checking here with # cache.get(flag_cache_key),the # flag_cache_key value is False views.py: def get_cached_value(request, cache_key): value = cache_key.get(cache_key) # This remains True until the cache key # expires. Problem: Although the cache key stays the same and it is correctly passed around through those 3 methods, the cached value doesn't seem to be updated between the task and the view. PS: The methods are correctly set and they are working as expected, my only problem seems to be the cache that doesn't update. -
Django CBV : Download PDF document from media
I would like to download pdf file in my view but I don't overcome to display browser window which let to download my file. The downloadPDF function seems to work well but nothing appears on my browser. This is my class : class TokenDownloadView(TemplateView): template_name = 'freepub/token.html' def get_context_data(self, **kwargs): now = timezone.now() context = super().get_context_data(**kwargs) context['token'] = self.kwargs['token'] token = context['token'] download = Download.objects.get(token__iexact=token) upload_doc = Document.objects.get(id=download.pub_id).upload if download and download.expiration_date > now: print("token valide jusqu'à : " + str(download.expiration_date)) print("il est actuellement : " + str(now)) print(' ==> Token existe et valide <==') messages.success(self.request, 'Vous allez télécharger le document') self.downloadPDF(upload_doc) if download and download.expiration_date < now: print("token valide jusqu'à : " + str(download.expiration_date)) print("il est actuellement : " + str(now)) print('==> Token existe mais a expiré <==') messages.error(self.request, 'Document non téléchargé : la session a expiré return context def downloadPDF(self, upload_doc): from django.core.files.storage import FileSystemStorage from django.http import HttpResponse, HttpResponseNotFound fs = FileSystemStorage() filename = upload_doc if fs.exists(filename): with fs.open(filename) as pdf: response = HttpResponse(pdf, content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="mypdf.pdf"' return response else: return HttpResponseNotFound('The requested pdf was not found in our server.') I miss something in my class which could let to download my pdf ? -
nested serializers in Django
I have 4 models in my Django app - Schools, Universities, ExecutiveHeads and Students. There is a one to many relationship between School/University and ExecutiveHeads/Students. A student/executive head can be part of either a school or university. There can be multiple executive heads and students in a college or university. The models are defined as follows - Class University(model.Models): established_at = models.DateTimeField(auto_now=False, auto_now_add=True) established_by = models.TextField() name = models.TextField() Class School(model.Models): established_at = models.DateTimeField(auto_now=False, auto_now_add=True) established_by = models.TextField() name = models.TextField() associated_university = models.ForeignKey(University, null=True, on_delete=models.SET_NULL) Class ExecutiveHeads(model.Models): name = models.TextField() dob = models.DateTimeField(auto_now=False, auto_now_add=True) limit = models.Q(app_label=‘school’, model=‘School’) | models.Q(app_label=‘university’, model=‘University’) content_type = models.ForeignKey(ContentType, max_length=8, on_delete=models.CASCADE, limit_choices_to=limit) institute_id = models.PositiveIntegerField() institute_object = GenericForeignKey('content_type', ‘institute_id’) Class Students(model.Models): name = models.TextField() dob = models.DateTimeField(auto_now=False, auto_now_add=True) graduation_date = models.DateTimeField(auto_now=False, auto_now_add=True) limit = models.Q(app_label=‘school’, model=‘School’) | models.Q(app_label=‘university’, model=‘University’) content_type = models.ForeignKey(ContentType, max_length=8, on_delete=models.CASCADE, limit_choices_to=limit) institute_id = models.PositiveIntegerField() institute_object = GenericForeignKey('content_type', ‘institute_id’) I have the following serializers defined as shown here - class ExecutiveHeadsSerializer(serializers.ModelSerializer): Class Meta: model = ExecutiveHead fields = ‘__all__’ class Students(serializers.ModelSerializer): Class Meta: model = Students fields = ‘__all__’ Class SchoolSerializer(serializers.ModelSerializer): students = Students(many=True) executives = ExecutiveHeads(many=True) class Meta: model = School fields = ('established_at', 'established_by', 'name', 'associated_university’, ‘students’ , ‘executives’) …