Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django vs Laravel for a Social Media Web app
Despite looking at the similarities and differences between Laravel (PHP) vs Django (Python), I can't seem to decide what would be the best technology to use for a social media web application... for example if you were creating linked in type web application (website) Are there other technologies/frameworks that would support it better in terms of scalability? Although I am more experienced in PHP, I am comfortable to learn another framework but my confusion is that since I'm just starting off is it better to go with laravel than django? Any ideas or advice would be appreciated. -
Filter in django with or condition
I want to use filter with OR condition in django while filtering the object data. I have an object of a class and i have 3 or 4 field on which basis i want to filter the data with or condition in Django. For example. Obj = Books.objects.filter(title=title or price=price or description=description or author=author) I think this is not the right way to perform filter. What is the proper way to use OR condition in my django filter -
Fully API-based website - is it a good idea?
I sometimes hear about making web-site fully API based, meaning that even in browser the page is constructed based on API endpoint and practically nothing else. One of the benefits I see in this is that when you will make smartphone application you already have API that works and tested. And in case you need to change something you can change desktop and mobile app practically at the same time(with some tweaks maybe). Maybe I somehow misunderstood the idea, but I have some questions about the whole viability of it. Unfortunately I couldn't find any good article on this topic(which is strange, maybe it is because this is not what people do and I just misunderstood it completely). Just for example to be clear about the scope lets say we are building social-network-ish site. For mobile development API is the default way, but for desktop it seems to be overkill for me. I am used to Django framework and you can do page rendering quite easily - browser sends GET or POST request with parameters and you render a response page, can not be easier. But if I decide to use API on desktop browser then instead of simple request … -
Django how to send a argument in handler404?
When overridden as 404 errors to send to the function arguments? Need to poison the argument and the text of the error # views.py def handler404(request, error, text): response = render_to_response('error/40X.html', {'error': error, 'text':text}) response.status_code = error return response And the override code 404 errors: handler404 = 'app.views.handler404' Am using Django v1.10 and Python v3.5, and do not really want to create a function for each error. The question was translated, and I would be grateful for corrections, original -
Change Wagtail password in Django
I have inherited a django project which uses Wagtail for CMS. When I go to (project_url)/cms/ I am asked for a username and password, which I do not have. Is there any way to create a default user account in the settings.py file, or reset the existing account so that I can gain access to the CMS section? -
Django Factory Boy iterate over related parent
I have a project with Clients, Draftschedules, LineItems and Servers. Each client has a single DraftSchedule, each Draftschedule has many Lineitems Each Client has many Servers Each LineItem has a Single Server I have some code to generate LineItems for each DraftSchedule with random data. However the resulting LineItems contain Servers not actually owned by the Draftschedule Client class LineItemFactory(factory.django.DjangoModelFactory): class Meta: model = LineItem line_item_type = factory.Iterator(LineItemType.objects.all()) draftschedule = factory.Iterator(DraftSchedule.objects.all()) servers = factory.Iterator(Server.objects.all()) # <----- Problem line cost = factory.LazyAttribute(lambda x: faker.pydecimal(2, 2, positive=True)) detail = factory.LazyAttribute(lambda x: faker.sentence()) ... I'd like to restrict the server choice set to be only those servers owned by the parent client of the Draftschedule the Lineitem is being created for. So that when I call LineItemFactory() it returns a new LineItem object and I can garantee that the Server on the LineItem is actually owned by the Client associated with the DraftSchedule I've tried the following: servers = factory.Iterator(lambda x: x.draftschedule.client.servers.all()) where client.servers is the related name, but the function isn't iterable so I'm a bit stuck Is this possible or should I approach the problem from a different angle? -
Django filter queryset by timedelta
What could be nice way to filter devices which response was later than, for example, 500 seconds? So assume my model: class Device(models.Model): last_response = models.DateTimeField(null=True, blank=True) My best move was: from django.utils import timezone for d in Device.objects.all(): now = timezone.now() if d.last_response and (now - d.last_response).seconds < 500: # Do something But I don't want to query all database for this. How can I make it work with filter, like for d in Device.objects.filter(..some arguments..): ? -
chaining Viewsets in DRF
I have a Viewset like this: class ActivityViewSet(viewsets.ModelViewSet): queryset = Activity.objects.all() serializer_class = ActivitySerializer And Right now, to output activity with a route, I use this code: class RouteOrderingDetail(mixins.CreateModelMixin, mixins.RetrieveModelMixin, mixins.DestroyModelMixin, mixins.ListModelMixin, viewsets.GenericViewSet): queryset = RouteOrdering.objects.all() serializer_class = RouteOrderingSerializer def retrieve(self, request, pk=None): returned_data = RouteOrdering.objects.filter(route_id=pk) serializer = RouteOrderingSerializer(returned_data, many = True) if serializer.data == []: raise Http404 for x in serializer.data : act = x['activity_id'] new_data = Activity.objects.filter(id = act) new_data2 = ActivitySerializer(new_data, many = True) x['activity'] = new_data2.data return Response(sorted(serializer.data, key=lambda x: x['order'])) The part that I dont like is: act = x['activity_id'] new_data = Activity.objects.filter(id = act) new_data2 = ActivitySerializer(new_data, many = True) x['activity'] = new_data2.data I want this to get done with the original Activity viewset, and not manually. How can I achieve this? Thanks :) -
Disable checkbox in django admin if already checked
i have simple but problematic for me question. How i can disable checkbox, input if it's already filled/checked? I must disable some fields after first filling it. Thank you for all ideas, Sierran -
Deploying/packaging subsets of Django apps
We have a Django 1.10 project consisting of 7 apps (let's call them A-G). The project is actually three different servers consisting of different subsets of the apps like this: A+F, A+G, A+B+C+D+E. F and G are not referencing or referenced by any other app except for A. Is there a way to already group this on the Django project level? Maybe three projects, referencing apps from other projects? I could not find a way to do this without duplicating code. Is there a nice way to only deploy the given subsets? We do have three different settings files for each subset, only including the wanted apps. But this wouldn't mean we only deploy the code for those apps of course. We may not deploy app D for example for the subset server A+F. -
I am implementing social login and logout in django python version python 3.5.2 and django 1.8.1
Please can you any one help me if is there any python script means please provide me -
Using Django, how do I add a foreign key column that references the same table?
I want a table to include a foriegn key field to itself, and have tried the following code: from __future__ import unicode_literals from django.db import models # Create your models here. class CollectionModel(models.Model): parent = models.ForeignKey(CollectionModel, on_delete=models.CASCADE) This produces the following error: $ ./manage.py makemigrations eav Traceback (most recent call last): File "./manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/usr/lib/python2.7/site-packages/django/core/management/__init__.py", line 353, in execute_from_command_line utility.execute() File "/usr/lib/python2.7/site-packages/django/core/management/__init__.py", line 327, in execute django.setup() File "/usr/lib/python2.7/site-packages/django/__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models(all_models) File "/usr/lib/python2.7/site-packages/django/apps/config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "/usr/lib64/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/home/username/Documents/devel/python/project/eav/models.py", line 7, in <module> class CollectionModel(models.Model): File "/home/username/Documents/devel/python/project/eav/models.py", line 8, in CollectionModel parent = models.ForeignKey(CollectionModel, on_delete=models.CASCADE) NameError: name 'CollectionModel' is not defined How do I include a foriegn key to the same table as a field? -
How to test a FileField in Django REST Framework
I have this serializer which I am trying to test: class AttachmentSerializer(CustomModelSerializer): order = serializers.PrimaryKeyRelatedField() file = FileField() class Meta: model = Attachment fields = ( 'id', 'order', 'name', 'file_type', 'file', 'created_at', ) My test simply checks whether it is valid or not: def test_serializer_create(self): self.data = { 'order': self.order.pk, 'name': 'sample_name', 'file_type': 'image', 'created_at': datetime.now(), 'file': open(self.image_path, 'rb').read() } serializer = AttachmentSerializer(data=self.data) self.assertTrue(serializer.is_valid()) And I am constantly getting this error: {'file': ['No file was submitted. Check the encoding type on the form.']} I tried to create a file in a number of different ways, such as with StringIO/BytesIO, File and etc. to no avail. What might be wrong? -
Celery - [Errno 111] Connection refused when celery task is triggered using delay()
I have two application servers(both having the django application). Both have celery worker running. RabbitMQ server is set up on a third different server. When any test task is executed from any of the two application servers through shell using delay(), they get executed fine. If the same task is triggered from server1 from the browser (through ajax) it works fine again. But in case of server2 (having the same config and code as server1), when the same task is triggered from the browser it gives [Errno 111] Connection refused error. The error trace is as follows: File "../lib/python2.7/site-packages/celery/app/task.py" in delay 453. return self.apply_async(args, kwargs) File "../lib/python2.7/site-packages/celery/app/task.py" in apply_async 559. **dict(self._get_exec_options(), **options) File "../lib/python2.7/site-packages/celery/app/base.py" in send_task 353. reply_to=reply_to or self.oid, **options File "../lib/python2.7/site-packages/celery/app/amqp.py" in publish_task 305. **kwargs File "../lib/python2.7/site-packages/kombu/messaging.py" in publish 172. routing_key, mandatory, immediate, exchange, declare) File "../lib/python2.7/site-packages/kombu/connection.py" in _ensured 457. interval_max) File "../lib/python2.7/site-packages/kombu/connection.py" in ensure_connection 369. interval_start, interval_step, interval_max, callback) File "../lib/python2.7/site-packages/kombu/utils/__init__.py" in retry_over_time 246. return fun(*args, **kwargs) File "../local/lib/python2.7/site-packages/kombu/connection.py" in connect 237. return self.connection File "../lib/python2.7/site-packages/kombu/connection.py" in connection 742. self._connection = self._establish_connection() File "../lib/python2.7/site-packages/kombu/connection.py" in _establish_connection 697. conn = self.transport.establish_connection() File "../lib/python2.7/site-packages/kombu/transport/pyamqp.py" in establish_connection 116. conn = self.Connection(**opts) File "../lib/python2.7/site-packages/amqp/connection.py" in __init__ 165. self.transport = self.Transport(host, connect_timeout, … -
Need to mock a non test method in Django
I have a test class just like the one below: @mock.patch('/path/something/<file.apply_async>') class SortAPITestCase(APITestCase): def hit_scan("""some args"""): scan_uri = 'some url' data = 'some data' resp = self.client.post(scan_uri, data=data) id = resp.data['id'] self.assertEqual(resp.status_code, 201) return data, id def setUp(self): super(SortAPITestCase, self).setUp() self.scan_data, self.id = self.hit_scan() def test_1(self, mock_obj): ..... def test_2(self, mock_obj): ..... In Scan API, POST is allowed, which calls a celery task like: def post("""some args"""): """ here there is a celery task that gets called""" The celery task prints out a message when it is called As the Scan API is being called by a non test method hit_scan, the celery task isn't getting mocked and the print statement is showing up whenever I am running the django test. If the Scan API were called by a test_ method then the celery task gets mocked. So, Is there way to prevent the print statement from coming up in the console when I run the test?? By the way, all the test cases pass. There is no problem from that point of view. I just wanted the console to look better with only .... instead of the print statements from celery task also showing up. -
Django queryset filter performance
I have a queryset :- queryset = my_object.someobject_set.all() From there onwards, I want to filter from the queryset. i.e: print queryset.filter(name='some1').exists() print queryset.filter(name='some1').exists() print queryset.filter(name='some1').exists() But for each of the filter queries, there is a database hit again. How can I cache the queryset and then filter from it? I even tried to evaluate the queryset before filtering by doing this:- print len(queryset) But this doesn't work. Any help?? -
block timeslot using django python
I'm new in django 1.8 python 3.5 plz help me to solve my problem My task is I want to register a activities like (camel ride etc.) with different timeslot per day. also I want to block register activity for specific date. and it shows on calender which activity is available and which activity is block .and its work dynamically updation .plz help how to do this. -
Exception Value: name 'myapp' is not defined
enter code here ecomstore/settings.py INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'uploader', 'myapp', ) ecomstore/urls.py from django.conf.urls import patterns, include, url from django.contrib import admin from django.conf import settings from django.conf.urls.static import static admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'ecomstore.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^admin/', include(admin.site.urls)), url(r'^catalog/$', 'ecomstore.views.catalog'), url(r'^myapp/', include(myapp.urls)), url(r'^upload/$', 'uploader.views.home', name = 'imageupload'), ) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) myapp/urls.py from django.conf.urls import patterns, include, url urlpatterns = patterns('', url(r'^hello/', 'myapp.views.hello', name = 'hello'), ) myapp/views.py from django.shortcuts import render from django.http import HttpResponse # Create your views here. def hello(request, number): text = "<h1>welcome to my app number %s!</h1>"% number return render(request, "myapp/template/hello.html", {}) return HttpResponse(text) My application throwing "NameError at /admin/ name 'myapp' is not defined" Please guide me. Regards, Durga. -
Django rest framework: unit testing database issue
I am doing unit testing of the rest Apis. I am using django rest framework. Apis are saving data into and getting data from the database. Both of the operations are not working or if it is working i am not able to see that in the databases. Apis are also using django-fsm, because of which i need same data from the db for the other tests. Tests depends on previous tests due to django-fsm. There is always state changing with the api. But now i am not able to see any data in database during test runs. Don't know where it is saving the data or in which database. Below is my test settings:- DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': join(PROJECT_ROOT, 'run', 'db_for_testing.sqlite3'), 'TEST': { 'NAME': 'test_db_for_testing', }, }, } below is my api:- class DummyView(CreateAPIView): def post(self, request, *args, **kwargs): data = request.data.copy() serializer = self.get_serializer(data=data) serializer.is_valid(raise_exception=True) order = self.model(book=serializer.data.get('book')) order.save() data = { 'status_code': 200, 'message': 'successfully.' } return Response(data, status=status.HTTP_200_OK) As my tests depends on the previous test saving the data to db, so the other tests also fails. Help guys. thanks in advance. -
Django form not displaying form fields
I searched for similar questions, however the cloest was an issue where the form instance was not being passed to the template correctly, which does not seem to be the issue here. I am new to django, and was just trying to do a super simple form. My code: forms.py: from django import forms from .models import FormModelTest class TestForm(forms.Form): test1 = forms.CharField(max_length=100) test2 = forms.CharField(max_length=100) models.py: from __future__ import unicode_literals from django.db import models from django.forms import ModelForm class FormModelTest(models.Model): test1 = models.CharField(max_length = 140) test2 = models.CharField(max_length = 140) def __str__(self): return self.title class TestForm(ModelForm): class Meta: model = FormModelTest fields = ['test1', 'test2'] views.py: from django.shortcuts import render def index(request): return render(request, 'testapp/home.html') def battlegen(request): return render(request, 'testapp/form.html',) # Create your views here. from testapp.forms import TestForm def post_form_upload(request): if request.method == 'GET': form = TestForm() else: # A POST request: Handle Form Upload form = TestForm(request.POST) # Bind data from request.POST into a PostForm # If data is valid, proceeds to create a new post and redirect the user if form.is_valid(): test1 = form.cleaned_data['test1'] test2 = form.cleaned_data['test2'] post = m.Post.objects.create(test1=test1, test2=test2) return HttpResponseRedirect(reverse('post_detail', kwargs={'post_id': post.id})) return render(request, 'testapp/form.html', { 'form': form, }) form.html: {% block content … -
django makemigrations to rename field without user input
I have a model with CharField named oldName. I want to rename the field to newName. When I run python manage.py makemigrations, I get a confirmation request "Did you rename model.oldName to model.newName (a CharField)? [y/N]" However, I want to run the whole thing inside a docker container and there is no provision to provide the user input. Is there a way to force the migration without need for user input? PS: I tried --noinput option with makemigrations. In this case migrations are not getting applied. -
Is there any api that provide aws CloudFront Popular Objects Report?
I want to get CloudFront Popular Objects Report using api that will work with python. -
Django admin login returns Forbidden 403 CSRF verification failed. Request aborted
Pretty new to Django. Working through a second project following the Polls tutorial on Django website. Previous effort went well, albeit simple. This time around encountering problems accessing admin login. I have created a superuser and using those credentials, when I try to login to http://127.0.0.1:8000/admin/login/?next=/admin/ I get the following error: Forbidden (403) CSRF verification failed. Request aborted. Reason given for failure: CSRF cookie not set. Looking at this and this, most answers either detail clearing browser cookies, include 'django.middleware.csrf.CsrfViewMiddleware' in your middleware (which I do), or creating an exemption or workaround. 1) My question is why the admin portal does not seem to work now, but it did for my previous project and I am following the same steps? 2) Shouldn't the properties for the admin panel be inherited through the project initiation? 3) How would I set the CSRF for admin when the documentation appears to state that the CSRF middleware is activated by default? Thanks for any help. settings.py DEBUG = True SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') ALLOWED_HOSTS = ['*'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'search', ] MIDDLEWARE_CLASSES = [ 'django.middleware.csrf.CsrfViewMiddleware', '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', ] -
Django rest framework APIRequestFactory ValueError: No JSON object could be decoded
import json from rest_framework.test import APITestCase, APIRequestFactory factory = APIRequestFactory() class MyViewSetTest(APITestCase): def test_create(self): my_view = MyViewSet.as_view({'post': 'create'}) data = {...} request = factory.post('/myurl/', data=json.dumps(data), content_type="application/json") response = my_view(request, format='json') # got error on this line here are last few lines of error trace File "/usr/lib/python2.7/json/decoder.py", line 366, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/usr/lib/python2.7/json/decoder.py", line 384, in raw_decode raise ValueError("No JSON object could be decoded") ValueError: No JSON object could be decoded I've played around with content_type and format parameters but no success. on one tab running the django server (on port 8000) and in another tab test. this is working fine when u use generic views but not in case of viewset. PS: I was able to get the response using requests library -
Django - 'RawQuerySet' object has no attribute 'all'
I got this error message if i'm using SQL statement to populate data in dropdown. Error message 'RawQuerySet' object has no attribute 'all' My code form.fields["set_auto_reply_for_fan_page"].queryset = FacebookFanPage.objects.raw('SELECT * ' 'FROM fbautoreply_facebookfanpage ' 'JOIN fbautoreply_facebookaccount ON fbautoreply_facebookfanpage.facebook_account_id = fbautoreply_facebookaccount.id ' 'WHERE fbautoreply_facebookaccount.user_id = %s ', [str(request.user.id)]) Please advice. Thank you.