Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django static s3 production
Having issues pushing small app static files to heroku. Please bear in mind I am a novice still both to django and heroku. I think my problem may actually be two different issues: serving static, and serving media. Utilizing django-storages. I haven't had luck running the production environment to serve the media files. I am using django 1.8, and my dependencies are in my requirements.txt file for heroku. Here are relevant portions of my code: #settings.py INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'smart_selects', 'storages', ) AWS_S3_SECURE_URLS = False AWS_QUERYSTRING_AUTH = False AWS_ACCESS_KEY_ID = "snip" AWS_SECRET_ACCESS_KEY = "snip" AWS_STORAGE_BUCKET_NAME = "snip" AWS_S3_CUSTOM_DOMAIN = '{}.s3.amazonaws.com'.format(AWS_STORAGE_BUCKET_NAME) #didn't seem to work for me, but was suggested in a guide AWS_S3_HOST = "s3-us-west-2.amazonaws.com/{}/".format(AWS_STORAGE_BUCKET_NAME) #STATICFILES_STORAGE = "myapp.s3utils.StaticS3BotoStorage" STATICFILES_STORAGE = "storages.backends.s3boto.S3BotoStorage" #DEFAULT_FILE_STORAGE = "myapp.s3utils.MediaS3BotoStorage" DEFAULT_FILE_STORAGE = "storages.backends.s3boto.S3BotoStorage" MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIAFILES_LOCATION = 'media' #MEDIA_URL = '/media/' # what it was for dev MEDIA_URL = "https://{}/{}/".format(AWS_S3_HOST, MEDIAFILES_LOCATION) #STATIC_URL = '/static/' # what it was for dev STATICFILES_LOCATION = 'static' STATIC_URL = "https://{}/{}/".format(AWS_S3_HOST, STATICFILES_LOCATION) STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),) STATIC_ROOT = os.path.join(BASE_DIR, 'collected_static') I know I should be storing things in the env, that is to come. First, I'm having trouble connecting my app to s3 … -
Serializer.is_valid() is always False
I have the following Serializer to handle a user: class FriendSerializer(serializers.Serializer): login = serializers.CharField(max_length=15, required=True) password = serializers.CharField(max_length=15, required=True) mail = serializers.CharField(max_length=50, required=True) Currently, my view which processes the POST request to register a new user is, based on the Django REST tutorial: @api_view(['POST']) def register_new_user(request): if request.method == 'POST': print('POST request !') stream = BytesIO(request.body) data = JSONParser().parse(stream) print(data) serializer = FriendSerializer(data=data) print(serializer.is_valid()) else: print('Not a POST request!') return HttpResponse('Nothing') Thus, to simulate a client with a POST request, I use the following lines: import requests import json json_data = json.dumps({'login': 'mylogin', 'password': 'mypassword', 'mail': 'mymail'}) r = requests.post('http://127.0.0.1:8000/register_new_user', json=json_data) However, although the print(data) retrieves, as expected, {"login": "mylogin", "mail": "mymail", "password": "mypassword"} The serializer.is_valid() always returns False. Am I missing any processing of my request? -
Import Errors while deploying Django project
I am deploying a django project for the first time and am having some difficulties. Firstly, when following the django installation instructions on the web server I am using they instruct you to input the following command into the shell: export PYTHONPATH=/home/USERNAME/public_html/lib/python If I do not run this command I get a import error for django.core.management. It is annoying to have to enter this in every time I log into the shell! I have tried adding *manage.py* sys.path.append('/home/USERNAME/public_html/lib/python') but this doesnt work and I still have to run the export command every time I log into shell. My second issue is I am also getting an import error for the site packages my project is using. Using $ pip list It showes all the packages are correctly installed. So in conclusion, I am getting an import error for django.core.management everytime I log into shell. Then I will enter export PYTHONPATH=/home/USERNAME/public_html/lib/python and my first error goes away. But after that I get import errors for every site package i try to use even though they are correctly installed. Any advice on how to correct these issues? -
Django - LEFT OUTER JOIN with additional conditions
Is it possible in Django for the ORM to emit a query with a JOIN clause that would contain additional expressions? I want to achieve something like that: LEFT OUTER JOIN "meals_meal" ON ("restaurants_restaurant"."id" = "meals_meal"."restaurant_id") AND "meals_meal"."collection_to" > now() AND "meals_meal"."status" = 0 PS. Please don't ask me for the rest of this query as it's not important for this question. The same goes for my django code - I've analyzed this problem and I'm positive it can't be solved any other way. -
User creation with unique constraint in Django Rest framework
I researched about it in Google, and have tried in lot of ways but still not able to get it right. Here are the requirements: A one to one field for extending User model, so this has been achieved and the new model is called Customer. Now, with new user 201 response is returned BUT not all the data is serialized, only date_of_birth is coming in json format, I want even the User to be in that json response. If I try to add a user with a username which already exists it plays up really bad. I am trying with Try and Except but it really doesnt work. I want a response of 409 conflict to be sent if the username already exists. Here is UserSerializer.py: from django.contrib.auth.models import User from rest_framework import serializers class UserSerializer(serializers.HyperlinkedModelSerializer): new_username = serializers.SerializerMethodField() class Meta: model = User fields = ('url', 'pk', 'username', 'email', 'is_staff', 'new_username') extra_kwargs = { 'username': {'validators': []}, } def get_new_username(self, obj): return obj.username Here is Customer model: from django.db import models from django.contrib.auth.models import User class Customer(models.Model): user = models.OneToOneField(User, related_name="customer", on_delete=models.CASCADE) date_of_birth = models.DateField(max_length=8) def __unicode__(self): return u'%s' % self.user.username Here is CustomerSerializer class: from django.contrib.auth.models import … -
django-photologue retrieve photos on angular2 frontend
I am trying to use django-photologue, I installed it and did mentioned settings. I have a model Blog as follows: class Blog(models.Model): title = models.CharField(max_length=150) thumbnail = models.ForeignKey(Photo, related_name='blogs') I am able to add images to blog objects, however I do not see the thumbnail in my admin interface (clicking on it basically opens base.html stored in templates folder which I simply copied from example_project, this base.html is not important for me, however seeing this thumbnail could be interesting): How can I retrieve blog objects on my frontend with all associated images? I tried writing a view as follows: @api_view(('GET',)) def get_blogs(request): blogs = Blog.objects.all() serializer = BlogSerializer(blogs, many=True) return Response(serializer.data) which returns: [ { "id": 1, "title": "My test blog", "thumbnail": 1 } ] How can I retrieve images on my frontend? -
missing 1 required positional argument: 'queryset'
I am attempting to update an extended user model profile in admin.py actions. I have been researching this for a couple hours now and have come up short. I am receiving a pc_add_1() missing 1 required positional argument: 'queryset' error, please help. class ProfileAdminInLine(admin.StackedInline): model = Profile class ProfileAdmin(UserAdmin): list_display = ['username', 'email', 'first_name', 'last_name', 'is_staff', 'rewards_punch_card', 'rewards_tier', 'lularippee_credits'] list_select_related = True inlines = [ProfileAdminInLine] actions = ['pc_add_1', 'pc_add_2', 'pc_add_3', 'pc_add_4', 'pc_add_5', 'pc_add_6', 'pc_add_7', 'pc_add_8', 'pc_add_9'] def rewards_tier(self, user): return user.profile.rewards_tier def rewards_punch_card(self, user): return user.profile.rewards_current def lularippee_credits(self, user): return user.profile.rewards_credits def pc_add_1(self, request, user, queryset): punch_card = user.profile.rewards_current tier = user.profile.rewards_tier credits = user.profile.rewards_credits punch_cards_updated = queryset.update(punch_card + 1) if punch_cards_updated == 10: queryset.update(punch_card == 0) if tier == 1: queryset.update(tier + 1) queryset.update(credits + 25) elif tier == 2: queryset.update(tier + 1) queryset.update(credits + 35) elif tier == 3: queryset.update(tier + 1) queryset.update(credits + 45) elif tier == 4: queryset.update(tier + 1) queryset.update(credits + 55) elif tier == 5: queryset.update(credits + 65) elif tier == 6: queryset.update(credits + 65) else: pass -
How to update with method PUT django-rest-framework
when prompted PUT (update) out this error Can not call .is_valid () as no data = keyword argument was passed when instantiating the serializer instance. my view: def get_serializer(self, *args, **kwargs): queryset = Producer.objects.get(pk=self.kwargs['pk']) if self.request.user.is_authenticated: return ProducerSerializer(queryset, fields=('short_info',)) if self.request.method == 'PUT' or self.request.method == 'PATCH': return ProducerUpdateSerializer else: return ProducerSerializer(queryset, fields=('website', 'phone', 'email', 'contacts', 'short_info')) def get_queryset(self): return Producer.objects.filter(pk=self.kwargs['pk']) my serializer class DynamicFieldsModelSerializer(serializers.ModelSerializer): def __init__(self, *args, **kwargs): # Don't pass the 'fields' arg up to the superclass fields = kwargs.pop('fields', None) # Instantiate the superclass normally super(DynamicFieldsModelSerializer, self).__init__(*args, **kwargs) if fields is not None: for i in fields: print self.fields.pop(i) class ProducerSerializer(DynamicFieldsModelSerializer): tags = TagListSerializerField() categories = serializers.StringRelatedField(many=True) contacts = ProducerContactSerializer(many=True) country = CountryField(country_dict=True) business_type = ChoicesSerializerField() class Meta: model = Producer fields = ('id', 'business_type', 'logo', 'name', 'slug', 'country', 'city', 'street_address', 'zip', 'short_info', 'info', 'website', 'categories', 'tags', 'contacts', 'email', 'phone') class ProducerUpdateSerializer(serializers.ModelSerializer): tags = TagListSerializerField() categories = serializers.StringRelatedField(many=True) class Meta: model = Producer fields = ('id', 'business_type', 'logo', 'name', 'slug', 'country', 'city', 'street_address', 'zip', 'short_info', 'info', 'website', 'categories', 'tags') when prompted PUT (update) out this error Can not call .is_valid () as no data = keyword argument was passed when instantiating the serializer instance. -
Django smart select many to many field filter_horizontal/filter_vertical does not allow chaining
Hi I am doing a project in Django 1.10. For this project I am using django-smart-select for chaining input in the admin panel. It works fine. But for many to many fields chaining if I use filter_horizontal/filter_vertical then the chaining does not work any more. There was no solution in there github page. How can i solve this problem? Is there another app like this? -
Django TemplateDoesNotExist {% extends base.html %} - where should template be?
I'm starting a very simple Django app but having trouble with extending an html file. I have base.html and index.html both within my_site/my_app/templates/my_app. i.e. my_site/my_app/templates/my_app/base.html and my_site/my_app/templates/my_app/index.html. Within the index.html file I have {% extends 'base.html' %}. My settings.py file has BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] But when I visit my index view at http://127.0.0.1:8000/index/: def index(request): return render(request, 'my_app/index.html') I get the following error: TemplateDoesNotExist at /index/ base.html Request Method: GET Request URL: http://127.0.0.1:8000/index/ Django Version: 1.10.3 Exception Type: TemplateDoesNotExist Exception Value: base.html Do I have the base.html file saved in the wrong place or is it something else? I have not been able to solve this. -
Alternatives to django-autocomplete-light and django-ajax-selects?
I have dropdowns in my project forms that might include hundreds of values . I spent some time trying to use django-autocomplete-light and django-ajax-selects packages but it simply doesn't work for me and I am not getting answers on SO. Django ajax-selects package is not working. What I am missing? django-autocomplete-light displays empty dropdown in the form Is there a pure Django simple solution for this problem without JS? Popup with search for example. -
django Display Uploaded photo in template
in my UserProfile app i'm trying to add a photo Upload ,in the admin panel i can see the photo link when i upload it from user profile and it work fine but i can't display it in my template urls.oy urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) models class UserProfile(models.Model): user = models.OneToOneField(User, related_name='user') photo = models.FileField(null=True, blank=True) def create_profile(sender, **kwargs): user = kwargs["instance"] if kwargs["created"]: user_profile = UserProfile(user=user) user_profile.save() post_save.connect(create_profile, sender=User) views @login_required() def edit_user(request, pk): user = User.objects.get(pk=pk) user_form = UserForm(instance=user) ProfileInlineFormset = inlineformset_factory(User, UserProfile, fields=('photo',)) formset = ProfileInlineFormset(instance=user) if request.user.is_authenticated() and request.user.id == user.id: if request.method == "POST": user_form = UserForm(request.POST, request.FILES, instance=user) formset = ProfileInlineFormset(request.POST, request.FILES, instance=user) if user_form.is_valid(): created_user = user_form.save(commit=False) formset = ProfileInlineFormset(request.POST, request.FILES, instance=created_user) if formset.is_valid(): created_user.save() formset.save() return HttpResponseRedirect('/accounts/profile/') return render(request, "account/account_update.html", { "noodle": pk, "noodle_form": user_form, "formset": formset, }) else: raise PermissionDenied in my template i tried all this combinations but none works <div> <img src="{{user.user.photo}}" alt="image example"/> <img src="{{user.photo.url}}" alt="image example"/> <img src="{{user.image.url}}" alt="image example"/> <img src="{{instance.photo.url}}" alt="image example"/> <img src="{{instance.image.url}}" alt="image example"/> <img src="{{UserProfile.photo.url}}" alt="image example"/> <img src="{{UserProfile.image.url}}" alt="image example"/> <img src="{{created_usere.image.url}}" alt="image example"/> <img src="{{created_user.photo.url}}" alt="image example"/> </div> -
how to use StreamingHttpResponse in render_to_response
I tried to use StreamingHttpResponse in render_to_response,but failed. My codes are below: def index(request): def test(): yield "nihaoma" import time time.sleep(5) yield "shidene" yield "haodene" #return StreamingHttpResponse(test()) return render_to_response("result.html",{'output':StreamingHttpResponse(test())}) I can get what i want by return StreamingHttpResponse(test()),however,I want to let the string which will be print to the browser can be more goodlooking,so I want it print in my result.html templete file and I tried to use render_to_response("result.html",{'output':StreamingHttpResponse(test())}),but this can not print the strings in def test(),it will only print <django.http.response.StreamingHttpResponse object at 0x7f71dbfa05f8> to the browser. My result.html file content is: {% extends "base.html" %} {% block extrastyle %} <style> #myoutput{ position:fixed; top: 30%; left: 50%; width:45%; height:60%; margin-top: 0px; margin-left: -22%; border: 15px solid transparent; background-color: transparent; color:#ffc080; font-size:15px; font-weight:600; font-family:文泉驿等宽正黑; overflow:auto; } </style> {% endblock %} {% block content %} <div id="myoutput"> {{ output|linebreaksbr }} </div> {% endblock %} Can anybody help me? [I worked on django 1.10.3] thx. -
django-autocomplete-light displays empty dropdown in the form
I am trying to use django-autocomplete-light From this tutorial https://github.com/yourlabs/django-autocomplete-light/blob/master/docs/tutorial.rst for my tenant value My tenant model is class Tenant(CommonInfo): version = IntegerVersionField( ) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=40) def __unicode__(self): return u'%s %s %s ' % ("#", self.id,"first_name", self.first_name, "last_name") In my view: from django.shortcuts import render from dal import autocomplete from client.models import Tenant class TenantAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): # Don't forget to filter out results depending on the visitor ! if not self.request.user.is_authenticated(): return Tenant.objects.none() qs = Tenant.objects.all() if self.q: qs = qs.filter(last_name__istartswith=self.q) return qs in url from django.conf.urls import url, include,patterns from client import views urlpatterns = [ url( r'^tenant-autocomplete/$', views.TenantAutocomplete.as_view(), name='tenant-autocomplete', ), ] and in form class LeaseTenantForm(forms.ModelForm): tenant = forms.ModelChoiceField( queryset=LeaseTenant.objects.all(), widget=autocomplete.ModelSelect2(url='tenant-autocomplete') ) class Meta: model = LeaseTenant exclude = ['lease'] However my template I don't see the input text field but the empty dropdown. Tenant* > > <select class="modelselect2" data-autocomplete-light-function="select2" > data-autocomplete-light-url="/client/tenant-autocomplete/" > id="id_tenant" name="tenant"> <option value="" > selected="selected">---------</option> </select> </div> </div> So basically the autocomplete is not working . What should I validate to make it work? -
Celery group multiple tasks in one design
I am new to Celery and got a question. My setup is Django-Redis-Celery Let's take an example of a task sending email: TASKS @task def send_email(message): mailserver.sendOneMessage(message) VIEWS class newaccount(APIView): def post(self, request, format=None): send_email.delay(request.data.email) This works perfectly fine, django sends messages to redis and those are picked up by celery then to execute task. But i want to improve the system so that celery picks up all messages from redis at certain interval and executes a single task with multiple messages, because connectig to email server is slow and sending multiple messages as a single request will result in a faster process. I want something like this to work: TASKS @task def send_emails(messages): mailserver.sendMultipleMessages(messages) -
python-social-auth patterns errors
I downloaded python-social-auth from github and tried to use but I encounter an error when I try to install patterns packet. I'm using the last version of django and the last version of python. I've read that patterns is no longer available with python 3.x. Here patterns package is used: urlpatterns = patterns('', url(r'^$', 'example.app.views.home'), url(r'^admin/', include(admin.site.urls)), url(r'^email-sent/', 'example.app.views.validation_sent'), url(r'^login/$', 'example.app.views.home'), url(r'^logout/$', 'example.app.views.logout'), url(r'^done/$', 'example.app.views.done', name='done'), url(r'^ajax-auth/(?P<backend>[^/]+)/$', 'example.app.views.ajax_auth', name='ajax-auth'), url(r'^email/$', 'example.app.views.require_email', name='require_email'), url(r'', include('social.apps.django_app.urls', namespace='social')) ) I tried to delete patterns and put [ ... ] but it doesn't work. Any suggestion? -
django leaflet - adding/removing controls on HTML page button click
I am currently using django-leaflet and leaflet-draw controls. I want to make the draw controls available (add to map) on a certain event such as a toggle button. I currently have a simple jQuery skeleton: $("#mode").on("click", function(){ if(document.getElementById('mode').checked){ $("#save").removeClass("hidden"); alert("Edit Mode"); //event where I want to add controls to map //map.addControl(drawControl); }else{ $("#save").addClass("hidden"); alert("View Mode"); //event where I want to remove controls from map //map.removeControl(drawControl); } }); I have my map.js external from the html file and I call this in my template with only this line (as instructed in django-leaflet): {% leaflet_map "mapdiv" callback="leafletinit" %} Note: I also tried to include the drawControl variable available on the same page but I don't think I'm doing it correctly... My map.js is loading correctly as it does load the map and the controls on a straight forward no event view -
Django reverse relation order_by queryset duplication
I'm using Django to build out in-house application and I'd like to use django's reverse relation order_by options. As specified in documentation, doing that can result in queryset duplication. In other words, using order_by() on the QuerySet could return more items than you were working on to begin with - which is probably neither expected nor useful. For example, this piece of code class Reservation(models.Model): class Meta: ordering = ('status', 'service_date', 'stops__time') status = model.Charfield(max_length=100) class Stop(models.Model): class Meta: ordering = ('time',) time = models.TimeField(blank=True, null=True) reservation = models.ForeignKey(Reservation, related_name='stops') is returning duplicated results. How can I solve that? Is there any other way that won't result in queryset duplication? -
Get selected radio button value in view in Django
I have a case where I want to use radio buttons as my query option so I can get correct query set according to selected radio button. I can not find a way to get selected radio button value in form. There are a lot of info about using form class. what about simple html form. part of form is: <label for="house-all-id">All</label> <input type="radio" id="house-all-id" name="h-type" value="0"/> <label for="house-orp-id">Just case one</label> <input type="radio" id="house-orp-id" name="h-type" value="1"/> <label for="house-inm-id">Just case two</label> <input type="radio" id="house-inm-id" name="h-type" value="2"/> These radio-buttons are part of a from with another widgets to help my get correct QuerySet. In view: h_type = request.POST.get('h_type') This returns a none-type object. How can I get value of selected radio button? -
django + Nginx + Gunicorn - 404 for Static file when debug is false
I dont know how nginx serves the static files /etc/nginx/site-available/default : upstream example.com { server unix:/home/www/example/env/run/gunicorn.sock fail_timeout=0; } server { listen 80; server_name example.com; client_max_body_size 4G; access_log /home/www/example/logs/nginx-access.log; error_log //home/www/example/logs/nginx-error.log; location /static/ { alias /home/www/example/codeab/static/; } location /uploads/ { alias /home/www/example/codeab/uploads/; } location / { include proxy_params; proxy_pass http://unix:/home/www/example/env/run/gunicorn.sock; } # Error pages error_page 500 502 503 504 /500.html; location = /500.html { root /home/www/example/templates/; } error_page 404 /401.html; location = /401.html { root /home/www/example/codeab/templates/; internal; } } Django setting.py STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static_content/'), ) STATIC_ROOT = os.path.join(BASE_DIR,'static/') Also , I did collectstatic before DEBUG = False It seems that nginx is not considering the above config file, as for 404 page it is not showing my custom 401.html page. After editing the config, I linked it to site-enabled by sudo ln -s /etc/site-available/default /etc/site-enabled/default service nginx reload sudo service nginx restart Please help, or let me know If I am missing any things. -
django rest framework model foreign key
I have two models class Order(models.Model): fields... class OrderItem(models.Model): fiels... order = models.ForeignKey(Order, related_name='items') and I have two serializers: class CreateOrderItemSerializer(serializers.ModelSerializer): class Meta: model = OrderItem resource_name = 'order-item' fields = ('order', 'count') ..... class OrderSerializer(serializers.ModelSerializer): items = CreateOrderItemSerializer(many=True) class Meta: model = Order resource_name = 'order' fields = ('id','items') I posted order with items array like this: { 'ordername': 'foo', 'items': [{ 'name': 'foo1', },{ 'name': 'foo2', }, ] } But I have error: "order":["This field is required."] how can I first create order later create items with this orderid? -
Maximum Recursion Depth? How to prevent?
I'm trying to recurse my list. but even if I have only one task under another task it runs ERROR maximum recursion depth? Why? task_recurse.html {% if items %} <ul> {% for task in items %} <li> {{ task.name }} {% with items=task.subtask.all template_name="task_recurse.html" %} {% include template_name %} {% endwith %} </li> {% endfor %} </ul> {% endif %} task.html {% include "task_recurse.html" with items=items %} Task model class task(models.Model): name = models.CharField(max_length=100) notes = models.TextField() created = models.DateTimeField() created_by = models.ForeignKey(User) subtask = models.ManyToManyField('self') It gives me a error on the view? Is this the problem? def tasks(request): items = task.objects.all() return render(request, 'tasks.html', {'items': items}) So two questions really: 1) Why does this return maximum recursion depth when I only have two tasks where only one task is a subtask ? 2) How can I prevent infinite recursion ? -
Detailed documentation of pydanny's cookiecutter?
I tried using it but instead of kick-starting me it only caused a lot of confusions. Is there a book or article somewhere that explains what every single file that cookiecutter generates does? I mean there's a documentation but it does not really help. Feel free to delete if this does not belong here. -
Custom lookup is not being registered in Django
I've created a custom lookup. I'm using it for a query, however, when I do so, the error Related Field got invalid lookup: lcb is thrown. I'm assuming that this is because this custom lookup isn't being registered properly. As you'll see below, I've tried several things and I'm lost as to what the issue is. Here's my code: tenants/views.py from main.lookups import * def find_tenants(request, house_id): house = HouseListing.objects.get(pk=house_id) applications = HousingApplication.objects.filter(date_from__gte=house.available_from) applications = applications.filter(pets__lcb=house.allowed_pets.values_list('id', flat=True)) context = {'house': house, 'applications': applications} return render(request, 'landlords/find-tenants.html', context) main/lookups.py from django.db.models import Lookup, ManyToManyField # Custom lookups @ManyToManyField.register_lookup class ListContainedBy(Lookup): lookup_name = 'lcb' def as_sql(self, compiler, connection): lhs, lhs_params = self.process_lhs(compiler, connection) rhs, rhs_params = self.process_rhs(compiler, connection) params = lhs_params + rhs_params return '%s <@ %s' % (lhs, rhs), params I find this very strange, as the docs suggest registering the lookup in the AppConfig, or in models.py. I've tried both of these things and neither worked. Traceback Environment: Request Method: GET Request URL: http://127.0.0.1:8000/landlords/find-tenants/5/ Django Version: 1.10.2 Python Version: 2.7.12 Installed Applications: ['main.apps.MainConfig', 'tenants.apps.TenantsConfig', 'landlords.apps.LandlordsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'django.contrib.postgres', 'imagekit'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "/Users/mightyspaj/Development/Projects/housingfinder/lib/python2.7/site-packages/django/core/handlers/exception.py" in inner 39. … -
Grab file from Desktop in Django Shell
I have an app named cars inside my Django project that has a utils.py file that contains various utility methods used by the application. One of them (grab_new_models) is used to process a CSV file that's normally picked up via a periodic tasks that fetches the file from a remote location. The method itself is passed the CSV file itself normally so that the method looks like def grab_new_models(csv_file): Right now I'm trying to update the code with some new functionality and having issues testing it locally. Using the Django shell, I can't figure out how to pass the file into the method to test it. I have a copy of the csv file on my Desktop. How do I call this method from the Django shell and pass it my local csv file?