Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Pycharm says Expected }} after |default in a template
<div class="person_roles_div"> <table> <thead></thead> <tbody> {% for position in person.positions %} <tr> <td>{{ position.provider|default:"" }} {{ position.role }}</td> <td>{{ position.facility|default:"" }}</td> <td>{{ position.startdate|default:"" }}</td> <td>{{ position.enddate|default:"" }}</td> <td> <button id="remove_position_sk_{{ position.position_sk }}" class="position_remove_button">Remove</button> </td> </tr> {% endfor %} </tbody> </table> </div> In the first four td tags that output a context variable and specify a default, PyCharm is highlighting the : and blank space right before and after each "" The hovertip message is (( or {% expected The page runs fine. Any idea what setting I should looking at? -
How do you access models from other installed apps in Django when in the same subdirectory?
I have the following structure for my project: myproject/ |-- myproject/ | |-- __init__.py | |-- settings.py | |-- urls.py | |-- wsgi.py |-- apps/ | |-- dashboard/ | | |-- static/ | | |-- templates/ | | |-- __init__.py | | |-- admin.py | | |-- apps.py | | |-- forms.py | | |-- models.py | | |-- tests.py | | |-- views.py | |-- data/ | | |-- __init__.py | | |-- apps.py | | |-- models.py | | |-- router.py | | |-- tests.py | |-- __init__.py |-- manage.py The settings file has these installed apps added: 'apps.data', 'apps.dashboard', In the main project I can import from the apps I've created no issues. However, the dashboard app is dependant on the data app and I can't seem to import from the data app. urls.py imports 'import apps.dashboard.views' with no issues but I've tried a number of things to import the models from data into dashboard. I'm using the models from data in the dashboard views. None of the following work: from data.models import ModelName from apps.data.models import ModelName from .data.models import ModelName from .apps.data.models import ModelName I get 'ImportError: No module named data.models' regardless. In the apps.py … -
Display Word Count in Blog Post with Wagtail
I am wondering how to create a template tag that will get the word count for an entire blog post in Wagtail. I have looked around and seen some different ways to do with with python, but not quite sure how to do it with wagtail given views are often abstracted away. It seems like the query also gets more complex given that in many cases there can be multiple parts to a wagtail template (intro, body, etc.) that the creator might want to count. I noticed there is also a nice package that does this in the admin for you, but I would like to display it on the user side. I am guessing this is a pretty simple answer, but am still not familiar with passing new variables to templates in Wagtail without a view. Thanks! -
Django customize dumpdata output json to meet with elasticsearch default document format
Is there a way to replace field with with a custom name while dumping django model data? I am trying to update documents in elasticsearch. Elasticsearch expects pk field labelled as id and it do not expect a nested field named as field itself. Default dumpdata for a single object is as given below [ { "fields": { "field1": 1, "field2": null, ... }, "model": "core.mymodel", "pk": 1 } ] What required is [ { "_index": "myIndex", "_type":"core.mymodel" "_id": 1, "_source": { "field_1": "value_1", "field_2": "value_2", ... "field_n": "value_n" } } ] Is there a way to customize the output of django's dumpdata? Any help is greatly appreciated. TIA -
404 error when adding a new app on django
Hi there! I'm having an issue with my site, in making and incorporating a second app. The first works perfectly. You can see the demo site here: http://216.158.236.51 but when I try to visit the new url pages created [ http://216.158.236.51/signup ] for example, it just gives me a 404. It gives me a 404 for both the new app pages and for other new pages created within the first app. I'm pretty sure I did everything correctly from the django side. Not sure if I have to reload the nginx or gunicorn. or what backend problems there are... any advice would be great. my url patterns look like this: from django.conf.urls import url, include from django.contrib import admin from blackcrowtours import views from accounts import views from django.conf.urls.static import static from django.conf import settings urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^accounts/', include('accounts.urls'), name='accounts'), url(r'^signup/', accounts.views.signup, name='signup'), url(r'^$', views.home, name='home'), url(r'^yourtrips/', views.yourtrips, name='yourtrips'), url(r'^about/', views.about, name='about'), url(r'^whyus/', views.whyus, name='whyus'), url(r'^accommodations/', views.accommodations, name='accommodations'), url(r'^yourguides/', views.yourguides, name='yourguides'), url(r'^westerneurotrip/', views.westerneurotrip, name='westerneurotrip'), url(r'^contact/', views.contact, name='contact'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) account app views from django.shortcuts import render from django.contrib.auth.models import User from django.contrib.auth import authenticate, login def signup(request): return render(request, 'accounts/signup.html') account app urls from django.conf.urls … -
How to test a Django on_commit hook without truncating?
The on_commit function has been added to Django 1.9 to be able to trigger an action (e.g. a Celery task) after the current transaction has committed. They mention later in the docs that one should use TransactionTestCase to test features that rely on that function. However, unlike TestCase (which uses transactions and rolls them back), TransactionTestCase empties the whole database after each test. Unfortunately, I have data migrations that preload some useful data inside the database, which means that subsequent tests do not work anymore after the first test clears the database. I ended up resorting to a dirty trick by mocking on_commit : with mock.patch.object(transaction, 'on_commit', lambda t: t()): test_something() Is there a better way? -
How to handle different POST request on class-based-view?
i'm working with Django, and until now i have only had the necesity to make a single POST request for the page to work, but now i need to make multiple POST request, and i don't know how to handle a different POST request with the same method. Maybe i'm not explaining me very well. I have a view.py like class List(View): def post(self, request): #Receive the JSON return JsonResponse(data,safe=False) #data is a list of dicts [] def get(self,request): return render(request,'list.html') list =List.as_view() Now, with this i return information to create a list of elements, and each of them has a button that opens a modal where i want to show more information. The thing is, i could just send all the information needed with the post method i have, but i don't think is correct to send too much information with one request when not all of it could be used. So, my idea is that the button first make a new POST request for tha data i need, and then create the modal with it. My problem is that i don't know how to handle the second request, because, in theory, if i send another request, will be … -
Seedstar's django-react-redux boilerplate - How to access the admin area?
I go to /admin, but the response is NOT FOUND. With this boilerplate, React/Redux is handling the routing. Does that mean I have to create custom Admin views and no longer can take advantage of Django's built-in Admin system? -
Create static wsdl in python application
I am using python(3.3)/django(1.8) application. Whenever I restart my server it changes wsdl attribute's order. Could someone tell me how to create static wsdl. Thanks in advance -
Django - Change URL path for adding user within admin (/admin/auth/user/add/)
I'm currently overriding admin templates for the User and Group models. Per the image below, the overridden templates reside in a sub-directory under a templates directory (see below). My ultimate goal is to override the {% block breadcrumbs %} within the templates. As a result I would like to change the default url address for some of the pages. For example when adding a user to the admin, the default url is "http://127.0.0.1:8000/admin/auth/user/add/." How can I change this to "http://127.0.0.1:8000/admin/portfolio/adduser/." -
How do I upload Pillow processed image to S3 on Django?
I'm trying below code that I wrote but it's throwing an error. I'm not sure what I'm doing wrong. Any help is appreciated def upload_img(request): maxsize = (1024, 1024) im = Image.open(request.FILES['image']) im.thumbnail(maxsize) img_name = 'test.jpg' s3 = boto3.client('s3') s3.put_object( Bucket=settings.AWS_S3_DEV_IMG_BUCKET, Key=img_name, Body=im.save(img_name, "JPEG"), ContentType='image/jpeg', ) ERROR: 'ParamValidationError: Parameter validation failed: Invalid type for parameter Body, value: None, type: <type 'NoneType'>, valid types: <type 'str'>, <type 'bytearray'>, file-like object -
Django/python 2.7 & I18N. How to localize the 404 "not found" page in French, spanish, chineese...?
Is it possible to localize 4O4, 500.. pages in django using i18N packages ? I mean i want to have a "not found page", in english (default), french, spanish, chinese, hebrew. I unsuccessfully tried today visiting : https://code.djangoproject.com/ticket/18948 Django url internationalization not working in production mode Django, creating a custom 500/404 error page and other pages Thank you for your help -
Excluding multiple app in django dumpdata using call_command
I'm using call_command to launch a datadump, I would like to exclude multiple apps, so if I was not using call_command, I would do it like the django documentation tell to do it : python manage.py dumpdata --format json -e app1 -e app2 But in call_command I don't know how I should call it : from django.core.management import call_command call_command("dumpdata", format="json", ?) What is not working : call_command("dumpdata", format="json", exclude="app1") call_command("dumpdata", format="json", exclude="app1 app2") # CommandError: No installed app with label 'a'. call_command("dumpdata", format="json", e="app1") call_command("dumpdata", format="json", e="app1 app2") # Does not fail but does not exclude anything either call_command("dumpdata", format="json", e="app1", e="app2") # SyntaxError: keyword argument repeated Is it even possible to exclude something from dumpdata using call_command ? Thanks in advance. -
Emails sent in django appear quoted in mail client
Registration to send activation email when the user tries to sign up for the website. The code works fine but when I receive the email the text is shown as quoted as if it was forwarded. This can be seen in the screen shot below: Below is the template txt file that Django-Registration uses to send this email. When I use the original text supplied by Django-Registration, it appears well in my email. I have edited to display my own custom message while preserving all appropriate tags: {% load i18n %} {% blocktrans with first_name=user.first_name%} Dear {{ first_name }}, Welcome to the ***** ****** community. We look forward to matching you to creative projects and great teams. Please click the below link within {{ expiration_days }} days to validate your email. After this you can log in any time you wish. {% endblocktrans %} http://{{site.domain}}{% url 'registration_activate' activation_key %} {% blocktrans %} Best wishes, ***** and ****** ***** ****** {% endblocktrans %} I have no idea what I'm doing wrong and have been adjusting the formatting all afternoon but cannot work it out. Any help would be appreciated -
How to Handle Incomplete Django/Nginx File Server URLs?
I have a Django website that uses Nginx on a separate file server to serve up images uploaded by my users. When any user views another user's photos, the link to the photo will have this structure: https://fs01.mysite.com/media/photos/<username>_<photo-id>.jpg When the page is rendered, the user's photo is served up by the file server (fs). But what is the Nginx way of handling incomplete (one could also say incorrect) requests to subdirectories of the above URL? For example, if a user enters this URL: https://fs01.mysite.com ...they see Nginx's default "Welcome to nginx on ..." page. If they enter this URL: https://fs01.mysite.com/media ...they'll get the Nginx "404 Not Found" page. And if they enter this URL: https://fs01.mysite.com/media/photos ...they'll get the Nginx "403 Forbidden" page. How do you handle these situations in Nginx? -
Loading a different skin into django-ckeditor
I'm trying to get BootstrapCK4-Skin working with django-ckeditor. I've got this in settings.py: CKEDITOR_CONFIGS = { 'default': { 'skin': 'bootstrapck', 'toolbar': 'Custom', ... I've extracted BootstrapCK4 to 'static/ckeditor/ckeditor/skins/' I no longer get any form of CKEditor. It just gives me a text box. What am I doing wrong? -
How To: Grainy landing page image loading before full-res version?
I'm struggling to optimise load times for my landing page. Despite having all image assets saved for Web, with exceptionally low bandwidth internet connection my image on the landing page is still unsatisfactorily slow to load. I've seen that the Barclays homepage (http://www.barclays.co.uk/) has a nice feature where initially a grainy version of the main image is shown, followed by a full-res version being loaded once the other assets on the page have fully loaded. I want to achieve this behaviour for my landing page. Does anyone have any sources/tutorials on how this is implemented? I'm running Django 1.7. Thanks! -
Filtering using viewsets in django rest framework
Please consider these three models: class Movie(models.Model): name = models.CharField(max_length=254, unique=True) language = models.CharField(max_length=14) synopsis = models.TextField() class TimeTable(models.Model): date = models.DateField() class Show(models.Model): day = models.ForeignKey(TimeTable) time = models.TimeField(choices=CHOICE_TIME) movie = models.ForeignKey(Movie) class Meta: unique_together = ('day', 'time') And each of them has their serializers: class MovieSerializer(serializers.HyperlinkedModelSerializer): movie_id = serializers.IntegerField(read_only=True, source="id") class Meta: model = Movie fields = '__all__' def get_censor_rating(self, obj): return obj.get_censor_rating_display() class TimeTableSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = TimeTable fields = '__all__' class ShowSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Show fields = '__all__' And their routers router.register(r'movie-list', views.MovieViewSet) router.register(r'time-table', views.TimeTableViewSet) router.register(r'show-list', views.ShowViewSet) Now I would like to get all the TimeTable objects (i.e. date list) by filtering all the Show objects by a specific movie object. This code seems to be the working and getting the list like I want it m = Movie.objects.get(id=request_id) TimeTable.objects.filter(show__movie=m).distinct() But I have no clue how to use this in django rest framework? I tried doing this way (which I am pretty sure its wrong), and I am getting error: views.py: class DateListViewSet(viewsets.ModelViewSet, movie_id): movie = Movie.objects.get(id=movie_id) queryset = TimeTable.objects.filter(show__movie=movie).distinct() serializer_class = TimeTableSerializer urls.py: router.register(r'date-list/(?P<movie_id>.+)/', views.InTheatersViewSet) How can I filter using viewsets in django rest framework? Or if there is any prefered way … -
Django CloudinaryField uploaded image URL is wrong
When uploading an image to Cloudinary using the CloudinaryField in my model, the file URL is being prepended with image/upload which yields an invalid image URL when attempting to view in the template. models.py image = CloudinaryField('image', blank=True, null=True) views.py from cloudinary.uploader import upload if form.is_valid(): instance = form.save(commit=True) image_data = re.sub('^data:image/.+;base64,', '', data['graphic']).decode('base64') image_file = ContentFile(image_data, 'your-image.png') public_id_string = str(instance.id) + settings.CLOUDINARY_SUFFIX response = upload(image_file, tags=DEFAULT_TAG, public_id=public_id_string, folder='') instance.image = response['public_id'] instance.save() return HttpResponse(status=201) Object in Admin Here you can see the incorrect file name with the appended folder 'image/upload'. I expect to just see '58dev' here. Clicking on the filename opens the url http://res.cloudinary.com/xxxxx/image/upload/v1/image/upload/58dev when it should be http://res.cloudinary.com/xxxxx/image/upload/v1/58dev -
Django Upload Image to AWS S3 Not Working After Upgrade to Django 1.10
I have (finally) upgraded to Django 1.10 from Django 1.8 and while there has been some obvious challenges, the only struggle is my image upload to S3. While upgrading Django, I was also forced to upgrade Boto & PIL. While the original image will still correctly upload to requested bucket, the save function that would create a thumb and would save it to another bucket no longer works. Here is my code that was working correctly until the Django/Boto/PIL upgrade: class Photo(models.Model): ... def save(self, *args, **kwargs): super(Photo, self).save(*args, **kwargs) self.create_avatar_thumb() def create_avatar_thumb(self): import os from PIL import Image from django.core.files.storage import default_storage as storage if not self.filename: return "" file_path = self.filename.name filename_base, filename_ext = os.path.splitext(file_path) original_file_path = "%s%s" % (filename_base, filename_ext) xm_file_path = original_file_path.replace('originals/', 'xm/') if storage.exists(xm_file_path): return "exists" # resize the original image to xs f = storage.open(file_path, 'r') image = Image.open(f) print image # example 1 xm_size = 40, 40 image.thumbnail(xm_size, Image.ANTIALIAS) f_thumb = storage.open(xm_file_path, "w") print f_thumb # example 2 image.save(f_thumb, quality=100) f_thumb.close() My testing: I get no errors running this script. Two observations: When I run print, the #example 1 would print twice and the print on #example 2 is empty -
Showing error with imported in Django mysql table
I have such a model in my models.py class DeviceType(models.Model): device_type_id = models.IntegerField(unique=True, blank=True, null=True,db_column='device_type_id') device_type_name = models.CharField(max_length=64) class Meta: # managed = False db_table = 'device_type' For the test I tried to add the table to admin view, it's added, but when I try to see the result I have an error: (1054, "Unknown column 'device_type.id' in 'field list'") Request Method: GET Request URL: http://172.17.45.9:8001/admin/_my_alfanet_/devicetype/ Django Version: 1.10.6 Exception Type: OperationalError Exception Value: (1054, "Unknown column 'device_type.id' in 'field list'") Exception Location: /etc/network/scripts/my_alfanet_env/lib/python2.7/site-packages/MySQLdb/connections.py in defaulterrorhandler, line 36 Python Executable: /etc/network/scripts/my_alfanet_env/bin/python Python Version: 2.7.9 Python Path: ['/etc/network/scripts', '/etc/network/scripts/ansible/lib', '/etc/network/scripts', '/etc/network/scripts/my_alfanet_env/lib/python27.zip', '/etc/network/scripts/my_alfanet_env/lib/python2.7', '/etc/network/scripts/my_alfanet_env/lib/python2.7/plat-linux2', '/etc/network/scripts/my_alfanet_env/lib/python2.7/lib-tk', '/etc/network/scripts/my_alfanet_env/lib/python2.7/lib-old', '/etc/network/scripts/my_alfanet_env/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7', '/usr/local/lib/python2.7/plat-linux2', '/usr/local/lib/python2.7/lib-tk', '/etc/network/scripts/my_alfanet_env/lib/python2.7/site-packages'] Server time: Fri, 3 Mar 2017 15:18:57 +0000 It looks like django try to add it's own column to sql request and this is create an error. Who could help, wich solution could be about this issue? -
Field that refers to a computer directory
I've been trying to add a field that refers to a local file. I've tried FileField but that uploads it. I don't want to upload the file, I just want a link/reference to the file. URLField doesn't allow local URLs either. I guess I can just save it as a CharField and create a custom form to choose the file? Thanks in advance. -
Using settings.AUTH_USER_MODEL in models
I'm using django 1.8.2 and DRF 3.3.2. I have custom user model that I've defined in settings like: settings.py AUTH_USER_MODEL = 'auth_app.my_user_name' When I'm trying to use it in my main_app/models.py: class MyClass(models.Model): previous_owner = models.ForeignKey(settings.AUTH_USER_MODEL) ...I get "AttributeError: 'module' object has no attribute 'AUTH_USER_MODEL'" which is very strange, because many sources, including django docs are saying, that I'm doing it the right way. P.S. Not sure if it relevant, but I'm using composed settings which consists of two files, like: base.py AUTH_USER_MODEL = 'my_user_app.my_user_name' development.py import base.py -
Django URL not working with parenthesis
I have a URL that looks like this in my urls.py: url(r'^ex/(?P<example>[\w ]+)$', views.example, name = 'example') One of my variables looks like this: Example (something).I get a 404 page not found with the the URL and I know that it has to do with the parenthesis. How do I fix this without changing the variable? -
Return data contained in two different models in django rest framework
I have two models a User model and a profile model. I am using the user id as the foreign key for the profile model. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,primary_key=True) bio = models.TextField(max_length=500, blank=True) website = models.TextField(max_length=200, blank=True) phoneno = models.TextField(max_length=200, blank=True) gender = models.TextField(max_length=200, blank=True) avatar = models.ImageField('profile picture', upload_to='images/avatar/', default='/images/avatar/blank.png') I am using the built in user model by django which contains the fields of username, password etc... I want to create a serializer wherein I can return the details of both the Profile and User Model. So far I can return the details of the user if I use UserSerializer instead of the ProfileUserCombinedSerializer below. However I have created ProfileUserCombinedSerializer so that I can combine the values of the two,so far I have the following class UserSeralizer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ('username', 'password',"email","first_name","last_name") class ProfileUserCombinedSerializer(serializers.HyperlinkedModelSerializer): user = ProfileSerializer() class Meta: model = User fields = ('username',"user") How do I append the corresponding profile model to the queryset so that the corresponding fields of bio, website ect get serialized so I can view them in the browsable api. class returnProfileDetailsFromUser(generics.ListAPIView): serializer_class = ProfileUserCombinedSerializer def get_queryset(self): i = self.kwargs['id'] queryset = User.objects.all() queryset = queryset.filter(id=i) …