Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Quick database update based on previous value in Django
I have a QuerySet which contains Page objects, which have page_number attribute. The QuerySet is sorted by page_number, so running [i.page_number for i in pages_query_set] would return something like, for example, [1,2,3,5,6,10,11,13,16,19,21]. My task is to write a method that moves the Page objects so they would be consecutive: in this example, the page that was 5 would become 4, 6 would become 5, 10 would be 6, 11 is 7, 13 is 8, etc. This is my initial solution, a method inside PageQuerySet class: def validatePageNumbers(self): prev_page = 0 for page in self: if page.page_number > prev_page+1: page.page_number = prev_page+1 page.save() prev_page = page.page_number Functionally, it works fine. But calling save() every time really slows it down (probably due to calling database queries every time). I need to find a faster approach. If there had been only one "gap" in this sequence, I would just slice the QuerySet and use something like sliced_qs.update(page_number=models.F('page_number')-gap), because I've seen a singular update() being much faster than several save(). But the gaps are multiple and pretty random. So I'm confused. F objects don't seem to support such looping. It would be great if I could use a callable in update(), but I haven't … -
Django : How work template.Variable
I hava a view : def simple_view(request): return render(request, 'template.html', {'begin': 1, 'end': 42}) And this is a part of my RandomNode class : class RandomNode(template.Node): def __init__(self, begin, end): self.begin = begin self.end = end def render(self, context): not_exist = False try: begin = template.Variable(self.begin).resolve(context) self.begin = int(begin) ... I want to understand how work this line : begin = template.Variable(self.begin).resolve(context) Doc say : To use the Variable class, simply instantiate it with the name of the variable to be resolved, and then call variable.resolve(context) So in my example, I instanciate Variable with self.begin and not begin, why it's working ? In second time, I want to understand why is important to check if a variable exist in a context template when I use a custom tag with variables paramaters ? I can just test if variables are not None... for example If I call {% random a b %} if b is not defined in my template context, what is the risk ?? Thank you -
Using Twilio For East Africa - Kenya, Tanzania, Malawi
We have now created a beta GIS platform (PostgreSQL, Django, Leaflet) that also enables users to send SMS messages to a Twilio number, which are then viewed within the app and then annotated by admins to reports. The aim of these crowd-sourced reports is to empower local communities in rural East Africa with a voice to share incidents relating to water pollution and sanitation. We will be showcasing the web GIS platform to the wider international community (who have come together in East Africa to deal with this issue - known as the 'maji programme'). To cut it short, we are using Twilio to receive SMS messages and currently only have a UK mobile number joined to the account. In order to conduct a field trial, it is very, very important that we can enable citizens to report and send SMS messages to a more local mobile number, namely Kenya and Tanzania, with Malawi soon to follow. Having recently seen that Twilio has added support for Kenya, we are looking to see how Tanzania and Malawi might be addressed. Is it a case that we wait for Twilio to roll out support in these countries (already sent them that question) … -
Django command leaks memory
In our project, we have a Django command like: class Command(BaseCommand): def handle(self, *args, **options): for event in Event.objects.all().order_by('-id').iterator(): event.do_stuff() event.do_stuff() performs some more database lookups and then saves the result. All of event.do_stuff() calls are distinct and does not influence one another. The problem is that if there are more than 100k events, process consumes more and more memory until it is killed. It is impossible for one event.do_stuff() call to use so much memory. One workaround is to run this command with 50k batches of events. To me, it seems like a problem in Django caching of queries performed inside event.do_stuff() call. Is there any way how to clear Django model cache? Or can this be caused by something else? We use Django 1.8.4. -
Django display properties in the order as passed to values
I use Django framework and I try to run a query as below; ComDiseases.objects.filter(bs_date='12/2016', district=2).values('com_disease', 'male', 'female', 'children', 'elderly') The result I got is: [{'elderly': 8, 'com_disease': u'Dengue', 'male': 5, 'children': 7, 'female': 6}, {'elderly': 8, 'com_disease': u'Diarrhea', 'male': 5, 'children': 7, 'female': 6}] But I want my result to display properties in the same order as passed to the values, that means; [{'com_disease': u'Dengue', 'male': 5, 'female': 6, 'children': 7, 'elderly': 8}, {'com_disease': u'Diarrhea', 'male': 5, 'female': 6, 'children': 7, 'elderly': 8}] Is there a way I can achieve this, I read the documentation and other posts but I couldn't find any successful answer for this. Appreciate your help on this. -
django, examples of using a callable for choices in forms.ChoiceField
In Django documentation, it says that the choices= parameter for forms.ChoiceField can be a callable. https://docs.djangoproject.com/en/1.10/ref/forms/fields/ Anyone there that can give me an example of how that would look like? Can't find any more about it in the official documentation. Thanks! -
Update Django server after crating thumbnail with AWS Lambda
I have a Django web project that is using Amazon S3 for media files. The file upload is happening async direct from the browser. I need to create some thumbnail images for each file that is uploaded. I found a tutorial for how to do this using AWS Lambda (which I've never used before) but seems like the future of web. The only issue I am trying to figure out in my head is: how I will update my database back on the django web server with the information for the newly created thumbnail images? I intend to create a new database model (thumbnails) that will store the URL and tie the thumbmail to the main image information. The only thing I have come up with is to expose a url on my web app to accept HTTP requests (assuming lambda can send HTTP requests). So when the lambda function completes a thumbnail image, it will send the request to my web app with the information for the newly created thumbnail image using POST or PUT. The thing I don't like about this approach is that it won't work when developing locally. Does anyone have any experience using Lambda to … -
Django: call python function when clicking on button
Let's say that I have a python function that only sends email to myself, that I want to call whenever the user clicks on a button in a template, without any redirection (maybe just a popup messege). Is there a way to do that? -
ImportError: No module named engine - Django suit related?
I am using Django and Django Suit V2 - I am trying to create a custom home page for my django site using templates. I keep getting this error: File "/usr/local/lib/python2.7/dist-packages/suit/apps.py", line 89, in add_suit_default_template_tags from django.template.engine import Engine ImportError: No module named Engine I want to make sure of what I'm doing before I go in and mess with the main files. But I also notice another problem - is I have a virtual environment - this is pointing to my local files rather than my venv site-packages. Anyone else deal with "No module named Engine" error before? Any Suggestions? -
manage.py runserver fails "Process finished with exit code 1073741819"
I've been working on a django project for a while and I just moved it all to my brand new laptop. After installing everything that I should need to run my Django project with Pycharm, I get the following error when I try to debug it: Performing system checks... Process finished with exit code 1073741819 The same project works perfectly fine on my main computer, so I assume I must be missing something on my laptop. Also, if I try to use 'python manage.py runserver' directly from the console, I receive a windows message saying that "Python has stopped working" Any idea what could trigger that? -
Type Error: is not JSON serializable
I`m trying to pass database objects from one view to another view. But when I try to achieve this using SESSION, I am getting this "is not JSON serializiable" error. My Views.py: def index(request): listset = TheaterBase.objects.all() request.session['s_listset'] = listset def otherview(request): result = request.session.get('s_listset') How to pass the Database objects in between the views? Thanks in advance -
Django settings as a class attributes
I want to use django settings as a class attributes, something like this: from django.conf import Settings, settings class DjangoSettings: INSTALLED_APPS = [...] MIDDLEWARE_CLASSES = [...] ROOT_URLCONF = 'project.urls' TEMPLATES = [...] WSGI_APPLICATION = 'project.wsgi.application' DEBUG = True ALLOWED_HOSTS = [] ... settings.configure(options=DjangoSettings) It results in exception: CommandError: You must set settings.ALLOWED_HOSTS if DEBUG is False. I pass DjangoSettings to options because I need default_settings not to be overwritten. Some notes: I need django settings exactly as class attributes, not instance attributes. Configuration without os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings") but with settings.configure() I use Django 1.10.4 -
Django .values_list() alternative that returns a QuerySet for a ForeignKey field's model?
I'm looking for a clean way to convert one type of QuerySet to another based on a models ForeignKey field, so basically something like a .values_list('my_fk', flat=True) but returning a proper QuerySet instead of a values_list() variant. For example: class Parent(models.Model): child = models.ForeignKey(Child) ... children_qs = Parent.objects.filter(...).theMagicMethod('child') Here children_qs should now be a queryset for all Child instances used in the earlier query, instead of a queryset returning Parent instance. You can sort of do this with a custom queryset and an __in lookup but it feels a bit smelly: class ParentQuerySet(models.QuerySet): ... def children(self): return Child.objects.filter(id__in=self.values_list('child_id', flat=True)) This takes all the child_id FK's from the records in the Parent's queryset and re-query Child directly. When I inspect the SQL it does a sub query, and I'm not sure if this is optimal or has some odd side effects. It does look like the ordering from the original Parent query is gone, and so are duplicates. Does anyone got something better then this? -
can't click category url Django 1.10
enter image description here I see URL, but click on it not goving at page. If I go directly to the link, the page opens. In my opinion the matter lies in the def post_list model class Category(models.Model): name = models.CharField(max_length=128, unique=True, verbose_name='Название') slug = models.SlugField(unique=True) image = models.ImageField(null=True, blank=True, verbose_name='Изображение') def save(self, *args, **kwargs): self.slug = slugify(self.name) super(Category, self).save(*args, **kwargs) class Meta: verbose_name = 'Категории' verbose_name_plural = 'Категории' def __str__(self): # For Python 2, use __unicode__ too return self.name def get_absolute_url(self): return reverse('show_category', kwargs={'slug': self.slug}) class Post(models.Model): category = models.ForeignKey(Category, default=1, verbose_name='Категория') user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1, verbose_name='Пользователь') title = models.CharField(max_length=120, verbose_name='Заголовок') slug = models.SlugField(unique=True) image = models.ImageField(null=True, blank=True, verbose_name='Изображение') content = models.TextField(max_length=10000, verbose_name='Контент') updated = models.DateTimeField(auto_now=True, auto_now_add=False, verbose_name='Обновлено') timestamp = models.DateTimeField(auto_now=False, auto_now_add=True, verbose_name='Создано') keywords = models.CharField(max_length=1024, blank=True, null=True) description = models.CharField(max_length=1024, blank=True, null=True) class Meta: verbose_name = 'Статьи' verbose_name_plural = 'Статьи' ordering = ["-timestamp", "-updated"] def __str__(self): # For Python 2, use __unicode__ too return self.title def get_absolute_url(self): return reverse('detail', kwargs={'slug': self.slug, 'category': self.category}) views only problem page def post_list(request): queryset_list = Post.objects.all() category_list = Category.objects.all() search = request.GET.get("s") if search: queryset_list = queryset_list.filter( Q(title__icontains=search) | Q(content__icontains=search) #| #Q(user__first_name__icontains=search) | #Q(user__last_name__icontains=search) ).distinct() paginator = Paginator(queryset_list, 5) # Show 5 … -
How to add Remote virtual environment python interpreter in pycharm along with vagrant
I am running pycharm in my windows box, while my Django project is running inside vagrant ubuntu box, I am pulling all my project files to window pycharm along with the remote python interpreter(which is OS default). The problem is I am not able to setup the remote virtualenv python interpreter. How to set up remote virtualenv python interpreter in pycharm ? not the default OS one. -
How to dumpdata from django-tenant-schemas?
I am trying to use manage.py dumpdata on my app's model but I am not able to see the json data in my dump file as I am using the django-tenant-schemas app to manage models for various clients. Is there any solution to dumpdata related to specific schema? -
Django - Is it okay to have a model with only one field?
In 5th grade when we learned how to outline a research paper, our teacher taught us that you should never have a single bullet point. I feel like I am breaking this rule, and there might be a better way. I have model, Movie, which has fields like title and year. I want to also include genre. However, movies can fall into more than one genre. So I feel like I need to have a many-to-many relationship. But I don't really want to make Genre it's own model class, because there would only be one field, Genre.genre. It seems wrong to me. I know I could have genre be a CharField and separate genres with some sort of a separator sentinel, ie action|adventure|comedy. But is that the best way to do it? I am planning to run raw SQL queries against this database, so simplicity is of high value right now. -
Migrating a a website to Django/Flask
The context: I'm migrating a website that was made in pure HTML/CSS. it contains dozens of pages and hundreds (maybe thousands) of images and scripts references. My question: is there any thing or any trick for automating the task of changing the links for the templating system (I mean, changing filename.img into {{url_for('static', filename='myimage.img') }}) other than having to manually skim over the dozens of pages and change that manually? -
Git local master branch displays differently to live version, even though it's up-to-date
I have been working on one of the pages of my Django project on my local Git branch, and am now looking to merge those changes with my master branch. I have checked out my local master branch, and viewed the page locally in the browser, however, what is being displayed by my local master branch is different to what is being displayed on the live version of the project. When I view this particular page on the live version, it displays a PDF embedded in a 'tabbed content' area within the webpage, and on one of the tabs, the PDF shows a table with four columns. However, when I view this page on my local master branch, the same tab shows a PDF displaying a table with only two columns... (choosing which columns to display on the PDF was the thing that I was most recently working on). I have tried running a git pull origin master from my local master branch, to make sure that my local version is the same as/ up-to-date with the version on the live server, and Git displays a message stating that it is Already up-to-date But if this is the case, then … -
Django read Static JSON file directly using Ajax call?
It may not sounds good, but in my case I have static json files in the application and I want read them directly using AJAX call without having to create separate service call.A separate service call is required because URL pattern does not match and so I will get 404. Can I achieve this in Django? Thanks -
Get all match records based on their last child in Django ORM?
I have these two classes in my models.py : class BaseObject(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) create_date = models.DateTimeField(auto_now_add=True) update_date = models.DateTimeField(auto_now=True) class Meta: ordering = ['create_date'] class Person(BaseObject): first_name = models.CharField(max_length=30, null=True, blank=True) last_name = models.CharField(max_length=30, null=True, blank=True) phone_number = models.CharField(max_length=15,unique=True) gender = models.CharField(max_length=1,choices=PERSON_GENDER,default='M') birthday = models.DateField(null=True, blank=True) email = models.EmailField(null=True, blank=True) class Driver(Person): balance = models.PositiveIntegerField(null=True, blank=True) score = models.PositiveIntegerField(null=True, blank=True) class Position(BaseObject): person = models.ForeignKey(Driver, on_delete=models.CASCADE) latitude = models.FloatField() longitude = models.FloatField() As you can see each driver may have several positions by passing the time. I want a query using Django ORM that gives me last position of each driver, imagine that i receive a latitude and longitude from client and wish to return all cars that is near. I tried this : radius = 5 drivers = Driver.objects.filter(position__latitude__range=(data.get('latitude') - radius, data.get('latitude') + radius))\ .filter(position__longitude__range=(data.get('longitude') - radius, data.get('longitude') + radius))\ But the problem is that i give a single driver several time based on his saved positions. Now i just want to get the drivers based on their last update position, not previous positions. Thankyou -
django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named 'MySQLdb'
I have created a django project for which i used MySQL database. I have mysql-python connector in mysql installed tools. I am not sure whether i set a required path in environmental variables. When i running the server, it raising an error : django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named 'MySQLdb'. I would appreciate helping me solve this. Traceback: Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x0000000004F167B8> Traceback (most recent call last): File "c:\python34\lib\site-packages\django\db\backends\mysql\base.py", line 25, in <module> import MySQLdb as Database ImportError: No module named 'MySQLdb' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "c:\python34\lib\site-packages\django\utils\autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "c:\python34\lib\site-packages\django\core\management\commands\runserver.py", line 113, in inner_run autoreload.raise_last_exception() File "c:\python34\lib\site-packages\django\utils\autoreload.py", line 249, in raise_last_exception six.reraise(*_exception) File "c:\python34\lib\site-packages\django\utils\six.py", line 685, in reraise raise value.with_traceback(tb) File "c:\python34\lib\site-packages\django\utils\autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "c:\python34\lib\site-packages\django\__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "c:\python34\lib\site-packages\django\apps\registry.py", line 108, in populate app_config.import_models(all_models) File "c:\python34\lib\site-packages\django\apps\config.py", line 199, in import_models self.models_module = import_module(models_module_name) File "c:\python34\lib\importlib\__init__.py", line 104, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 2231, in _gcd_import File "<frozen importlib._bootstrap>", line 2214, in _find_and_load File "<frozen importlib._bootstrap>", line 2203, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line … -
Django: getting just first element, not all using filter
I have three models that looks like this: class Blog(models.Model): name = models.CharField(max_length=100) user = models.OneToOneField(User) def __unicode__(self): return self.name class BlogPost(models.Model): title = models.CharField(max_length=100) blog = models.ForeignKey(Blog) def __unicode__(self): return self.title class Stream(models.Model): user = models.OneToOneField(User) blog = models.ManyToManyField(Blog, blank=True) def __unicode__(self): return '%s' % self.user In steam object i have two blog objects. In first blog object i have three blogpost in the second is the same. Then i create queryset: stream = Stream.objects.get(pk=1) blog = Blog.objects.filter(stream=stream) print (blog) <QuerySet [<Blog: Blog object>, <Blog: Blog object>]> blogpost = BlogPost.objects.filter(blog=blog) print (blogpost) <QuerySet [<BlogPost: BlogPost object>, <BlogPost: BlogPost object>, <BlogPost: BlogPost object>]> In blogpost I get only from first blog object elements not from all. Anybody know why it happens? -
Git- understanding the output of diff command
I have recently started working on a Python/ Django project that uses Git as its version control. I am relatively new to Git, having not used it much before. I currently have a number of branches of development- and want to merge some of the changes on my current branch with the master, but don't want to merge all of the changes from this branch. My thought was to compare the particular files on my local branch where the changes that I want to merge are, with the same files on the master branch, so that I could see which changes I want to keep, and which ones I want to discard. I was then planning on creating a new branch from master, and manually copying over the few changes that I want to keep from my current local branch. I ran the following command from my local branch: git diff budgetsReports3 master -- costing/views.py in order to see the differences between the views.py file in the costing app on my local budgetsReports3 branch and the master branch. This command has produced the following output: diff --git a/costing/views.py b/costing/views.py index 452b082..f8a3f77 100644 --- a/costing/views.py +++ b/costing/views.py @@ -1324,12 +1324,6 @@ … -
Only allow Select One Django_tables2
I have a table that populates on using django_tables2, with two columns: tables.py class SummaryTable(tables.Table): update = CheckBoxColumnWithName(verbose_name = "Select",accessor="pk", orderable=False) class Meta: model = Vehicle fields = ('update', 'vehid') # Add class="paleblue" to <table> tag attrs = {'class':'paleblue'} Columns update and vehid. What I need is to restrict the user to only select one checkbox, if they select another checkbox, it unselects the first and selects the new choice. Can anyone advise how to do this?