Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: filtering expected content type?
Django offers a way to restrict the accepted methods using the @request_http_method decorator, so if a particular view can only respond to a GET request we can do: @require_http_methods(['GET']) def only_get(request): pass Otherwise we get a 403 (FORBIDDEN) response. However, I would also like to accept a Content-Type of json. If it's not json it should reject the request as well (I am guessing a 403 response would also be the appropriate one). Does Django have anything similar to the require_http_methods decorator, but for content types? If not, how else could I tackle this scenario? -
Python-social-auth check associations
How can I check if user is associated with a specific backend? I can do try catch with request.user.social_auth.get(provider='facebook') but I better like boolean checks like: request.user.social_auth.facebook.is_available And how can I do this in template? Should I implement the method on the user model myself? -
Not able to see Google+ API data and API details when using google as social account provider in django-all-auth
We are using google as social provider with below configuration in a django website: django-allauth==0.23.0 SOCIALACCOUNT_PROVIDERS = { 'google': { 'SCOPE': ['profile', 'email'], 'AUTH_PARAMS': { 'access_type': 'online' } }} Credentials are created in API Manager in Google developer console. We are able to login to website using google. But, there is no data (Quota, Traffic etc.) visible in google developer console for this Google+ API. -
How to stop a supervisord program immediately and ignore the `stopwaitsecs` settings
I use supervisord to manage my django-celery task queue. To prevent potential data loss, I set the stopwaitsecs configuration to an extremely large value. In some rare cases I need to stop the program immediately. How can I achieve that? -
Django decorator unresolved reference
I created a decorator to return JSON from a view, however when using it ontop of the method I am getting an unresolved reference. This is the decorator: def json_response(func): def decorator(request, *args, **kwargs): ... return HttpResponse(data, 'application/json') return decorator And this is how I am trying to use it: @json_response def get_json(request, param1, param2): return { 'param1': param1, 'param2': param2 } What am I doing wrong? I am using Django 1.4. -
Recent entries from each category in django model
I need to show in the template most recent entries from each category is the Instarama, Facebook, Twitter. Here my solution, but it does not work. My get_queryset method but isn't working: def get_queryset(self): return super(OnlineManager, self).get_queryset().filter(is_online=True).order_by('-date').annotate(Count('social_channel'))[:1] This is my model: class Social(models.Model): social_channel = models.CharField(max_length=25, choices=SOCIAL_CHANNELS, default=SOCIAL_CHANNELS[0][0], blank=True) text = models.TextField(max_length=5000, blank=True, default='') is_online = models.BooleanField(default=True) position = models.PositiveIntegerField(default=0) date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.social_channel class Meta: ordering = ['position'] -
Login in view tests causing TypeError: quote_from_bytes() expected bytes in Django
I have this simple test: def setUp(self): self.carrier = Carrier.objects.create(name='SomeCarrier') self.dispatcher = Dispatcher.objects.create(carrier=self.carrier, email='dispatcher@email.com') self.dispatcher.set_password('40') self.dispatcher.save() login = self.client.login(username='dispatcher@email.com', password='40') self.assertTrue(login) def test_payment_page_redirects_if_carrier_has_no_plan(self): response = self.client.get(reverse('billing:payment')) self.assertRedirects(response, reverse("dashboard:home")) the line when I do self.client.get(...) is giving me the following error: Traceback (most recent call last): File "/home/dasar/virtualenvs/mds3/lib/python3.4/site-packages/django/core/handlers/base.py", line 204, in get_response response = middleware_method(request, response) File "/home/dasar/DjangoProjects/backend/apps/dashboard/middleware.py", line 13, in process_response response.set_cookie('userName', quote(request.user.name)) File "/usr/lib/python3.4/urllib/parse.py", line 694, in quote return quote_from_bytes(string, safe) File "/usr/lib/python3.4/urllib/parse.py", line 719, in quote_from_bytes raise TypeError("quote_from_bytes() expected bytes") TypeError: quote_from_bytes() expected bytes If I remove self.clinet.login code from the setUp function, the error disappears. What could be the problem? -
Django model migration added two unwanted fields when using AbstractBaseUser class
Django 1.9 Python 3.4 I created a custom Users model using AbstractBaseUser class. Below is the code. class UserModel(AbstractBaseUser): # custom user class SYSTEM = 0 TENANT = 1 parent_type_choices = ( (SYSTEM, 'System'), (TENANT, 'Tenant') ) sys_id = models.BigIntegerField(primary_key=True, blank=False) parent_type = models.PositiveIntegerField(choices=parent_type_choices, null=False, blank=False) parent_sys_id = models.ForeignKey('tenant.TenantModel', on_delete = models.SET_NULL, null=True, blank=True) last_name = models.CharField(null=False, blank=False, max_length=40) first_name = models.CharField(max_length=40, null=False, blank=False) display_name = models.CharField(max_length=80, unique=True, null=False, blank=False) login = models.CharField(max_length=40, unique=True, null=False, blank=False) authentication_method = models.CharField(max_length=80) pwd = models.CharField(max_length=40) access_valid_start = models.DateTimeField() access_valid_end = models.DateTimeField() created_when = models.DateTimeField() created_by = models.BigIntegerField() last_updated_when = models.DateTimeField() last_updated_by = models.BigIntegerField() notes = models.CharField(max_length=2048) USERNAME_FIELD = "login" class Meta: app_label = "accounts" db_table = "Users" When I migrated the changes, table was created in db with two extra fields which I didn't defined. Password and last_login were added. desc Users; +-----------------------+------------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-----------------------+------------------+------+-----+---------+-------+ | password | varchar(128) | NO | | NULL | | | last_login | datetime | YES | | NULL | | | sys_id | bigint(20) | NO | PRI | NULL | | | parent_type | int(10) unsigned | NO | | NULL | | … -
Unable to discern Class based views and recursive **Kwargs fetching in pyBB library?
I'm modifying the django PyBB library but cant figure out what this recursive view is doing. Firstly I'm used to method based views and secondly, I'm not clear on how the context dictionary is being set here. class IndexView(generic.ListView): template_name = 'pybb/index.html' context_object_name = 'categories' def get_queryset(self): return perms.filter_categories(self.request.user, Category.objects.all()) def get_context_data(self, **kwargs): ctx = super(IndexView, self).get_context_data(**kwargs) categories = ctx['categories'] for category in categories: category.forums_accessed = perms.filter_forums(self.request.user, category.forums.filter(parent=None)) ctx['categories'] = categories return ctx This works but I need more context for several templates that I'm extending and including. So, currently, the context variable is a dictionary of 'categories' = categories; where categories is a list of category objects. Each of the categories then has an attribute .forums_accessed which is a list of forum objects. Now, I want to define an attributes .topics_created for each forum attribute to have a list of topic objects under each forum. Something like this: class IndexView(generic.ListView): template_name = 'pybb/index.html' context_object_name = 'categories' def get_context_data(self, **kwargs): ctx = super(IndexView, self).get_context_data(**kwargs) categories = ctx['categories'] for category in categories: category.forums_accessed = perms.filter_forums(self.request.user, category.forums.filter(parent=None)) for forum in category.forums_accessed: qs = forum.topics.order_by('-sticky', '-updated', '-id').select_related() forum.topics_created = perms.filter_topics(self.request.user, qs) ctx['categories'] = categories return ctx I'm passing the context to each template … -
How to avoid or direct elsewhere django's django.server access logs?
I'm new to django and tried to configure logging in my django project. I've setup few loggers/handlers etc in settings.py file. Now in my python code I only initiate a single logger and using it for logging. In the log file I am seeing logs from my logger but also separate access logs having below format - [09/Sep/2016 07:55:32] INFO [django.server:131] "GET /static/images/logo.png HTTP/1.1" 304 0 I have disable_existing_loggers set to True, also propagate is set to False in handler configuration. My idea is to keep the access logs separate from app logs, but I'm not able to figure out how to direct access logs correctly. -
Getting indirect routes Django ORM
I am making a backend for a bus routing app and I am stuck and this particular part. Firstly this is my models.py file. from __future__ import unicode_literals from colorfield.fields import ColorField from django.db import models # Create your models here. class BusStop(models.Model): name = models.CharField(max_length=100, blank=False) lat = models.DecimalField( max_digits=9, decimal_places=6, blank=True, null=True) long = models.DecimalField( max_digits=9, decimal_places=6, blank=True, null=True) isDisabled = models.BooleanField(default=False) stop_info = models.TextField(blank=True, null=True) def __unicode__(self): return self.name class BusRoute(models.Model): name = models.CharField(max_length=100, blank=False) start_stop = models.ForeignKey(BusStop, related_name="routes_start") end_stop = models.ForeignKey(BusStop, related_name="routes_end") path = models.ManyToManyField(BusStop, through="BusRoutePath") def route_path(self): return ",".join([str(p) for p in self.path.all()]) def __unicode__(self): return self.name class BusRoutePath(models.Model): """ Path of the route with ordering of bus stops. """ route = models.ForeignKey(BusRoute) stop = models.ForeignKey(BusStop) order = models.IntegerField("Bus stop order") # This should start with 0 duration = models.DurationField(blank=True, null=True) fare_bt_stops = models.DecimalField( max_digits=6, decimal_places=2, blank=False) def __unicode__(self): return "%s-%s-%d" % (self.route.name, self.stop.name, self.order) class Bus(models.Model): class Meta: verbose_name = 'Bus' verbose_name_plural = 'Buses' color = ColorField(default='#FF0000') number = models.CharField(max_length=50, blank=True, null=True) bus_info = models.TextField(blank=True, null=True) def __unicode__(self): return self.number class Ride(models.Model): route = models.ForeignKey(BusRoute) bus = models.ForeignKey(Bus) departure = models.DateTimeField(blank=False) schedule_info = models.TextField() status = models.CharField(max_length=100, default="On Time", choices=[('On Time', 'On Time'), ('Delayed', … -
ImportError: No module name rest_framework
I have both python 2.7 and 3.5 installed. While creating a django project, I selected Python 3.5 as my python interpreter. And I also installed rest framework but I find this error while running my django project. Help Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/Library/Python/2.7/site-packages/Django-1.10-py2.7.egg/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/Library/Python/2.7/site-packages/Django-1.10-py2.7.egg/django/core/management/__init__.py", line 341, in execute django.setup() File "/Library/Python/2.7/site-packages/Django-1.10-py2.7.egg/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/Library/Python/2.7/site-packages/Django-1.10-py2.7.egg/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/Library/Python/2.7/site-packages/Django-1.10-py2.7.egg/django/apps/config.py", line 90, in create module = import_module(entry) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) ImportError: No module named rest_framework -
Django haystack - icontains not working
I have a field in my index as title = indexes.CharField(model_attr='title') So When I am querying like SearchQuerySet().filter(title__icontains='text').models(MyModel) this doesn't return the exact results as expected. Expected: This should return all the objects which matches 'text' with their title. Any suggestions? -
How to store my python/django object in session using redis-django?
I have an object to store in redis-django session so that i can update or edit that object in session. Can anyone help me how to do it or explain me how it works ? -
i want to add my sql database as well as default database that is mysqli
settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } i do not have an idea about how to use SQL database also in my Django project please provide me a simple as well as easy way to do. i want to use multiple database as well the default one and mySQL database -
What does .only django queryset really do?
I heard in the Django documentation it optimizes so I did a little bit of experimentation. So I did this: >>> x = Artist.objects.only('id').filter() >>> print x.query SELECT "store_artist"."id" FROM "store_artist" >>> y = Artist.objects.filter() >>> print y.query SELECT "store_artist"."id", "store_artist"."name", "store_artist"."birth_date" FROM "store_artist" I can see that the query changed however I did a further test: >>> for _x in x: ... _x.name ... u'Beyone' u'Beyoneeee' u'Beyone231231' u'Beyone2222' u'No Album' >>> for _y in y: ... _y.name ... u'Beyone' u'Beyoneeee' u'Beyone231231' u'Beyone2222' u'No Album' So if you've noticed it just has the same result. How did that happen? I thought that in the y variable I just fetched the id so the name should not appear or be invalid Here is my model by the way: class Artist(EsIndexable, models.Model): name = models.CharField(max_length=50) birth_date = models.DateField() -
Django Postgres ArrayField __contain lookup does not behave expectedly
This is my models.py: class Dog(models.Model): name = models.CharField(max_length=200) data = JSONField() def __unicode__(self): return self.name I did this in the django shell: Dog.objects.create(name='Rufus', data={ 'breed': 'labrador', 'owner': { 'name': 'Bob', 'other_pets': [{ 'name': 'Fishy', }], }, }) Dog.objects.create(name='Meg', data={'breed': 'collie'}) Dog.objects.filter(data__breed__contains='l') However when I did the last command it gave me an empy queryset return: <QuerySet []> The two objects (Meg and Rufus) should have both returned because they both contain l -
run django projact from another python program
are anyway to run django project from another python program without useing subprocess or os.system. im trying to use : os.system("python manage.py runserver") and : subprocess.call("python", "manage.py", "runserver") but i want to run it from kivy in android and android don't have python builtin django local server is using as serverside of webwiew. i find runpy module but it can't run django. how can i do this ? -
How do i save many to many fields objects using django rest framework
I have three models Blogs, Posted, Tags. In Blogs model I have fields 'postedin' as foreign key to Posted model and 'tags' as manytomany fields to Tags model. models.py: class Posted(models.Model): name = models.CharField(_('Posted In'),max_length=255, unique=True) class Tags(models.Model): name = models.CharField(_('Tag Name'),max_length=255, unique=True) class Blogs(models.Model): author = models.ForeignKey(CustomUser) title=models.CharField(max_length=100) postedin=models.ForeignKey(Posted) tags= models.ManyToManyField(Tags) content = models.TextField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) views.py: class BlogViewSet(viewsets.ModelViewSet): queryset=Blogs.objects.order_by('-created_at') serializer_class= BlogsSerializer def get_permissions(self): if self.request.method in permissions.SAFE_METHODS: return (permissions.AllowAny(),) return (permissions.IsAuthenticated(),IsAuthorOfBlog()) def perform_create(self,serializer): serializer.save(author=self.request.user) return super(BlogViewSet,self).perform_create(serializer) serializers.py: class TagsSerializer(serializers.ModelSerializer): class Meta: model = Tags fields = ('pk','name') read_only_fields=('pk','name') class PostedSerializer(serializers.ModelSerializer): class Meta: model = Posted fields = ('pk','name') read_only_fields=('pk','name') class BlogsSerializer(serializers.ModelSerializer): author = AccountSerializer(read_only=True,required=False) tags=TagsSerializer(read_only=True,many=True) tags_id = serializers.PrimaryKeyRelatedField(queryset=Tags.objects.all(), write_only=True) postedin = PostedSerializer(read_only=True) postedin_id = serializers.PrimaryKeyRelatedField(queryset=Posted.objects.all(), write_only=True) class Meta: model = Blogs fields = ('pk','author','title','tags','tags_id','postedin','postedin_id','content','created_at','updated_at') read_only_fields=('pk','created_at','updated_at') def get_validation_exclusions(self, *args, **kwargs): exclusions = super(BlogsSerializer, self).get_validation_exclusions() return exclusions + ['author'] def create(self, validated_data): postedin = validated_data.pop('postedin_id') tags = validated_data.pop('tags_id') blogs = Blogs.objects.create(tags=tags,postedin=postedin, **validated_data) return blogs Request sent: {title: "nvnbv", postedin_id: "1", tags_id: ["2", "5", "1", "4"], content: "nmvmvjm"} response receive: {tags_id: ["Incorrect type. Expected pk value, received list."]} I am beginner in Django-rest-framework.How to solve this error. Thanks in advance ! -
Websocket error when using Elastic Beanstalk with Django channels
I am trying to get a chat app powered by django channels to work on AWS Elastic Beanstalk with a load balancer. I am basically modifying the code from https://github.com/jacobian/channels-example to work with Elastic Beanstalk. I am able to successfully run it locally on with the command python manage.py runserver The problem is when I deploy it with Elastic Beanstalk, I get the following error when the chat app is launched WebSocket connection to 'wss://mydomain.com/test/' failed: Error during WebSocket handshake: Unexpected response code: 200 I tried solutions proposed at http://stackoverflow.com/a/29831723/3667089 but it just showed a different error code WebSocket connection to 'wss://mydomain.com/test/websocket' failed: Error during WebSocket handshake: Unexpected response code: 404 I also already changed the load balancer listener port to TCP 80 and obtained a SSL certificate to change the secure listener port to SSL 443 but still get the same error. I also read Websockets with socket.io on AWS Elastic Beanstalk but there isn't an option to configure the proxy server for Django, I think it is using Apache by default. What am I missing for the configuration of Elastic Beanstalk to make it work? Another question is can someone explain to me how Elastic Beanstalk work behind … -
how to call a function in python with different number of attributes and with another logic?
I have a function in python that has 2 arguments: for example def get_shiff(instance): total=0 if instance.x: total+=instance.x/2 elif instance.y: total.+=instance.y*40 return total Can I call this function in python in another file as this: def get_shiff(instance,type) # the same thing for total but add this logic if type=="standard" : total+=instance.z*100 return total -
Is there a point to email verification?
I know in the old days email verification was used in order to stop "accidently" spamming innocent users when other people sign up with their email accounts. But since non-verified accounts dont get deleted. This seems like such a trivial benefit. Is there anything else that email verification offers? -
Django how to define permissions so users can only edit certain model hierarchies?
If I have models like this.. class Family(Model): name = models.CharField() class Father(Model): family = ForeignKey(Family) class Mother(Model): family = ForeignKey(Family) class Child(Model): family = ForeignKey(Family) Django makes group permissions automatically so I can define groups that can edit/create/etc... the family model. How can I limit it to only let a user edit a certain instance of the family model? So if I want the 'Johnson' family admin to only have permission to edit things under the 'Johnson' family tree. I can think of two ways, one would be defining a custom permission like (https://docs.djangoproject.com/en/1.10/topics/auth/customizing/#custom-permissions) but I have no idea what the docs are saying there and they do not do a good job of explaining it. I can also think of possibly adding a field on the user model and checking the value of that, but it feels wrong to do it that way... -
How to modify a string of a field in a queryset in Django, to display it in a templatetag
I have the next queryset: fotosinfo=IndexHasFotografia.objects.filter(index_idindex=infoindex,ubicacion_fotografiaindex=1).values('fotografia_idfotografia__pk','fotografia_idfotografia__ruta_fotografia','fotografia_idfotografia__nombre_fotografia') Where fotografia_idfotografia__ruta_fotografia stores an image URL, but the stored route is something like this ./image.jpg and it must be /files/image.jpg. In template I can add /files before the template tag, but I can't remove the dot before the slash. I can't change the way that images are stored, because I have stored a lot of images. I displayed other images using json, and that was easier, but now I must use template tags. So, how can I remove that dot to show the image URL in a template tag? -
How to customize django-oscar to take payments after placing an order?
In djnago-oscar's payment integration steps. I need to allow user to preview the order first and then when he clicks on place order button on the preview screen, he is redirected to the payment gateway pages, makes payment there and then the user is redirected back to the order confirmation page. Currently djnago-oscar has following flow for placing order. 1.Shipping address 2.Shipping method 3.Payment 4.Preview 5.Confirmation I want to change it to something like following. 1.Shipping address 2.Preview 3.Payment 4.Confirmation Is it possible to do it and if yes how?