Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Filtering by condition in child of object in Django
Django 1.11. I have a model Cat: class Cat(OrderedModel): age = models.IntegerField() and a model Flea: class Flea(models.Model): dangerous = models.BooleanField() cat = models.ForeignKey(Cat) A cat can have many fleas. Cats are an ordered model. Given a position in this order, I want to get the next cat which has no dangerous fleas. My first attempt: def get_next_cat(self, current_pos): cat = Cat.objects.filter(order__gt=current_pos).first() fleas = Flea.objects.filter(cat=cat, dangerous=False) if fleas is None: return get_next_cat(current_pos + 1) return cat This seems verbose, and I would like to be able to perform this logic in the first statement of the method. I.e. to get the first next cat such as that cat's fleas all have false for their dangerous property. Is this possible? -
Django/Django-Tagulous Filter with tag amount
I have an app called Article. I'm using django-tagulous for tagging. I want to filter articles with the amount of same tags. Example: Article 1 and Article 2 have 10 tags. 4 of them are the same. Article 1 and Article 3 have 10 tags. 7 of them are the same. In this scenario Article 3 should be returned because 70% of the tags are the same. Another scenario: Article 4 has 4 tags, Article 5 has all tags of Article 4 plus 2 more. Article 4 has 4 tags, Article 6 has 2 tags of Article 4 plus 8 more. In this scenario Article 5 should be returned. I'm using a custom queryset on Article to filter for tags: class QuerySet(QuerySet): def tag_search(self, tags, this_article_id): tags = [tag for tag in tags] same = Article.objects.filter(Q(tags__in=tags)) same.exclude(id__in=[this_article_id]) same = [Article.objects.filter(id=s) for s in set(s.id for s in same)] return same my objects on Article: objects = CustomQuerySetManager() my CustomQuerySetManager: class CustomQuerySetManager(models.Manager): """A re-usable Manager to access a custom QuerySet""" def __getattr__(self, attr, *args): try: return getattr(self.__class__, attr, *args) except AttributeError: # don't delegate internal methods to the queryset if attr.startswith('__') and attr.endswith('__'): raise return getattr(self.get_query_set(), attr, *args) def get_query_set(self): return … -
NoReverseMatch Exception Value Reverse for 'books_recsys_app.views.home' not found
I am making a movie recommender app. This error occurs when searching for a movie in views.py. views.py data = post_data.get('data', None) if data: return redirect('%s?%s' % (reverse('books_recsys_app.views.home'),urllib.urlencode({'q': data}))) -
Remove default language prefix from url in django i18n
I'm using Django 1.5. I have setup internationalization in the project and has set up following variables in the settings.py file LANGUAGE_CODE = 'en' LANGUAGES = ( ('en', 'English'), ('es', 'Spanish') ) and the urls.py file contians urlpatterns += i18n_patterns('', url(r'^', include(app_urlpatterns)), ) But this appends en to every URL like https://example.com/en/dashboard I want to hide the default language from the URL pattern. I tried putting prefix_default_language=False in the url pattern urlpatterns += i18n_patterns('', url(r'^', include(app_urlpatterns)), prefix_default_language=False ) But this gives error as i18n_patterns() got an unexpected keyword argument 'prefix_default_language' How can I hide default language prefix from the URL in Django 1.5? -
Can't get value of excel formula by pandas read_excel except manually save the file again
I'm using xlsxwriter to create my excel file data.xlsx. The file contain some cell with formula: for example: =73-B2 Then I make a xhr query to read that data.xlsx by pandas (from django) pd.read_excel('data.xlsx','sheet_name="dn") However the first time read that file, value of the cell contains formula can't be get, except I manually open data.xlsx, save it.. then got the value. I found related question but there is not a solution -
no name "urls" in module django
I am unable to import from the django.urls package in Django 2.1.7 Really would like a solution to this problem. Can anyone help me with this issue? from django.urls import path from . import views urlpatterns = [ path(' ',views.index, name ='index'), ] -
how to send csv file directly to an ftp server
This is my function: def download_outage_info_all(request): upload_data = download_data_form(request.POST) if upload_data.is_valid(): print("valid") start = upload_data.cleaned_data['start_date_time'] end = upload_data.cleaned_data['end_date_time'] print(start, '-', end) start_timestamp = datetime.strptime( start, '%Y-%m-%d %H:%M') end_timestamp = datetime.strptime( end, '%Y-%m-%d %H:%M') try: info = planned_outages.objects.filter( start_timestamp__gte=start_timestamp, end_timestamp__lte=end_timestamp).values() except Exception as e: print("EXCEPTION", e) print("**** Data not found *** ") filename_date_part = datetime.now().strftime("%Y%m%d%H%M") response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment;filename=meteologica_availability_' + \ filename_date_part + '.csv' writer = csv.writer(response, delimiter=';') writer.writerow(['starts YYYY-mm-dd HH:MM:SS', 'time_zone', 'ends YYYY-mm-dd HH:MM:SS', 'asset id', 'availability type', 'PowerKW']) for x in info: try: unit_mw = unit_details.objects.get( unit_id=x['unit_id_id']) # prints to csv file writer.writerow([x['start_timestamp'], 'UTC', x['end_timestamp'], unit_mw.unit_name,x['availability_type'], x['capacity_kw']]) except Exception as e: print("EXCEPTION", e) print("**** Data not found for unit_mw*** ") return response This is a django view, I don't want to save the csv on my local system, I just want to directly send it to an ftp server. -
DRF - has_object_permission not called
So I looked through the similar questions on the same topic and I think I am following all the rules specified for has_object_permission. This is what I have in my settings. REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', 'users.permissions.CanAccessData', # this is my custom class ], . . . } This is my permission class class CanAccessData(permissions.BasePermission): message = 'You do not have permission to perform this action.' def has_permission(self, request, view): print "has_permission`" return True def has_object_permission(self, request, view, obj): print "has_object_permission" return False Here is my view structure: class CompleteList(generics.ListCreateAPIView): permission_classes = (CanAccessData,) serializer_class = SomeSerializer model = Some filter_backends = (filters.OrderingFilter, filters.SearchFilter) ordering_fields = (tuple of Some fields) search_fields = ordering_fields ordering = ('-create_date') Still, has_object_permission is not getting called, has_permission gets called though. Thanks. -
Django "List" and "Detail" Views for rows with duplicate fields
Duplicate Field rows! Duplicate Field rows! So I have a model Application with a field school_name which can take take duplicate values, among other fields. What I expect to achieve is: a "list" view of all duplicate school name values and their respective counts, and a "detail" view for each of the duplicated fields in that, when I click on a row in my 'list' view (or something of that sort), I'm able to view all the rows that contain this duplicate field, and the rest of the fields for that particular entry. What I mean is this: Listing the rows. Then when I click on row 1(Dedan Kimathi University of Technology), or click a detail button or something of the sort for row 1, I expect to get this: So far I have 2 queries: duplicates = Application.objects.values('school_name').annotate(name_count=Count('school_name')).filter(name_count__gt=0) The query above returns the duplicate rows and their count(as in image 1), while the one below, records = Application.objects.filter(school_name__in=[item['school_name'] for item in duplicates]) returns the other fields for the rows(as in image 2), only that it brings all the rows in the db. What I expect is, when I click a row on the 'list', I get a 'detailed' view … -
Django Execute Spesific Sql querry to Select and Monitoring Data
I have a MySQL database and I'm trying to make a Django app to reach latest data. What I'm trying to do is select latest data in my database and monitoring it, don't need to insert or update anything. I was using pure PHP before it and my querry was "SELECT id, source_id, MAX(time) FROM table WHERE id = %s AND source_id = %s",[id],[source_id] so i don't have any model in my django app since the table already exists and I just need to reach that data. I search internet and can't find any useful information. Is there any way? -
Django manytomany accessing related column
I'm trying to get my head around how Django understands m2m relationships, in SQL you would just add some joins through the intermediate table. I have a Container which contains various Samples. A Sample can be spread over various Containers. So in my container I add a alias samples m2m field (essentially a book mark to the other table). What I can do is get a single Container and display the form information, I would like to add the Sample columns to the form, if I do this for the samples m2m field it returns a multifield, but how do I access the other related fields through the m2m sample_id >=< container_id ? class Container(models.Model): container_id = models.AutoField(primary_key=True) samples = models.ManyToManyField(Sample, through='JoinSampleContainer', through_fields=('container_id', 'sample_id'), related_name='container') location_id = models.ForeignKey(Location, db_column='location_id', on_delete = models.PROTECT) icon_desc = models.ForeignKey(Icon, db_column='icon_desc', null=True, blank=True, default='Box',on_delete = models.PROTECT) container_name = models.CharField(max_length=50, blank=True, null=True) container_type = models.CharField(max_length=50, blank=True, null=True) In my Sample table I add the containers alias to act as a bookmark to the other table class Sample(models.Model): sample_id = models.AutoField(primary_key=True) containers = models.ManyToManyField(Container, through='JoinSampleContainer', through_fields=('sample_id', 'container_id'), related_name='sample') sample_number = models.IntegerField() material_type = models.CharField(max_length=200, default='', blank=True, null=True, choices = MATERIALS) weight = models.DecimalField(max_digits=6, decimal_places=2) description = models.CharField(max_length=500, … -
Is there a way to implement "Sort, Filter, Group by" in Django?
Is there a way to implement the following functions or features in Django, or Javascript has to be used (in template) Sort by (button) Group by Filter -
How do I use django's GenericStackedInline with an additional ForeignKey correctly?
I have the following django models: class Project(models.Model): name = models.CharField(max_length=255, verbose_name="Project Name") class ProjectMember(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name="members") user_or_group = models.Q(app_label='django.contrib.auth', model='User') | models.Q(app_label='django.contrib.auth', model='Group') member_content_type = models.ForeignKey(ContentType, editable=False, on_delete=models.CASCADE, limit_choices_to=user_or_group) member_object_id = models.PositiveIntegerField() member = GenericForeignKey('member_content_type', 'member_object_id') In django's admin, I would like to add ProjectMembers in the edit page of the Project model. I tried it like this: class ProjectMemberInline(GenericStackedInline): model = ProjectMember ct_field = "member_content_type" ct_fk_field = "member_object_id" extra = 1 @admin.register(Project) class ProjectAdmin(ModelAdmin): inlines = [ ProjectMemberInline, ] In the admin page of Project, I see the extra inline, but the only field in the form is (weirdly) project, although that should obviously be the project I'm editing. If I use StackedInline instead of GenericStackedInline, then project is not shown and I'm asked for the membe_object_id, which is correct. What am I doing wrong using GenericStackedInline here? -
django serializer manytomany field validation
I have a serializer and i want to validate if atleast one is selected from the many to many fields . I have two ManyToMany fields in the objects which are levels and categories. My serializer: class WorkflowSerializer(serializers.ModelSerializer): class Meta: model = Workflow fields = ('id', 'name', 'description', 'levels', 'categories') read_only_fields = ['id'] depth = 2 def validate_categories(self,categories): if len(self.categories)==0: raise serializers.ValidationError("You haven't selected any category,Please select alteast one") def validate_levels(self, levels): for level in levels: if len(level['permissions'])==0: raise serializers.ValidationError("You haven't specified a permission for the level") return levels Rn now the validationjs are not working as it should.The data is getting saved even if none is selected in the Many to Many field -
Heroku is using python instead of python3
I need a little help. After made some django apps i wanted to make something with heroku. But when I want to run heroku local web my heroku is using my python (version 2.7) but I need to use my python3 (veriosion 3.7). I'm using ubuntu upgraded to newest version. These are my errors: root@rudepeeter-VirtualBox:/home/rudepeeter/Documents/heroku_game/python-getting-started# /snap/bin/heroku local web [OKAY] Loaded ENV .env File as KEY=VALUE Format 9:52:24 AM web.1 | [2019-02-20 09:52:24 +0000] [3601] [INFO] Starting gunicorn 19.9.0 9:52:24 AM web.1 | [2019-02-20 09:52:24 +0000] [3601] [INFO] Listening at: http://0.0.0.0:5000 (3601) 9:52:24 AM web.1 | [2019-02-20 09:52:24 +0000] [3601] [INFO] Using worker: sync 9:52:24 AM web.1 | [2019-02-20 09:52:24 +0000] [3605] [INFO] Booting worker with pid: 3605 9:52:24 AM web.1 | [2019-02-20 09:52:24 +0000] [3605] [ERROR] Exception in worker process 9:52:24 AM web.1 | Traceback (most recent call last): 9:52:24 AM web.1 | File "/usr/local/lib/python2.7/dist-packages/gunicorn/arbiter.py", line 583, in spawn_worker 9:52:24 AM web.1 | worker.init_process() 9:52:24 AM web.1 | File "/usr/local/lib/python2.7/dist-packages/gunicorn/workers/base.py", line 129, in init_process 9:52:24 AM web.1 | self.load_wsgi() 9:52:24 AM web.1 | File "/usr/local/lib/python2.7/dist-packages/gunicorn/workers/base.py", line 138, in load_wsgi 9:52:24 AM web.1 | self.wsgi = self.app.wsgi() 9:52:24 AM web.1 | File "/usr/local/lib/python2.7/dist-packages/gunicorn/app/base.py", line 67, in wsgi 9:52:24 AM web.1 | … -
How to make installable package for Django project for Windows machine?
What is the easiest way to make a Django+DRF +Angular files (optionally) package so it can be installed on the Windows machinge? Currently we look at these options: 1) Write setup.py - but it does not create virtual environment and does not deal with Angular files 2) Build .exe file, using libraries like py2exe or pyinstaller - but they currently throw a lot of strange errors and should be build exactly for specified architecture. 3) Build separate .exe for Angular and somehow write install scripts for python - may be in some .bat files or something else. Will be grateful for any advices! -
How to avoid so many queries in Django with reverse foreign keys
these are my models (simplified): Models: class Tariff(models.Model): name = models.CharField(max_length=25, blank=True, null=True) service = models.ForeignKey(Service, models.DO_NOTHING, blank=True, null=True) cost = models.DecimalField(max_digits=18, decimal_places=3, blank=True, null=True) price = models.DecimalField(max_digits=18, decimal_places=3, blank=True, null=True) class Meta: managed = True db_table = 'Tariff' class Service(models.Model): name = models.CharField(max_length=255, blank=True, null=True) class Meta: managed = True db_table = 'Service' class CalendarValue(models.Model): calendar = models.ForeignKey(Calendar, models.DO_NOTHING, blank=True, null=True) service = models.ForeignKey(Service, models.DO_NOTHING, blank=True, null=True) date = models.DateField(blank=True, null=True) value = models.CharField(max_length=50, blank=True, null=True) class Meta: managed = True db_table = 'CalendarValue' Serializer: class AvailabilitySerializer(serializers.ModelSerializer): sum_cost = serializers.DecimalField(18, 3) sum_price = serializers.DecimalField(18, 3) service__id = serializers.IntegerField() service__name = serializers.CharField() calendarvalue = serializers.SerializerMethodField() class Meta: model = Tariff fields = ('name', 'sum_cost', 'sum_price', 'service__id', 'service__name', 'calendarvalue') def get_calendarvalue(self, tariff): start_date = self.context.get('datefrom') end_date = self.context.get('dateto') service = Service.objects.get(id=tariff['service__id']) return CalendarValueSerializer(CalendarValue.objects.filter(service=service, date__range=[start_date, end_date]), read_only=True, many=True).data This works pefectly, I get all tariffs, with their services and all calendar values per each services. But I notice that it mades a query per each Service to get its Calendarvalue. Is there any way to get all data without so many queries? Thanks. -
Capture pk from url into formtools (admin interface)
I am using Django 2.1, working through the admin interface, and wish to use formtools for a short sequence of form inputs. My url added in the view/class is: def get_urls(self): urls = super().get_urls() custom_urls = [ path('runCompTimes/<int:pk>/apply', CompTeeWizard.as_view(COMPFORMS, initial_dict={}), name='apply_CompTimes'), ] return custom_urls + urls I want to add the <int:pk> key/value into initial_dict for CompTeeWizard instance. Relevant parts of the class (with comments on retrieved items): class CompTeeWizard(SessionWizardView): def __init__(self, *args, **kwargs): super(CompTeeWizard, self).__init__(*args, **kwargs) # nothing in these args def get_context_data(self, form, **kwargs): context = super(CompTeeWizard, self).get_context_data(form=form, **kwargs) return context # nothing shown here def get_form_initial(self, step): return self.initial_dict.get(step, {}) def get_form_kwargs(self, step): kwargs = super(CompTeeWizard, self).get_form_kwargs(step) return kwargs # nothing shown here Any assistance greatly appreciated, thanks. -
Python go tought User fields
i have a celery task/For loop that should run trough a specficic list of user-fields at the database but for some reasone i always get the error: File "/home/user/docs/PyCharm/myproject/tasks.py", line 38, in check_addr for User.acc_addr in users: TypeError: 'method' object is not iterable tasks.py @periodic_task(run_every=(crontab(minute='*/1')), name="Check addr", ignore_result=True) def check_addr(): users = User.objects.all for User.acc_addr in users: print(users.acc_addr) Thanks for help -
Double slash in path to media files
I have django app (very old version 1.0.4), and I have problem with building path, in this case to media files. When my variable in settings is: MEDIA_URL_WWWW = '/' I get a path where there is no / between media and content- domain.net/admin/files/mediacontent/ But when my variable has a double slash //. MEDIA_URL_WWWW = '//' I get a path where there is a double // between media and content domain.net/admin/files/media//content/ -
Django query.py joinpromoter.add_votes() provokes dictionary update sequence element #0 has length X; 2 is required
Every time my code reaches a certain line it seems to provoke a dictionary update sequence element #0 has length X; 2 is required error. The value X can change, but the error is always provoked when this function is called: File "/path/to/venv/lib/python3.6/site-packages/django/db/models/sql/query.py" in _add_q 1289. joinpromoter.add_votes(needed_inner) It's python 3.6.7, django 2.1.7 Here is the error stack Traceback: File "/path/to/venv/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/path/to/venv/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 126. response = self.process_exception_by_middleware(e, request) File "/path/to/venv/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 124. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "./playerdata/api/tokens.py" in token_queries 87. if request.user.is_authenticated: File "/path/to/venv/lib/python3.6/site-packages/django/utils/functional.py" in inner 213. self._setup() File "/path/to/venv/lib/python3.6/site-packages/django/utils/functional.py" in _setup 347. self._wrapped = self._setupfunc() File "/path/to/venv/lib/python3.6/site-packages/django/contrib/auth/middleware.py" in <lambda> 24. request.user = SimpleLazyObject(lambda: get_user(request)) File "/path/to/venv/lib/python3.6/site-packages/django/contrib/auth/middleware.py" in get_user 12. request._cached_user = auth.get_user(request) File "/path/to/venv/lib/python3.6/site-packages/django/contrib/auth/__init__.py" in get_user 189. user = backend.get_user(user_id) File "/path/to/venv/lib/python3.6/site-packages/django/contrib/auth/backends.py" in get_user 98. user = UserModel._default_manager.get(pk=user_id) File "/path/to/venv/lib/python3.6/site-packages/django/db/models/manager.py" in manager_method 82. return getattr(self.get_queryset(), name)(*args, **kwargs) File "/path/to/venv/lib/python3.6/site-packages/django/db/models/query.py" in get 390. clone = self.filter(*args, **kwargs) File "/path/to/venv/lib/python3.6/site-packages/django/db/models/query.py" in filter 844. return self._filter_or_exclude(False, *args, **kwargs) File "/path/to/venv/lib/python3.6/site-packages/django/db/models/query.py" in _filter_or_exclude 862. clone.query.add_q(Q(*args, **kwargs)) File "/path/to/venv/lib/python3.6/site-packages/django/db/models/sql/query.py" in add_q 1263. clause, _ = self._add_q(q_object, self.used_aliases) File "/path/to/venv/lib/python3.6/site-packages/django/db/models/sql/query.py" in _add_q 1289. joinpromoter.add_votes(needed_inner) File "/path/to/venv/lib/python3.6/site-packages/django/db/models/sql/query.py" in add_votes 2171. self.votes.update(votes) File "/usr/lib/python3.6/collections/__init__.py" in update 620. … -
Is it possible to develop mobile app with Django
I have been learning python lately and know I am on the stage of thinking to develop an application and I decided to develop web app and mobile app using the language I have been learning (python) I then decided to use Django to develop my web app however I heard that instagram was built with Django and I wondered if it is possible to develop mobile app using Django. **My Question Is ** Is it possible to develop mobile app using Django? -
how to fix error Uncaught ReferenceError: ajax is not defined
i am using jquery and ajax with django in order to create 3 depended dropdownlist country city roads but the problem that the system display the below error : Uncaught ReferenceError: ajax is not defined i will display the django function , the html file and the urls.py file i will appreciate any help views.py from django.shortcuts import render from django.http import HttpResponse from testapp.models import * import json as simplejson def home2(request): countries = country.objects.all() print(countries) return render(request, 'home2.html',{'countries': countries}) def getdetails(request): #country_name = request.POST['country_name'] country_name = request.GET['cnt'] print ("ajax country_name ", country_name) result_set = [] all_cities = [] answer = str(country_name[1:-1]) selected_country = country.objects.get(name=answer) print ("selected country name ", selected_country) all_cities = selected_country.city_set.all() for city in all_cities: print ("city name", city.name) result_set.append({'name': city.name}) return HttpResponse(simplejson.dumps(result_set),content_type='application/json') home2.html <html> <head> <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script> <script> $(document).ready(function(){ $('select#selectcountries').change(function () { var optionSelected = $(this).find("option:selected"); var valueSelected = optionSelected.val(); var country_name = optionSelected.text(); data = {'cnt' : country_name }; ajax('/getdetails',data,function(result){ console.log(result); $("#selectcities option").remove(); for (var i = result.length - 1; i >= 0; i--) { $("#selectcities").append('<option>'+ result[i].name +'</option>'); }; }); }); }); </script> </head> <body> <select name="selectcountries" id="selectcountries"> {% for item in countries %} <option val="{{ item.name }}"> {{ item.name }} </option> {% … -
How to make a django blog form?
I am trying to make a wordpress like blog form using Django.But,i can't accept images along with text like that in wordpress.If i am trying to upload images separately. Then how can i publish them in between paragraphs? I want user to also set position of images in their blog post. -
python calling one function from another
Im creating a serializer using python django DRF .Im creating a separate helper class and trying to override the create method. My helper class: class WorkFlowHelper: def create_levels(self,levels): for level in levels: workflow_level = WorkflowLevel() workflow_level.workflow=self, workflow_level.level = level['level'] workflow_level.operation=level['operation'] workflow_level.save() self.levels.add(workflow_level) self.assign_level_permissions(self,level) def assign_level_permissions(self,level): for permission in level['permissions']: workflow_permission_obj = WorkflowPermission.objects.get(short_name=permission['short_name']) self.permissions.add(workflow_permission_obj) def create_categories(self,categories): for category in categories: workflow_category_obj = WorkflowCategory.objects.get(short_name=category['short_name']) self.categories.add(workflow_category_obj) def create(self, name, description ,tenant, levels, categories): workflow = Workflow.objects.create(name=name, description=description, tenant=tenant) self.create_levels(workflow,levels) self.create_categories(workflow,categories) workflow.save() In my serializer i have to call the create method like : def create(self, validated_data): name=validated_data['name'] description=validated_data.get('description'), tenant=self.context['request'].user.tenant levels = self.initial_data['levels'] categories = self.initial_data['categories'] creates = WorkFlowHelper.create(creates,name,description,tenant,levels,categories) In the helper class ,im calling other functions from a function inside the same class. Im having doubts on how to pass in the self in the function call.