Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django is running on private ip instead of the public one, is it problematic?
I just configured basically a server and before installing gunicorn + nginx I wanted to try my django runserver. So, I have a public IP and a private one. My front (Simple index.html + react) is correctly deserving the public IP, but my django only pass by the private one when I start ./manage.py runserver 0.0.0.0:8080 When I try: ./manage.py runserver public.I.P:8080 I have this error: Error: That IP address can't be assigned to. Is that normal? -
Reverse for 'post/profile/' with arguments '()' and keyword arguments '{'user': 1}' not found. 0 pattern(s) tried: []
i have a problem in my django project. when i want show posts that belongs to specific user id this show me this error urls.py: url(r'^profile/(?P<user>\d+)/$', profile) views.py: def profile(request, user=None): queryset = Post.objects.filter(user=user) context ={ "object_list" : queryset, } return render(request, 'profile.html', context) html page: {% if request.user.is_authenticated %} <li><a href=" {% url 'post/profile/' user=request.user.id %} ">My ADS</a></li> models.py: class Post(models.Model): """docstring for Post""" user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1) post_title = models.CharField(max_length=50) image = models.ImageField(upload_to = 'user/',null=True, blank=True, height_field="height_field", width_field="width_field") height_field = models.IntegerField(default=0) width_field = models.IntegerField(default=0) content = models.TextField() updated = models.DateTimeField(auto_now=True, auto_now_add=False) timestamp = models.DateTimeField(auto_now=True, auto_now_add=False) def __str__(self): return (self.post_title) def get_absolute_url(self): return reverse("posts:detailpost", kwargs={"id": self.id}) -
Django Update Profile View - Only allow logged in users to edit their own accounts
I have a Django model that is a AbstractBaseUser, I have made an update form where users can update their profile information, however, I am unable to find a way to let logged in users edit their own profile. If anyone has any idea on how to solve this problem please let me know. Thanks in advance. :) Please let me know if you require viewing any more code than is provided. UpdateProfile view (note: There are 2 versions of the 'same' view, I am just looking for a solution for either of them. I would rather user the CBV if possible, however, I don't mind using the FBV) class UpdateProfile(generic.UpdateView): model = Designer form_class = UserUpdateForm success_url = reverse_lazy('home') template_name = 'main/profile_update.html' def update_profile(request): user = request.user form = UserUpdateForm(request.POST, instance=user) form.actual_user = request.user if request.method == 'POST': if form.is_valid(): form.save() return HttpResponseRedirect(reverse('update_profile_success')) else: form = UserUpdateForm() context = {'form': form, } return render(request, 'main/profile_update.html', context) Thanks. All help is appreciated :) -
passing parameter from angular $http.get to django views.py through url
I'm trying to do a GET request from angular passing through a parameter to django's view.py. The url that I'm getting back is /contact/api/getName?name=John and neither of them is hitting api_get_client_info in views.py because the string and values inside api_get_client_info are being printed. But I am getting a "success" message after the request. HTML: <select ng-change="selectName(name)" ng-model="name"> <option value="" disabled>Select from List</option> <option ng-repeat="name in nameList" value="{{name.Name}}"> {{name.Name}} </option> </select> $http.get request in angular controller: $scope.selectName= function(name){ Method 1: $http.get("/contact/api/getName", {params: {"personName": name}}) .success(function(response) { console.log("success"); }) .error(function(response){ console.log("failed"); }) Method 2: $http({ method:'GET', url: '/contact/api/getName?=' + name }) .success(function(data) { console.log("success"); }) .error(function(data){ console.log("failed"); }) } Django url.py urlpattern = [ url(r'^api/getName(?P<personName>[a-zA-Z0-9_]+)/$', views.api_get_person_info), url(r'', views.main, name='contact', ] Django views.py def api_get_person_info(request): print("here") person = request.GET.get("personName") print(person) -
FreeBSD. Django-shell permission denied
I am trying to debug some application using Python 2.7.9 and Django 1.10 on FreeBSD. Generally speaking I have two users with equal rights and permission but when I run django-shell using first user, and execute my script in the shell everything ok. The problems starts when I try to execute the same script from second user, I get: File "/usr/local/lib/python2.7/shelve.py", line 223, in __init__ Shelf.__init__(self, anydbm.open(filename, flag), protocol, writeback) File "/usr/local/lib/python2.7/anydbm.py", line 85, in open return mod.open(file, flag, mode) error: (13, 'Permission denied') I set all directories in usr/local to has - chmod 777. First and second users are in the same groups and from my point of view has the same permissions. I will be thankful for any hints or help, I am stuck with any ideas. Thank you in advance. -
is_superuser didn't works in template
I have method in my model in django app (1.8): def is_online_public(self): if (self.online_from <= timezone.now()) and (self.online_to <= timezone.now()): return 'not user.is_superuser' else: return 'user.is_superuser' and I want to set condition in template if fields online_from and online_to are past, show only for admin user. Here is my condition in template: {% if user.is_superuser %} yes {% else %} no {% endif %} I have set user on superuser mode in admin panel and I always have no. -
Django 1.10 wysiwyg editor (redactor) image don't show and save
I have big problem with wysiwyg i exclude it good and in django-admin site i want add my post i have it but when i try upload my image i have this enter image description here and when i click OK i still have blank area this is my setting.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog', 'redactor', ] STATICFIELS_DIRS = [ os.path.join(BASE_DIR, "static"), '/mysite/blog/static/' ] STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT =[ os.path.join(BASE_DIR, 'media'), '/mysite/blog/media/' ] REDACTOR_OPTIONS = {'lang': 'en'} REDACTOR_UPLOAD = 'uploads/' REDACTOR_UPLOAD_HANDLER = 'redactor.handlers.DateDirectoryUploader' REDACTOR_AUTH_DECORATOR = 'django.contrib.auth.decorators.login_required' REDACTOR_FILE_STORAGE = 'mysite.file_storages.StorageClass' this is my structure of project enter image description here This is my models.py class Post(models.Model): STATUS_CHOICES = ( ('draft', 'Roboczy'), ('published', 'Opublikowany') ) title = models.CharField(max_length=300) slug = models.SlugField(max_length=300, unique_for_date='publish') body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) text = RedactorField(upload_to='tmp/', allow_file_upload=True, allow_image_upload=True, default='') status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='draft') object = models.Manager() published = PublishedManager() class Meta: ordering = ('-publish',) def __str__(self): return self.title def get_absolute_url(self): return reverse('blog:post_detail', args=[self.publish.year, self.publish.strftime('%m'), self.publish.strftime('%d'), self.slug]) and this is my admin.py from django.contrib import admin from django import forms from .models import Post from redactor.widgets import RedactorEditor class PostAdminForm(forms.ModelForm): class Meta: model … -
How do I retrieve the values of selected checkboxes and show it in the template?
What am I doing ? I'm training on a simple application where one can order a pizza and select his toppings, once the form submitted it shows the submitted queries in the template file. What is the problem? I'm having a really hard time showing the checked checkboxes from the form on the template file. Here are my files : models.py class PickedDatas(models.Model): name = models.CharField(max_length=255, blank=True, null=True) class Picked(models.Model): name = models.CharField(max_length=255) picked = models.ManyToManyField(PickedDatas, blank=True) forms.py class CustomChoiceField(forms.ModelMultipleChoiceField): def label_from_instance(self, obj): return mark_safe('%s' % (obj.name)) class SomeForm(forms.ModelForm): class Meta: model = Picked fields = ['name', 'picked'] picked = CustomChoiceField(queryset=PickedDatas.objects.all(), widget=forms.CheckboxSelectMultiple()) views.py def some_view(request): if request.method == 'POST': form = SomeForm(request.POST) if form.is_valid(): ... else: form = SomeForm return render(request, 'features.html', {'form':form, 'picked':Picked.objects.all()}) As for the template file, I'm using the for loop to show Picked models datas. How can I achieve what I am trying to do ? -
error while installing mysql using pip (python)
i'm new boy in python, recently i am starting to understand Django, for some basic functonality i have to use pip, while i try to install some package using pip it Give error live Belove. Thank you For Your Kind Responce. C:\Users\Artoon>pip install mysql Collecting mysql Collecting MySQL-python (from mysql) Using cached MySQL-python-1.2.5.zip Building wheels for collected packages: MySQL-python Running setup.py bdist_wheel for MySQL-python ... error Complete output from command c:\paython36\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\Artoon\\AppData\\Local\\Temp\\pip-build-la79b8wq\\MySQL-python\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" bdist_wheel -d C:\Users\Artoon\AppData\Local\Temp\tmpg_5j7u4fpip-wheel- --python-tag cp36: running bdist_wheel running build running build_py creating build creating build\lib.win-amd64-3.6 copying _mysql_exceptions.py -> build\lib.win-amd64-3.6 creating build\lib.win-amd64-3.6\MySQLdb copying MySQLdb\__init__.py -> build\lib.win-amd64-3.6\MySQLdb copying MySQLdb\converters.py -> build\lib.win-amd64-3.6\MySQLdb copying MySQLdb\connections.py -> build\lib.win-amd64-3.6\MySQLdb copying MySQLdb\cursors.py -> build\lib.win-amd64-3.6\MySQLdb copying MySQLdb\release.py -> build\lib.win-amd64-3.6\MySQLdb copying MySQLdb\times.py -> build\lib.win-amd64-3.6\MySQLdb creating build\lib.win-amd64-3.6\MySQLdb\constants copying MySQLdb\constants\__init__.py -> build\lib.win-amd64-3.6\MySQLdb\constants copying MySQLdb\constants\CR.py -> build\lib.win-amd64-3.6\MySQLdb\constants copying MySQLdb\constants\FIELD_TYPE.py -> build\lib.win-amd64-3.6\MySQLdb\constants copying MySQLdb\constants\ER.py -> build\lib.win-amd64-3.6\MySQLdb\constants copying MySQLdb\constants\FLAG.py -> build\lib.win-amd64-3.6\MySQLdb\constants copying MySQLdb\constants\REFRESH.py -> build\lib.win-amd64-3.6\MySQLdb\constants copying MySQLdb\constants\CLIENT.py -> build\lib.win-amd64-3.6\MySQLdb\constants running build_ext building '_mysql' extension creating build\temp.win-amd64-3.6 creating build\temp.win-amd64-3.6\Release C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\BIN\x86_amd64\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -Dversion_info=(1,2,5,'final',1) -D__version__=1.2.5 "-IC:\Program Files (x86)\MySQL\MySQL Connector C 6.0.2\include" -Ic:\paython36\include -Ic:\paython36\include "-IC:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\INCLUDE" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt" "-IC:\Program Files … -
function inside function is not working in django
i have written a function inside a function for getting image height and width. but when i hit url all code works except get_image_size function this is my code class ProductDetailView(DetailView): """ Modified Context Data in PDP pages """ def get_context_data(self, **kwargs): urlImage = 'http://'+ str(self.request.get_host()) + '/media/images/products/2016/12/dog.jpg' print "link is",urlImage def get_image_size(urlImage): print "<<<<<<<<<<<<<<<<<<<<<,," data = requests.get(urlImage).content im = Image.open(BytesIO(data)) return im.size if __name__ == "__main__": print "===========>" width, height = get_image_size(urlImage) print "height is--", height print "width is --",width what is the issue with it. -
Django raise ValidationError
i have a problem with raise ValidationError, it won't display if the user writes only 1,2,3 words. If i press submit it shows only the title Contact and the submit button. It should show if user writes under 4 words. views.py def contact(request): data = dict() if request.method == "POST": form = ContactForm(request.POST) if form.is_valid(): subject = form.cleaned_data['subject'] email = form.cleaned_data['email'] message = form.cleaned_data['message'] try: send_mail(subject, message, email, ['inbox01@yahoo.com']) except BadHeaderError: return HttpResponse('Invalid header found.') return HttpResponseRedirect('/contact/thanks/') else: data['form'] = ContactForm( initial={'subject': 'I love your site!'} ) return render(request, 'contact_form.html', data) forms.py from django import forms class ContactForm(forms.Form): subject = forms.CharField(max_length=100) email = forms.EmailField(required=True) message = forms.CharField(widget=forms.Textarea, min_length=7) def clean_message(self): message = self.cleaned_data['message'] num_words = len(message.split()) if num_words < 4: raise forms.ValidationError('Not enough words!') return message contact_form.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Contact us</title> </head> <body> <h1>Contact us</h1> <form action="" method="POST"> <table> {{ form.as_table }} </table> {% csrf_token %} <input type="submit" value="Submit"> </form> </body> </html> -
Datatables Ajax works when reading JSON from file, but not from variable (Django)
I've been stuck with this problem for a few days now. I'm trying to feed JSON data to DataTables, but it only works if I use static file as source (see below index.html). index.html $(document).ready(function() { $('#mydata').DataTable( { "ajax": { "url": '{% static "myapp/supplier.json" %}', //<= works {# "url": '{{ suppliers_all }}',#} //<=does not work "dataSrc": "" }, "columns": [ { "data": "name" }, { "data": "classification" }, ] } ); } ); views.py def index(request): suppliers_all = Supplier.objects.all().values('name', 'classification') suppliers_all = json.dumps(list(suppliers_all)) context = {'suppliers_all': suppliers_all, } return render(request, 'myapp/index.html', context) JSON output: [{"classification": "Base Supplier", "name": "Supplier Name1"}, {"classification": "Strategic Supplier", "name": "Supplier Name2"}] When I use django passed variable {{ suppliers_all }} browser debugging returns a 404 not found error. I tried hardcoding JSON output according to websites examples, tried many different ways, but it will never work if it's not fetched directly from file. -
Copy values from another field when create new field of the same model
I have django 1.10 project. There are I have a model Feedback: class Feedback(FirstMixin, SecondMixin, models.Model): company = models.OneToOneField( verbose_name='Company', to=Company, related_name='feedback' ) This model exists and DB table's column Company is filled by keys to Company's items. Now I need to add some new field to the model: custom_name = models.CharField( verbose_name='Company Custom Name', null=False, max_length=settings.DATABASE_STRING_LENGTH ) This field should store custom names of Companies. What should I do to make values of this field the same as relevant Companies names during migration? Should I change migration's code or is there are some way to define it in model? -
Using a 'mapping dictionary' to save entries in model with django
i would like to pull info from different APIs that contains basically the same information and gather them in a generic model. How could I create a mapping to make the relations easier? For example, at the moment I have a 'Contact_API_A' model: class ContactAPIA(models.Model): id = models.CharField(primary_key=True, max_length=100) name = models.CharField(max_length=50) a 'Contact_API_B' model: class ContactAPIB(models.Model): UUID = models.CharField(primary_key=True, max_length=100) full_name = models.CharField(max_length=50) These models contain the naming conventions of the APIs. and a 'Contact' model which is using my own naming convention: class Contact(models.Model): id = models.CharField(primary_key=True, max_length=100) full_name = models.CharField(max_length=50) source = models.CharField(max_length=10) In my view I am fetching the contacts from the respective APIs & saving them in their models using a dictionary. views: def get_contacts_API_A(request): ... contacts_api_a = API_A.contacts() for contact in contacts_api_a: contact_api_a_dict = { 'id':contact.id, 'name':contact.name} c = ContactAPIA(**contact_api_a_dict) c.save() in a second step i am inserting those contaccts into my generic contact model. views: def contacts_api_a_to_contacts(request): ... contacts = ContactAPIA.objects.all() for contact in contacts: contact_api_a_to_contacts_dict = { 'id':contact.id, 'full_name':contact.name, 'source':'api_a'} c = Contact(**contact_api_a_to_contact_dict) c.save() The actual contact dictionaries contain far more information so i tried to move them to a 'mapping.py' file and importing that file into views. When doing so i … -
ranking a query based on string match
I'm trying to build a query which will rank the models based on a given string in Django. For example, if the given string is "adc", then number one rank would be any model that contains this exact string in their chosen field, second rank would be the one closest to the string "adc 1" etc.. Is there any available libraries/frameworks I can use to accomplish this task? If not, any direction as to how this could be accomplished would be helpful. -
python/django: Invalid block tag: 'paginate'
I am trying to use django-endless-pagination as twitter style. I followed the documentation as in link. When I trying to render the template, it raises an error : Invalid block tag: 'paginate'. I would appreciate helping me solve this issue or suggest an alternate approach for infinite scroll in django. view.py: @page_template('entry_index_page.html') def entry_index(request, template = 'entry_index.html', page_template = 'entry_index_page.html', extra_context=None): context = { 'entries': Entry.objects.all(), } if extra_context is not None: context.update(extra_context) if request.is_ajax(): template = page_template return render_to_response( template, context, context_instance=RequestContext(request)) settings.py: INSTALLED_APPS = ( 'endless_pagination', ) from django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS TEMPLATE_CONTEXT_PROCESSORS += ( 'django.core.context_processors.request', ) entry_index.html: <h2>Entries:</h2> {% include page_template %} {%load staticfiles%} {% block js %} {{ block.super }} <script src="http://code.jquery.com/jquery-latest.js"></script> <script src="{%static 'endless-pagination.js'%}"></script> <script>$.endlessPaginate();</script> <script> $.endlessPaginate({ paginateOnScroll: true, paginateOnScrollMargin: 20 }); {% endblock %} entry_index_page.html: {% load endless %} {% paginate entries %} {% for entry in entries %} {{entry.name}} {% endfor %} {% show_more %} -
Django Cassandra models.py
I'm using Django web framework for Cassandra. While creating clustered keys, I'm getting the follwing error. RuntimeError: On Django Cassandra Models with more than one primary_key field, The model must specify class Meta attribute 'get_pk_field'. E.g. class Meta: get_pk_field='id' So that Django knows which primary key field to use in queryies such as Model.objects.get(pk=123) Code is: class user_info(DjangoCassandraModel): user_f_name = columns.Text() user_l_name = columns.Text() user_since = columns.DateTime(default=timezone.now()) user_mobno = columns.Integer(primary_key=True, lustering_order="DESC") user_email = columns.Text(partition_key=True) Could you please share some learning resources with Django on cassandra? -
Django import module name fail
I trying to use Channels to create a realtime app with Django. The project has a structure like this: I try to import ws_message from consumer.py in routing.py here is the code in rounting.py from channels.routing import route from witg_backend.gift.consumer import ws_message channel_routing = [route("websocket.receive", ws_message),] It shows this error message when run django File "C:\Users\User\Anaconda3\lib\site-packages\channels\routing.py", line 74, in resolve_routing raise ImproperlyConfigured("Cannot import channel routing %r: %s" % (routing, e)) django.core.exceptions.ImproperlyConfigured: Cannot import channel routing 'witg_backend.routing.channel_routing': No module named 'witg_backend.gift' It run fine for somedays ago, the error appear suddently without anything has been changed. I have også tried from gift.consumer import ws_message it showed unresolved import in Eclipse, but django can run without raise any error, it just ignored the routing. *Using Django 1.10 and Python 3.5 -
Simultaneously making calculation on two fields in django, but only one is being performed at a time.
I'm trying to perform the both operations at the same time but only one is getting returned at a time. If I remove either of them, the other one get performed. Is there any way round to get both of them working at the same time? I'm talking about grossannualsalary and textDeduct. class Salarie(models.Model): grossmonthlysalary = models.FloatField( _('Monthly Salary'), null=False, blank=False, default=0.00 ) monthlyincometax = models.FloatField( _('Monthly Income Tax'), null=False, blank=False ) contractperiod = models.IntegerField( _('Contract Period'), null=False, blank=False ) grossannualsalary = models.FloatField( _('Gross Annual Salary'), null=True, blank=True ) taxDeduct = models.FloatField( _('Tax Deduction'), null=False, blank=False, default=0.00 ) def save(self, *args, **kwargs): self.grossannualsalary = self.grossmonthlysalary * self.contractperiod super(Salarie, self).save(*args, **kwargs) def save(self, *args, **kwargs): self.taxDeduct = self.grossmonthlysalary * self.monthlyincometax / 100 super(Salarie, self).save(*args, **kwargs) -
Django: ImportError: No module named templates
I am facing a problem using Django in PyCharm 2016.3. I get an error which says that module 'templates' is not imported. Can anyone help me with this? Thank you in advance. The stack trace is: Traceback (most recent call last): File "C:\Program Files (x86)\JetBrains\PyCharm 2016.3\helpers\pycharm\django_test_manage.py", line 134, in utility.execute() File "C:\Program Files (x86)\JetBrains\PyCharm 2016.3\helpers\pycharm\django_test_manage.py", line 109, in execute PycharmTestCommand().run_from_argv(self.argv) File "C:\Python27\lib\site-packages\django\core\management\commands\test.py", line 29, in run_from_argv super(Command, self).run_from_argv(argv) File "C:\Python27\lib\site-packages\django\core\management\base.py", line 294, in run_from_argv self.execute(*args, **cmd_options) File "C:\Python27\lib\site-packages\django\core\management\base.py", line 345, in execute output = self.handle(*args, **options) File "C:\Program Files (x86)\JetBrains\PyCharm 2016.3\helpers\pycharm\django_test_manage.py", line 96, in handle failures = TestRunner(test_labels, **options) File "C:\Program Files (x86)\JetBrains\PyCharm 2016.3\helpers\pycharm\django_test_runner.py", line 256, in run_tests extra_tests=extra_tests, **options) File "C:\Program Files (x86)\JetBrains\PyCharm 2016.3\helpers\pycharm\django_test_runner.py", line 156, in run_tests return super(DjangoTeamcityTestRunner, self).run_tests(test_labels, extra_tests, **kwargs) File "C:\Python27\lib\site-packages\django\test\runner.py", line 548, in run_tests suite = self.build_suite(test_labels, extra_tests) File "C:\Program Files (x86)\JetBrains\PyCharm 2016.3\helpers\pycharm\django_test_runner.py", line 120, in build_suite suite = super(DjangoTeamcityTestRunner, self).build_suite(*args, **kwargs) File "C:\Python27\lib\site-packages\django\test\runner.py", line 437, in build_suite tests = self.test_loader.loadTestsFromName(label) File "C:\Python27\lib\unittest\loader.py", line 91, in loadTestsFromName module = import('.'.join(parts_copy)) ImportError: No module named templates -
how to use dictonary in django
i want to filter out the of promotion count, and save the service_type and promotion code for that particular count here is my view promotions=Promotions.objects.filter(member=request.user) dictt={} for promotion in promotions: c=customer_request.objects.filter(promotion=promotion) e=c.count() dictt[e]=e for w in c: coupon_code=Promotions.objects.get(pk=w.promotion_id) dictt.update({e:{coupon_code.coupon_code,w.service_type}}) sorted_dictt = sorted(dictt.items(), key=operator.itemgetter(0), reverse=True) and i am displaying dict on html as follows {% for a in sorted_dictt %} <tr> <td style="color:#f38619;"></td> <td style="color:#f38619;">{{a.1}}</td> <td style="color:#f38619;">{{a.0}}</td> </tr> {%endfor%} now i am getting result as: it should be display as how to do it? -
Add a saving path with xhtml2pdf and download link?
I'm using xhtml2pdf in order to convert my form to PDF file. By default, it saves this PDF to the same place than my manage.py file. I'm asking How I can modify the saving path in order to send the PDF on my Desktop for example (with MacOSX) This is my function : def BirthCertificate_PDF(request, id) : birthcertificate = get_object_or_404(BirthCertificate, pk=id) data = {"birthcertificate" : birthcertificate} template = get_template('BC_raw.html') html = template.render(Context(data)) #filename = 'acte_de_naissance_' + str(BirthCertificate.lastname) filename = 'Acte_Naissance_' + str(BirthCertificate.objects.get(pk=id).lastname) + '_' + str(BirthCertificate.objects.get(pk=id).firstname) + '_' + str(BirthCertificate.objects.get(pk=id).birthday) + '.pdf' file = open(filename, "w+b") pisaStatus = pisa.CreatePDF(html.encode('utf-8'), dest=file, encoding='utf-8') file.seek(0) pdf = file.read() if pdf : context = {"birthcertificate":birthcertificate} return render(request, 'BC_resume.html', context) file.close() return HttpResponse(pdf, 'application/pdf') I read this documentation : xhtml2pdf doc But I don't have any solution. --------------------------------------------------------------------------------------------------------------------------------- Then I have an other question (maybe I should create a new question ?). I put an HTML button which let to save the PDF. But I would like to have the following function : I click on the button --> I get a window letting to open the PDF or save it This is my html template which let to save the pdf : <h2 align="center"> … -
Django merge and sort queryset based on field (createdtstamp)
I have three django models and I want to merge queryset and sort them based on object creation date (createdtstamp). I am using django-simple-history stores Django model state on every create/update/delete. player = Player.history.all().values('first_name','history_date', 'history_id', 'history_type', 'history_user_id', 'id', 'createdtstamp') coach = Coach.history.all().values('coach_name','history_date', 'history_id', 'history_type', 'history_user_id', 'id', 'createdtstamp') title = Title.history.all().values('title_name', 'history_date', 'history_id', 'history_type', 'history_user_id', 'id', 'createdtstamp') #merge queryset and sort based on createdtstamp result_list = sorted(chain(player, coach, title), key=lambda instance: instance.createdtstamp) queryjson = json.dumps(result_list, cls=DjangoJSONEncoder) return HttpResponse(queryjson) How can I sort query result based on createdtstamp field (sort by latest)? Similar question have been asked before Display objects from different models at the same page according to their published date But my question is different as Player.history.select_related doesn't have Coach and Title fields. Player.history.select_related('Coach', 'Title').all().order_by('-createdtstamp'). -
Clear cache when time is up in django
I have problem with issue, with cache. I want to clear cache always when time is up. Below is part of my model in django 1.8 but app didn't used my method clear_cache_when_times_up. Is class model good place to clear cache when time is up? I want to clear cache on list and on detail page, because there I use time. class Article(BaseModel): title = models.CharField(max_length=255) short_text = models.TextField(max_length=10000, default='') livestream_url = models.URLField(default='', blank=True, null=True) livestream_from = models.DateTimeField('livestream from', blank=True, null=True) livestream_to = models.DateTimeField('livestream to', blank=True, null=True) def has_livestream(self): if self.livestream_from is None and self.livestream_to is None: return False return (self.livestream_from <= timezone.now()) and (self.livestream_to >= timezone.now()) def clear_cache_when_times_up(self): if self.has_livestream(): print('################## test #################') return cache.clear() -
Django query with ManyToMany relationship through
I am implementing the connect function like Linkedin. My models are class AFSUser(models.Model): connects = models.ManyToManyField("self", through='UserConnect', symmetrical=False) class UserConnect(models.Model): date_followed = models.DateTimeField(auto_now_add=True) date_approved = models.DateTimeField(null=True, blank=True) date_rejected = models.DateTimeField(null=True, blank=True) requester = models.ForeignKey(AFSUser, on_delete=models.CASCADE, related_name='request_user') acceptor = models.ForeignKey(AFSUser, on_delete=models.CASCADE, related_name='accept_user') I want to list connections of a user. I tried approved_connections = UserConnect.objects.filter(Q(requester=afsUser) | Q(acceptor=afsUser), date_aprroved__isnull=False, date_rejected__isnull=False) Then get the list from there. Any other way so i can do users = userA.connects.filter(...)