Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Does django use cache by default?
Is their predefined default caching system for django projects if nothing is configured ? If yes. how it works ? -
newbie - understanding Django's class-based views dynamic filtering
I'm trying to follow and learning about dynamic filtering in Django from the docs. https://docs.djangoproject.com/en/1.10/topics/class-based-views/generic-display/#dynamic-filtering I've just been following along step by step and copy/pasted the code from docs. But I don't understand the last bit about added the publisher into the context, meaning I can't figure out how to query that data in the template. The only thing I can get a "hold" of publisher. Because in the PublisherDetail view publisher_detail.html you would just do something straight forward like this, to list all the books from a publisher: {% for book in book_list %} {{ book.title }} {% endfor %} This is part that is tripping me up. We can also add the publisher into the context at the same time, so we can use it in the template: # ... def get_context_data(self, **kwargs): # Call the base implementation first to get a context context = super(PublisherBookList, self).get_context_data(**kwargs) # Add in the publisher context['publisher'] = self.publisher return context -
Django how to set the default language in the i18n_patterns?
settings.py from django.utils.translation import ugettext_lazy as _ LANGUAGE_CODE = 'hi' # list of activated languages LANGUAGES = ( ('hi', _('Hindi')), ('en', _('English')), ) urls.py urlpatterns += i18n_patterns( url(r'^', include('howdy.urls')), url(r'^', include('accounts.urls')), url(r'^admin/', admin.site.urls), url(r'^i18n/', include('django.conf.urls.i18n')), url(r'^accounts/', include('allauth.urls')) ) So the default I set here is "hi" , but whenever I am hitting the URL[private mode] without appending any language in it, its redirecting with "en" in the url, not the "hi". What I am missing here to make it default point to "hi" language ? -
how to update the images in browser while developing website in django
In a browser while running a localhost server(127.0.0.1:8000) (while developing a website) the images is not updating . It is displaying the previous images which are in the folder. Even though if we replace the images with same name. First time it is opening in other browser but when we make changes in images(background images) it is not updating -
Django "if" condition with context_processors variable
I'm creating some themes for my Django website and I would like to modify the HTML text color in function of context_processors variable. The context_processors variable is : Datasystems or Cameroun (I have two themes up to now, but I will have maybe 4 or 5 themes at the end). So, if the variable is Datasystems, text' color should be blue. If the variable is Cameroun, text' color should be green. My context_processors.py (it works perfectly) file looks like : from django.conf import settings from Configurations.models import Theme def GetTheme(request): return {'mytheme' : Theme.objects.values_list('favorite_theme').last()[0].encode("ascii")} My HTML template looks like : {% extends 'Base_Accueil.html' %} {% load staticfiles %} {% load static %} {% block content %} <p align="center"><img src="{% static 'images/logo.png' %}"></p> {% if {% get_static_prefix %}{{ mytheme }} == "Datasystems" %} <h2 align="center"> <font color="#0083A2"> Bienvenue sur la page d'accueil du logiciel DatasystemsEC</font></align></h2> <p></p> {% if {% get_static_prefix %}{{ mytheme }} == "Cameroun" %} <h2 align="center"> <font color="#007A5E"> Bienvenue sur la page d'accueil du logiciel DatasystemsEC</font></align></h2> <p></p> {% endif %} {% if user.is_authenticated %} <h3 align="center"> <font color="#0083A2"> Vous êtes connecté(e) en tant que {{ user.username }} </font></align></h3> {% endif %} {% endblock content %} How I can execute … -
Deserializing JSON Date field in Python/Django
I am trying to port a web crawler app from .Net to Python. It receives json responses similar to the following: [ { "Code": "AAA", "Date": "/Date(1481875200000)/", "Value": 12345.00 } ] This could easily be deserialized by Newtonsoft Json. However I can't seem to deserialize this with Python's built in Json Decoder from django.db import models class ItemModel(models.Model): code = models.CharField(max_length=5) date = models.DateTimeField() value = models.IntegerField(default=0) import json parsed_data = json.loads(json_data, encoding='utf-8') new_model=ItemModel() new_model.code = parsed_data["Code"] new_model.date = parsed_data["Date"] new_model.value = parsed_data["Value"] new_model.save() which gives ValidationError: [u"'/Date(1481875200000)/' value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format."] Edit: Now I know this is caused because of assigning a string to a Date Time field Is there a way to try parse this data to the django model? - as I have no way to modify the json response. Also is this the right way to do this? as the code seems intuitively iffy to me. -
Sending a file in post method on form submit and populating a datatable with the json response
I have a datatable defined this way which i can not change . var table = $('#dt-table').dataTable({ "sPaginationType": "bootstrap", "processing": true, "bServerSide": true, 'bPaginate' : true, "bStateSave": true, "sAjaxSource": 'myurl', On click of a button i want to make a post request and pass a file to the backend. After searching i found out that i can change the table settings using var oSettings = table.fnSettings(); So my click button action is something like : $('form').on('submit', function(e){ e.preventDefault(); var data = new FormData($(this)[0]); console.log(data); var oSettings = table.fnSettings(); oSettings.sAjaxSource="/home/file_upload/; oSettings.sServerMethod="POST"; //oSettings.aoData.push(data) table.fnDraw(); So what i am not able to do is how do i pass this formdata to my backend . I am able to get the post method in the backed but not the file . The basic motto is to populate the data table with json data obtained from the server by processing this file . Also i am using django form which looks like this : <form name="form" method="post" id="file-upload-form" enctype="multipart/form-data">{% csrf_token %} {{ form.as_p }} <input type="file" name="file"/> <button type="submit" class="btn btn-primary" id='upload-btn'>Upload</button> </form> If you need any extra info , please comment . Any help is appreciated . -
AttributeError: type object ' ' has no attribute 'as_view'
views.py from django.shortcuts import render from django.contrib.auth.decorators import login_required from django.utils.decorators import method_decorator from briefcase.BaseBriefcaseView import BaseBriefcaseView from briefcase.models import Customer @method_decorator(login_required, name='dispatch') class BriefcaseIndexView(BaseBriefcaseView): model = Customer template_name = 'briefcase/index.html' urls.py from django.conf.urls import url from briefcase.views import BriefcaseIndexView, invoice_view urlpatterns = [ url(r'^$', BriefcaseIndexView.as_view(), name='index'), url(r'^index/invoice_view$', invoice_view.as_view(), name='invoice'), ] BaseBriefcase.py from cmms.views import DefaultContextView class BaseBriefcaseView(DefaultContextView): extra_context = {} def get_context_data(self, **kwargs): context = super(BaseBriefcaseView, self).get_context_data(**kwargs) context["side_menu"] = self.get_side_menu() context["main_menu"] = self.get_main_menu() context["side_filter"] = self.get_side_filter() context["module"] = "Briefcase" return context And the error i get is....... url(r'^$', BriefcaseIndexView.as_view(), name='index'), AttributeError: type object 'BriefcaseIndexView' has no attribute >'as_view' What am I getting wrong? -
django admin action delete - why many db-writes
I have been adding items from a txt to my database in a djago-view - with and without the @transaction.atomic-decorator, i.e. with a loop over db-writes or one db-write -- the performance difference is near infinite!^^ now: the default delete-action in the admin panel clearly does the (inferior) loop over db-wirtes. Which takes really long for deleting 1000 entries. Why is this, is there a reason, am I missing something?! Or should I fix this and open a pull request ;) (would be my first oss-contribution :)) -
Django: Two ModelChoiceField - how to keep data of the unsubmitted form
I have 2 forms and if i submit one, I want to keep the data of the other form. The problem is, that i can't get the data from the post request. So what can I do? -
Search view with multiple pages and order by relevancy
I am writing a very simple search view: class SearchView(generic.ListView): template_name = 'polls/search.html' context_object_name = 'results' def get_queryset(self): """ Extract query from parameters and return search results. """ query = self.request.GET.get('query') if query: query = query.strip() return Question.objects.filter(question_text__icontains=query) else: return Question.objects.none() <!DOCTYPE html> {% if results %} <ul> {% for result in results %} <li><a href="{% url 'polls:vote' result.id %}">{{ result }}</a></li> {% endfor %} </ul> {% else %} <p>No matches found.</p> {% endif %} <p><a href="{% url 'polls:index' %}">Back to overview?</a></p> The results should be ordered by the total votes on choices: Question.objects.filter(question_text__icontains=query).order_by('choice__votes') This query does not seem to work and returns questions multiple times. How could the results be split on multiple pages? -
ValueError: The keyword argument `name` must be the name of a method of the decorated class:
views.py from django.shortcuts import render from django.contrib.auth.decorators import login_required from django.utils.decorators import method_decorator from briefcase.BaseBriefcaseView import BaseBriefcaseView from briefcase.models import Customer @method_decorator(login_required, name='dispatch') class BriefcaseIndexView(DefaultContextView): model = Customer template_name = 'briefcase/index.html' urls.py from django.conf.urls import url from briefcase.views import BriefcaseIndexView, invoice_view urlpatterns = [ url(r'^$', BriefcaseIndexView.as_view(), name='index'), url(r'^index/invoice_view$', invoice_view.as_view(), name='invoice'), ] And the error i get is....... ValueError: The keyword argument name must be the name of a method of the decorated class: . Got 'dispatch' instead Please help a django newbie. What am I doing wrong? -
Store django model description in database
Classical django application have file models.py. This file contains description for entities which describe database table. What about alternative? Describe models but not in text(python)-file, but in database. Thank you in advance! -
Django JWT and OAuth authentication and Authorization
At the moment I am using JWT authentication for my django REST API. But from the JWT library I cant't refresh the token after expire. (5 minutes) https://github.com/GetBlimp/django-rest-framework-jwt So I need to integrate the OAuth 2.0 for the refresh token and JWT token for access token. How can I integrate JWT + OAuth 2.0 for my REST Framework. or any samples ? EX: https://github.com/GetBlimp/django-rest-framework-jwt plus https://django-oauth-toolkit.readthedocs.io/en/latest/# -
make django not update certain fields
I have a Django model against a postgresql database table where I want Django to not update field_3 as its a timestamp field that DB is supposed to fill in. class AbcModel: model_id = models.AutoField(primary_key=True) field_1 = models.BigIntegerField() field_2 = models.TextField() field_3 = models.DateTimeField(blank=True, null=True) class Meta: managed = False db_table = 'abc_table' The corresponding table schema abc_table model_id integer not null default nextval('command_running_command_id_seq'::regclass) field_1 integer not null field_2 text not null field_3 timestamp without time zone default now() What I tried - I read that one should call Model.save(update_fields=[list of fields to be updated]). class AbcModel(models.Model): def save(self, *args, **kwargs): u_fields = ['field_1', 'field_2'] super(CommandRunning, self).save(update_fields=u_fields) But I get an Exception Cannot force an update in save() with no primary key. If I include model_id in update_fields, I get following exception The following fields do not exist in this model or are m2m fields: model_id What am I missing here? -
django object is getting saved in database, getting showed in django admin, but its not getting rendered in django template
I am facing problem. I am trying to save django model object. Object is getting saved in database, getting showed in django admin, but its not getting rendered in django template. class TicketType(TimeStampedModel, TitleDescriptionModel): STATUS = Choices(('active', 'Active'), ('inactive', 'Inactive')) HIDE_TICKET = Choices(('not_on_sale', 'NOT ON SALE'), ('custom', 'CUSTOM')) quantity = models.IntegerField(default=1) remaining_tickets = models.IntegerField(default=0) price = models.DecimalField(default=0.0, decimal_places=3, max_digits=20) discounted_price = models.DecimalField(decimal_places=3, max_digits=20, default=-1) ticket_sale_start = models.DateTimeField() ticket_sale_end = models.DateTimeField() status = models.CharField(choices=STATUS, default=STATUS.active, max_length=10) max_tickets_per_order = models.IntegerField(default=0) show_ticket_on_event_page = models.BooleanField(default=True) show_desc_on_event_page = models.BooleanField(default=True) ticket_auto_hide = models.BooleanField(default=True) ticket_auto_hide_when = models.CharField(choices=HIDE_TICKET, default=HIDE_TICKET.not_on_sale, max_length=15) auto_hide_until = models.DateTimeField(blank=True, null=True) auto_hide_after = models.DateTimeField(blank=True, null=True) reserved_seating = models.BooleanField(default=False) show = models.ForeignKey(Shows, related_name='types_of_tickets', blank=True, null=True) sold_out = models.BooleanField(default=False, help_text=_('tickets sold out')) objects = TicketTypeQuerySet.as_manager() history = HistoricalRecords() def __str__(self): if self.show: result = self.show.event.title + " - " + self.show.title + " " + self.title else: result = self.title return result Save method is ttype1 = TicketType.objects.create( title="Ticket One", description="height above 4'6 Inch", quantity=500, remaining_tickets=500, price=949.0, ticket_sale_start=tdnow, ticket_sale_end=single_date, status="Active", max_tickets_per_order=10, show=show ) its getting saved and getting displayed in django admin but its not rendering unless i hit save button from django admin for one time. So each object i need to hit save button from … -
Django staff see no apps
Goal: 1. User in ManagementUser model be able to add/edit/remove MarketingUser from Django-Admin Problem: When I login by management user I got You don't have permission to edit anything. Here is my source code. models: class AbstractSBrandUser(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) branch = models.ForeignKey(Branch, on_delete=models.SET_NULL, null=True) mobile = models.CharField(max_length=15) class Meta: abstract = True permissions = ( ('has_read_user_permission', 'has read permission on user table'), ('has_edit_user_permission', 'has edit permission on user table'), ('has_remove_user_permission', 'has remove permission on user table'), ) mgmt_users.py: from apps.commons.models import AbstractSBrandUser class ManagementUser(AbstractSBrandUser): pass marketing_users.py: class MarketingUser(AbstractSBrandUser): pass populate_db.py: MANAGEMENT_PERMISSION = ( 'has_read_user_permission', 'has_edit_user_permission', 'has_remove_user_permission', ) def create_user_groups(): Group.objects.get_or_create(name="Management") Group.objects.get_or_create(name="Marketing") def create_branches(): Branch.objects.get_or_create(name="ศรีนครินทร์", address="ศรีนครินทร์", province="กรุงเทพ", district="สวนหลวง", postal_code="10250", phone="+662-721-3111", fax="+662-721-3022", tax_id="0123456") Branch.objects.get_or_create(name="สยามแอดสยาม", address="ปทุมวัน", province="กรุงเทพ", district="ปทุมวัน", postal_code="10330", phone="+662-612-5437", fax="+662-217-3029", tax_id="6543321") def create_mgmt_users(): create_branches() user1 = User.objects.create_user(username='John', email='lennon@thebeatles.com', password='johnpassword', is_staff=True) user2 = User.objects.create_user(username='Andy', email='lemon@thebeatles.com', password='andypassword', is_staff=True) user3 = User.objects.create_user(username='Tummy', email='tummo@ufo.com', password='tummypassword', is_staff=True) user4 = User.objects.create_user(username='Pax', email='pax@kodomo.com', password='paxpassword', is_staff=True) branch1 = Branch.objects.get(name="ศรีนครินทร์") branch2 = Branch.objects.get(name="สยามแอดสยาม") ManagementUser.objects.bulk_create([ ManagementUser(user=user1, branch=branch1, mobile="1111111"), ManagementUser(user=user2, branch=branch1, mobile="2222222"), ManagementUser(user=user3, branch=branch2, mobile="3333333"), ManagementUser(user=user4, branch=branch2, mobile="4444444"), ]) mgmt_group, is_created = Group.objects.get_or_create(name="Management") content_type = ContentType.objects.get_for_model(ManagementUser) for item in MANAGEMENT_PERMISSION: permission = Permission.objects.filter(codename__exact=item, content_type=content_type).first() mgmt_group.permissions.add(permission) user_list = [mgmt_record.user for mgmt_record in ManagementUser.objects.all()] for user in user_list: user.groups.set([mgmt_group]) -
Django: how to exit in settings.py
I have a Django website which has different settings for development and production (DEBUG/SECRET_KEY, etc). Production provides these settings with environmental variables. In the settings.py I want to exit if the expected settings aren't given like so: if not DEBUG and SECRET_KEY == DEFAULT_SECRET_KEY: sys.exit("SECRET_KEY must be set when DEBUG = False") Is it correct to exit in the settings.py file like this? -
I am a beginner at django, trying to create my first app.
models.py date = models.DateField( (date), default=date.today) views.py date = request.POST.get('date') The error i am getting invalid literal for int() with base 10: '' Request Method: POST Request URL: http://127.0.0.1:8000/users/save/ Django Version: 1.10.4 Exception Type: ValueError Exception Value: invalid literal for int() with base 10: '' Exception Location: C:\Users\Androcid\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\models\fields\__init__.py in get_prep_value, line 1832 -
Django and MySql savepoint does not exist after deadlock
I've been dealing with it for a while now and can't find a good solution. I have a code that handles a deadlock by retrying when needed, but I get a DB error when doing that savepoint does not exist. I think I understand (or at least have the general idea) why this is happening but cannot think of a solution. the code for the handeling of the deadlocks, and retry: def execute_wrapper(*args, **kwargs): attempts = 0 while attempts < 2: try: return original(*args, **kwargs) except OperationalError as e: code = e.args[0] if attempts == 0 and code == 1213: deadlock_log_path = os.path.join("local_data", os.environ['USER'], "logs", "deadlocks") deadlock_log_file_name = datetime.datetime.now().strftime("%d.%B.%Y.%I:%M%p") dead_lock_full_name = os.path.join(deadlock_log_path, deadlock_log_file_name) safe_makedirs(deadlock_log_path) with connection.cursor() as cursor: cursor.execute("SHOW ENGINE INNODB STATUS") with open(dead_lock_full_name, 'w') as f: f.write(cursor.fetchall()[0][2]) logging.getLogger(__name__).info("Dead lock Trace: {}".format(e)) if attempts == 1 or code != 1213: raise e attempts += 1 time.sleep(0.2) I know that the best is to avoid deadlocks, but let's assume that the idea to retry is the good enough. anyone of you knows what is the problem and how to deal with it? Thanks in advance -
Streaming a Growing Log File To Browser (DRF/Angular)
I am using Django Rest Framework/AngularJs for developing a web application. I have a use case in which server needs to stream the contents of a file in realtime, the file itself is growing since some other application is logging in to it. I know many inefficient ways to do this. Can you suggest some better ways to achieve this. The Django "view" function should not return till the file is growing but still be able to send the incremental data to the client. Any help will be appreciated. -
Models DecimalField default value as geocode result value
I want to set fields: loc_lat and loc_lng base on geocoding from 'location' field. How can I achieve that? When I'm putting some operations between model field definitions I'm getting an error, so I can't do it that way. How can I set latitude and longitude default value as coordinates from geocoding, without interrupting model fields? Please notice that I'm new to Django. Stack Trace: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.5/dist-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.5/dist-packages/django/core/management/__init__.py", line 341, in execute django.setup() File "/usr/local/lib/python3.5/dist-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python3.5/dist-packages/django/apps/registry.py", line 108, in populate app_config.import_models(all_models) File "/usr/local/lib/python3.5/dist-packages/django/apps/config.py", line 199, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python3.5/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 "/home/username/Projects/app/app/events/models.py", line 7, in <module> class Event(models.Model): File "/home/username/Projects/app/app/events/models.py", line 14, in Event geocode_result = gmaps.geocode(location) File "/home/username/.local/lib/python3.5/site-packages/googlemaps/client.py", line 356, in wrapper result = func(*args, **kwargs) File "/home/username/.local/lib/python3.5/site-packages/googlemaps/geocoding.py", line 68, in geocode return … -
django select_related for multiple foreign keys from diffrent databases
I have three table two from legacy database and one from default database.Now my models have 3 foreign key constraints 2 from legacy database and one from default database. i am using a code in views function to all the related database: appuser_all_list = Users.objects.using("cms").select_related().order_by('id', 'name').all(). Now in this cases, it is using all the tables from cms but one foreign key constraints belong to other database.How can I use all 3 foreign key constraints.Any idea and thanks in advance -
ImportError: cannot import name suggest_extension
I cannot import suggest_extension about imagekit I tried reinstall imagekit and pilkit but id did not solved how can i solve this problem? environment mac os django -
IOError [Errno 21] Is a directory: u'<path to templates>'
I have been working with Django 1.6. Everything working fine. Recently, I found that later versions of Django have better features and hence upgraded my django using pip install -U Django. It got updraded to 1.10.6. Now I am getting this error. (with DEBUG=True) Django Version: 1.10.6 Exception Type: IOError Exception Value: [Errno 21] Is a directory: u'<absolute_path_to_templates>' Exception Location: /usr/local/lib/python2.7/dist-packages/django/template/loaders/filesystem.py in get_contents, line 24 Python Executable: /usr/bin/python Python Version: 2.7.6 And this: Error during template rendering In template <path_to_template>/code1.html, error at line 1 1 {% extends "code2.html" %} Did I miss anything that is to be done after upgrading Django to 1.10.6 ? BTW, If I run with DEBUG = False, it does launch the app but my static files (js,css,images) are not getting loaded and also the UI is a bit distorted. Does Django 1.10.6 has different way of loading static files as compared to Django 1.6 ? Does extends have a different syntax in 1.10.6. I did google a lot didn't find anything useful for my case. My settings.py has this: STATIC_URL = '/static/' STATIC_ROOT = "<absolute path to static filesfolder>/static" Following some suggestion online, I tried adding STATICFILES_DIRS = (BASE_DIR,'static') instead. Earlier I was very clear …