Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
working with django and ajax
I am trying to send request data using ajax to my backend server consist of python & django Python Code views.py def JSON_Sample(request): response_data = {} response_data['result'] = "Success" response_data['message'] = "AJAX Worked" return JsonResponse(response_data) AJAX request AJAX request $.ajax({ url:"http://localhost:8000/login/json", dataType:"jsonp", success:function(response){ alert("finaly sucess"); } }); Error in this is cross origin request blocked. I am newbie in it please help me out what should i do in my code ? -
What is wrong with my python-social-auth (django) configuration
Python-social-auth is quite hard to understand, with many changes which are not in documentation. I am using Python 2.7. What is wrong with my configuration? INSTALLED_APPS = [ 'app', 'social_django', ] AUTHENTICATION_BACKENDS = ( 'social_auth.backends.google.GoogleOAuth2Backend', 'django.contrib.auth.backends.ModelBackend', 'social_core.backends.google.GoogleOAuth2', ) GOOGLE_OAUTH2_CLIENT_ID = '1089975505509-1a1n18n45190l3pfs3ot5qrapa1e5fa24i.apps.googleusercontent.com' GOOGLE_OAUTH2_CLIENT_SECRET = 'XZZqfj3PjZ7f35USlZNEJDNmv' LOGIN_REDIRECT_URL = '/members' or also saw this version, which is likely depreciated: SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = '1089975505509-1a1n18n45190l3pfs3ot5qrapa1e5fai.apps.googleusercontent.com' SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = 'XZZqfj3PjZ7f35USlZNEJDNm' SOCIAL_AUTH_LOGIN_REDIRECT_URL = '/home' SOCIAL_AUTH_URL_NAMESPACE = 'social' And templates:` TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'social_django.context_processors.backends', 'social_django.context_processors.login_redirect', 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'social_django.context_processors.backends', 'social_django.context_processors.login_redirect', ], }, }, ] General urls.py redirect to app urls.py `urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'', include('app.urls')), url('', include('social_django.urls', namespace='social')) ] Local app urls.py: urlpatterns = [ url(r'intro', views.intro), ] Views: def intro(request): return render(request, "blog/intro.html", {}) Link in template: <a href="{% url 'social:begin' 'google-oauth2' %}">Login with Google</a> What is wrong? How to make it all work, what I shall get in response if it works properly? -
Django: ImproperlyConfigured: The TEMPLATE_DIRS setting must be a list or a tuple. Please fix your settings
I'm running Django 1.9 In settings.py I have: OUR_ROOT = os.path.realpath(os.path.dirname(__file__)) TEMPLATE_DIRS = (os.path.join(OUR_ROOT, 'templates'),) But when I enter the main page the django log shows: ImproperlyConfigured: The TEMPLATE_DIRS setting must be a list or a tuple. Please fix your settings. i don't understand what is the problem since (os.path.join(OUR_ROOT, 'templates'),) is a tuple like ("hh",) is a tuple. Any idea what could be wrong? -
Get foreign key unicode value in the template rather than its id
My model consists of ForeignKey and I am using generics.DetailView to render object detail in the django view. MyModel class MyModel(models.Model): myField = models.ForeignKey(...) def get_fields(self): # called by the template return [(field.verbose_name, field.value_to_string(self)) for field in type(self)._meta.fields] MyView class Detail(DetailView): model = MyModel template_name = 'path/to/template.html' def get_context_data(self, **kwargs): context = super(Detail, self).get_context_data(**kwargs) # do something return context And MyTemplate {% for field, value in object.get_fields %} <tr> <th>{{ field }}</th> <td>{{ value }}</td> </tr> {% endfor %} Now when the template renders, what I get is id rather than __unicode__ representation. Same problem is seen for the ChoiceField as well(I get value rather than their labels). So my question is, how can I get label or unicode representation rather than their actual values? -
Localize date times inside a Django templatetag
I am working on a templatetag in Django which should take care of some date- and time formatting. I would like the date to be show in Dutch, but it keeps coming back in English. from django import template register = template.Library() @register.filter() def get_date_string(event): if event.date_type == 1: retval = event.date_1.strftime("%-d %B %Y") if event.date_1_starttime is not None: retval += " van " + event.date_1_starttime.strftime("%H:%M") if event.date_1_endtime is not None: retval += " tot " + event.date_1_endtime.strftime("%H:%M") return retval According to the Python documentation %B should provide a localized month full name. In the template I just use: {{ object|get_date_string }} I hope someone can help me with this. -
Django 1.10 - It is safe to delete non-processed migration file?
I created a migration file using python3 manage.py makemigrations my_app. However I ran that command by mistake. Is it safe just to delete the newly created non-processed migration file? Or is there something else that needs to be done? -
Zurb Foundation - Create a custom form but now posts wont be created
so I created a form for the website Im building using Foundation Forms, and now it wont create the post. Here is the html: <div style="padding-bottom: 5px; padding-top: 10px;"> <label> <h3><small><font color="black">Post Title</font></small></h3> <input type="text" placeholder="Enter Post Title Here"> </label> </div> <!--Post Content--> <div style="padding-bottom: 5px;"> <label> <h3><small><font color="black">Post Content</font></small></h3> <textarea placeholder="Enter Post Content Here"></textarea> </label> <hr> </div> <!--Post File--> <label for="exampleFileUpload" class="button">Upload File</label> <input type="file" id="exampleFileUpload" class="show-for-sr"> <br> <hr> <!--Submit Post--> <label> <input name= "myfiles" type='submit' class='button' value='Create Post'/> </label> </form> </div> </div> -
django signup views not working properly
i want to create a registration view so, it takes username, password, and email for registration and i am using Django User Model, but it is giving me an error. AttributeError at /signup/ 'SignUpForm' object has no attribute 'cleaned_data' please tell me how to fix this, forms.py class SignUpForm(forms.Form): username = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Username'})) email = forms.EmailField(widget=forms.EmailInput(attrs={'class': 'form-control', 'placeholder': 'Email'})) password = forms.CharField(widget=forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': 'Password'})) confirm_password = forms.CharField(widget=forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': 'Confirm Password'}), label="Confirm Password") class Meta: model = User def __init__(self, *args, **kwargs): super(SignUpForm, self).__init__(*args, **kwargs) self.fields['username'].validators.append(ForbiddenUsernamesValidator) self.fields['username'].validators.append(InvalidUsernameValidator) self.fields['username'].validators.append(UniqueUsernameIgnoreCaseValidator) self.fields['email'].validators.append(UniqueEmailValidator) def clean(self): super(SignUpForm, self).clean() password = self.cleaned_data.get('password') confirm_password = self.cleaned_data.get('confirm_password') if password and password != confirm_password: self._errors['password'] = self.error_class(['Passwords don\'t match']) return self.cleaned_data views.py def signup(request): if request.method == 'POST': form = SignUpForm(request.POST or None) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') email = form.cleaned_data.get('email') print(username) print(password) print(email) messages.add_message(request, messages.SUCCESS, 'YOU ARE REGISTRED SUCCESSFULLY') return render(request, 'authentication/signup.html', {}) else: return render(request, 'authentication/signup.html', {'form': form}) else: return render(request, 'authentication/signup.html', {'form': SignUpForm}) -
connect() to unix:/tmp/socket.sock failed (111: Connection refused) while connecting to upstream
I am following this tutorial to host django application nginx but it gives 502 Bad Getway error connect() to unix:/tmp/socket.sock failed (111: Connection refused) while connecting to upstream. Below is my sample.ini [uwsgi] project = mysite base = /home/ubuntu/Arti/Project chdir = %(base)/%(project) home = %(base)/Env/%(project) module = %(project).wsgi:application master = true processes = 2 socket = /tmp/%(project).sock chmod-socket = 666 vacuum = true Below is my uwsgi.conf description "uWSGI" start on runlevel [2345] stop on runlevel [06] respawn env UWSGI=/usr/local/bin/uwsgi env LOGTO=/var/log/uwsgi.log exec $UWSGI --master --emperor /etc/uwsgi/sites --die-on-term --uid django --gid www-data --logto $LOGTO nginx file server { listen 8087; server_name 127.0.0.1; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/ubuntu/Arti/Project/mysite/; } location / { include uwsgi_params; uwsgi_pass unix:/tmp/mysite.sock; } } -
Python Django models basics
I am learning django and trying to create a simple Question-Answer app where users can also like the questions and/or answers. Now what I want to do is track who liked a particular question/answer so I created a separate model for tracking this as follows: class Votes(models.Model): answer_id = models.ForeignKey(Answers, related_name='likes_answers', null=True, default=None, db_column='answer_id') question_id = models.ForeignKey(Questions, related_name='likes_questions', null=True, default=None, db_column='question_id') likes_count = models.IntegerField(blank=True, default=0) liked_by = models.ForeignKey(User, related_name='like_user', null=True, default=None, on_delete=models.CASCADE) Now the problem with this approach is that everytime a question or an answer is liked there will be an entry to this model which will create multiple entries of same question_id or answer_id with different users. Although the users are different, but a lot of answer_ids and question_ids are getting repeated...Is that right approach or can I make it better? -
Get multiple values of a model in Django-Rest-framework POST call
I am collecting some data making use of Django Rest Framework. I want to make an API to accept POST call and required query_set, which will be the Address. Now I want that the API should accept multiple Address, so the POST request will contain data set something like - { { "some_id": id1, "address_line_1": some random address 1 "address_line_2": some random address 2 }, { "some_id": id2, "address_line_1": some random address 1 "address_line_2": some random address 2 } } My address model is as following: class Address(models.Model): some_id = models.IntegerField() address_line_1 = models.CharField(max_length = 200) address_line_2 = models.CharField(max_length = 200) I have my serializer as- class AddressSerializer(serializers.ModelSerializer): class Meta: model = Address fields = {'some_id', 'address_line_1', 'address_line_2'} I am not sure which view to use to achieve this functionality. Also I want to render a form, similar to what GenericAPIView provides, containing all the fields of address model when I hit the API from browser. Something like- I am a newbie to Django Rest Framework so any help is greatly appreciated. -
Django models, unique together causing updation not insertion
Hi have you ever experienced this before. so lets say I have class Models(models.Model): id = models.IntegerField(primary_key=True) other_id = models.IntegerField() class Meta: unique_together = ('id', 'other_id') m = Models(id = 1, other_id =2) m.save() m = Models(id = 1, other_id = 3) m.save() the result on db will be model with id = 1 and other_id = 3 so basically it is doing updation not insertion -
Django follower structure with manytomany field unable to display in Admin
Here is my follower model: class SocialProfile(models.Model): user = models.OneToOneField(User, unique=True) follows = models.ManyToManyField('self', related_name='followed_by', symmetrical=False) In Admin: class SocialprofileAdmin(admin.ModelAdmin): model = SocialProfile.follows.through The above admin code in admin will give me: An overall view: Inside each profile: I just need it to display username instead of SocialProfile object. I tried a few version like this but they are not working: class FollowsInline(admin.TabularInline): model = SocialProfile.follows.through class UserAdmin(admin.ModelAdmin): list_display = ('user', 'follows') inlines = [FollowsInline, ] -
Django 1.10, static files not working when DEBUG is set to False
My static files stop working when I make DEBUG = False but work perfectly when DEBUG = True. I want to add a custom 404.html page that would render the custom 404 http error. My 404.html page works perfectly when I make DEBUG = True, but by doing this I lose all the static files contents on my webpage. I have read the official documentation to do the same and followed the procedure, but unable to get any luck :( My environment: Django 1.10.5 Python 3.4.3 Sublime IDE Win10 OS Kindly help... -
I get different form to post device list in a group
I want to post the list of device id in a group. I have designed the serializer and APIView for that. But i get different form in browsable API. How can i now test if my post function is working or not? Here is my model, serializer and APIView class DeviceGroup(models.Model): token = models.UUIDField(default=uuid.uuid4, unique=True, editable=False) name = models.CharField(max_length=250, blank=False, null=False) owner = models.ForeignKey(User, blank=False, null=False) class DeviceGroupSerializer(serializers.ModelSerializer): id = serializers.UUIDField(source='token', format='hex', read_only=True) owner = serializers.PrimaryKeyRelatedField(queryset=User.objects.all()) class Meta: model = DeviceGroup fields = ['id','name','owner'] class DeviceGroupAPIView(APIView): permission_classes = (permissions.IsAuthenticated,) serializer_class = DeviceGroupSerializer def get_object(self, user, token): try: return DeviceGroup.objects.filter(owner=user).get(token=token) except ObjectDoesNotExist: return error.RequestedResourceNotFound().as_response() def get(self, request, token=None, format=None): device = self.get_object(request.user, token) serializer = DeviceGroupSerializer(device).data return Response(serializer) def post(self, request, token=None, format=None): print('token') device_group_instance = DeviceGroup.objects.get(token=token) print('token', device_group_instance) for device_token in request.data['devices']: device = Device.objects.get(token=device_token, owner=request.user) device.group = device_group_instance device.save() Here is the screenshot. The url also can be seen for posting list of device id in a group -
The view first.views.download didn't return an HttpResponse object
THis is the download view i have created.Its giving error def download(request):#Download View class GeneratePdf(View): def get(self, request, *args, **kwargs): pdf = render_to_pdf('pdf/invoice.html', data) return HttpResponse(pdf, content_type='application/pdf') -
ModuleNotFound error in django in Django tastypie web application
I am pretty new to Django. When i try to include the urls from the api.py file it returns me an error. Here is api.py file from the articles app folder from tastypie.resources import ModelResource from tastypie.constants import ALL from article.models import Article class ArticleResource(ModelResource): class Meta: querySet = Article.objects.all() resource_name = 'article' here is the urls.py file from the article app folder from django.conf.urls import url from article.views import * from .api import ArticleResource from django.conf.urls import include article_resource = ArticleResource() urlpatterns = [ url(r'^api/',include('article_resource.urls')) ] and the error i get back is this Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x0470C9C0> Traceback (most recent call last): File "C:\Users\Vineeth\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "C:\Users\Vineeth\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\commands\runserver.py", line 121, in inner_run self.check(display_num_errors=True) File "C:\Users\Vineeth\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\base.py", line 374, in check include_deployment_checks=include_deployment_checks, File "C:\Users\Vineeth\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\base.py", line 361, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\Vineeth\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\checks\registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\Vineeth\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\checks\urls.py", line 14, in check_url_config return check_resolver(resolver) File "C:\Users\Vineeth\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\checks\urls.py", line 24, in check_resolver for pattern in resolver.url_patterns: File "C:\Users\Vineeth\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Vineeth\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\urls\resolvers.py", line 313, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\Vineeth\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) … -
NOT NULL constraint failed: device_api_devicegroup.owner_id
I am getting not null contraint failed error while posting a group. How should i fix it? I don't want to show the user in the api so i have not used it in the serializer fields. Do i have to compulsorily add it there? Here is my model, serializer and APIView class DeviceGroup(models.Model): token = models.UUIDField(default=uuid.uuid4, unique=True, editable=False) name = models.CharField(max_length=250, blank=False, null=False) owner = models.ForeignKey(User, blank=False, null=False) class DeviceGroupSerializer(serializers.ModelSerializer): id = serializers.UUIDField(source='token', format='hex', read_only=True) class Meta: model = DeviceGroup fields = ['id','name'] class DevicesGroupsAPIView(APIView): permission_classes = (permissions.IsAuthenticated,) serializer_class = DeviceGroupSerializer def get_object(self, user, token): try: return BaseDevice.objects.filter(owner=user).get(token=token) except ObjectDoesNotExist: return error.RequestedResourceNotFound().as_response() def get(self, request, format=None): """ Returns a list of groups """ reply = {} try: groups = DeviceGroup.objects.filter(owner=request.user) reply['data'] = DeviceGroupSerializer(groups, many=True).data except: reply['data'] = [] return Response(reply, status.HTTP_200_OK) def post(self, request, format=None): """ create a new group """ print('request.data', request.data) print('user', request.user) serializer = DeviceGroupSerializer(data=request.data) print('serializer', serializer) if serializer.is_valid(): serializer.save() return Response(serializers.data, status.HTTP_200_OK) return Response(serializer.errors, status.HTTP_204_NO_CONTENT) -
django - 'int' object has no attribute 'keys'
t_cat_id = t_cat.id cursor.execute("select offered_item,offered_item_category_id from foundation_swaptable where accepted_item = %s", t_cat.id) the code above throws the exception below: 'int' object has no attribute 'keys' when I surround t_cat.id with square brackets as below: cursor.execute("select offered_item,offered_item_category_id from foundation_swaptable where accepted_item = %s", [t_cat.id]) the error is gone. where t_cat is an mptt category object which I fetch as below: MpttCategory.objects.get(category_name=t_category) and it has an id column in DB representation which is integer. can anyone tell me why I get this exception. I just can't associate a meaning with the error. please tell me if more info is needed.. ps. I am a little drunk :) -
Multiple models in a createview
I am using form_valid to run some equations on data before committing to the db. One of my equations requires data from a different model than the one my CreateView is based on. Is there a way to pull data from a model different than the model the CreateView is based on? Model One (referenced in the CreateView): class Plan(models.Model): field = models.FloatField() growth_percent = models.FloatField() Model Two (it holds another field that has the other argument I need): class Data(models.Model): another_arg = models.FloatField() Here's where I am trying to grab 'another_arg' from the second model and pass it as an argument to a function. CreateView in Views.py: class PlanCreateView(generic.CreateView): model = models.Plan fields = ['field'] def form_valid(self, **kwargs): self.object = form.save(commit=False) form.instance.growth_percent = get_growth_by_percent(form.instance.field, another_arg) self.object.save() function that growth_percent is referencing in a services.py file: def get_growth_by_percent(arg1, arg2): growth_percent = arg1 * arg2 return growth_percent_calc Am I going about this right? -
invalid literal for int() with base 10: 'a'
I am trying to create a comment model for a post in django.I want to print the user name along with the comment. This is my comment model class Comment(models.Model): item = models.ForeignKey('app.Item', related_name='comments') user = models.ForeignKey('auth.User', blank=True, null=True) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) approved_comment = models.BooleanField(default=False) def approve(self): self.approved_comment = True self.save() def __str__(self): return self.text This is my view def add_comment_to_post(request, pk): item = get_object_or_404(Item, pk=pk) if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.user = user.username comment.item = item comment.save() return redirect('item_detail', pk=item.pk) else: form = CommentForm() return render(request, 'app/add_comment_to_post.html', {'form': form} ) This is my html code {% for comment in item.comments.all %} {% if user.is_authenticated or comment.approved_comment %} <div class="comment"> <div class="date"> {{ comment.created_date }} {% if not comment.approved_comment %} <a class="btn btn-default" href="{% url 'comment_remove' pk=comment.pk %}"><span class="glyphicon glyphicon-remove"></span></a> <a class="btn btn-default" href="{% url 'comment_approve' pk=comment.pk %}"><span class="glyphicon glyphicon-ok"></span></a> {% endif %} </div> <p> {{comment.user}} <p> <p>{{ comment.text|linebreaks }}</p> </div> {% endif %} {% empty %} <p>No comments here yet :(</p> {% endfor %} -
Django Channels + Elastic Beanstalk
I've set up an Application load balancer that redirects /ws/ requests to port 5000 where I have Daphne running along with 4 workers (that reload via Supervisord). However, in the Chrome console I get the error WebSocket connection to 'wss://api.example.com/ws/' failed: WebSocket is closed before the connection is established. when attempting to connect to my WebSocket via simple JavaScript code (see Multichat for something quite close). Any ideas? Routing.py websocket_routing = [ # Called when WebSockets connect route("websocket.connect", ws_connect), # Called when WebSockets get sent a data frame route("websocket.receive", ws_receive), # Called when WebSockets disconnect route("websocket.disconnect", ws_disconnect), ] Settings.py # Channel settings CHANNEL_LAYERS = { "default": { "BACKEND": "asgi_redis.RedisChannelLayer", "CONFIG": { "hosts": ["redis://:xxxxx@xxxx-redis.xxxxx.1234.usxx.cache.amazonaws.com:6379/0"], }, "ROUTING": "Project.routing.channel_routing", }, } Supervisord.conf [program:Daphne] environment=PATH="/opt/python/run/venv/bin" environment=LD_LIBRARY_PATH="/usr/local/lib" command=/opt/python/run/venv/bin/daphne -b 0.0.0.0 -p 5000 Project.asgi:channel_layer directory=/opt/python/current/app autostart=true autorestart=true redirect_stderr=true stdout_logfile=/tmp/daphne.out.log [program:Worker] environment=PATH="/opt/python/run/venv/bin" environment=LD_LIBRARY_PATH="/usr/local/lib" command=/opt/python/run/venv/bin/python manage.py runworker -v2 directory=/opt/python/current/app process_name=%(program_name)s_%(process_num)02d numprocs=4 autostart=true autorestart=true redirect_stderr=true stdout_logfile=/tmp/workers.out.log daphne.out.log 2017-03-05 00:58:24,168 INFO Starting server at tcp:port=5000:interface=0.0.0.0, channel layer Project.asgi:channel_layer. 2017-03-05 00:58:24,179 INFO Using busy-loop synchronous mode on channel layer 2017-03-05 00:58:24,182 INFO Listening on endpoint tcp:port=5000:interface=0.0.0.0 workers.out.log 2017-03-05 00:58:25,017 - INFO - runworker - Using single-threaded worker. 2017-03-05 00:58:25,019 - INFO - runworker - Using single-threaded worker. 2017-03-05 00:58:25,010 - INFO … -
Django-Celery: importing tasks into celery.py file
I am following the tutorial on here to get periodic tasks defined in my django project working. The article suggests having a celery.py file of the form: from celery import Celery from celery.schedules import crontab app = Celery() @app.on_after_configure.connect def setup_periodic_tasks(sender, **kwargs): # Calls test('hello') every 10 seconds. sender.add_periodic_task(10.0, my_task.s('hello'), name='add every 10') ) @app.task def my_task(arg): print(arg) which works. Now this is good but I don't want to define my tasks locally. my question is, how can I add tasks from other apps? Lets say my project is called my_proj and it has two apps: my_proj and app_with_tasks. the celery.py file above is at the root level in my_proj app's directory and I want to add periodic tasks from app_with_tasks 's tasks.py file. what should I use as my import line? -
django prefetch throughtable
I have a Django model which has a manyToMany relation with an additionnal column: class Field(models.Model): table = models.ForeignKey(Table, on_delete=models.CASCADE, verbose_name=_(u"Table"), related_name="fields") supportedLanguages = models.ManyToManyField(Language, through='FieldsLanguages', through_fields=('field', 'language'), verbose_name=_(u"Supported language"), help_text=_( u"The language that the field supports (must be a language supported by the table.") ) Here is my through table: class FieldsLanguages(models.Model): field = models.ForeignKey(Field, on_delete=models.CASCADE) language = models.ForeignKey(Language, on_delete=models.CASCADE) defaultValue = models.CharField(max_length=255, blank=True, null=True, verbose_name=_(u"Default value"), help_text=_( u"The default value of this field in this language (Overrides the default value of the field).")) I would like to retrieve each defaultValue from the through table and its language in one query. I thought this would do the job: table = Table.objects.get(pk=1) fields = list(table.fields.prefetch_related("supportedLanguages").all().order_by("position")) But unfortunately it doesn't get me the defaultValue of each relation but only it's Language. It could be done in the same query as the query goes already through FieldsLanguages to retrive the Foreign Keys. Any idea how can I accomplish this? Thanks. -
Django/Taggit Searching for posts when all tags and title are contained in the database
I am trying to make a simple search system for my website. I am using python 3.6, Django 1.10.5 and Taggit 0.22.0. When I enter tags into the search form I want it to query the database and return any posts whose tags or title contain at least part of any tags searched. For example: /search/?q=random%2C+stuff would return: Post1 {Title: "How to be funny" Tags: "Random", "isn't", "Funny"} Post2 {Title: "How to make Stuffed Turkey" Tags: "Cooking", "Thanksgiving"} #models.py class Post(models.Model): title = models.CharField(max_length=256) tags = TaggableManager() def __str__(self): return self.title #views.py def index(request): query = request.GET.get('q') # .lower() if (query == None or not query): tags = Post.tags.most_common()[:10] return render(request, 'search/search.html', {'tags':tags}) else: queryList = query.split(',') results = # Query the database to get results return render(request, 'search/results.html', {'query':query, 'results':results}) I have been searching for the best way to achieve this query in django Also the results should be case intensive, plugging TAGGIT_CASE_INSENSITIVE = True into settings.py has not worked for me