Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest: How To Serialize Image / File Uploads
How do I serialize a list of image files sent via a multipart file request? ImageModel: user = models.ForeignKey(CustomUser, related_name='images') image = models.ImageField(upload_to=custom_upload) timestamp = models.DateField(auto_now_add=True) Command Line: curl -X PUT -F 'images=@i0.jpg' -F 'images=@i1.jpg' API_RESOURCE In View: request.data == <QueryDict: {u'images': [<InMemoryUploadedFile: i0.jpg (image/jpeg)>, <InMemoryUploadedFile: i1.jpg (image/jpeg)>]}> -
Change Django date time field auto_now_add format
I want to know if there is any way to change Django dateTimeField format, I want to set the time using auto_now_add attribute but I can't get it to save it with the format I want. I know that there is a way suing models.DateField but I need to use auto_now_add. Thanks -
Issues Deploying Django Application to AWS because of Date model
I am trying to do a simple sign in application using Django and host it on AWS using Amazon Linux My model is class Work(models.Model): user = models.CharField(_("User"), max_length = 50, default = None) intern = models.ForeignKey("Intern", default = 1) date = models.DateField(_("Date"), default= timezone.now().today(), blank=True) time_in = models.TimeField(_("Time In"),default= timezone.now().time(), blank=True) time_out = models.TimeField(_("Time Out"),default= timezone.now().time(), blank=True) I have tried timezone.now().time and datetime.datetime.now().time() and none of these work When I try to run migrate on the server I get this error log Apply all migrations: admin, auth, clockin, contenttypes, database, sessions, watson Running migrations: Applying clockin.0006_auto_20170523_1101...System check identified some issues: WARNINGS: clockin.Work.date: (fields.W161) Fixed default value provided. HINT: It seems you set a fixed date / time / datetime value as default for this field. This may not be what you want. If you want to have the current date as default, use `django.utils.timezone.now` Traceback (most recent call last): File "pmi_alpha/manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/opt/python/run/venv/local/lib/python3.4/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/opt/python/run/venv/local/lib/python3.4/site-packages/django/core/management/__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/opt/python/run/venv/local/lib/python3.4/site-packages/django/core/management/base.py", line 294, in run_from_argv self.execute(*args, **cmd_options) File "/opt/python/run/venv/local/lib/python3.4/site-packages/django/core/management/base.py", line 345, in execute output = self.handle(*args, **options) File "/opt/python/run/venv/local/lib/python3.4/site-packages/django/core/management/commands/migrate.py", line 204, in handle fake_initial=fake_initial, File "/opt/python/run/venv/local/lib/python3.4/site-packages/django/db/migrations/executor.py", line 115, … -
Django Choices As Uppercase With Spaces
I am having an issue where when using Django choices in a model, it will save the value with lowercase and no spaces. I have to import alot of data into the database and I want it to be formatted with capitalized letters and spaces. I have tried changing the value that saves to have spaces and capital letters but it doesn't appear to work. class Station(models.Model): FORMAT_CHOICES = ( ('AC', 'AC'), ('Adult Hits', 'Adult Hits'), ('CHR', 'CHR'), ('Classic Country', 'Classic Country'), ('Classic Hits', 'Classic Hits'), ('Country', 'Country'), ('Gospel', 'Gospel'), ('Hot AC', 'Hot Ac'), ('News Talk', 'News Talk'), ('Oldies', 'Oldies'), ('Rock', 'Rock'), ('Sports', 'Sports'), ('Urban', 'Urban'), ('Urban AC', 'Urban AC') ) TIMEZONE_CHOICES = ( ('Alaska', 'Alaska'), ('Central', 'Central'), ('Eastern', 'Eastern'), ('Mountain', 'Mountain'), ('Western', 'Western'), ) market = models.ForeignKey(Market, verbose_name=u'Market') call_letters = models.CharField('Call Letters', max_length=40) frequency = models.CharField('Frequency', max_length=40) state = models.CharField('State', max_length=40) region = models.ForeignKey(Region, verbose_name=u'Region') timezone = models.CharField('Timezone', max_length=40, choices=TIMEZONE_CHOICES) format = models.CharField('Format', max_length=40, choices=FORMAT_CHOICES) positioning = models.CharField('Positioning Statement', max_length=100) def __unicode__(self): return self.call_letters What is the best way to accomplish storing the model data for choice fields with capitalized first letters of words and with spaces? -
Cannot resolve keyword 'i' into field. Choices are: id, joined_on, user, user_id
I do not understand what I am doing wrong. I am trying to update a model through the form and I have been following tutorial online they all point in the direction of getting the 'id'. I have done it but I keep getting this error: Cannot resolve keyword 'i' into field. Choices are: id, joined_on, user, user_id the id key is there, but he thinks is an 'i' what I am looking for. Any Idea? view.py def testRegistration(request): id = UserProfileModel.objects.get('id') user_status_form = UserDetailsForm(request.POST or None, instance=id) if request.method == 'POST': if user_status_form.is_valid(): user_status = user_status_form.save(commit=False) user_status.user = get_user(request) user_status.save() user_status_form = UserDetailsForm() else: user_status_form = UserDetailsForm() return HttpResponseRedirect('testRegistration') return render( request, 'registrationTest.html', {'user_status_form' : user_status_form, } ) model.py class UserProfileModel(models.Model): user = models.OneToOneField(User, unique=True) joined_on = models.DateTimeField(auto_now=True, null=True) Traceback Environment: Request Method: GET Request URL: http://127.0.0.1:8000/testRegistration Django Version: 1.10.5 Python Version: 3.5.2 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app'] 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.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "/Applications/anaconda/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner 39. response = get_response(request) File "/Applications/anaconda/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/Applications/anaconda/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/xxx/xxx/xxx/app/views.py" in testRegistration 88. id = UserProfileModel.objects.get('id') File "/Applications/anaconda/lib/python3.5/site-packages/django/db/models/manager.py" … -
Links in Markdown with django-markdown-deux?
I'm working with django-markdown-deux and trying to include a Django URL in my markdown. If I just include this raw in my template: {% load markdown_deux_tags %} {% url 'privacy_view' %} It outputs /privacy just fine. But as soon as I try to do a Markdown link: [Privacy]({% url 'privacy_view' %}). The text appears, but the link is just set to #. What am I doing wrong? Doing this doesn't help either: [Privacy][1] [1]: {% url 'privacy_view' %} -
Django Tutorial: name 'HttpResponse' is not defined
I am learning Django via their tutorial for getting started. I have looked at other Django Tutorial errors and did not see this one (although I did not search every listing). I have made the changes to mysite/urls.py and polls/urls.py exactly as they demonstrate and I have run the server command: python manage.py runserver I get the following error: Since I am new to Django, I do not know what is going on. Please help. -
How to return the absolute path in Django RF
I upload the files to the server to specific folders, organized by projects. On DB I save: id 4 path /var/local/vvv/project-files/project_2/v_5//r_4_C5R1ud0W8AQwnxa.jpg:large.jpeg filename r_4_C5R1ud0W8AQwnxa.jpg:large.jpeg file_type jpeg How can I get the absolute path ? Something like this: http://127.0.0.1:8000/media/r_4_C5R1ud0W8AQwnxa.jpg The only thing I could do is: http://127.0.0.1:8000/api/vv/download_resource/4 but it doesn't work for what i need. Please HELP -
How to load a template using the include tag and render it with a dynamic context
in my template, I'd need to set a dynamically retrieved image as a background image by using css background-image: url('{% static <image_path> %}') where <image_path> = {{ instance.image }} Any hint more then welcome! Thank you -
Graphene Django "Must provide query string"
I have setup a Graphene server using Django. When I run my queries through GraphiQL (the web client), everything works fine. However, when I run from anywhere else, I get the error: "Must provide query string." I did some troubleshooting. GraphiQL sends POST data to the GraphQL server with Content-Type: application/json. Here is the body of the request that I copied from Chrome network tab for GraphiQL: {"query":"query PartnersQuery {\n partners{\n name\n url\n logo\n }\n}","variables":"null","operationName":"PartnersQuery"} When I copy it to Postman with Content-Type: application/json, I get the following response: { "errors": [ { "message": "Must provide query string." } ] } What can be the cause of this problem? I have not done anything crazy with the schema. Just followed the tutorials from graphene's docs. What else can cause an issue like this? -
How to display markers only in selected area
It seems to be an easy task. But i can't find any how-to instructions. Deal is, i have a map with lot of areas and markers on it class Incidences(models.Model): name = models.CharField(max_length=20) location = models.PointField(srid=4326) objects = models.GeoManager() def __unicode__(self): return self.name class Meta: verbose_name_plural =" Incidences" class Counties(models.Model): counties = models.CharField(max_length=25) newSpots = models.IntegerField() activeSpots = models.IntegerField() destroyedSpots = models.IntegerField() moneyCollected = models.IntegerField() codes = models.IntegerField() cty_code = models.CharField(max_length=24) dis = models.IntegerField() geom = models.MultiPolygonField(srid=4326) def __unicode__(self): return self.counties class Meta: verbose_name_plural = 'Counties' and a code that show pop-up on every county onEachFeature: function (feature, myLayer) { layer.bindPopup(feature.properties.description); } I want to make that all markers to be shown in this area+pop-up on click. What is the best way to do it ? -
Can't send a post request using Postman with Django
I am using Postman + Django rest framework to create a Post request locally but I keep getting a ParseError. My Get requests are working fine but the post requests are not working as expected. JSON parse error - Expecting ',' delimiter: line 3 column 2 (char 37) I am not even getting the 400 error defined in the code and Postman returns a 500 internal server error message. Here is my photo_list views.py: from django.http import HttpResponse, JsonResponse from django.views.decorators.csrf import csrf_exempt from rest_framework.renderers import JSONRenderer from rest_framework.parsers import JSONParser from .models import Photo from .serializers import PhotoSerializer @csrf_exempt def photo_list(request, pk=0): """ List all photos, or create a new one. """ if request.method == 'GET': if int(pk) > 0: # convert pk to an int then check if it is greater than zero photo = Photo.objects.get(pk=pk) serializer = PhotoSerializer(photo, many=False) return JsonResponse(serializer.data, safe=False) photos = Photo.objects.all() serializer = PhotoSerializer(photos, many=True) return JsonResponse(serializer.data, safe=False) elif request.method == 'POST': data = JSONParser().parse(request) serializer = PhotoSerializer(data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status=400) -
Using a proxy model as the User model in Django
I have a model that proxies the django User model, to change the USERNAME_FIELD. When I tried to set this as my AUTH_USER_MODEL setting, I got a TypeError. The answer to on a question from someone who encountered this as well, says that you can't use proxy models of User as AUTH_USER_MODEL. Is there any other way to make Django's built-in views like the admin login page and contrib.auth views use my proxied model, without resorting to subclassing the User and creating a separate table, -
Django allauth Redirect on Password Change Success
This question has been brought up before here: https://github.com/pennersr/django-allauth/issues/468 It's closed and is a few years old, which could explain why its not working for me. I am simply trying to redirect to a different page other than the change password page after the password is successfully changed. Here is my code, which is not making the page redirect on success. #ursl.py url(r'accounts/password/change', views.custom_password_change), url(r'^accounts/', include('allauth.urls')) ... #views.py from allauth.account.views import PasswordChangeView from django.contrib.auth.decorators import login_required class CustomPasswordChangeView(PasswordChangeView): print("Getting Here") @property def success_url(self): print('Inside Success') return '/unknown/' custom_password_change = login_required(CustomPasswordChangeView.as_view()) After submitting a password change, my terminal is printing "Getting Here" so it is definitely getting to that custom view. But its not printing "Inside Success". Any help is appreciated! Thanks! -
Django Rest Framework list_route and queryset on tree structure
Trying to display hierarchy of categories through DRF serializer and it fails GET /api/mobile/v1/categories/tree/ HTTP/1.1 Host: localhost:8000 Accept: application/json Content-Type: application/json Cache-Control: no-cache Postman-Token: c6b6c0e4-18f3-f8c4-1d77-75fc21a6a431 builtins.AttributeError AttributeError: Got AttributeError when attempting to get a value for field `id` on serializer `CategoryTreeSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `TreeQuerySet` instance. Original exception text was: 'TreeQuerySet' object has no attribute 'id'. Viewset class CategoryViewSet( mixins.ListModelMixin, viewsets.GenericViewSet ): """Category view set. List model viewset for ``Category`` model. """ queryset = Category.objects.all() serializer_class = CategorySerializer pagination_class = None @decorators.list_route(methods=['get']) def tree(self, *args, **kwargs): categories = Category.objects.filter(parent=None).all() serializer = CategoryTreeSerializer(categories) return Response(status=status.HTTP_200_OK, data=serializer.data My Model class Category(MPTTModel): id = models.CharField( max_length=32, primary_key=True, unique=True, verbose_name=_('ID'), help_text=_('Forsquare ID of the category.'), ) parent = TreeForeignKey( 'self', blank=True, null=True, related_name='children', db_index=True, verbose_name=_('Parent category'), help_text=_('Parent category.'), ) name = models.CharField(max_length=255, verbose_name=_('Name')) plural_name = models.CharField( max_length=255, verbose_name=_('Plural name') ) class Meta: verbose_name = _('Category') verbose_name_plural = _('Categories') class MPTTMeta: order_insertion_by = ['name'] def __str__(self): return self.name Serializer class CategoryTreeSerializer(serializers.ModelSerializer): """Category serializer. Serializer for ``Category`` model. Excludes fields specified for MPTT. """ children = serializers.ListField(child=RecursiveField()) class Meta: model = Category fields = ('id', 'name', 'plural_name', 'children',) -
print() not working in django
i'm getting error while using print(), in the following code programsListItems = programsList['items'] programsNextPage = programsList['nextPageURL'] print("check") and in the browser i'm getting error like this write() argument must be str, not bytes and the log is as follows File "C:\Users\....\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\exception.py", line 41, in inner response = get_response(request) File "C:\Users\....\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\....\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "F:\WORK\AdminDashBoard\admin_dashboard\search\views.py", line 99, in institutedetails print("check") File "C:\Users\....\AppData\Local\Programs\Python\Python36-32\lib\codecs.py", line 377, in write self.stream.write(data) TypeError: write() argument must be str, not bytes -
Django Invalid HTTP_HOST header: 'testserver'. You may need to add u'testserver' to ALLOWED_HOSTS
I started learning Django, I'm in the middle of implementing "Test a view" functionality. When I use test Client in the shell, the exception has occurred as follows. Invalid HTTP_HOST header: 'testserver'. You may need to add u'testserver' to ALLOWED_HOSTS. I run the command in the shell as follows. >>> from django.test.utils import setup_test_environment >>> setup_test_environment() >>> from django.test import Client >>> client = Client() >>> response = client.get('/') >>> response.status_code 400 In the tutorial, 404 should be appeared, but I get 400. When I continue running the command as follows, same exception has occurred. >>> response = client.get(reverse('polls:index')) >>> response.status_code 400 but the result must be 200.I guess I should declare ALLOWED_HOSTS in the settings.py, but how can I? I run the server on localhost using $python manage.py runserver. I wanna know the reason and solution. -
Creating Web app as MySQL DB as backend
I want to create a simple application which will use MySQL as backend DB.I will store some information and combine them to create an output file which will run some commands. What will be my best way to achieve this Spring Java or Python Django ? Thanks, -
build a JSON from Django-mptt
I am trying to build up a json from a tree structure. I use django-mptt to build the tree. But impossible for me to create a JSON out of it. I want the json to look like this: [ {"name": "Parent 1", "child": [ {"name": "Child 1-1"}, {"name": "Child 1-2"}, {"name": "Child 1-3"} ]}, {"name": "Parent 2", "child": [ {"name": "Child 2-1"}, {"name": "Child 2-2"}, {"name": "Child 2-3" ,"child": [ {"name": "Child 2-3-1"}, {"name": "Child 2-3-2"} ] } ] } ]; It can have multiple/unlimited children. So far I tried this. But unable to get the right syntax for the JSON var json = [ {% recursetree nodes %} {"text": "{{ node.item_title }}" {% if not node.is_leaf_node %} ,"nodes": [ {{ children }} {% endif %} }, {% endrecursetree %} ]; This gets me this output: var json = [ {"name": "Parent 1" ,"child": [ {"name": "Child 1-1" }, {"name": "Child 1-2" }, {"name": "Child 1-3" }, }, {"name": "Parent 2" ,"child": [ {"name": "Child 2-1" }, {"name": "Child 2-2" }, {"name": "Child 2-3" ,"child": [ {"name": "Child 2-3-1" }, {"name": "Child 2-3-2" }, }, ]; I cant figure out how to get the parentesis and hooks at the right … -
django 'admin' is not a registered namespace in pybbm-forum app on subdomain
I have django 1.10.7, python2.7, installed django-hosts, pybbm app. Pybbm forum on subdomain forum.example.com. When i'l trying open topic on url forum.example.com/topic/1/, that already have created, i get error. NoReverseMatch at /topic/1/ u'admin' is not a registered namespace my hosts.py # -*- coding: utf-8 -*- from django_hosts import patterns, host from django.conf import settings host_patterns = patterns('', host(r'example.com', settings.ROOT_URLCONF, name='www'), host(r'forum', 'forums.urls', name='forum'), ) my forums/urls.py, where i included pybb urls from django.conf.urls import include, url from django.conf.urls.static import static from django.conf import settings urlpatterns = [ url(r'^', include('pybb.urls', namespace='pybb')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Can you help how to better configure pybbm forum app with my django project on subdomain? -
ImproperlyConfigured: Error loading psycopg2 module on GCP
Currently I'm trying to launch my django web app to GCP by following this doc: here FYI: I'm using Django 1.9 and Python 2.7 After deploying the app using gcloud app deploy I checked my App Dashboard and saw these errors: 1) ImproperlyConfigured: Error loading psycopg2 module: No module named psycopg2 2) RuntimeError: populate() isn't reentrant After doing some research on how to fix the psycopg2 error I found a few answers here. But it was to no avail. Solutions to this problem is greatly appreciated. Thanks. -
Key error with installation of Django-organizations
I'm trying to installing django-organization. I tried using pip and got the following error (Same error when using the Git package). I'm using the cloud 9 platform with python 1.11 and python 2.7. Thanks a lot for the help Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/dist- packages/django/core/management/__init__.py", line 350, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 324, in execute django.setup() File "/usr/local/lib/python2.7/dist- packages/django/__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python2.7/dist- packages/django/apps/registry.py", line 108, in populate app_config.import_models(all_models) File "/usr/local/lib/python2.7/dist- packages/django/apps/config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/usr/local/lib/python2.7/dist- packages/organizations/models.py", line 26, in <module> from .abstract import (AbstractOrganization, File "/usr/local/lib/python2.7/dist- packages/organizations/abstract.py", line 37, in <module> from .base import OrgMeta, AbstractBaseOrganization, AbstractBaseOrganizationUser, AbstractBaseOrganizationOwner File "/usr/local/lib/python2.7/dist- packages/organizations/base.py", line 186, in <module> class OrganizationBase(six.with_metaclass(OrgMeta, AbstractBaseOrganization)): File "/usr/lib/python2.7/dist-packages/six.py", line 617, in with_metaclass return meta("NewBase", bases, {}) File "/usr/local/lib/python2.7/dist- packages/organizations/base.py", line 74, in __new__ return super(OrgMeta, cls).__new__(cls, name, bases, attrs) File "/usr/local/lib/python2.7/dist- packages/django/db/models/base.py", line 81, in __new__ module = attrs.pop('__module__') KeyError: u'__module__' -
I am using django(1.8.6), displaying and operations on page are very slow in admin site..!
To fix this I imported 'ENGINE': 'django_mysql_fix.backends.mysql' but getting below error. from django.db.backends.mysql.compiler import SQLInsertCompiler, \ ImportError: cannot import name SQLDateCompiler Any fix to speed up the page view because I`ll be working on more data in future..! -
Django 1.11 - Can't edit my model in Admin panel
Please could tell me why I can't modify my model in the admin panel of Django ? models.py : from django.db import models # Create your models here. class Games(models.Model): guid = models.CharField(max_length=100, unique=True, null=False, verbose_name="GUID") title = models.CharField(max_length=100, null=False, verbose_name="Titre") logo = models.CharField(max_length=100, null=True, blank=True, verbose_name="Logo") date = models.DateTimeField(auto_now_add=True, auto_now=False, verbose_name="Date de création") update = models.DateTimeField(auto_now=True, verbose_name="Dernière modification") admin.py from django.contrib import admin from .models import Games # Register your models here. class GamesAdmin(admin.ModelAdmin): list_display = ('logo', 'title', 'guid', 'date', 'update') list_filter = ('title', 'guid') date_hierarchy = 'update' ordering = ('date', ) search_field = ('guid', 'title') admin.site.register(Games, GamesAdmin) When I'm going to the admin panel, I see all the field of my model, I can also add a new field. But when I want to edit the field, there is no link clickable... Thanks ! -
Django migration dependencies reference nonexistent parent node
I have a problem with django migrations. I get this error: django.db.migrations.exceptions.NodeNotFoundError: Migration user.0050_merge_20170523_1254 dependencies reference nonexistent parent node ('user', '0049_auto_20170519_1934') I fix the errors, deleting some lines but after fix all this errors, I get other: ValueError: Could not find common ancestor of {'0050_merge_20170523_1254', '0007_auto_20170524_1540'} I cant solve that. I can drop database and do makemigrations again... but in production environment I want know how fix correctly, without drop database haha. Thanks!