Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Cannot get value of model form in templates
I am fairly new in using Django. I want to get data from model form by giving spcific id to model and show that data in a template. But I could not send value to template. I am getting nothing in template. Here is my code: def store_id(request,id): dev_games = GamesModel.objects.get(id=id) form = GameForm(instance=dev_games) return HttpResponseRedirect(request,'Developer/developed_games.html',{'form_data': form.instance, 'user': request.user} ) <div id="Edit" class="modal fade" role="dialog"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> </div> <div class="modal-body"> <form method="POST" action="#" class="form-signin"> <h1 class="form-signin-heading">Modify game</h1> {% csrf_token %} <table class="spaced_table modal_table"> {{form_data}} #could not get value here </table> <input type="submit" class="btn btn-lg btn-primary btn-block" value="Edit"> </form> </div> </div> </div> </div> -
How to feed data from django into a modal?
I'm trying to work out how to get data from django into a bootstrap modal. I'm quite new to django and i've only just started JS. I have a django view that queries for a list of users via ldap for a list of attributes. For example: attributes = ['cn', 'givenName', 'displayName', 'sAMAccountName', 'userPrincipalName', 'mail', 'uidNumber', 'lastLogon'] def ad_users(request): users = get_ad_users('ou=TestUsers,dc=testdomain,dc=org', '(objectCategory=person)', attributes) return render(request, 'users.html', {'ad_users': users}) I then display it on a page using a table. Using a template for loop in django I loop over the elements to generate the table rows. E.g. (ignoring styling and attributes etc). {% for user in ad_users %} to generate each <tr> and each <td> references an item. {{ user.displayName }} {{ user.mail }} etc. However at the end of the row I want to put a "view" button that displays a pop up modal with all the user attriubtes for the user of that row (not just what is displayed in the table). I really have no idea how to achieve this, any help would be appreciated. -
Working with data from models and pygal in Django
I'm using pygal to show a chart on a page. I have a model named Dog and a Model named Visit, dogs can have many visit requests: class Visit(models.Model): """Visit Model""" dog = models.ForeignKey(Dog, on_delete=models.CASCADE) first_name = models.CharField(max_length=50) surname = models.CharField(max_length=50) email = models.EmailField(max_length=50) phone_number = models.CharField(max_length=50) childeren = models.CharField(max_length=3) dog_number = models.IntegerField() job = models.CharField(max_length=500) class Dog(models.Model): """This class creates the Dog table""" name = models.CharField(max_length=50) breed = models.CharField(max_length=100) age = models.IntegerField() description = models.CharField(max_length=100) image = models.FileField(null=True, blank=True) Sex_Option = ( ('M', 'Male'), ('F', 'Female'), ) sex = models.CharField(max_length=1, choices=Sex_Option) I would like the pygal pie chart to show the name of each dog as well as the amount of visit requests each dog has displayed in the graph. Here is the code in my view I currently have: def dog_stats(request): """View for statistics page""" dogs = Dog.objects.all() pie_chart = pygal.Pie() pie_chart.title = 'Requsts to visit' for dog in dogs: pie_chart.add(dog.name, 11) pie_chart.render() context = { 'chart':pie_chart.render(), } return render(request, 'dogs/dogGraphs.html', context) As you can probably tell I am way off. I know that I know that I need to count the number of visit requests for each dog and them display them inside the number argument, but … -
from Sqlite3 to Mysql in django chatbot website
i'ev developed a chatbot web application using Django and python3 on web faction server. Basically the chahbot interacts with a store's users as a customer server.It uses the REST API to POST the user input and GET to display the chatbot output and a python file to process the input and find the output. How the chatting works: 1. chatboy.js: it first POST the user input in the API then run the python file chabot.py. 2. chabot.py: a python file that connects to the Django backend db.sqlite3 and the conversation.sqlite3. So it select the user input from db.sqlite3 then select the matching output in the conversation.sqlite3. Finally the file will update the chatbot output in the db.sqlite3. 3. chatboy.js: will GET the last chatbot output and display it. In development stage when i was testing the application in my local server everything works fine but problems came we i deployed the Django project in the internet. Mostly and the main ERORR that stops the application form working is : The database is locked I did many research and found out that: sqlite3 is not for production and only for small or stand alone application. sqlite3 have a multiple threads problem. … -
Should AppConfig be used for branding in django
Django apps should be self contained, but how to control branding and several other things, e.g. favicon locations? In my current implementation I use a AppConfig class to specify a verbose_name and the favicon and a template tag to apply branding to templates: from django.apps import AppConfig class PollsConfig(AppConfig): name = 'polls' from polls.apps import PollsConfig class EasyPollsConfig(PollsConfig): verbose_name = 'Easy Polls' favicon = 'easypolls/favicon.ico' from django import template from django.apps import apps register = template.Library() @register.simple_tag def get_app_config(app_label): return apps.get_app_config(app_label) {% load app_config %}{% get_app_config 'polls' as config %} <title>{% block title %}{% endblock %} - {{ config.verbose_name }}</title> {% if config.favicon %}<link rel='shortcut icon' type='image/x-icon' href='{% static config.favicon %}' />{% endif %} Is this the recommand way to configure apps? -
Hosting HTTPS Backend and Frontend on Raspi with Django REST and Apache
I have a DDNS domain myself.ddns.net that is forwarded on Port 80 and 443 to my Raspi, running an Apache Webserver. I installed Letsencrypt and generated a certificate for the webserver. In the Raspi I also installed Django REST that is running my backend on 0.0.0.0:8000. On my router I sucessfully forward Port 8000 to the Pi and the HTTP requests are working fine. Now I also want to access my Django REST backend via HTTPS and installed the django sslserver which I start with python manage.py runsslserver 0.0.0.0:8000 with a link to the LetsEncrypt certificate. The problem is that accessing the backend via https sometimes works, and sometimes it doesn't. I can't really figure out why. Is it ok if I use the certificate for backend and frontend or does this needs to be seperated? -
Why does setting CharField max_length to 255 solve DataError (Django)?
This is a solved problem, but it's quite unclear for me how it works. I use Django with PostgreSQL. I have a model with several fields. One of them, called track_code, is a CharField(max_length=13). There is a method in this class which contains the following block: new_order, created = Order.objects.get_or_create(shop=fshop, order_id=order['number']) new_order.shop = fshop new_order.order_id = order['number'] new_order.status = order['fulfillment-status'] new_order.created_at = order['created-at'] new_order.api_id = order['id'] new_order.payment = order['financial-status'] new_order.track_code = track new_order.save() Here shop is a ForeignKey. Every time I run this method, I get django.db.utils.DataError: value too long for type character varying(13). That appears to be a problem with the track_code field. track length never exceeds 12, that's for sure. I found a solution on SO for SlugField, not for CharField, but it works for both. It requires setting field's max_length to 255. The only thing I don't understand is why does it work? I've never tried to set track_code to something longer than 12, and that means I am not supposed to get these errors. But I do, and that's strange. -
How do I use the django-cms Python api to create a page?
I'm trying to write a CMS content migration script that will create our pages for django-cms. However even with the default install of Django-cms, Django-treebeard keeps raising exceptions and it's not clear to me why. For example, when this line is executed: api.create_page(title="Hello world", language='en', parent = None) My script always fails here (line 307-8) in mp_tree.py (v 4.1.0) from treebeard: if newobj.pk: raise NodeAlreadySaved("Attempted to add a tree node that is "\ "already in the database") Does anyone have a very simple example on how to use the cms.api.create_page() method? http://docs.django-cms.org/en/release-3.4.x/reference/api_references.html?highlight=create_page#cms.api.create_page Pip freeze shows these versions: aldryn-apphooks-config==0.2.7 aldryn-boilerplates==0.7.4 aldryn-common==1.0.4 aldryn-faq==1.2.2 aldryn-forms==2.1.3 aldryn-reversion==1.0.9 aldryn-search==0.3.0 aldryn-translation-tools==0.2.1 appdirs==1.4.3 boto==2.46.1 boto3==1.4.4 botocore==1.5.26 cmsplugin-filer==1.1.3 contextlib2==0.5.4 cssselect==1.0.0 cssutils==1.0.1 dj-database-url==0.4.1 Django==1.8.17 django-absolute==0.3 django-admin-sortable==2.0.21 django-admin-sortable2==0.6.6 django-appconf==1.0.2 django-appdata==0.1.6 django-cas-ng==3.5.6 django-classy-tags==0.8.0 django-cms==3.4.1 django-cors-headers==2.0.2 django-debug-toolbar==1.7 django-emailit==0.2.2 django-environ==0.4.1 django-extensions==1.7.7 django-filer==1.2.5 django-formtools==1.0 django-haystack==2.5.1 django-mptt==0.8.6 django-parler==1.6.5 django-polymorphic==0.8.1 django-reversion==1.10.2 django-sekizai==0.10.0 Django-Select2==4.3.2 django-simple-captcha==0.5.3 django-sizefield==0.9.1 django-sortedm2m==1.3.2 django-spurl==0.6.4 django-standard-form==1.1.1 -e git+https://github.com/jschneier/django-storages.git@043b91b10ebfebdf7e752d743ae630f0daa2c4f4#egg=django_storages django-storages-redux==1.3.2 django-tablib==3.1.2 django-taggit==0.21.3 django-treebeard==4.1.0 djangocms-admin-style==1.2.6.2 djangocms-attributes-field==0.1.2 djangocms-column==1.7.0 djangocms-googlemap==1.0.1 djangocms-installer==0.9.3 djangocms-link==2.0.3 djangocms-rest-api==0.2.0 djangocms-snippet==1.9.2 djangocms-style==2.0.1 djangocms-text-ckeditor==3.3.1 djangocms-video==2.0.3 djangorestframework==3.4.7 docutils==0.13.1 easy-thumbnails==2.3 google-auth==0.8.0 google-auth-httplib2==0.0.2 google-cloud-core==0.23.1 google-cloud-storage==0.23.1 googleapis-common-protos==1.5.2 html5lib==0.9999999 httplib2==0.10.3 jmespath==0.9.0 lxml==3.7.0 mysqlclient==1.3.10 packaging==16.8 Pillow==3.4.2 premailer==3.0.1 protobuf==3.2.0 psycopg2==2.6.2 pyasn1==0.2.3 pyasn1-modules==0.0.8 pyparsing==2.2.0 python-cas==1.2.0 python-dateutil==2.6.0 python-slugify==1.2.0 pytz==2016.10 raven==6.0.0 requests==2.12.3 rsa==3.4.2 s3transfer==0.1.10 six==1.10.0 sqlparse==0.2.3 tablib==0.11.3 tzlocal==1.3 Unidecode==0.4.19 URLObject==2.4.2 YURL==0.13 -
Django: How to create a form using inline_formset with a many to one relationship with user
I am trying to set up a form using Django's inlineformset_factory. The model is set up in a many to one relationship, each user will have many cases. I want the user to add a case. I have followed the general outline from this site models.py class Case(models.Model): date_due = models.DateField() user = models.ForeignKey(User, on_delete=models.CASCADE) forms.py CaseFormset = inlineformset_factory(User,Case, fields=('date_due',), can_delete = True) class CaseForm(forms.ModelForm): class Meta: model = Case fields = ('date_due',) views.py @login_required def add_case(request): if request.method == 'POST': form = CaseForm(request.POST) if form.is_valid(): case = form.save(commit = False) case_formset = CaseFormset(request.POST, instance = case) if case_formset.is_valid(): case.save() case_formset.save() return redirect('index') else: print(form.errors) else: form = CaseForm() case_formset = CaseFormset(request.POST, instance = Case()) return render(request, 'cases/add_case.html', {'form':form, 'case_formset':case_formset}) add_case.html <!DOCTYPE html> {% load staticfiles %} <html> <head> <body> <form method="post"> {% csrf_token %} {{ form.as_p }} {{ case_formset.management_form }} <button type="submit">Save changes</button> </form> </body> </head> </html> I am getting a Exception Type: ValidationError Exception Value: ['ManagementForm data is missing or has been tampered with'] Reading the docs it looks like I need to add the management_form to the formset, which I have done. I am not sure where else I am going wrong. I also tried a different … -
How to include submitted_date and submitted_by in a feedback form in Django?
I have a feedback form in my app. A user must be logged in to submit a feedback. A user is asked to enter feedback into the text-area. Upon submission, I want to store the user-details in submitted_by field and time of creation of the form as submitted_date (which also contains time). I have read many discussions regarding the use of auto-now_add=True and auto_now but there are many opinions about this topic and a little confusing too. I am using model-form to input data from the user. This is how my different file looks like: # myapp/models.py class Feedback(models.Model): content = models.TextField(max_length=100) submitted_by = models.ForeignKey(User) submitted_date = models.DateTimeField() # what do add here in arguments ? def __str__(self): return self.content + " @ " + self.submitted_date #myapp/forms.py class FeedbackForm(ModelForm): class Meta: model = Feedback fields = [ 'content' ] #myapp/views.py def addfeeback(request): if request.method == "POST": form = FeedbackForm(request.POST) if form.is_valid(): form.save() # Do I need to do something here ? return redirect('home') else: form = FeedbackForm() return render(request, 'myapp/addFeedback.html', { 'form': form}) #myapp/urls.py url(r'^feedback/$', core_views.addfeeback , name='add-feedback'), # addFeedback.html {% extends 'registration/base.html' %} {% block title %} Feedback {% endblock %} {% block content %} <form method="post" > {% … -
How is the value of {{ form.id }} generated in modelformset_factory - Django
When you put {{ form.id }} in a formset, which translates to something like <input id="id_form-0-id" name="form-0-id" type="hidden" value="52"> where does the value="52" come from? How did it get 52? -
How do I communicate with apps via JSON using Django rest fremework? API
I'm trying to decode and read a JSON message with python using the rest framework. How can I achiev it? I want to receive a JSON on Django server from my app (I'm using an iOS app) and answer it. Just to understand the conecept, I want to send a JSON with my app containig: [ { "qustion": "hello", } ] and answer it with: [ { "answer": "hello_user", } ] but if the question isn't 'hello', I want to return something like [ { "answer": "invalid question", } ] What I'm trying to do: at serializers.py: class AskSerializer(ModelSerializer): class Meta: fields = [ 'question', ] at views.py: class AskSerializerAPIView(APIView): def post(self): serizalizer = AskSerializer question = serializer.field ['question'] if question == 'hello' return ('hello user') #JSON answer at url.py url(r'^/ask/$', AskAPIView.as_view(), name='ask'), How can I achiev what I want?? Ufortunately I don't find any video that explain it and I'm not understanding the documentation... -
Is this possible to have pagination, where we can jupm pages, in django?
Let me clear my question further. I have this code in my django 1.10 template which provides pagination. {% block pagination %} {% if is_paginated %} <div class="pagination"> <span class="page-links"> {% if page_obj.has_previous %} <a href="{{ request.path }}?page={{ page_obj.previous_page_number }}">previous</a> {% endif %} <span class="page-current"> Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}. </span> {% if page_obj.has_next %} <a href="{{ request.path }}?page={{ page_obj.next_page_number }}">next</a> {% endif %} </span> </div> {% endif %} {% endblock %} Now the problem is by default you get paagination like previous Page 1 of 119. next but sometime we do not want to go one by one but want to jump the pages. Like I would like to go to page number 10. So rahter than clicking next 10 times, wouldn't it be nice to have 1 to 10 written in pagination and we could click to any page and reach there rather than clicking nex next next everytime. Is this possible in django template? -
shopify.RecurringApplicationCharge.cancel() AttributeError: 'function' object has no attribute 'body'
I see this issue about cancelling orders, I am getting the same behavior when trying to cancel RecurringApplicationCharges. I get the error: AttributeError: 'function' object has no attribute 'body' I get the shops current charge: user_current_charge = shopify.RecurringApplicationCharge.current() then I try and cancel it: shopify.RecurringApplicationCharge.cancel(user_current_charge) Is this not how it is supposed to work? -
Django model self-reference: prevent referencing to itself
I have the following model: class Category(models.Model): name = models.CharField(max_length=255) parent = models.ForeignKey('self', related_name='children') My question is that how I could prevent model to referencing itself (same object). Object should be only able to point to other categories but not to itself ('dogs' can have parent 'animals' but can't have parent 'dogs') -
Django: ModelMultipleChoiceField and transactions
When ModelMultipleChoiceField is updated, what happens? I assume all old values are deleted and new values are added to the m2m-link. But is there a gap between deleting old values and adding new ones? So, should I put saving ModelMultipleChoiceField inside a transaction? -
Django: limit_choices_to with with a "through" intermediate table
https://docs.djangoproject.com/en/1.10/ref/models/fields/:"limit_choices_to has no effect when used on a ManyToManyField with a custom intermediate table specified using the through parameter." Why?! And what to do if I need both through and limit_choices_to? Should I fall back from ModelForm to simple Form in this situation and do it all manually? Or is there a way to do it with ModelForm? -
Django: AppRegistryNotReady("Models aren't loaded yet.") exception after upgrading to 1.11
After upgrading from Django 1.10.6 to 1.11, with no changes in my code, I get the following exception when starting the server on my development platform (Visual Studio 2017 Community on Windows 10 64-bit): Traceback (most recent call last): File "...\manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "...\virtualenv35\lib\site-packages\django\core\management\__init__.py", line 363, in execute_from_command_line utility.execute() File "...\virtualenv35\lib\site-packages\django\core\management\__init__.py", line 337, in execute django.setup() File "...\virtualenv35\lib\site-packages\django\__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "...\virtualenv35\lib\site-packages\django\apps\registry.py", line 108, in populate app_config.import_models() File "...\virtualenv35\lib\site-packages\django\apps\config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "c:\Program Files (x86)\Python35-32\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 665, in exec_module File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "...\emma\models.py", line 129, in <module> class ProduktForm(ModelForm): File "...\virtualenv35\lib\site-packages\django\forms\models.py", line 252, in __new__ opts.field_classes) File "...\virtualenv35\lib\site-packages\django\forms\models.py", line 177, in fields_for_model formfield.queryset = formfield.queryset.complex_filter(limit_choices_to) File "...\virtualenv35\lib\site-packages\django\db\models\query.py", line 817, in complex_filter return self._filter_or_exclude(None, **filter_obj) File "...\virtualenv35\lib\site-packages\django\db\models\query.py", line 799, in _filter_or_exclude clone.query.add_q(Q(*args, **kwargs)) File "...\virtualenv35\lib\site-packages\django\db\models\sql\query.py", line 1260, in add_q clause, _ = self._add_q(q_object, self.used_aliases) File "...\virtualenv35\lib\site-packages\django\db\models\sql\query.py", line 1286, in _add_q allow_joins=allow_joins, split_subq=split_subq, File "...\virtualenv35\lib\site-packages\django\db\models\sql\query.py", line … -
Foreign Key constraint error In Django
I am extending the Abstract user model in Django and it's not letting me migrate throwing an error related to the foreign key. from django.db import models from django.contrib.auth.models import AbstractUser import uuid #Database model for Users. class User(AbstractUser): ''' Abstract user model inherited containing all basic fields such as: first and last name, username, email, password etc. Abstract User fields. ''' user_id = models.UUIDField( primary_key = True, default = uuid.uuid4, editable = False ) is_owner = models.BooleanField( default = False ) class Meta: db_table = 'Users' def __str__(self): self.constructLabel( self.first_name, self.last_name, self.user_id ) The error : django.db.utils.IntegrityError: (1215, 'Cannot add foreign key constraint') From the database error is: 2017-04-09 20:33:07 0x7f3440171700 Error in foreign key constraint of table shipapp/#sql-3c9_33: FOREIGN KEY (`user_id`) REFERENCES `users_user` (`user_id`): Cannot resolve table name close to: (`user_id`) Can anybody who has faced this before help me out? I have been out of touch since Django 1.8.5 was released. :( -
Django crispy form tab
I am now studying Django form. Right now I am focusing on crispy form. For now crispy and then after I master the form I will move on to Django Admin form and Django admin model form. Django 1.10 Python 3.6.0 I am following these tutorials: https://blog.bixly.com/awesome-forms-django-crispy-forms http://django-crispy-forms.readthedocs.io/en/latest/layouts.html# https://godjango.com/29-crispy-forms/ Here are my source code: views.py: from django.views.generic import FormView from apps.colors.forms import PersonDetailForm class ColorStudyView(FormView): template_name = 'colors/study.html' form_class = PersonDetailForm success_url = '/' forms.py: from crispy_forms.bootstrap import Tab, TabHolder from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit, Layout from django import forms class NoFormTagCrispyFormMixin(object): @property def helper(self): if not hasattr(self, '_helper'): self._helper = FormHelper() self._helper.form_tag = False return self._helper class PersonDetailForm(forms.Form): name = forms.CharField(max_length=100) age = forms.IntegerField(required=False) address1 = forms.CharField(max_length=50, required=False) address2 = forms.CharField(max_length=50, required=False) city = forms.CharField(max_length=50, required=False) state = forms.CharField(max_length=50, required=False) mobile = forms.CharField(max_length=32, required=False) home = forms.CharField(max_length=32, required=False) office = forms.CharField(max_length=32, required=False) twitter = forms.CharField(max_length=100, required=False) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_tag = False self.helper.layout = Layout( TabHolder( Tab('Information', 'name', 'age' ), Tab('Address', 'address1', 'address2', 'city', 'state' ), Tab('Contact', 'mobile', 'home', 'office', 'twitter', ) ) ) self.helper.layout.append(Submit('submit', 'Submit')) study.html: {% load crispy_forms_tags %} <!DOCTYPE html> <html lang="en"> <head> <link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet" /> … -
Django update model form with unique constraint
What I'm trying to achieve is to update an instance with unique_together constraint via a model form. I've a "relationnal" model, e.g. a model with three fields, all as foreign key fields. This model is referenced by an another one through a through attribut. A part of my "relationnal" model : class EnseignantUECentre(models.Model): statut = models.ForeignKey(StatutEnseignant, blank=False, null=False) enseignantue = models.ForeignKey('EnseignantUE', blank=False, null=False) centre = models.ForeignKey('Centre', blank=False, null=False) class Meta: unique_together = ('enseignantue', 'centre') Two of theses fields, enseignantue and centre, are set once and for all. Only statut can be updated. I overloaded a Form._post_clean method to ensure that theses fields are not modified. def _post_clean(self): # si lors d'un update les valeurs centre et enseignantue # changent il y a erreur: Voir #272 super(EnseignantUECentreForm, self)._post_clean() import ipdb; ipdb.set_trace() if 'centre' in self.changed_data: # on ne récupère pas la valeur depuis self.initial # mais depuis l'instance if self.instance is not None: self._update_errors(ValidationError({'centre': ValidationError("Le centre est déjà associé, vous ne pouvez le modifier")})) if 'enseignantue' in self.changed_data: if self.instance is not None: self._update_errors(ValidationError({'enseignantue': ValidationError("L'enseignantue est déjà associé, vous ne pouvez le modifier")})) This code seems to working but while I debug it, I get a supplementary ValidationError filed in the … -
'NoneType' object has no attribute 'META'
The following is my Django 1.10 views.py code which produces my blog RSS feed. I am now trying to add my usage statistics tracking to this. I am keeping all my statistics code in a designated area of my project. All I need are these 3 lines of code within the rss views.py: from statistics.service.add import ServiceAdd as ServiceStatisticsAdd rss_reference = {'utc': timezone.now()} ServiceStatisticsAdd(request).add('rss', rss_reference, kwargs) The error I am getting is all about request. Originally the database def was def items(self):. When I went to add tracking I expected including request would have fixed the error. This is my views.py from datetime import datetime from django.contrib.syndication.views import Feed from django.urls import reverse from django.utils import timezone from database.ron_home.models import BlogWebsite from statistics.service.add import ServiceAdd as ServiceStatisticsAdd class BlogRssFeed(Feed): title = "Rons-Home.net Blog RSS Feed" link = "/en/blog/" description = "Ron Piggott shares updates from his health care and logistics of daily living with a physical disability." def item_title(self, obj): return obj.entry_title def item_description(self, obj): return obj.entry def item_link(self, obj): return reverse('blog:entry', args=[obj.reference]) def items(self, request, **kwargs): rss_reference = {'utc': timezone.now()} ServiceStatisticsAdd(request).add('rss', rss_reference, kwargs) return BlogWebsite.objects.filter(entry_date__lt=datetime.utcnow()).order_by('-entry_date')[:15] This is the complete traceback [09/Apr/2017 14:02:48] "GET / HTTP/1.1" 302 0 /usr/local/lib/python3.5/dist-packages/django/db/models/fields/__init__.py:1430: RuntimeWarning: … -
Password protect Excel file in python
I would like to password protect an excel file using the xlwt python package. I want it to work independent of the platform on which the file is opened. Is there any way to accomplish this? -
Urlpatterns and Django Debug Toolbar
Django 1.11 I'm reading "Two Scoops of Django". Namely about multiple settings files and multiple requirements files. So, it is recommended to separate base.py, local.py and production.py. And for base.py: INSTALLED_APPS += ("debug_toolbar", ) What troubles me is that Django Debug Toolbar also needs some addition to urls.py: from django.conf import settings from django.conf.urls import include, url if settings.DEBUG: import debug_toolbar urlpatterns = [ url(r'^__debug__/', include(debug_toolbar.urls)), ] + urlpatterns http://django-debug-toolbar.readthedocs.io/en/stable/installation.html#urlconf That is we should either accept this mix of debug and production notions or separate them into multiple files. I investigated this question. For example, this link: Django: Multiple url patterns starting at the root spread across files But I'm still somehow suspicious. Could you give me a piece of advice: what is the best practice of how separate this Django Debut Toolbar from production in urlpatterns. -
auth select chooses in forms.py
I have read this code in this question and look nice. but if I have user auth and I want user select only your odjects how to change that code ?for ex chooses your personal upload images. from django.forms.widgets import Select class ProvinceForm(ModelForm): class Meta: CHOICES = Province.objects.all() model = Province fields = ('name',) widgets = { 'name': Select(choices=( (x.id, x.name) for x in CHOICES )), } my model : class MyModel(models.Model): user = models.ForeignKey(User, unique=True) upload = models.ImageField(upload_to='images')