Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django deleting querysets with paging, not catching all parts of the set
I have a bit of a strange problem that I'm not quite able to explain. I have a django project with some old, stale objects lying around. For example, lets say my objects look something like this: class blog_post(models.Model): user_account = models.ForeignKey('accounts.Account') text = models.CharField(max_length=255) authors = models.ManyToManyField(author) created = models.DateTimeField(blank=True, null=True) This is not an exact copy of my model, but is close enough. I've created a management command to build ordered querysets of these objects, and then delete with with a Paginator My command looks something like this: all_accounts = Account.objects.all() for act in all_accounts.iterator(): stale_objects = blog_post.objects.filter(user_account=act, created=django.utils.timezone.now() - datetime.timedelta(days=7)) paginator = Paginator(stale_objects.order_by('id'), 100) for page in range(1, paginator.num_pages + 1): page_stale_objects = blog_post.objects.filter(id__in=paginator.page(page).object_list.values_list('id')) page_stale_objects.delete() The problem I'm having is, after I delete these objects with my command, there are still objects that fit the queryset parameters but are not deleted. So, I have to run the command 3+ times to properly find and remove all the objects. I first figured that my date range was just weirdly on the edge of the DateTime so was not catching objects made shortly after 1 week past my command time. This is not the case, I've removed the created=... … -
Using pip runs into an error
I setup an venv with python3 and wanna install all my needed packages with pip. On Python2.7 it works very well, but with Python3 I run into the following error: pip install Django==1.11.0 pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available. Collecting Django==1.11.0 Could not fetch URL https://pypi.python.org/simple/django/: There was a problem confirming the ssl certificate: Can't connect to HTTPS URL because the SSL module is not available. - skipping Could not find a version that satisfies the requirement Django==1.11.0 (from versions: ) No matching distribution found for Django==1.11.0 I have seen that there is a possible solution (not verified by myselfe) to get a pem-file with the certificate into my system. Now my questions: is it possible to deactivate this SSL/TSL setting? in case of Django, how to get and use the certificate to work with pip successful? is a list with all verified (by the community) certificate availablie to run this for all packages? -
Altering unique fields of inherited Django model
In Django, I'm trying to create a base model that can be used to track the different version of some other model's data in a transparent way. Something like: class Warehouse(models.Model): class Meta: abstract=True version_number = models.IntegerField() def save( self, *args, **kwargs ): # handling here version number incrementation # never overwrite data but create separate records, # don't delete but mark as deleted, etc. pass objects = CustomModelManagerFilteringOnVersionNumber() class SomeData(Warehouse): name = models.CharField( unique=True ) The problem I have is that SomeData.name is actually not unique, the tuple ('version_number', 'name' ) is. I know I can use the Meta class in SomeData with unique_together but I was wondering whether this could be done in a more transparent way. That is, dynamically modifying/creating this unique_together field. Final note: maybe handling this with model inheritance is not the correct approach but it looked pretty appealing to me if I can handle this field uniqueness problem. -
Django static files action
I am new in django and i Faced one problem. Sometimes when i edit static files as CSS and JS Django does not understand the changes and they do not happen immediately. Why? Thank you in advance! -
Is it faster to obtain current user data by using a filter or related object reference?
Which of the two methods are quicker in obtaining current user specific data? For example: class FriendProfileDetail(ListView): model = Friend def get_queryset(self): return self.model.objects.filter(friend_of=self.request.user.profile) VS class FriendProfileDetail(ListView): model = Friend def get_queryset(self): queryset = self.request.user.profile.friends.all() return queryset -
Adapt the new method
LOANWOLF_BANK_ACCOUNTS_LENGTH = { '001': {7}, # Banque de Montréal '002': {7}, # Scotia '003': {7}, # RBC '004': {7, 11}, # TD (7 or 11) '006': {7}, # BNC '010': {7}, # CIBC '016': {9}, # HSBC '039': {9}, # Banque Laurentienne '614': {10}, # Tangerine '815': {7}, # Desjardins '829': {7}, # Desjardins Ontario } has been modified so that it works with def clean_bank_account(self): bank_account = self.form.cleaned_data.get('bank_account') bank_transit = self.form.cleaned_data.get('bank_transit') if bank_account not in (None, ''): bank = self.form.cleaned_data.get('bank') if bank not in (None, ''): # Check bank account format for specific banks length = settings.LOANWOLF_BANK_ACCOUNTS_LENGTH.get(bank) if length: if bank_transit not in (None, ''): if not bank_account.isnumeric() or (len(bank_account) not in length): raise ValidationError( _('Bank account number must contain {} digits').format(' or '.join(map(str, sorted(length)))) # noqa ) else: raise ValidationError( _('Cannot validate bank account without a valid bank transit') # noqa ) return bank_account How could I modified the random_bank_transit method to that it will the same function? That method is simply def random_bank_account(bank): # 815-69919 450-634-1 acct_len = settings.LOANWOLF_BANK_ACCOUNTS_LENGTH.get(bank) out = [str(random.randint(1, 9))] + [ str(random.randint(0, 9)) for i in range(0, acct_len - 1)] return int(''.join(out)) For more informations, look at the following link Working with multiple … -
Django after inspectdb MSSQL do migrte , shows _alter_column_type_sql() takes exactly 4 arguments (5 given)
this code is base on python2.7 when I do the migrate , after inspectdb this is my error message model._meta.db_table, old_field, new_field, new_type TypeError: _alter_column_type_sql() takes exactly 4 arguments (5 given) plz help -
how to use django markdown in my blog
at first I successfully install django markdown pip install django-markdown than I add django-markdown in my setting.py file INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog', 'django-markdown', ] then, I change my urls.py like as: from django.conf.urls import include, url from django.contrib import admin from resume import views urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^home/$', views.home, name='home'), url(r'^blog/', include('blog.urls',namespace='blog',app_name='blog')), url('^markdown/', include('django_markdown.urls')), ] I also change my admin.py file like as: from django.contrib import admin from .models import Post from django_markdown.admin import MarkdownModelAdmin class PostAdmin(admin.ModelAdmin): list_display = ('title','slug','author','publish','status') list_filter = ('status','created','publish','author') search_fields = ('title','body') prepopulated_fields = {'slug':('title',)} raw_id_fields = ('author',) date_hierarchy = 'publish' ordering = ['status','publish'] # Register your models here. admin.site.register(Post,MarkdownModelAdmin, PostAdmin) but, when I start my runserver, django gives me an error like this: ModuleNotFoundError: No module named 'django-markdown' how can i solve my problem? -
Amazon s3 file download
I am working Django REST framework / AngularJS based web application. I am going to use amazon s3 to save all the images used in UI. But one problem: I want Only logged-in user could access these images - so I hate direct accessing to image files on s3 bucket via url like this: https://racerx-snap4that-media.s3.amazonaws.com/images/iPhone6White-1.png In other word - This link should work for only authenticated user. Is there any solution or protect policy for this? Please help me. -
how to save form to database (Django Python)
In my Django app I have a form with an email and a text area that needs to go into the database but am struggeling to do so. At the moment I have 2 different solutions in my code: the code -
Extending User model in Django
I am trying to create a profile model for all of my users. I have the following code in which I get one custom field birth_date, but cannot seem to get any of my other custom fields to work: forms.py: from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class SignUpForm(UserCreationForm): birth_date = forms.DateField(help_text='Required. Format: YYYY-MM-DD') class Meta: model = User fields = ('username', 'first_name','last_name', 'birth_date','location', 'password1', 'password2', ) models.py: from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=500, blank=True) location = models.CharField(max_length=30, blank=True) birth_date = models.DateField(null=True, blank=True) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() views.py from django.contrib.auth import login, authenticate from django.shortcuts import render, redirect from django.http import HttpResponse from .forms import SignUpForm def home(request): return HttpResponse('fd') def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): user = form.save() user.refresh_from_db() # load the profile instance created by the signal user.profile.birth_date = form.cleaned_data.get('birth_date') user.profile.college = form.cleaned_data.get('college') user.save() raw_password = form.cleaned_data.get('password1') user = authenticate(username=user.username, password=raw_password) login(request, user) return redirect('home') else: form = SignUpForm() return render(request, 'accounts/profile.html', {'form': form}) urls.py urlpatterns … -
Lot of threads for a simple django command
I just created a very simple command in a django (1.11.1) app as follow: simple_command.py import time from django.core.management import BaseCommand class Command(BaseCommand): def handle(self, *args, **options): while True: time.sleep(5) When I run python manage.py simple_command.py the process spawn 104 threads. Im counting the number of thread with ps -o nlwp ${PID}. Is this normal? It looks like lot of thread for such a simple command. Am I wrong here ? How can I do to lower the number of threads ? -
Using Swift websockets with PHP or Djangp/Python
How can I create a chat application using Swift with a backend using PHP or Python. I looked everywhere for someone showing this but couldn't find anything. I am not fully grasping the concept on how websockets is used in swift and in my backend also. If anyone can provide an explanation and refer me to someone implement a chat application with swift and PHP or Python as backend, it will be greatly appreciated Thanks -
Translating PostGIS query to GeoDjango
I am trying to figure out how to translate a PostGIS query to GeoDjango that uses two different tables, this is an example of a query I need to do SELECT a.* FROM county a, cd b WHERE a.state = 'Virginia' AND b.state = 'Virginia' AND b.cd114fp = '06' AND ST_Contains(b.geom, a.geom) This is the docs for geodjango queries https://docs.djangoproject.com/en/1.11/ref/contrib/gis/geoquerysets/ however, it doesn't go over how to do a more complicated query like the one above, and I'm not too familiar with django queryset. -
Deploying a Django Application to Elastic Beanstalk
I am new to Django and I am trying to deploy a Django App on AWS following the tutorial on AWS here. Everything works fine until I execute the command eb create django-env. The deploy exits with an error message: Invalid requirements.txt. In the log file I have the following: Collecting Django==1.9.12 (from -r /opt/python/ondeck/app/requirements.txt (line 1)) Downloading Django-1.9.12-py2.py3-none-any.whl (6.6MB) Collecting pkg-resources==0.0.0 (from -r /opt/python/ondeck/app/requirements.txt (line 2)) Could not find a version that satisfies the requirement pkg-resources==0.0.0 (from -r /opt/python/ondeck/app/requirements.txt (line 2)) (from versions: ) No matching distribution found for pkg-resources==0.0.0 (from -r /opt/python/ondeck/app/requirements.txt (line 2)) I am sorry if the issue may be trivial, but can anyone point to the right direction? Thank you in advance! -
Django display data from mysql to HTML table
I have a problem when i use Django to display data from mysql to HTML table. VIEW: @login_required(login_url='/login') def data_to_list(request): data_list = ES_device.objects.all() context = {'data_list': data_list} #return render(request, 'logfile/data_bi.html', context) return render_to_response('logfile/data_bi.html',locals()) MODEL: class device(models.Model): device_name = models.CharField(max_length=200, verbose_name='aaa', default=None) device_type = models.CharField(max_length=200, verbose_name='bbb', default=None) URL: url(r'^data_bi', data_to_list) HTML: <th>..</th> ... for item in data_list <tb>item.device_name</tb> <tb>item.device_type</tb> end for ... but the result just shows the table head, no 's results, why this happen?how to solve this? Thanks for your help! -
Use newly created object in receiver
Is it possible to use the newly created object in the receiver? similar from django.db import models from django.dispatch import receiver class MyModel(models.Model): text = models.CharField(...) ... @receiver(models.signals.post_save, sender=MyModel) def execute_after_save(sender, instance, created, *args, **kwargs): if created: # for example n = newObj.title -
Audio Editor in a Django App?
I'm in a little over my head with a project for a client, they want to build an audio editor that will allow the user to trim their uploaded audio files and save them. I've built the file uploader, and the detail view for the individual audio files, my question is how would this best be implemented? I've been looking at Peaks.js and I want to make sure thats the right way to go before diving in. Never used npm in a django project before, is it like using any other js library? I've also been told about sox, which is great for manipulating the sound files, but what about displaying the sound to the user/editing in the browser? Any help or general direction-pointing would be greatly appreciated and could save me a bunch of time potentially. -
dj-stripe does not allow extended current period end
I am using dj-stripe 0.8.0 on a test site to collect subscription payments with django 1.10.5 and Python 3.5. The payments system works and acts as it should. I have the live stripe payment system working on a staging site. How do I extend selected users CURRENT PERIOD END date past the designated expiry date of the users subscription date? Here is a screen shot of the users dj-stripe details, where I have extend the users CURRENT PERIOD END date to 2025-06-30. The users subscription is for 3 months, but I want to extend the expiry date past the date of 2017-08-08. Here is another screen shot of the users dj-stripe details, where I have extended the users CURRENT PERIOD END date AND added in TRIAL START and TRIAL END dates that I thought would handle this issue. Again, the users subscription is for 3 months, but I want to extend the expiry date past the date of 2017-08-08. But this is the screen shot that the users details are always reset back to: I have also tried to change the START date to a future date, but this is always reset back to the date of 2017-08-08. Is there … -
Traversing Django Foreign Keys efficiently for query sets
I'm having trouble efficiently getting (second degree) related objects. My models currently look like this class Transaction(models.Model): from_account = models.ForeignKey(Account, related_name="sent") to_account = models.ForeignKey(Account, related_name="recieved") ... class Account(models.Model): address = models.CharField(max_length=42, primary_key=True) ... What I have been doing so far to get an aggregated list of transaced_with for an account is as follows: accs = [] if hasattr(account, 'recieved'): for tx in account.recieved.all(): acc = tx.from_account accs.append(acc) if hasattr(account, 'sent'): for tx in account.sent.all(): acc = tx.to_account accs.append(acc) return accs This way however is very slow, so I was wondering, what is the the efficient way to aggregate these sort of related objects? What I want in the end is a list of address from the Accounts in accs -
All Fields of Django Model Entry Comma Separated
The code in the two if-blocks smells to violate DRY. How can it be written more generic? selected_class = eval(choice) records = selected_class.objects.all() if (choice == 'Treatment'): for record in records: response.write(str(record.id) + ',' + str(record.available_hours) + '\n') if (choice == 'Patient'): for record in records: response.write(str(record.id) + ',' + record.first_name + '\n') I could write in each model (Treatment and Patient) a method 'make_csv'. But, there must be a better way. -
How do I show the message of the input box after submitting my form?
I am building a form. And I wish to keep the input value visible after submitting the form. I followed some instructions online to use the showMessage() function, however, it's not working for me. <form id = "form1" action="." method="POST">{% csrf_token %} <div class=".col1" style="float:left;vertical-align: middle;"> {{ form.region }} {{ form.operator }} </div> <div id = "form1_value" class="col-xs-2 style="vertical-align: middle;"> {{ form.value }} </div> </form> <div> <input type="button" class = "btn" value="Run" onclick="SubmitForm1(), showMessage()"/> </div> -
cannot loading custom CSS in Django ontop of Bootstrap
I am able to load my static images, however; when it comes to loading my custom css sheets I cannot seem to get it working. Because my static images are loading,Ii believe that my settings.py is set up properly, however, I could be wrong. My static files for css and images are located within /static/img/hive.png and /static/css/main.css respectively. Any help is greatly appreciated! settings.py import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) ALLOWED_HOSTS = [] DEBUG = True INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'ideas.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'ideas.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True STATIC_URL = '/static/' home.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> … -
Getting the "latest" field in a set to serialize in Django Rest Framework
My current serializer looks like so: class BareboneEntitySerializer(serializers.ModelSerializer): class Meta: model = Entity fields = ( 'id', 'label', 'related_yid_count', 'description', ) There is one set: entityclassification_set Now, in my other serializer I have it like so: entityclassification_set = EntityClassificationSerializer(many=True) But after some time, I realized I only need the "latest" or the last element in the set, how can I add this field to the serializer? Is adding a property the only way to go about this? Or is there another way to do it? -
Split list of dictionaries into chunks
I have a python list with two list inside(one for each room - there are 2 rooms), with dictionaries inside. How can i transform this: A = [ [{'rate': Decimal('669.42000'), 'room': 2L, 'name': u'10% OFF'}, {'rate': Decimal('669.42000'), 'room': 2L, 'name': u'10% OFF'}, {'rate': Decimal('632.23000'), 'room': 2L, 'name': u'15% OFF'}, {'rate': Decimal('632.23000'), 'room': 2L, 'name': u'15% OFF'}], [{'rate': Decimal('855.36900'), 'room': 3L, 'name': u'10% OFF'}, {'rate': Decimal('855.36900'), 'room': 3L, 'name': u'10% OFF'}] ] Into This: A = [ [{'rate': Decimal('669.42000'), 'room': 2L, 'name': u'10% OFF'}, {'rate': Decimal('669.42000'), 'room': 2L, 'name': u'10% OFF'}], [{'rate': Decimal('632.23000'), 'room': 2L, 'name': u'15% OFF'}, {'rate': Decimal('632.23000'), 'room': 2L, 'name': u'15% OFF'}], [{'rate': Decimal('855.36900'), 'room': 3L, 'name': u'10% OFF'}, {'rate': Decimal('855.36900'), 'room': 3L, 'name': u'10% OFF'}] ] I need to create in the main list, three lists inside. one for each type of promo. Thanks