Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
pass field value to a function .extra()
After trying for hours, I am coming here. I have the following model: class Items(models.Model): date=models.DateField() giver=models.IntegerField() Class Givers(models.Model): name=models.CharField(max_length=25) Basically, an item could be given by donators from Givers model or it could be bought by user. If given, giver field stores id from Givers model. Else, it is 0. Now I want a query that will list out my items. If giver>0, I need to show the name of the giver. I can't create relationships here. This query has brought me so close and works like a charm on literal values but I want to provide the 'giver' field instead: data=Items.objects.all().extra(select={'giver_name':giver_name(1,False)}).values('giver_name','id','date') It works like a charm even if given any number (exists or not exists). But I want to do something like this but it fails cos field is not found or undefined: data=Items.objects.all().extra(select={'giver_name':giver_name(giver,False)}).values('giver_name','id','date') giver_name is a function that accepts id of a giver and a boolean value and returns a name. -
Max rows a django model can retreieve via model.objects.all()
In of my models, there exist 2 million rows and I query this based on a date range. When setting a limit to around 100-1000 rows, the query runs but when the number of rows is e.g. 100k then the query doesnt seem to run. My question is, is there a limit to how many queries a django model can make and if so what is it? queryset = Overall.objects.all()[:1000] ## works queryset = Overall.objects.all() ## doesnt work serializer = OverallSerializer(queryset, many=True) data = serializer.data -
Vagrant randomly refusing connections with Django project
I've been having a weird issue with Vagrant running a Django project. One day, it'll be working fine, and I'm humming along with API development with Postman. Next day, after executing vagrant up with zero configuration changes, the box will refuse any connections whatsoever. If I ssh into the box and execute curl with the same API URL request, it executes fine. Needless to say, this is highly frustrating. Unfortunately, I don't know Docker and don't have the time to learn, or I'd jump ship. In the meantime, any help is appreciated. Vagrant version 1.9.8 OSX 10.11 Vagrantfile: Vagrant.configure(2) do |config| config.vm.box = "ubuntu/trusty64" config.vm.network "forwarded_port", guest: 8080, host: 8080 config.vm.network "private_network", ip: "10.0.0.151" config.vm.synced_folder ".", "/home/vagrant/project" config.vm.provider "virtualbox" do |vb| vb.memory = "6096" vb.name = "local-work" end config.vm.provision "shell", path: "provision/install.sh" end In Postman, if I do http://10.0.0.151:8080/path/to/resource, it'll hang and return connection error. Same when accessing Django app on a different URL. -
Matching query doesn't exit in django
Here I am getting an error, matching query doesn't exist. Its is working in my local machine but when i am running it in docker i am getting this error, -
Django/unittest run command at the end of the test runner
I'm using the Django test runner to run my unit tests. Some of these tests use factories which create TONS of files on my local system. They all have a detectable name, and can be removed reasonably easily. I'm trying to avoid having to either A) Keep a file-deleting cron job running, or B) Change my custom image model's code to delete the file if it detects that we're testing. Instead, I'd like to have a command run once (and only once) at the end of the test run to clean up all files that the tests have generated. I wrote a small management command that deletes the files that match the intended convention. Is there a way to have the test runner run call_command on that upon completion of the entire test suite (and not just in the tearDown or tearDownClass methods of a particular test)? -
Django query for foreign key relationship
Let's say, I have Three models in Django User name username Dog name owner ForeignKey(User) Cat name owner Foreignkey(User) Now my question is - count how many owner have dogs and cats, with django orm? or total number of owners who have dogs and cats. What kind of joining it will be? -
KeyError when unittesting Django views/URLs
I'm trying to test a URL/view in Django 1.11 and keep getting some errors that appear to be related to URL namespaces. The namespace as defined in the projects main URLs file and the local URL name as defined in the app's URLs file match what I put in the test and all looks fine in the template as well. I've tried a few things from looking at the docs and have no idea what's going on. Would appreciate any help, thank you. My test for the URL/view: from django.test import TestCase, Client from .models import Course, Step from django.utils import timezone from django.core.urlresolvers import reverse, resolve ... ... class CourseViewsTests(TestCase): def setUp(self): self.course = Course.objects.create( title="Python Testing", description="Sample description" ) self.course2 = Course.objects.create( title="New Course", description="New course description" ) self.step = Step.objects.create( title="Intro to Doctests", description="Learn to write tests in your docstrings", course=self.course ) # self.client = Client() def test_course_list_view(self): resp = self.client.get(reverse('courses:list')) self.assertEqual(resp.status_code, 200) self.assertIn(self.course, resp.context['courses']) self.assertIn(self.course2, resp.context['courses']) My root urls.py: from django.conf.urls import url from django.contrib import admin from . import views from django.conf.urls import include from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns = [ url(r'^courses/', include('courses.urls', namespace="courses")), url(r'^admin/', admin.site.urls), url(r'^$', views.home, name="home"), ] urlpatterns += staticfiles_urlpatterns() My urls.py … -
django install failed in runnung dockerfile on ubuntu
Greeting, I followed the docker compose quickstart example at https://docs.docker.com/compose/django/, using my docker environment in CentOS VM and Ubuntu VM. The example works in CentOS, but not in Ubuntu. The failure happens in RUN pip install -r requirements.txt The error is as Step 6/7 : RUN pip install -r requirements.txt ---> Running in 7ed9830cea5f Collecting Django (from -r requirements.txt (line 1)) Retrying (Retry(total=4, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('<pip._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x7fe12ff70470>: Failed to establish a new connection: [Errno -3] Temporary failure in name resolution',)': /simple/django/ Retrying (Retry(total=3, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('<pip._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x7fe12ff70438>: Failed to establish a new connection: [Errno -3] Temporary failure in name resolution',)': /simple/django/ Retrying (Retry(total=2, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('<pip._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x7fe12ff706a0>: Failed to establish a new connection: [Errno -3] Temporary failure in name resolution',)': /simple/django/ Retrying (Retry(total=1, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('<pip._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x7fe12f4fe5f8>: Failed to establish a new connection: [Errno -3] Temporary failure in name resolution',)': /simple/django/ Retrying (Retry(total=0, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('<pip._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x7fe12f4fea58>: Failed to establish a new connection: [Errno -3] Temporary failure in name resolution',)': /simple/django/ Could not find a … -
always getting "This field is required" error on Django form
Hi I had a form with some field and it was working fine. And then I added one new field in the model and migrated it. Now when I run the program and click on submit then it shows error for that newly added field that This field is required although I am providing data for this field in the form. Model.py class UserInformation(models.Model): firstName = models.CharField(max_length=128) lastName = models.CharField(max_length=128) userName = models.CharField(max_length=128) institution = models.CharField(choices = [("@xyz.org","XYZ"), ("@abc.edu","ABC")], max_length=128) userEmail = models.CharField(default="N/A", max_length=128) phoneNumber = models.CharField(max_length=128) orchidNumber = models.CharField(max_length=128) PI = models.CharField(max_length=128) PIUsername = models.CharField(max_length=128) PIInstitution = models.CharField(default="N/A",choices = [("@xyz.org","XYZ"), ("@abc.edu","ABC")], max_length=128) PIEmail = models.CharField(default="N/A", max_length=128) PIPhoneNumber = models.CharField(max_length=128) In this model PIEmail is the field which I have added. forms.py class UserInformationForm(ModelForm): firstName = forms.CharField(max_length=254, widget=forms.TextInput({ 'class': 'form-control', })) lastName = forms.CharField( widget=forms.TextInput({ 'class': 'form-control', })) userName = forms.CharField( widget=forms.TextInput({ 'class': 'form-control', })) institution = forms.ChoiceField( choices = [("@xyz.org","XYZ"), ("@abc.edu","ABC")] ,widget=forms.Select({ 'class': 'form-control', })) phoneNumber = forms.CharField( required=False, widget=forms.TextInput({ 'class': 'form-control', })) orchidNumber = forms.CharField( required=False, widget=forms.TextInput({ 'class': 'form-control', })) PI = forms.CharField( widget=forms.TextInput({ 'class': 'form-control', })) PIUsername = forms.CharField( widget=forms.TextInput({ 'class': 'form-control', })) ctsaPIInstitution = forms.ChoiceField( choices = [("@xyz.org","XYZ"), ("@abc.edu","ABC")] ,widget=forms.Select({ 'class': 'form-control', })) PIPhoneNumber = forms.CharField( … -
Django Interactive lists based on Database query and user selection
I would like to create 2 lists in Django. The first one lists all results returned from a db query (external query). The second pane is blank until a selection is done. This is single selection drop down Once the user selects an item in the first drop down a list of all results for that selection is displayed (based on another db query). This selection is multi select. I am not sure what elements allow multi select in Django Example. Select City in first list, get a list of all centres in second list, select multiple centres in second list and submit The information being queried is from an external db, I could also use API, but my difficulty is not in the query but how to create the elements and update them based on selection. I am also using django-bootstrap3 -
MySQL giving various connection errors on linux, even on the same machine
I'm getting a bunch of errors trying to access my MySQL database, which seem related, but which kick in at different times. So I had a Django/Celery (using RabbitMQ) framework running machine learning jobs distributed across three different computers with a MySQL database to store the results in, and I all of the sudden couldn't access any of my data from Django. I tried to access the database directly as well, but no luck. When I ran sudo service mysql status it said it was stopped, so I restarted the service and then the computer with no luck. The big issue is that I seem to be getting inconsistent and intermittent errors, and I can't seem to piece them together into one problem. For example, sometimes when I run mysql -u root -p or mysqldump commands (to at least try and save the data I've collected), I get a ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (111) Although I've checked, and that socket is there at that path, and that's the same path that my /etc/mysql/my.cnf file specifies under socket. According to answers at here and elsewhere, I've also tried to change permissions, and change … -
JSON array only defined if invoked in function from Django - Not passed as argument?
Using Django, I'm passing a JSON array to my template as a string, then converting it back to JSON with JSON.parse. In an effort to clean up my code I would like to pass the JSON array into a function as an argument, versus' currently invoking it in the middle of the function. Here is the code as it is now, in the Django template: // Create Google Map function createMap() { var sampleList = JSON.parse('{{ samplesJson | escapejs}}'); var plotList = JSON.parse('{{ plotsJson | escapejs}}'); console.log(sampleList.length); } And here is the code as it is output client-side: // Create Google Map function createMap() { var sampleList = JSON.parse('[{\u0022id\u0022: 54, \u0022title\u0022: \u0022Test Sample 1\u0022, \u0022date\u0022: \u00222017\u002D10\u002D03 13:14:30.345076+00:00\u0022, \u0022coordinates\u0022: \u002245.58837890625, \u002D122.39273834228516\u0022, \u0022type_primary\u0022: \u0022Brix\u0022, \u0022value_primary\u0022: 15.52022647857666, \u0022type_secondary\u0022: \u0022Dry Matter\u0022, \u0022value_secondary\u0022: 16.35165786743164}, {\u0022id\u0022: 55, \u0022title\u0022: \u0022Test Sample 2\u0022, \u0022date\u0022: \u00222017\u002D10\u002D03 13:15:01.127750+00:00\u0022, \u0022coordinates\u0022: \u002245.58849334716797, \u002D122.39277648925781\u0022, \u0022type_primary\u0022: \u0022Brix\u0022, \u0022value_primary\u0022: 16.902915954589844, \u0022type_secondary\u0022: \u0022Dry Matter\u0022, \u0022value_secondary\u0022: 17.531015396118164}]'); var plotList = JSON.parse('[{\u0022id\u0022: 124, \u0022title\u0022: \u0022Test Plot\u0022, \u0022date\u0022: \u00222017\u002D10\u002D03 13:13:29+00:00\u0022, \u0022coordinates\u0022: \u0022[ {lat: 45.58871801349195,lng: \u002D122.3925570656067}, {lat: 45.58834260811055,lng: \u002D122.39249269259034}, {lat: 45.588297559296066,lng: \u002D122.39322225344239}, {lat: 45.58874804581401,lng: \u002D122.39320079577027}]\u0022, \u0022crop\u0022: \u0022Mango\u0022, \u0022samples\u0022: \u0022[54, 55]\u0022, \u0022aggregate\u0022: {\u0022Brix\u0022: 16.211571216583252, \u0022Dry Matter\u0022: 16.941336631774902}}, {\u0022id\u0022: 125, \u0022title\u0022: \u0022Test Plot 2\u0022, \u0022date\u0022: \u00222017\u002D10\u002D03 14:02:15.820832+00:00\u0022, \u0022coordinates\u0022: \u0022[\u005Cn {lat: 45.588755567618534,lng: \u002D122.39336172831116},\u005Cn … -
Got this UnboundLocalError at /nesting/ local variable 'content' referenced before assignment
I want to display the necessary field errors when the user who is populating the form does not enter valid information into the forms. However, each I time I test the error script by clicking the submit button without populating any of the fields I get this error : UnboundLocalError at /nesting/ local variable 'content' referenced before assignment How do I correct this? This is my code : veiws.py from django.shortcuts import render, redirect from django.views.generic import TemplateView from nesting.forms import Identity_form from nesting.models import Identity_unique class Identity_view(TemplateView): template_name = 'nesting/nesting.html' def get(self, request): form = Identity_form() Identities = Identity_unique.objects.filter(user = request.user) var = {'form': form, 'Identities': Identities} return render(request, self.template_name, var) def post(self, request): form = Identity_form(request.POST or None) if form.is_valid(): NIS = form.save(commit = False) NIS.user = request.user NIS.save() content = form.cleaned_data['NIS'] form = Identity_form() return redirect('nesting:nesting') The error messages is saying the error is caused by this line var = {'form': form, 'content': content} return render(request,self.template_name, var) nesting.html {% extends 'base.html' %} {% load widget_tweaks %} <html> <head> {% block head %} <title>nesting</title> {% endblock %} </head> <body> {% block body %} <div class = "container" style = "margin-top: 80px;"> <form method = 'post' novalidate> {% csrf_token … -
Using Python for real time scalable application
me and a friend are doing requirements survey for a project, and this project have one base feature that is in real-time, so we are searching for NoSQL solutions with python to build an API and we passed by Flask, Django Rest with mongo and Eve. And here we are asking for some insights about frameworks and recomentations to start with. We expect to build a stable and medium to large scale app. If anyone could help, we'll be grateful a lot. -
Django 1.11 don't include login.app
I have a problem with my login app, when I configure the logout in urls.py the traceback tell me the next: Performing system checks... Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x10fc44510> Traceback (most recent call last): File "/Users/dmuino/.virtualenvs/Pruebas/lib/python3.6/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/Users/dmuino/.virtualenvs/Pruebas/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run self.check(display_num_errors=True) File "/Users/dmuino/.virtualenvs/Pruebas/lib/python3.6/site-packages/django/core/management/base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "/Users/dmuino/.virtualenvs/Pruebas/lib/python3.6/site-packages/django/core/management/base.py", line 346, in _run_checks return checks.run_checks(**kwargs) File "/Users/dmuino/.virtualenvs/Pruebas/lib/python3.6/site-packages/django/core/checks/registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "/Users/dmuino/.virtualenvs/Pruebas/lib/python3.6/site-packages/django/core/checks/urls.py", line 16, in check_url_config return check_resolver(resolver) File "/Users/dmuino/.virtualenvs/Pruebas/lib/python3.6/site-packages/django/core/checks/urls.py", line 26, in check_resolver return check_method() File "/Users/dmuino/.virtualenvs/Pruebas/lib/python3.6/site-packages/django/urls/resolvers.py", line 254, in check for pattern in self.url_patterns: File "/Users/dmuino/.virtualenvs/Pruebas/lib/python3.6/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Users/dmuino/.virtualenvs/Pruebas/lib/python3.6/site-packages/django/urls/resolvers.py", line 405, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/Users/dmuino/.virtualenvs/Pruebas/lib/python3.6/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Users/dmuino/.virtualenvs/Pruebas/lib/python3.6/site-packages/django/urls/resolvers.py", line 398, in urlconf_module return import_module(self.urlconf_name) File "/Users/dmuino/.virtualenvs/Pruebas/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 978, in _gcd_import File "<frozen importlib._bootstrap>", line 961, in _find_and_load File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 655, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed File "/Users/dmuino/.virtualenvs/Pruebas/CursoProDjango/eventus/eventus/urls.py", line … -
querying a self referencing table in Django
I have a model which references itself so that I have a parent / child relationship between users in the db. A parent can have multiple children, but a child can only have one parent. Firstly, is this the correct way to define the model: class User(models.Model): name = models.CharField(max_length=50) parent = models.ForeignKey('self') Secondly, I need to query the model and return all the children of a particular parent. I have read some articles on tree structures where queries can be more complicated. But given I only need one layer deep, will this return all the children: children = User.objects.get(parent=PARENT_ID) where PARENT_ID is obviously the id of the parent -
How to loop through a dic value in python template
I am new to Python/Django development, i want to loop through a dic value that i am sending from my view on my template but i can't get the value base on index/key. Kindly help me out. My View def contact(request): contactDetails = {'name': ['Adeola Ajayi', 'Olayemi'], 'email': ['a@gmail.com', 'b@gmail.com']} return render(request, 'PythonWeb/contact.html', {'contactDetails':contactDetails}) My Template {% block content %} <br><br> {% for contact in contactDetails%} <p> name: {{ contact.name }} </p> <p> name: {{ contact.email }} </p> {% endfor %} {% endblock %} This is how i want my template to display name: Adeola Ajayi email: a@gmail.com name: Olayemi email: b@gmail.com -
how to connect django and vue.js webpack?
i work with django rest_framework and recently i should work with vue.js and i wanna a good tutorial for django + vue.js. please help me to find a good refrence. i am so confused. i already see this links https://www.youtube.com/watch?v=C7oiYr4_NdUa var cssLoader = { loader: 'css-loader', options: { minimize: process.env.NODE_ENV === 'production', sourceMap: options.sourceMap } } -
Possible to have multiple serializers per view using Django Rest Framework
As I'm working, my ./views.py is becoming really competitive and I'm wondering if there is a way to refactor it to be DRY. I think in order to do so, I would need the ability to use specify multiple serializers per view. data would need to be less ambigious so that it actually describes the data it is receiving so that it can be passed into the correct serializer, which would mean it would need to know the API route the received data came from. Not sure how to do that except with a one class per route, how I currently have it setup. Then there would need to be a way to specify multiple serializers in a view to send the respective data to. Not seeing that this is possible. # ./urls.py from .views import ( SecurityQuestionsAPIView, UserSigninTokenAPIView, UsernameRecoveryAPIView, ValidateKeyAPIView ) urlpatterns = [ url(r'^signin/', UserSigninTokenAPIView.as_view(), name='signin'), url(r'^verify/', verify_jwt_token), url(r'^refresh/', refresh_jwt_token), url(r'^username_recovery/', UsernameRecoveryAPIView.as_view(), name='username_recovery'), url(r'^validate_key/', ValidateKeyAPIView.as_view(), name='validate_key'), url(r'^security_questions/', SecurityQuestionsAPIView.as_view(), name='security_questions'), ] # ./views.py from .serializers import ( SecurityQuestionsSerializer, UserSigninTokenSerializer, UsernameRecoverySerializer, ValidateKeySerializer ) # Used for logging into the web application class UserSigninTokenAPIView(APIView): permission_classes = [AllowAny] serializer_class = UserSigninTokenSerializer def post(self, request, *args, **kwargs): data = request.data serializer = UserSigninTokenSerializer(data=data) … -
read file csv in memory django python
Hi I am reading a csv with open (' file. csv', r) this for a file stored in disk now I would like to read the file without having to be uploaded only in memory I tried this, but it gives me a mistake: file = request. File[' file'] open (file, r) in django python as I can do? -
FileNotFoundError when using django.test.client.post
I had some django test code that used to work in python 2 but started throwing some errors in python3. Here's a snippet: def test_filter(self): c1 = dt.Client() c1.login(username='user1', password='pass') f = open('data/tiny.txt', 'rb') test_file = { 'datafile': f, 'uid': 'bb', 'private': 'True', 'name': "tr1" } response = c1.post( '/api/v1/files', test_file, format='multipart' ) When I run this using python3 I get the following Exception: Exception ignored in: <bound method _TemporaryFileCloser.__del__ of <tempfile._TemporaryFileCloser object at 0x115904160>> Traceback (most recent call last): File "/Users/pete/miniconda3/envs/cenv3/lib/python3.6/tempfile.py", line 450, in __del__ self.close() File "/Users/pete/miniconda3/envs/cenv3/lib/python3.6/tempfile.py", line 446, in close unlink(self.name) FileNotFoundError: [Errno 2] No such file or directory: '/var/folders/yb/3jwdnlf17gd1dcq65th786d00000gn/T/tmpw_t0j9bw.upload' Interestingly, this exception doesn't affect the outcome of the tests. They still pass. It does get reported in the output and is rather annoying. Any ideas on what's causing this? Creating the object with a file using Object.create works fine and doesn't throw an error. -
How to get invoice_id from PayPal after success transaction
I want to get invoice_id that i send to PayPal. I send to PayPal invoice_id: ... <input type="hidden" name="invoice" value="MyOrderId" id="id_invoice"/> ... My success url looks like this: http://host?success=true I want to catch GET parameter success and edit some Order with id=invoice_id: ... if request.method == 'GET': if request.GET.get('success'): order = Order.object.get(id=request.GET.get('invoice_id')) order.status = 'Success' order.save() ... Maybe i need say to PayPal that i want to get returned invoice_id from it, or where i can find it and get? -
How to filter backward joins?
I have a model Article and several ArticleDescription (one for each language). class Article(models.Model): articleid = models.CharField(primary_key=True, max_length=100) def __unicode__(self): return str(self.articleid) class ArticleDescription(models.Model): article = models.ForeignKey(Article, on_delete=models.CASCADE) lang = models.CharField(max_length=2, default='en', blank=False, null=False) description = models.TextField(blank=True, null=True) class Meta: unique_together = ('article', 'lang') def __unicode__(self): return str(self.description) I am struggling now how to make a join to select only the current language's description in my template. I use this code to get my articles: c = models.Article.objects.all().order_by('articleid') In c, I have my ArticleDescriptions available in my template like this: {% for b in c %} {{ b.articledescription_set.all }} {% endfor %} But, I do not want all the descriptions, just the one for the current language. So I am looking for something like: c = models.Article.objects.all().join(ArticleDescription, lang=curlang).order_by('articleid') and then I can use the description like this in my template: {% for b in c %} {{ b.articledescription.description }} {% endfor %} But, I have no idea how to do this, or where to look. -
Django - Attach PDF generated by a view to an email
This question has some elements here, but no final answer. There is view generating a PDF with easy_pdf from easy_pdf.views import PDFTemplateResponseMixin class PostPDFDetailView(PDFTemplateResponseMixin,DetailView): model = models.Post template_name = 'post/post_pdf.html' Then, I want to attach this generated PDF to the following email : @receiver(post_save, sender=Post) def first_mail(sender, instance, **kwargs): if kwargs['created']: user_email = instance.client.email subject, from_email, to = 'New account', 'contact@example.com', user_email post_id = str(instance.id) domain = Site.objects.get_current().domain post_pdf = domain + '/post/' + post_id + '.pdf' text_content = render_to_string('post/mail_post.txt') html_content = render_to_string('post/mail_post.html') # create the email, and attach the HTML version as well. msg = EmailMultiAlternatives(subject, text_content, from_email, [to]) msg.attach_alternative(html_content, "text/html") msg.attach_file(post_pdf, 'application/pdf') msg.send() I also have tried this one: msg.attach_file(domain + '/post/' + post_id + '.pdf', 'application/pdf') -
All django databases are deleted
Because I deleted the mysql file by mistake last time, I can't use any database, including django, how to recover all the data tables of django **django==1.9.8** **python==3.5.2** This is my profile