Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Generic Detail View must be called with either an object pk or slug
I have searched through other questions regarding the same error message, but it seems as if it should work to me (I am using Django 2 btw.) class Book(models.Model): name = models.CharField(max_length=200) slug = models.SlugField(default='') def save(self, *args, **kwargs): self.slug = self.name.lower().replace(' ', '_') my path: path('<slug:slug>', views.BookDetailView.as_view(), name='book-detail'), the view: class BookDetailView(DetailView): model = Book template_name = 'books/bookdetail.html' context_object_name = 'book' slug_url_kwarg = 'slug' Still, it's throwing the error message. What have I done wrong? Thanks in Advance -
Django - all objects from last hour
I would like to get all objects from last hour. For example: I have 13:58 and i would like to get all objects from 13 to 14 This is my code: now = datetime.datetime.now() earlier = now - datetime.datetime(now.year, now.month, now.day, now.hour, 0,0) MyModel.objects.filter(date__range=(earlier, now)) but I have a error: RuntimeWarning: DateTimeField MyModel.date received a naive datetime (2018-02-14 17:16:58.478000) while time zone support is active. RuntimeWarning) My settings: USE_TZ = True TIME_ZONE = 'Europe/Warsaw' -
Django tests - database constraint still exists even with a migration
I'm having difficulty with migrations/constraints in tests. I started with something like this: class MyModel(AbstractModelWithoutCSlug): id = models.IntegerField(primary_key=True, db_column='other_id') cslug = models.CharField(max_length=60, null=True, unique=True) This created the unique constraint on cslug without an issue. The unique=True was removed on the field (and made the migrations) to allow a command to run that would require the ability to temporarily have non-unique values. When I run the tests, I get an IntegrityError on the lack of uniqueness, even though a migration exists removing unique=True. Is it possible the migrations aren't always done in tests? I've never encountered an issue with migrations not being run before. Additionally: I'm using factory boy for the models. Could this also have an effect on it? -
Is it possible to add another class to a django-bootstrap-ui template tag
In my django project, I'm using django-bootstrap-ui 0.5.1. I have it in my settings.py INSTALLED_APPS variable, as well as installed in my virtual environment via my requirements.txt file. I've confirmed everything is working by using a basic {% container %} tag and its child tags {% row %} and {% column xs="8" sm="6" md="4" lg="3" %}, for example. My question is this: If {% container %} renders the following code: <div class='container'> </div> How can I add another class to that div, alongside 'container', so that the output looks like: <div class='container custom-class'> </div> -
Serve multiple Django apps from the same domain, routing using paths not subdomains
I would like to serve "app1" and "app2" from the same domain using paths to route the app: https://exampe.com/app1/ and https://exampe.com/app2/ Normally I would do this using subdomains, but this is an attempt to give a more seamless experience for the user - so it all looks like one app ( app1 and app2 have the same header and footer) This is not possible with DNS, but perhaps there is an nginx or other solution? -
Empty download file from django view
I am using django 1.11.2 and I want to have view with downloadable file. After click on link the file is downloading but file is empty and instead of png, I recieved empty txt file. def download_file(request, uuid): response = HttpResponse(content_type='application/force-download') response['Content-Disposition'] = 'attachment; filename=%s' % smart_str(models.DownloadLink.objects.get(uuid=uuid).download_file.file) response['Content-Length'] = 'http://{}{}'.format(Site.objects.get_current(), models.DownloadLink.objects.get(uuid=uuid).download_file.file.url) return response EDIT: value here response['Content-Length'] is http://127.0.0.1:8000/media/filer_public/49/54/4954a7bb-8ad3-4679-9248-bffc7d186ca8/photo-105221.jpeg -
Using Javascript to insert url into Django template
I made a map application using Mapbox, where a user can click on a feature and a popup shows with details about the feature. I would also like to provide a link in the popup to the DetailView of the object using Javascript, but I'm having trouble generating the anchor tag. So far I have new mapboxgl.Popup() .setLngLat(e.lngLat) .setHTML('<a href="{% url app_name:view pk=foo %}">To Detail View</a>') .addTo(map); But when I try it out on the development server, it gives me a 404 error with a request url of http://127.0.0.1:8000/map/%7B%25%20url%20app_name:view%20pk%3Dfoo%20%25%7D How do I get it to pass the correct url? I've also tried inserting the link into a normal HTML div and I get the same problem. -
Fast moving average computation with Django ORM
We run Postgres 9.6.5 and Django 2.0. We have a Model with fields created_at and value. We need to calculate a 90-day moving average for a certain date_range. This is how we do this: output = [] for offset in range(len(date_range)): output.append( Ticket.objects.filter( created_at__date__range=(date_range[offset]-timezone.timedelta(days=90), date_range[offset]), ).aggregate(Avg('value'))['value__avg'].days ) This uses Avg aggregate function, so it's reasonably fast, however we need one query for every date in date_range. For longer ranges this means a lot of queries. Postgres can do this in a single query. My question is - can we somehow do this in a single query using Django ORM? (I know that I can execute raw SQL with Django ORM, but I wanted to avoid that if possible, that's why I'm asking...) -
Iterate through model instance variables in Django
Consider a model defined as below: class ProblemVerificationModel(CreateUpdateDateModel): problem = models.ForeignKey(Problem, related_name="problem_survey") verifier = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="verified_problem") is_problem_properly_formated = ... # BooleanField some_field = ... #BooleanField some_other_field = ... #BooleanField I need to find sum of all integer-like values (True->1, False->0) of a ProblemVerificationModel model instance. I can add these values by accessing each field using instance.field and add them all. However, I want to know if there is more clean way of doing this. -
Post methods doesn't work in Django 1.8, Python3 TypeError: can't concat bytes to str
When I try to use forms with a POST method, I'm getting a TypeError: can't concat bytes to str. It's not only happening when I use my forms, but when I input login/password for admin panel too. Environment: Request Method: POST Request URL: http://photofresh.site/blog/post_new/ Django Version: 1.8 Python Version: 3.5.0 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'bootstrap3', 'blog'] Installed Middleware: ['django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "/usr/local/lib/python3.5/site-packages/django/core/handlers/base.py" in get_response 125. response = middleware_method(request, callback, callback_args, callback_kwargs) File "/usr/local/lib/python3.5/site-packages/django/middleware/csrf.py" in process_view 174. request_csrf_token = request.POST.get('csrfmiddlewaretoken', '') File "/usr/local/lib/python3.5/site-packages/django/core/handlers/wsgi.py" in _get_post 137. self._load_post_and_files() File "/usr/local/lib/python3.5/site-packages/django/http/request.py" in _load_post_and_files 272. self._post, self._files = QueryDict(self.body, encoding=self._encoding), MultiValueDict() File "/usr/local/lib/python3.5/site-packages/django/http/request.py" in body 233. self._body = self.read() File "/usr/local/lib/python3.5/site-packages/django/http/request.py" in read 292. return self._stream.read(*args, **kwargs) File "/usr/local/lib/python3.5/site-packages/django/core/handlers/wsgi.py" in read 51. result = self.buffer + self._read_limited() Exception Type: TypeError at /blog/post_new/ Exception Value: can't concat bytes to str -
How do I make an object out of a dict in python?
I currently have a dict, where: one_result = {'name':'Acme', 'description': 'Fun time', 'results': {'fun_status': 'Extra', 'fun_title': 'Foo' } } I access the values of this dict in many places in my code and also put many of the results in an array and store it in DB: class Record(models.Model): results = JSONField(default=[], null=True, blank=True) I would like to keep things DRY and make a Python object out of the result, so I can access the attributes directly, instead of via key_names: result.name VS result['name'] Is there a way that I can create an object that is backed by a dict(), and easily serialized/deserialized into JSON in my db? -
Django app and Wordpress page on same VServer but different domains
I have on virtual server with 2 domains configured. One domain should host a wordpress page and the other domain will be a django web application. I did some research, but I am confused. I know that for Wordpress Apache is the way to go. But for Django I often read that Nginx is the best setup. My question is: What is the best practice in terms of web server setup when hosting 2 domains on the same (virtual) server, where one domain hosts a wordpress page and the other domain hosts a django web application? -
Check if the field value was changed in save method
I've got model, which has 'active' field, I'd like to do action if it's value has changed class Good(TimeStampedModel): active = models.BooleanField(default=True) def save(self, **kwargs): #if self has changed: #do_something() super().save(self, **kwargs) -
can we run django applications without virtual environment? how?
I am completely new to Django framework, I want to create Django application without using the virtual environment, is it possible? If yes please explain how? -
Django - registering an Admin model view in one app from another app
I'm slightly confused as how I'm meant to do this, partly because the documentation is translated a little poorly from Chinese, partly because I am just getting my head around class based views. I have the following directory structure: Project manage.py db.sqlite3 /docs /static /templates /main_app __init__.py settings.py urls.py * wsgi.py /apps /xadmin adminx.py * /survey admin.py * And the following URL mappings in main_app.urls: from django.conf.urls import url, include from django.contrib import admin import xadmin xadmin.autodiscover() urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^survey/', include('survey.urls')), url(r'xadmin/', include(xadmin.site.urls)), ] The survey.admin has it's classes, e.g. class SurveyAdmin(admin.ModelAdmin): list_display = ('name', 'is_published', 'need_logged_user', 'template') list_filter = ('is_published', 'need_logged_user') inlines = [CategoryInline, QuestionInline] actions = [make_published] admin.site.register(Survey, SurveyAdmin) I know my Survey app's models are working properly, because when I check db.sql3, I can see my dummy entries in there. When I log into 127.0.0.1:8000/admin, I can see that the SurveyAdmin view is registered and available. When I log into 127.0.0.1:8000/xadmin however, SurveyAdmin isn't registered. From the xadmin docs I get that I have to register admin class views in xadmin.adminx. The admin class views I want to register already exist in survey.admin. I believe all I need to get this working is to … -
django tastypie field filtering using ```and```
In tastypie docs you can do the below subjects = fields.ToManyField(SubjectResource, attribute=lambda bundle: Subject.objects.filter(notes=bundle.obj, name__startswith='Personal')) I'm trying to create an and filter in there. subjects = fields.ToManyField(SubjectResource, attribute=lambda bundle: Subject.objects.filter(notes=bundle.obj, name__startswith='Personal' and date__isnull=False)) If I do. subjects = fields.ToManyField(SubjectResource, attribute=lambda bundle: Subject.objects.filter(notes=bundle.obj, name__startswith='Personal', date__isnull=False)) It creates and or filter. and raises as syntax error. How do I create the and? Cheers -
Saving attachments from Sendgrid Parse
Im using sendgrid parse to send emails to a webhook. This is delivered to a url in my django application. Im not sending the RAW message. This is my view: @csrf_exempt def parse_sendgrid(request): if request.method == "POST": print request.FILES["attachment1"].read() open('tisiscool.jpg', 'wb').write(request.FILES["attachment1"].read()) For some reason, the image is not displaying, like its corrupted? ITs an image I attach to an email, so the image is fine. The content of the image is just gibberish, I thought it would be base64? Is the image encoded or something by SendGrid? -
A method that is called when the databases are updated via the admin panel
the idea is that I will not need to, each time enter some data, the value of which depends on the value of other data. For example. class Example(models.Model): 1_score_team_1 = models.IntegerField() 2_score_team_1 = models.IntegerField() 1_score_team_2 = models.IntegerField() 2_score_team_2 = models.IntegerField() total_score_of_team_1 = models.IntegerField() total_score_of_team_2 = models.IntegerField() def function: total_score_of_team_1 = 1_score_team_1 + 2_score_team_1 total_score_of_team_2 = 1_score_team_2 + 2_score_team_2 return update total score of two teams This method should be called every time I enter data through the admin panel. -
Add an extra total row in admin - Django
admin.py for an app is: from django.contrib import admin from django.db.models import Subquery, Sum, OuterRef from .models import GoodsItem, FinishedGoodsItem, SoldGoodsItem @admin.register(SoldGoodsItem) class SoldGoodsItemAdmin(admin.ModelAdmin): fields = ('date', 'goods_item', 'weight') list_display = ('date', 'goods_item', 'weight') @admin.register(FinishedGoodsItem) class FinishedGoodsItemAdmin(admin.ModelAdmin): fields = ('date', 'goods_item', 'weight') list_display = ('date', 'goods_item', 'weight') @admin.register(GoodsItem) class GoodsItemAdmin(admin.ModelAdmin): list_display = ('__str__', 'finished_good', 'sold_good', 'stock_available') def get_queryset(self, request): qs = super(GoodsItemAdmin, self).get_queryset(request) qs = qs.annotate( finished_good = Subquery(FinishedGoodsItem.objects.filter(goods_item=OuterRef('pk'))\ .values('goods_item_id').annotate(sum=Sum('weight')).values('sum')[:1]), sold_good = Subquery(SoldGoodsItem.objects.filter(goods_item=OuterRef('pk'))\ .values('goods_item_id').annotate(sum=Sum('weight')).values('sum')[:1]) ) return qs def finished_good(self, obj): return obj.finished_good def sold_good(self, obj): return obj.sold_good def stock_available(self, obj): finished_good = 0 if self.finished_good(obj) is None else self.finished_good(obj) sold_good = 0 if self.sold_good(obj) is None else self.sold_good(obj) return '-' if (finished_good == 0 and sold_good == 0) else finished_good - sold_good admin.site.site_header = 'Rajeshwari Steels' For GoodsItemAdmin, I want to display an extra row with the totals at the bottom of the records table. The total row should display the total for all three columns, which are finished_good, sold_good and stock_available. Here all three columns are displayed using methods in GoodsItemAdmin and are annotated on queryset by overriding get_queryset method. I found this question, while searched for the solution. The answers for that question suggest to override admin template … -
Django and mongoengine connection MongoCR Failed authentication
I am using Django 1.9 and mongoengine to connect to my mongo back-end database and having difficulties connecting to the default database. I am doing it this way: DBNAME = 'admin' _MONGODB_USER = 'bobO' _MONGO_PASSWD = '1234' _MONGO_HOST = 'localhost' _MONGODB_NAME = 'test' _MONGO_DATABASE_HOST = \ 'mongodb://%s:%s@%s/%s' \ % (_MONGODB_USER, _MONGO_PASSWD, _MONGO_HOST, _MONGODB_NAME) mongoengine.connect(DBNAME, host=_MONGO_DATABASE_HOST) I am getting this error from pycharm and the mongod cmd: pyCharm raise ConnectionError("Cannot connect to database %s :\n%s" % (alias, e)) mongoengine.connection.ConnectionError: Cannot connect to database default : command SON([('authenticate', 1), ('user', u'johnO'), ('nonce', u'fae6a365d185a4cd'), ('key', u'1ef81a71166f8878a02b3c7c297e2959')]) failed: auth failed CMD-running Mongod Failed to authenticate johnO@test from client 127.0.0.1:56458 with mechanism MONGODB-CR: AuthenticationFailed: MONGODB-CR credentials missing in the user document 2018-02-14T13:45:50.701+0000 I NETWORK [conn4] end connection 127.0.0.1:56458 (1 connection now open) Any guidance on properly connecting them together would be great. I dont seem to understand this MONGODB-CR. Have i missed something crucial on my credentials? I do have an admin database and have created a user. Thanks -
Why is evaluating a Django QuerySet in a Boolean context slower than calling `exists` on it?
So the Django docs state the following: And to find whether a queryset contains any items: if some_queryset.exists(): print("There is at least one object in some_queryset") Which will be faster than: if some_queryset: print("There is at least one object in some_queryset") Why is that though? What good reason is there? Often when evaluating a QuerySet in a Boolean context, all a user cares about is whether there's at least one item which presumably is why exists is faster. Why can't __bool__ on QuerySet simply do the same amount of work as exists? Look at the source code, there seems to be a bit of work involved: def __bool__(self): self._fetch_all() return bool(self._result_cache) But no documentation providing context on why. For me, simply calling if some_queryset: is much cleaner and more Pythonic. -
Need Help: Google Django All-Auth Redirect not working with EC2 AWS in Production
I'm trying to connect the Django All-Auth Google App with the Google credentials for AWS in production. EC2 Gunicorn and Nginx. Google does not accept URLS without a .org or .com. My training program only taught us to deploy Django using the IPv4 Public IP and not the amazonaws.com IP version. Example screenshot: So I got a .org domain from noip.com to point to a public AWS IP but it's not working in production. I've tried every URL in creation and NOTHING is working: http://travelbuddy.hopto.org/accounts/google/login/callback https://travelbuddy.hopto.org/accounts/google/login/callback http://travelbuddy.hopto.org/oauth2callback https://travelbuddy.hopto.org/oauth2callback I was tried to get the code from settings.py on AWS to post here, BUT now the file is read-only for some reason. I can't even edit it. I have wasted countless HOURS and an entire day on this! Help please. -
pip3 install couchdbkit. install failed with "Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-_302m_0e/couchdbkit/"
Unable to install couchdbkit in ubuntu. Command: pip3 install couchdbkit Giving this following error: Collecting couchdbkit Using cached couchdbkit-0.6.5.tar.gz Complete output from command python setup.py egg_info: Traceback (most recent call last): File "", line 1, in File "/tmp/pip-build-_302m_0e/couchdbkit/setup.py", line 25, in long_description = file( NameError: name 'file' is not defined ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-_302m_0e/couchdbkit/ Please guide me if there any other way to install couchdbkit in ubuntu. -
Django queryset retrieve nothing but the instance exist
I'm facing an issue with Django that I have never seen. When I try to make a query to filter a user the result is empty, but the user really exists. I don't know if Django has some issue when the database is hugue. I don't know how to start to understand how can I fix it. Here is an example copied directly from my shell: In [18]: from django.contrib.auth.models import User In [19]: User.objects.get(pk=22247).email Out[19]: u'person@example.com' In [20]: User.objects.filter(email='person@example.com') Out[20]: [] How can it be possible? Somebody can give some guidance to fix it? Thanks a lot! Usefull data: Im using Python 2.7.14 and Django 1.8.16 Also this bug doesn't happen all the time, sometimes it retrieve the instance correctly but the 80% of the queries retrieve nothing. -
403 Forbidden Angular4-Django
I'm building a website with books using Angular 4 and Django. When the user gets on the landing page (not logged in) he should be able to see a section with the books that were recently added. However, the books aren't loading and in my console I keep getting this error GET http://127.0.0.1:8000/api/books 403 (Forbidden) When the user logs in he's able to see the books just fine. My view in Django (have already imported permissions): class BookList(generics.ListCreateAPIView): permission_classes = (permissions.AllowAny,) serializer_class = BookSerializer def get_queryset(self): queryset = Book.objects.all() category = self.request.query_params.get('category', None) if category is not None: queryset = queryset.filter(category__contains = category) return queryset