Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Dropzone rizes a MultiValueDictKeyError with Django
I am trying to use Dropzone with Django, but I get a MultiValueDictKeyError. This is my html form: <form action="{% url 'AlbumsManagerApp:album_add_photo' album_pk=album.id %}" class="dropzone" method="POST"> {% csrf_token %} <div class="nav nav-bar"> <input type="submit" name="submit-accept" value="Aceptar" class="btn btn-success"> <input type="submit" name="submit-cancel" value="Cancelar" class="btn btn-danger"> </div> </form> This is my view: class AlbumAddPhotoView(LoginRequiredMixin, View): def get(self, request, album_pk): album = Album.objects.get(id=album_pk) context={'album': album } return render(request, 'AlbumsManagerApp/form_upload.html', context) def post(self, request, album_pk): if 'submit-accept' in request.POST: files = request.FILES['file'] print(files) return redirect('AlbumsManagerApp:albums', album_pk=album_pk) I followed the answer to the question Trying to use django and dropzone/, but I still get the same error. -
django find groups composed entirely of some people in many-to-many with through table?
In a many to many relationship like the following: class Person(models.Model): name = models.CharField(max_length=128) def __unicode__(self): return self.name class Group(models.Model): name = models.CharField(max_length=128) members = models.ManyToManyField(Person, through='Membership') def __unicode__(self): return self.name class Membership(models.Model): person = models.ForeignKey(Person) group = models.ForeignKey(Group) date_joined = models.DateField() invite_reason = models.CharField(max_length=64) If I have a queryset of Person objects, how can I search for Groups that are composed of exactly these people? people = Person.objects.filter( .. some filter requirements ... ) groupsComposedOfOnlyAndAllThosePeople = ??? -
Django MySql, foreign key query
I have the following Models in Django. from django.db import models #Show DB Table Model class Shows(models.Model): show_key = models.CharField(primary_key=True, max_length=7) show_date = models.DateField(blank=True, null=True) show_venue = models.CharField(max_length=50, blank=True, null=True) show_city = models.CharField(max_length=50, blank=True, null=True) show_state = models.CharField(max_length=3, blank=True, null=True) show_country = models.CharField(max_length=3, blank=True, null=True) class Meta: managed = False db_table = 'shows' #Songs DB Table Model class Songs(models.Model): song_key = models.CharField(primary_key=True, max_length=8) show_key = models.ForeignKey('Shows', models.DO_NOTHING, db_column='show_key', blank=True, null=True) song_name = models.CharField(max_length=100, blank=True, null=True) song_set = models.CharField(max_length=20, blank=True, null=True) song_track = models.IntegerField(blank=True, null=True) song_encore = models.IntegerField(blank=True, null=True) song_segue = models.CharField(max_length=1, blank=True, null=True) song_notes = models.CharField(max_length=100, blank=True, null=True) song_cover = models.CharField(max_length=50, blank=True, null=True) song_with_guest = models.CharField(max_length=50, blank=True, null=True) class Meta: managed = False db_table = 'songs' I am trying make a query that will find all objects meeting a certain criteria, ie: Shows.objects.filter(show_date__year=2000) This above query would return multiple objects. I need to take it a step further and pull all of the information from the Songs table/model relating to the filtered Show objects. The models are related in the sense that the "show_key" is a primary key / foreign key relationship and is one to many. I also need to package all of the found data up into a … -
Settings of Virtual Environment in Python with Visual Studio Code
I tried but completely failed to find any useful info on the internet. I am a beginner in Django, installed "virtualenv" with pip, and created an environment under "D:\Dropbox\Git\Python\Django_projects" called "env_mysite". If I were in Command Prompt, everything works as expected. Now since I tried to code with Visual Studio Code, I would like to use "ctrl+shift+p" to quickly select python interpreter, which in my case would be either the "normal python" or the one in the virtual environment in the D: path aforementioned, depends on the project. After googling, I understand it seems that this may be because of the wrong path settings in the User Settings in VS Code. My current path settings are as below: python.venvPath and python.pythonPath. I hope some of you guys can help me with how to set the correct path under Windows. Appreciated. -
Improving security of passing permissions to UI from the backend
I am working a django-angular application that is based on permissions to build the UI. Initially, I was passing the list of permissions assigned to the user to the UI as they are (.e.g add_user). But I was instructed by the CTO to change each into numerical or other form of encryption so add_user for e.g. becomes 311. Can someone really enlighten me how this exactly improves the security of the app? The backend now sends 311 etc to the front end but now, I have to keep track of numbers ->permisions. The backend still checks permissions based on add_user kind. Is this the way to go to improve the overall security of the app? -
Django docs Polls App,Diferent queryset returns same object values but QuestionIndexViewTests works for one query and fails for other
In polls application I added annotation to check one to many relationship between Question and Choice models such that, Index only return questions with more than one choices to be displayed but my testcase fails all the time with annotation where both query returns same data. views.py(Working) class IndexView(generic.ListView): template_name = 'polls/index.html' context_object_name = 'latest_question_list' def get_queryset(self): """Return the last five published questions.""" return Question.objects.filter(pub_date__lte=timezone.now()).order_by('-pub_date')[:5] views.py(Not Working: Added .annotate(num = Count('choice')).filter(num__gt=1)) class IndexView(generic.ListView): template_name = 'polls/index.html' context_object_name = 'latest_question_list' def get_queryset(self): """Return the last five published questions.""" return Question.objects.annotate(num = Count('choice')).filter(num__gt=1).filter(pub_date__lte=timezone.now()).order_by('-pub_date')[:5] tests.py class QuestionIndexViewTests(TestCase): def test_no_questions(self): """ If no questions exist, an appropriate message is displayed. """ response = self.client.get(reverse('polls:index')) self.assertEqual(response.status_code, 200) self.assertContains(response, "No polls are available.") self.assertQuerysetEqual(response.context['latest_question_list'], []) def test_past_question(self): """ Questions with a pub_date in the past are displayed on the index page. """ create_question(question_text="Past question.", days=-30) response = self.client.get(reverse('polls:index')) self.assertQuerysetEqual( response.context['latest_question_list'], ['<Question: Past question.>'] ) def test_future_question(self): """ Questions with a pub_date in the future aren't displayed on the index page. """ create_question(question_text="Future question.", days=30) response = self.client.get(reverse('polls:index')) self.assertContains(response, "No polls are available.") self.assertQuerysetEqual(response.context['latest_question_list'], []) def test_future_question_and_past_question(self): """ Even if both past and future questions exist, only past questions are displayed. """ create_question(question_text="Past question.", days=-30) create_question(question_text="Future question.", … -
Exception installing Django with Azure CLI
I'm trying to installing Django on Azure CLI but I'm running into issues with pip install Django. It almost looks like I need to run this with elevated permissions, sudo? Has anyone run into this? pip install Django Collecting Django Using cached Django-2.0.4-py3-none-any.whl Collecting pytz (from Django) Using cached pytz-2018.4-py2.py3-none-any.whl Installing collected packages: pytz, Django Exception: Traceback (most recent call last): File "/usr/local/lib/python3.5/dist-packages/pip/basecommand.py", line 215, in main status = self.run(options, args) File "/usr/local/lib/python3.5/dist-packages/pip/commands/install.py", line 342, in run prefix=options.prefix_path, File "/usr/local/lib/python3.5/dist-packages/pip/req/req_set.py", line 784, in install **kwargs File "/usr/local/lib/python3.5/dist-packages/pip/req/req_install.py", line 851, in install self.move_wheel_files(self.source_dir, root=root, prefix=prefix) File "/usr/local/lib/python3.5/dist-packages/pip/req/req_install.py", line 1064, in move_wheel_files isolated=self.isolated, File "/usr/local/lib/python3.5/dist-packages/pip/wheel.py", line 345, in move_wheel_files clobber(source, lib_dir, True) File "/usr/local/lib/python3.5/dist-packages/pip/wheel.py", line 316, in clobber ensure_dir(destdir) File "/usr/local/lib/python3.5/dist-packages/pip/utils/__init__.py", line 83, in ensure_dir os.makedirs(path) File "/usr/lib/python3.5/os.py", line 241, in makedirs mkdir(name, mode) PermissionError: [Errno 13] Permission denied: '/usr/local/lib/python3.5/dist-packages/pytz'` -
Can't get a GET response in DJango Rest
I'm trying to learn DJango Rest so I made a litte test to see if I could obtain some things from the database, but I'm getting some problems. Here's my models.py: from django.db import models # Create your models here. class Stock(models.Model): ticker = models.CharField(max_length=10) open = models.FloatField() close = models.FloatField() volume = models.IntegerField() def __str__(self): return self.ticker Here's my serializers.py: from rest_framework import serializers from .models import Stock class StockSerializer(serializers.ModelSerializer): ticker = serializers.CharField() open = serializers.FloatField() close = serializers.FloatField() volume = serializers.IntegerField() def create(self, validated_data): return Stock.objects.check(**validated_data) def update(self, instance, validated_data): instance.ticker = validated_data.get('ticker', instance.ticket) instance.open = validated_data.get('open', instance.open) instance.close = validated_data.get('close', instance.close) instance.volume = validated_data.get('volume', instance.volume) instance.save() return instance class Meta: model = Stock fields = '__all__' Here's my views.py: from django.http import Http404 from rest_framework import status from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework.views import APIView from .models import Stock from .serializers import StockSerializer # List all stocks or create a new one # stocks/ @api_view(['GET', 'POST']) def stock_list(self, request, format=None): if request.method == 'GET': stocks = Stock.objects.all() serializer = StockSerializer(stocks, many=True) return Response(serializer.data) elif request.method == 'POST': serializer = StockSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) @api_view(['GET', 'POST', 'DELETE']) def … -
Migrating a Django backend for a JS app to WordPress
I have a Django-based site with a JavaScript single page app which consumes a REST API built with the Django Rest Framework. I need to migrate my site to WordPress, and from resources I have studied it seems that this should be fairly straightforward and painless, with the WordPress REST API assuming the role of my DRF API. I am new to WordPress development, however, and a number of aspects of any potential migration remain unclear to me. The main points are listed below: Should I simply convert my Django app to a WordPress plugin? This seems the simplest option, and I have already started doing this, but the app will only ever be available on my site, and all of the plugin tutorials I have found assume a public plugin, so I was wondering if there are other options. Also a plugin implies extending WordPress functionality, which I'm not doing (I guess?). Where do I store my data? It's read-only, and there's not much of it (only a couple of MB). In Django I have just used the admin interface to insert data, and run queries using the Django query API. What are the equivalent features in WordPress? Can … -
Redirect to delete view in Django admin
I'm working on a Django/Wagtail project. I have a very customized feature in the admin view what will delete an object when hitting Save if certain conditions are met. I have this in my class (that is a snippet): def save(self, *args, **kwargs): if condition: self.delete() else: return super(MyModel, self).save(*args, **kwargs) This works as expected. The object gets deleted, but after this I get an error page because the browser remains in the same URL /snippets/myapp/mymodel/1234/ but the object doesn't exist anymore. I thought of two possible solutions for this. Possible solution 1: def save(self, *args, **kwargs): if condition: self.delete() #### ===== > Redirect to objects list view else: return super(MyModel, self).save(*args, **kwargs) Possible solution 2: def save(self, *args, **kwargs): if condition: #### ===== > Don't delete and redirect to delete view (.../mymodel/1234/delete/) else: return super(MyModel, self).save(*args, **kwargs) These are the two possible solutions I thought, but I don't know how to do any of them, even after reading docs here and there. How can I do what I'm trying to achieve? -
[Django][JSON] Updating django model with json arrays
The issue I'm running into is that I would like to update a Django model with json values. The trouble is that some of the values in the json are a lists with multiple numbers. This is what the json looks like: json = {'fields': {'resources': [], 'initiative': [8, 21, 22]}, 'pk': 81} {'fields': {'resources': [], 'initiative': [5, 8, 22]}, 'pk': 82} {'fields': {'resources': [], 'initiative': [8, 22]}, 'pk': 83} {'fields': {'resources': [], 'initiative': [6]}, 'pk': 84} def update_model(): for row in json: Model.objects.filter(id=row['pk']).update(initiative_id=row['fields']['initiative'][0], resources_id=row['fields']['resources'][0]) I can't figure how to get the Model line spaced correctly on Stack. Anyway, when I run this I get "IndexError: list index out of range" presumably because this method can only handle a list with 1 value. Anyone know how I can do this with the json formatting I have? -
Django all Q() arguments
I am reading Django documentation, particularly about Q() class. It has several sections about it, like: Q() objects and Complex lookups with Q objects There, authors mention arguments that can be passed to Q(), like Q(question__startswith='What') I know that there are other arguments possible, like Q(name__icontains='What') That brings a conclusion, that a complete list of all available args must exist somewhere, unfortunately, despite that, searching through official documentation or googling lead to nothing If someone can explain me, what should I do in this situation, it will be much appreciated -
Custom django admin templates not working clearly
The django admin contact comes without the design coming up properly my settings file INSTALLED_APPS File structures All other functions are working only do not have design. How can ı fix this template problem? Thanks for your answers... -
how to show only starts in django star ratings
I am using django-star ratings and its working fine but when I along with stars its also showing its additional details. I am just writing {% ratings object 18 18 %} in my HTML and its showing me starts but also Average: 4.50 Rating Count: 2 You Rated: Not rated Please log in to rate. I have read the documentation but I unable to find anything. I don't want to show this additional details on list page of items but want on detail page of that item. -
Connect/disconnect loop with Django channels in production mode
I have a Django app using Django Channels for handling notifications working perfectly local. I'm using channels==1.1.8, python 2.7, Redis as channel-layer (asgi-redis==1.4.3) and Angular as frontend. The app is deployed on several Kubernetes pods and in production mode I get a WSCONNECT/WSDISCONNECT loop all the time, with this kind of log: WebSocket force closed for daphne.response.WUHCSLAiSR!daHwhQvcvV due to receive backpressure Is there any setting to put into production mode? What can this issue be related to? Thank you in advance. -
Why does Django Admin calls UserCreationForm save method with commit=False?
Where does the django admin actually saves it's models? I wanted to print some model fields that are only created after saving occurs, but UserCreationForm save method always gets called with commit=False and seem to return user so the save occurs somewhere else. class MyUserCreationForm(UserCreationForm): ... def save(self, commit=True): # django admin calling this with commit=False... save occurs somewhere else. ... if commit: print("this never gets printed") user.save() # line below prints nothing print(user.field_set_after_model_is_saved) return user p.s: my model is getting saved normally, just not where I expected. -
Streaming very large json directly from a POST request in Django
I'm looking for efficient ways to handle very large json files (i.e. possibly several GB in size, amounting to a few million json objects) in requests to a Django 2.0 server (using Django REST Framework). Each row needs to go through some processing, and then get saved to a DB. The biggest painpoint thus far is the sheer memory consumption of the file itself, and the memory consumption steadily still increasing while the data is being processed in Django, without any ability to manually release the memory used. Is there a recommended way of processing very large json files in requests to a Django app, without slaughtering memory consumption? Possible to combine with compressing (gzip)? I'm thinking of uploading the json as a regular file, stream that to disk, and then stream from the file on disk using ijson or similar? Is there a more straightforward way? -
inserting data in two database at the same time
I have two Models in my application in Django The Change model is only for storing the change logs made in Model Ip My models.py class Change(models.Model): author = models.ForeignKey('auth.User', null=False, on_delete=models.CASCADE, default='auth.User') ip = models.ForeignKey('Ip', on_delete=models.CASCADE, default='') old_cluster = models.ForeignKey('Cluster', on_delete=models.CASCADE, default='') old_status = models.ForeignKey('Status', on_delete=models.CASCADE, default='') new_cluster = models.CharField(max_length=20) new_status =models.CharField(max_length=20) change_date = models.DateTimeField(default=timezone.now) class Ip(models.Model): author = models.ForeignKey('auth.User', null=False, on_delete=models.CASCADE, default='auth.User') number = models.CharField(max_length=20, unique=True, default='') status = models.ForeignKey('Status', on_delete=models.CASCADE, default='') cluster = models.ForeignKey('Cluster', on_delete=models.CASCADE, default='') created_date = models.DateTimeField(default=timezone.now) def __str__(self): return self.number class Meta: ordering = ('number',) my views.py def ip_edit(request, id): ip_edit = get_object_or_404(Ip, id=id) form = EditManagementForm(request.POST, instance=ip_edit) change_form = ChangeLogsForm() if request.method == "POST": if form.is_valid(): ip_edit = form.save(commit=False) ip_edit.save() change_form = ChangeLogsForm(request.POST) if change_form.is_valid(): ip_change = change_form.save(commit=False) ip_change.author = request.user ip_change.ip = request.number ip_change.save() return redirect('/app/management') else: form = EditManagementForm(instance=ip_edit) args = { 'form': form, } return render(request, 'app/ip_edit.html', args and my forms.py class EditManagementForm(forms.ModelForm): class Meta: model = Ip fields = ( 'number', 'status', 'cluster', ) widgets = { 'number': TextInput(attrs={'class': 'ls-form-text'}), } class ChangeLogsForm(forms.ModelForm): class Meta: model = Change fields = ( 'ip', 'old_cluster', 'old_status', 'new_cluster', 'new_status', ) when I save the ip information editing, no error occurs, but it … -
Django pagination: How do 'paginator' and 'page_obj' get injected into a template's context?
I'm trying to understand some source code which is used in a ListView to generate pagination links at the bottom of the page. For example, on a page listing 'experts', it looks like this: It seems to be implemented somewhat differently from the way described in https://docs.djangoproject.com/en/2.0/topics/pagination/. There is an inclusion tag called paginator: from django import template from django.core.paginator import EmptyPage from dashboard.views.utils import query_dict_from_params_or_cookies register = template.Library() def query_params(params): query = params.copy() if query.get('page'): del query['page'] return '&' + query.urlencode() if query.urlencode() else '' @register.inclusion_tag('templatetags/paginator.html', takes_context=True) def paginator(context, adjacent_pages=2): request = context['request'] page_obj = context['page_obj'] page_range = context['paginator'].page_range page_number = page_obj.number last_page_number = len(page_range) left_idx = max(0, page_number - adjacent_pages - 1) right_idx = min(page_number + adjacent_pages, last_page_number) if left_idx == 2: left_idx -= 1 if right_idx == last_page_number - 2: right_idx += 1 window = page_range[left_idx:right_idx] try: previous_page_number = page_obj.previous_page_number() except EmptyPage: previous_page_number = None try: next_page_number = page_obj.next_page_number() except EmptyPage: next_page_number = None params = query_dict_from_params_or_cookies(request) return { 'has_previous': page_obj.has_previous(), 'has_next': page_obj.has_next(), 'previous_page_number': previous_page_number, 'next_page_number': next_page_number, 'last_page_number': last_page_number, 'page_range': window, 'page_number': page_number, 'show_first': page_number > adjacent_pages + 1, 'show_left_gap': page_number > adjacent_pages + 3, 'show_last': page_number < last_page_number - adjacent_pages, 'show_right_gap': page_number < last_page_number - adjacent_pages … -
Django CreateView success_url fails
I have built an address model, address list and create address. My problem is that the create view does not redirect the browser to the success_url. The create view is displayed correctly and upon submit the new address is added to the database but the browser IP address does not change. Consequently, the user thinks it failed so clicks submit again. Changing the browser IP address directly will show all created address multiple times. I created a simple project and repeated this code in it and the browser does redirect to the list view as expected. I have also tried overriding get_success_url(self) with no change. I have change the success_url, again no change. Here is my console output starting with the initial address List View. [13/Apr/2018 12:42:57] "GET /accounts/my_address/ HTTP/1.1" 200 4853 [13/Apr/2018 12:43:01] "GET /accounts/create-address/ HTTP/1.1" 200 5715 [13/Apr/2018 12:43:11] "POST /accounts/create-address/ HTTP/1.1" 302 0 [13/Apr/2018 12:43:11] "GET /accounts/my_address/ HTTP/1.1" 200 5898 But this is the browser IP address http://127.0.0.1:8007/accounts/create-address/ My question is how do I debug this to determine why the browser IP does not change. models.py class Address(models.Model): """ Allow an account to have multiple addresses for which one must be active. Shipments will be sent to … -
angular httperror unexpected token < in JSON at position 1 with django RF backend
the django get response: privacytypes =[ {'name': 'Semi-Private', 'value': 's'}, {'name': 'Private', 'value': 'p'}, {'name': 'Full Buyout', 'value': 'f'} ] amenities = [ {'name': 'Surround Sound'}, {'name': 'Stage'}, {'name': 'Television'}, {'name': 'Screen + Projector'}, {'name': 'Natural Light'}, {'name': 'Wifi'}, {'name': 'Wheelchair Accessible'}, {'name': 'Outdoor Seating'} ] seatingoptions = [ {'name': 'Cocktail/Standing'}, {'name': 'Classroom'}, {'name': 'U-Shape'}, {'name': "60' Rounds"}, {'name': 'Boardroom'}, {'name': 'Theater'}, {'name': 'Hallow Square'} ] return Response({ 'neighborhoods': serializedneighborhoods.data, 'venuetypes': serializedvenuetypes.data, 'cuisines': serializedcuisines.data, 'experientialtypes': serializedexperientialtypes.data, 'privacytypes': privacytypes, 'amenities': amenities, 'seatingoptions': seatingoptions }) the angular subscription: this.browsevenuedependancyservice.browsevenuesdependancy(selectedcity) .subscribe( (req: any)=>{ this.neighborhoodchoices = req.neighborhoods; this.venuetypechoices = req.venuetypes; this.privacytypechoices = req.privacytypes; this.cuisinechoices = req.cuisines; this.experientialchoices = req.experientialtypes; this.ammenitieschoices = req.amenities; this.seatingtypeschoices = req.seatingoptions; the error: SyntaxError: Unexpected token < in JSON at position 1 at Object.parse I am using angular 5 httpclient. Really not sure what is causing this. this is a funny story since I need to add more words yet I have nothing else to say: A guy walks into a bar and hurts his leg. -
Join django models with forward and reverse relations in a single query
I'm trying to do some django lookups for display purposes. I need to pick related data from a lot of different tables but I'm struggling to query all the data I need. class Machine(models.Model): company = models.ForeignKey(Company, related_name='machineCompany', on_delete=models.CASCADE) machine_ID = models.CharField(max_length=60, primary_key=True ) machine_name = models.CharField(max_length=30) ... class MachineDetail(models.Model): machine = models.ForeignKey(Machine, related_name='machineDetails', on_delete=models.CASCADE,null=True,blank=True, unique=True) manufacturer = models.CharField(max_length=30) ... class Company(models.Model): company_ID = models.CharField(max_length=40, primary_key = True) name = models.CharField(max_length=30) ... class Insurance(models.Model): machine = models.ForeignKey(Machine, related_name='insuranceMachine', on_delete=models.CASCADE) insurance_ID = models.CharField(max_length=60, primary_key=True ) ... class InsuranceProcess(models.Model): insurance = models.ForeignKey(Insurance, related_name='insurancesProcess', on_delete=models.CASCADE,null = True, unique=True) days_week = models.IntegerField() ... I want to get for a certain 'machine_ID' the following attributes in a single queryset [MachineDetail.manufacturer, Company.name, InsuranceProcess.days_week] This is what I managed so far: queryset = MachineDetail.objects.select_related().filter(machine = argument).values_list( 'manufacturer', 'machine__company__name') <QuerySet [manuracturer: xxx, name: xxx]> I excluded the attributes that not interest me using values_list() and added Company.name using django lookups __ but was not able to put "days_week" in the same query. Is there a way to do it without escalating the number of needed queries? -
django query to retrieve dictionary of children values keyed by parent name?
With the following models with a one-to-many relationship, where a kid can have some collection of toys: class Kid(models.Model): name = models.CharField(max_length=200) class Toy(models.Model): name = models.CharField(max_length=200) material = models.CharField(max_length=200) owner = models.ForeignKey(Kid) I would like to generate a dictionary with kid names as keys and a list of tuples as values. The following query gets me the list of tuples as shown: kids = Kid.objects.all() kids.filter( toy__name__in[ some list of names ] ).\ values_list( 'name', 'toy__name', 'toy__material' ) [ ( 'billy', 'hotwheelscar', 'metal' ), ( 'billy', 'actionFigure', 'plastic' ), ( 'sam', 'hotwheelscar', 'metal' ), ( 'sam', 'doll', 'plastic' ), ( 'sam', 'dollHouse', 'plastic' ), ( 'jimmy', 'hotwheelscar', 'metal' ), ( 'jimmy', 'actionFigure', 'plastic' ) ] But is there a way I could get these results in a form like the following: { 'billy': [ ( 'hotwheelscar', 'metal' ), ( 'actionFigure', 'plastic' ) ], 'sam': [ ( 'hotwheelscar', 'metal' ), ( 'doll', 'plastic' ), ( 'dollhouse', 'plastic' ) ], 'jimmy': [ ( 'hotwheelscar', 'metal' ), ( 'actionFigure', 'plastic' ) ] } Without having to first retrieve the values_list of tuples as I have done and then iterate over them creating a dictionary myself? The structure of the values being represented … -
Using Django-ModelTranslation with Django-Oscar, but "No new translatable fields detected"
I'm trying to use Django-ModelTranslation to provide translation fields for products in Django-Oscar. I followed the documentation on Registering Models for Translation but keep getting this in response: No new translatable fields detected. I don't know if this might be part of the problem but I first started a Mezzanine project and then integrated Oscar into it using Oscar's docs. Translation fields were added to Mezzanine perfectly. Below, I show how I forked Oscar's catalogue app and added it to settings.py. project/settings.py: from oscar import get_core_apps # Django-ModelTranslation settings USE_MODELTRANSLATION = True MODELTRANSLATION_FALLBACK_LANGUAGES = ('en',) LANGUAGES = ( ('en', _('English')), ('de', _('German')), ) INSTALLED_APPS = [ ..., ] + get_core_apps(['forked_apps.catalogue']) project/forked_apps/catalogue/translation.py: from modeltranslation.translator import translator, TranslationOptions from oscar.apps.catalogue.abstract_models import AbstractProduct class AbstractProductTranslationOptions(TranslationOptions): fields = ('title', 'description',) translator.register(AbstractProduct, AbstractProductTranslationOptions) I then ran sync_translation_fields to no avail. What have I missed? -
Filter by type in Django queryset?
I'm trying to make a custom queryset where I need to check the type of a foreign key. The code below works but seems not optimal to me: class BadgeQuerySet(models.QuerySet): def linked_to_convive(self): pks_badges_linked_to_convive = [badge.pk for badge in Badge.objects.all() if badge.owner and type(badge.owner.profile) == Convive] return self.filter(pk__in=pks_badges_linked_to_convive) I browsed Django doc and didn't find something like this: Badge.objects.filter(owner__profile__type=Convive) Question 1: Why Django does not provide this kind of tool? Question 2: Is there a way to improve my working code, making it simpler? Thanks.