Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Debugging is not supported for python 2.5 or earlier?
I keep getting this error in visual studios. There are currently no documentation that I can find that solves this error. Im using Pythong 3.7. Also, I get this same error when I try to debug a Django web application as well as a just regular python web application. I have also tested with Google Chrome, Internet Explorer, and Firefox, all of which give me the same error. The configuration is set up for 3.7 -
Django/Postgres: Returning error: duplicate key value violates unique constraint
I have had this issue occur several times with a project I've been working on, and though I used the "python manage.py sqlsequencereset " fix that I've found on this site, it works for a while, and then begins throwing the error again. The error I keep getting is pretty straightforward: IntegrityError at /projects/v/portola/planting-sites/new/ duplicate key value violates unique constraint "urbanforest_plantingsite_pkey" DETAIL: Key (id)=(194016) already exists. In my view I have: form = PlantingSiteForm(request.POST) if form.is_valid(): f = form.save(commit=False) if PlantingSite.objects.all().exists(): last_planting_site = PlantingSite.objects.all().order_by('-created_at')[0] f.id_planting_site = last_planting_site.id_planting_site f.id_planting_site += 1 else: f.id_planting_site = 100000 if request.POST.get('neighborhood_id'): f.neighborhood = Neighborhood.objects.filter(id_neighborhood=request.POST.get('neighborhood_id'))[0] if request.POST.get('district_id'): f.district = District.objects.filter(id_district=request.POST.get('district_id'))[0] if request.POST.get('basin_type_id'): f.basin_type = BasinType.objects.filter(id_basin_type=request.POST.get('basin_type_id'))[0] if request.POST.get('aspect_id'): f.aspect = Aspect.objects.filter(id_aspect=request.POST.get('aspect_id'))[0] if request.POST.get('orientation_id'): f.orientation = Orientation.objects.filter(id_orientation=request.POST.get('orientation_id'))[0] if request.POST.get('hardscape_damage_id'): f.hardscape_damage = HardscapeDamage.objects.filter(id_hardscape_damage=request.POST.get('hardscape_damage_id'))[0] if request.POST.get('status_id'): f.status = PlantingSiteStatus.objects.filter(id_planting_site_status=request.POST.get('status_id'))[0] else: f.status = PlantingSiteStatus.objects.filter(id_planting_site_status=9)[0] if f.zipcode: f.property_zipcode = f.zipcode f.created_by_fuf = True f.created_by = request.user f.save() I've done the sqlsequencereset a couple of times now, and then the error returns after a couple of weeks. I'm not importing any data, but my coworkers are using their phone in the field to create new objects, one at a time. Running sqlsequencereset gets me this code: SELECT setval(pg_get_serial_sequence('"urbanforest_plantingsite"','id'), coalesce(max("id"), 1), max("id") IS NOT … -
How to map JSON keys with non-alphanumeric characters in Django Rest Framework Serializer
I have some JSON keys that contain non-alphanumeric characters e.g. "my-key=" I need to map this key to a field my_key in my Django model. The traditional way to do this is to add a custom field to the ModelSerializer where you specify the source: class MyModelSerializer(serializers.ModelSerializer): my_key= = serializers.CharField(source='my_key') class Meta: model = MyModel fields = ('my-key=',) However this obviously doesn't work because: my_key= = serializers.CharField(source='my_key') is not valid python for declaring an attribute. How do I map my JSON key to the model field? -
Reusable admin form generator always checks last field
(This is all pseudocode and is not guaranteed to run.) I am trying to make a "django admin form generator function" that outputs a django form. The current use case is to write reusable code that disallows admins from leaving a field empty, without also marking these fields as non-nullable. So suppose there exists a model Foo, in which are some nullable fields: class Foo(Model): field1 = FloatField(null=True, blank=True, default=0.0) field2 = FloatField(null=True, blank=True, default=0.0) field3 = FloatField(null=True, blank=True, default=0.0) and corresponding FooAdmin and FooForm, such that these fields cannot be made None from the admin. class FooAdmin(ModelAdmin): class FooForm(ModelForm): class Meta(object): model = Foo fields = '__all__' def _ensure_no_blanks(self, field): value = self.cleaned_data.get(field) if value is None: raise forms.ValidationError(_('This field is required.')) return value # repeat methods for every field to check def clean_field1(self): return self._ensure_no_blanks('field1') def clean_field2(self): return self._ensure_no_blanks('field2') def clean_field3(self): return self._ensure_no_blanks('field3') form = FooForm As you can see, having to write clean_field1, clean_field2, and clean_field_n are repetitive and error-prone, so I write this helper function to generate model admins (pseudocode): def form_with_fields(model_class, required_fields): class CustomForm(ModelForm): class Meta(object): model = model_class fields = '__all__' def _ensure_no_blanks(self, field): print field value = self.cleaned_data.get(field) if value is None: raise … -
Idiomatic translation of Django models to different API schemas, perhaps with Django Rest Framework
Whats the best/idiomatic way to create and pass data between different API integrations in Django or with Django Rest Framework? I'm imaging something like a translation serializer that hooks between APIs that could be reused everywhere, and wanted to see what the best practices are. Say I have a standard Django Rest Framework based API and model that I expose via DRF that looks something like this : (But has alot more complexity and nested relationships class Person(models.Model): first_name = models.CharField(max_length=255, blank=True, null=True) middle_name = models.CharField(max_length=255, blank=True, null=True) last_name = models.CharField(max_length=255, blank=True, null=True) company = models.ForeignKey(Company, blank=True, null=True) class PersonSerializer(serializers.HyperlinkedModelSerializer): company = CompanySerializer(required=False) class Meta: model = Person fields = '__all__' class PersonViewSet(viewsets.ModelViewSet): queryset = Person.objects.all() serializer_class = PersonSerializer Response looks something like this { "first_name": "Oliver", "middle_name": null, "last_name": "Zhou", "company": { "name": "Company ABC", "url": "http://localhost:8000/companies/1234/" } } Now, depending on different actions in the application, I have a different API I need to integrate with and pass the Person data to, for example, an API with a schema with something like this : { "first_name": "Oliver", "middle_name": null, "last_name": "Zhou", "company": { "name": "Company ABC" } } What I've been doing is ugly and a spaghetti network … -
How to pass a user instance in a class-based view
I would like to pass the user instance of the current user in a class-based view and feed it in a second step to a model containing the column author. Related to that column I get the following integrity error: NOT NULL constraint failed... From the traceback I can see that my variable loggedUser which I had attributed self.request.user is a SimpleLazyObject. How can I pass my user instance? Thank you! View: class PlotGraphView(LoginRequiredMixin, TemplateView): redirect_field_name = '' login_url = '' template_name = "plot.html" def get_context_data(self, **kwargs): loggedUser = self.request.user context = super(PlotGraphView, self).get_context_data(**kwargs) context['logger'] = Logger.objects.get(name=logger_name) context['plot'] = plots.plotgraph(logger_name, loggedUser) Model: class Data(models.Model): logger = models.ForeignKey('Logger', on_delete=models.CASCADE) date = models.CharField(max_length=20) relative_humidity = models.FloatField(max_length=5) temperature = models.FloatField(max_length=5) author = models.ForeignKey(User, on_delete=models.PROTECT) -
Express multiple one-to-many and one-to-one relationship in Django
I am designing a delivery app. It has User, Address and Store models. I have following requirements: User can have multiple delivery address Store is located at only one location. An address cannot be linked with both user and store. Models looks as follow: class User(AbstractBaseUser): ... class Address(models.Model): ... class Store(models.Model): ... First requirement can be shown as: user = models.ForeignKey(User, on_delete=models.CASCADE) Second requirement can be shown as(in Address model as): store = models.OneToOneField(Store, on_delete=models.CASCADE) Also, second requirement can be shown as(in Store model as): address = models.OneToOneField(Address, on_delete=models.CASCADE) What is the best way to represent the third requirement. And how do I take care of serialization in this case? Thanks. -
view is correct, but django templates aren't rendering
I'm trying to figure my URLs out. My views seems to function in the console, but nothing renders in the templates after the search is completed. My search seems to function regardless of what i have in the user_list function as long as the user is defined with the following: user_list = Employee.objects.all() args = {'users':users} return render(request, 'user_list.html', args) My user_list falls under search and functions correctly with the filter. return render(request, 'user_list.html', args) It's after the filter that I try to render a view called results with: return render(request, 'results.html', args) The navigation is correct and it takes me to the URL and I can view the POST from the previous view in the console and it is correct. However, the template is empty when there is code in results.html In settings INSTALLED_APPS I have my app defined as: 'mysite.search', My application structure is laid out as the following: My project urls.py is setup as: from django.conf.urls import url, include from django.contrib import admin from django.views.generic import TemplateView from django_filters.views import FilterView from mysite.search.filters import UserFilter urlpatterns = [ url(r'^$', TemplateView.as_view(template_name='home.html'), name='home'), url(r'^search/$', FilterView.as_view(filterset_class=UserFilter, template_name='search/user_list.html'), name='search'), url(r'^admin/', include(admin.site.urls)), ] My application urls.py is setup as: from django.conf.urls import … -
Recommendation for REST API using Python
I will be working on a project that consists of developing some REST API for a web app with MongoDB database using Python (Django framework to be particular ) I have the basic knowledge with Python , so in order to accelerate the learning phase and get things going much faster I need some advice on what should I learn first and if possible some suggestions Please help me :) thank you -
Django CMS on Raspberry Pi 3 Fails
Today I tried to install django CMS for a while on my Raspberry pi but it will not work. I Installed a fresh "RASPBIAN STRETCH LITE" then i entered following commands via an ssh connection: sudo wget https://bootstrap.pypa.io/get-pip.py sudo python get-pip.py sudo pip install Django==1.10 sudo pip install virtualenv cd /srv sudo mkdir django_cms cd django_cms sudo virtualenv env source env/bin/activate sudo pip install --upgrade pip sudo pip install djangocms-installer sudo mkdir django_site cd django_site/ sudo djangocms -f -p . web_site All this follows this guide And this error get thrown after executing the last command above: Creating the project Please wait while I install dependencies ERROR: cmd : [u'pip', u'install', u'-q', u'django-cms>=3.5,<3.6', u'djangocms-admin-style>=1.2,<1.3', u'django-treebeard>=4.0,<5.0', u'https://github.com/divio/djangocms-text-ckeditor/archive/master.zip?1520455195.14', u'https://github.com/divio/djangocms-file/archive/master.zip?1520455195.14', u'https://github.com/divio/djangocms-link/archive/master.zip?1520455195.14', u'https://github.com/divio/djangocms-style/archive/master.zip?1520455195.14', u'https://github.com/divio/djangocms-googlemap/archive/master.zip?1520455195.14', u'https://github.com/divio/djangocms-snippet/archive/master.zip?1520455195.14', u'https://github.com/divio/djangocms-picture/archive/master.zip?1520455195.14', u'https://github.com/divio/djangocms-video/archive/master.zip?1520455195.14', u'https://github.com/divio/djangocms-column/archive/master.zip?1520455195.14', u'easy_thumbnails', u'django-filer>=1.3', u'Django<2.0', u'pytz', u'django-classy-tags>=0.7', u'html5lib>=0.999999,<0.99999999', u'Pillow>=3.0', u'django-sekizai>=0.9', u'six'] :Command "/usr/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-FFzxtb/Pillow/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-CPB18v-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-build-FFzxtb/Pillow/ The installation has failed. ***************************************************************** Check documentation at https://djangocms-installer.readthedocs.io ***************************************************************** Traceback (most recent call last): File "/usr/local/bin/djangocms", line 11, in <module> sys.exit(execute()) File "/usr/local/lib/python2.7/dist-packages/djangocms_installer/main.py", line 33, in execute verbose=config_data.verbose File "/usr/local/lib/python2.7/dist-packages/djangocms_installer/install/__init__.py", line 95, in requirements output = subprocess.check_output(['pip'] + args, stderr=subprocess.STDOUT) File "/usr/lib/python2.7/subprocess.py", … -
Bad magic number when deploying on Heroku
I am trying to deploy a Django app to Heroku which uses a client to connect to the api of an invoice service. Everything works when running localy, but when deploying on Heroku I get a Bad magic number errror: error at /bexiopy/auth/ Bad magic number Request Method: GET Request URL: https://oust-test.herokuapp.com/bexiopy/auth/ Django Version: 2.0.3 Exception Type: error Exception Value: Bad magic number Exception Location: /app/.heroku/python/lib/python3.6/dbm/__init__.py in open, line 94 Python Executable: /app/.heroku/python/bin/python Python Version: 3.6.4 Python Path: ['/app', '/app/.heroku/python/bin', '/app', '/app/.heroku/python/lib/python36.zip', '/app/.heroku/python/lib/python3.6', '/app/.heroku/python/lib/python3.6/lib-dynload', '/app/.heroku/python/lib/python3.6/site-packages', '/app'] Server time: mer, 7 Mar 2018 19:53:24 +0000 Environment: Request Method: GET Request URL: https://oust-test.herokuapp.com/bexiopy/auth/ Django Version: 2.0.3 Python Version: 3.6.4 Installed Applications: ['jet.dashboard', 'jet', 'nested_admin', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'whitenoise.runserver_nostatic', 'django.contrib.staticfiles', 'django_celery_beat', 'django_celery_results', 'bexiopy.apps.BexiopyConfig', 'database'] Installed Middleware: ('whitenoise.middleware.WhiteNoiseMiddleware', 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', '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 "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 35. response = get_response(request) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 128. response = self.process_exception_by_middleware(e, request) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 126. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/app/.heroku/python/lib/python3.6/site-packages/django/views/generic/base.py" in view 69. return self.dispatch(request, *args, **kwargs) File "/app/.heroku/python/lib/python3.6/site-packages/django/views/generic/base.py" in dispatch 89. return handler(request, *args, **kwargs) File "/app/.heroku/python/lib/python3.6/site-packages/bexiopy/views.py" in get 29. client = Client() File "/app/.heroku/python/lib/python3.6/site-packages/bexiopy/api.py" in __init__ 360. self.load_access_token_from_file() File "/app/.heroku/python/lib/python3.6/site-packages/bexiopy/api.py" in load_access_token_from_file 611. access_token … -
Django CMS -- Unregister Custom Menu?
Any idea how to unregister customized menus? The docs only show how to add them and I don't see any unregister attribute on menu_pool. I blindly tried menu_pool.clear(), but that didn't work. The prior menus remain discoverable with menu_pool.get_registered_menus() and in logging. -
Django model's clean() method not raising the expected ValidationErrors for individual fields
I have a Django model called CheckIn with (among others) two fields, min_weeks and max_weeks. I would like to build in validation such that min_weeks is always less than or equal to max_weeks. Following https://docs.djangoproject.com/en/dev/ref/models/instances/?from=olddo#django.db.models.Model.clean (in particular, the last example in which the ValidationError is passed a dictionary which maps fields to errors), I tried the following clean() method: from django.db import models from django.core.exceptions import ValidationError class CheckIn(models.Model): min_weeks = models.IntegerField(blank=True, null=True) max_weeks = models.IntegerField(blank=True, null=True) def clean(self): if self.min_weeks > self.max_weeks: raise ValidationError({ 'min_weeks': ValidationError("'min_weeks' should be smaller than 'max_weeks'", code='invalid'), 'max_weeks': ValidationError("'max_weeks' should be greater than 'min_weeks'", code='invalid')}) The model is used in a ModelForm: class CheckInForm(forms.ModelForm): class Meta: model = CheckIn fields = [ 'min_weeks', 'max_weeks', ] The fields are displayed manually in the template. Here is an excerpt: <div class="row"> <div class="input-field col s4"> <div class="js-hide-edit-field-text {% if not check_in_type or form.min_weeks.value %}hide{% endif %}"> {% if check_in_type and not form.min_weeks.value %} <span class='js-max-weeks inherited-field text'>{{ check_in_type.min_weeks }}</span> <a href='#' class='js-hide-edit-field-edit edit-icon right'><i class="material-icons">mode_edit</i></a> <label class="active"> Min Weeks </label> {% endif %} </div> <div class="js-hide-edit-field {% if check_in_type and not form.min_weeks.value %}hide{% endif %}"> {{ form.min_weeks|add_error_class:"invalid"|attr:"data-duration-weeks-mask" }} {{ form.min_weeks.errors }} {{ form.min_weeks|label_with_classes }} </div> </div> … -
How to set subdomains whit ip using nginx
Can subdomains be used with ip on Nginx for testing, like teste.x.x.x.x I did this but does not work. server_name teste.x.x.x.x teste2.x.x.x.x ; Thanks -
Custom validation in a CUSTOM Django admin
I've a custom django admin that extends a default change_form (I do it because a need some logic for uploading images), but I need a way to show the page again if no image was uploaded, and show the errors. Some code to illustrate: class MyModel(models.Model): ... main_photo = models.ForeignKey(Photo) photos = models.ManyToManyField(Photo, related_name='collage') I extend the change_form.html admin template for this model: myapp/templates/admin/mymodel/change_form.html {% extends "admin/change_form.html" %} {% block inline_field_sets %} {% for inline_admin_formset in inline_admin_formsets %} {% include inline_admin_formset.opts.template %} {% endfor %} <fieldset class="module"> <h2>Upload photos</h2> <h3>Main photo</h3> <input name="main_photo" type="file" /> <h3>Others</h3> <input name="photos" type="file" multiple /> </fieldset> {% endblock inline_field_sets %} Now I overwrite the save_model method from ModelAdmin in the admin.py @admin.register(MyModel) class MyModelAdmin(admin.ModelAdmin): ... exclude = ['main_photo', 'photos'] def save_model(self, request, obj, form, change): photos = request.FILES.getlist('photos') main_photo = request.FILES.get('main_photo', None) if not main_photo: pass # --> I NEED THE WAY TO NOTIFY THE USER THIS IMAGE MUST BE UPLOADED # raise ValidationError("msg") --> It's not an option because this doesnt show the form re-rendered with the error. # some internal bussiness logic here: folder_to_save = '{0}/{1}'.format(self.folder_to_save_img, obj.id) obj.main_photo = Photo.objects.create(folder=folder_to_save, original=main_photo) obj.save() if photos: for photo in photos: obj.photos.add(Photo.objects.create(folder=folder_to_save, original=photo)) -
Django with Docker - Server not starting
I have followed the steps in the official docker tutorial for getting up and running with django: https://docs.docker.com/compose/django/ It works fine until I have to run docker-compose up It doesn't directly give me an error, but it won't run the server either, stopping at this point: (Screenshot of the Docker Quickstart Terminal) I am on Windows and have therefore used docker-toolbox. Thanks for your suggestions! -
Running Wagtail site with Docker
I'm trying to convert an existing Wagtail site to run with Docker. I have created the image and then run the container, but I'm unable to connect in the browser window. Getting 0.0.0.0 didn’t send any data. ERR_EMPTY_RESPONSE. Dockerfile: FROM python:3.6 RUN mkdir /app WORKDIR /app COPY ./ /app RUN pip install --no-cache-dir -r /app/requirements/base.txt RUN mkdir -p -m 700 /app/static RUN mkdir -p -m 700 /app/media ENV DJANGO_SETTINGS_MODULE=mysite.settings.dev DJANGO_DEBUG=on ENV SECRET_KEY=notsosecretkey ENV DATABASE_URL=postgres://none ENV SENDGRID_KEY=sendgridkey EXPOSE 8080 RUN chmod +x /app/entrypoint.sh \ && chmod +x /app/start-app.sh RUN python manage.py collectstatic --noinput ENTRYPOINT ["/app/entrypoint.sh"] CMD ["/app/start-app.sh"] docker-compose.yml: version: '2' services: db: environment: POSTGRES_DB: app_db POSTGRES_USER: app_user POSTGRES_PASSWORD: changeme restart: always image: postgres:9.6 expose: - "5432" ports: - "5432:5432" app: container_name: mysite_dev build: context: . dockerfile: Dockerfile depends_on: - db links: - db:db volumes: - .:/app ports: - "8080:8080" environment: DATABASE_URL: postgres://app_user:changeme@db/app_db command: python manage.py runserver 0.0.0.0:8080 entrypoint.sh: #!/bin/sh set -e exec "$@" start-app.sh: #!/bin/sh python manage.py runserver 0.0.0.0:8080 I run docker run -p 8080:8080 app:latest and it works when I run docker ps showing that it's at 0.0.0.0:8080->8080/tcp, but when I go to 0.0.0.0:8080 in the browser window, I get the error. What am I missing? -
Is there any open-source free codes of a Django Python database app with a CRUD and search functionality? [on hold]
Is there any open-source free codes and tutorials of a Django Python database app with a CRUD and search functionality? Need to develop a bioinformatics-oriented application with an extended search and data view functionality. And I am thinking what technology would be more appropriate: Django Python or YII PHP. Thx. -
Trouble using an Oracle View in Models.py
My group and I are attempting to rewrite our website. We are keeping an Oracle database back-end, and rewriting the front-end with Python Django. No problem connecting to Oracle, or accessing the datatables. Now I'm trying to add an Oracle view to the models.py, and I can't get it to work. I googled this question with many results, so I know it is possible and apparently common, but I can't get it to work. All I've done so far is add the class to models.py. We are using PhCharm as our IDE. When I try to access the data using the Python Console, I can import the class, but when I try to load the QuerySet I get the error "Unable to get repr for " in the result window. Does anyone see something I'm missing from my model? Here is the model: class LawBillRoleActionInfoView(LawBaseClass): combo_id = models.AutoField(primary_key=True) rltp_role_cd = models.CharField(max_length=2, blank=True) bill_dft_no = models.CharField(max_length=6, blank=True) session_id = models.IntegerField(blank=True, null=True) ebrl_appl_seq = models.IntegerField(blank=True, null=True) enty_id_seq = models.IntegerField(blank=True, null=True) lst_nm = models.CharField(max_length=100, blank=True) fst_nm = models.CharField(max_length=40, blank=True) mi = models.CharField(max_length=1, blank=True) entity = models.CharField(max_length=145, blank=True, null=True) prtydist = models.CharField(max_length=11, blank=True, null=True) blac_appl_seq = models.IntegerField(blank=None, null=True) role_descr = models.CharField(max_length=80, blank=True) shr_ttl = … -
Why can't I display my background image in django template?
I have an app by the name 'main' having static folder and template folder. My static folder goes like static/main/background/city.png I am trying to set background image of my html file but it does not load. Can you tell me what is it that I'am doing wrong? <style> body{ background-image:url("{static 'main/background/city.png'}"); } </style> -
Django: Modify model field value when form is submitted
I have a model field for each use that keeps track of their score on my website. Every time a user does some I want to add or subtract from their score. In this particular case, I would like to change the users score when they publish a post on my site. I am able to access the user's score, but not modify it. Here is what I have so far: def createPost(request): user = UserProfile.objects.get(user=request.user) current_score = user.user_score if request.method == 'POST': form = PostForm(request.POST) if form.is_valid(): ... user.user_score = current_score - 1 ... else: form = PostForm() return render(request,'feed/userpost_form.html',{'form':form}) I am not getting any errors and publishing the post works fine, just not modifying the user's score. Also, I am using Django 1.11 -
Between Django and WAMP which would be better for using their sql for my Android studio project?
I want to use the database and communicate between both using REST API. -
Rest framework: different serializer for input and output data on post/put operations
Lets say I have these models: class Download(MPTTTimeStampedModel): endpoint = models.ForeignKey(EndPoint, related_name="downloads",) class EndPoint(TimeStampedModel): name = models.CharField(max_length=100, verbose_name=_(u"Nombre")) url = models.CharField(max_length=2000, verbose_name=_(u"Url")) These serializers: class DownloadSerializer(serializers.ModelSerializer): class Meta: model = Download fields = ('id', 'endpoint') def create(self, validated_data): ... def update(self, validated_data): ... class EndPointSerializer(serializers.ModelSerializer): class Meta: model = EndPoint fields = ('id', 'name', 'url') def create(self, validated_data): ... def update(self, validated_data): ... And this generic api view: class DownloadList(generics.ListCreateAPIView): queryset = Download.objects.all() serializer_class = DownloadSerializer This will allow me to create a download by sending a json representation looking like this: { 'id': null, 'endpoint': 19 } And upon creation, the web service will send me back the data with the id from the database. Now, I actually want the web service to send me back not just the endpoint id but a complete representation of the object, Something like this: { 'id': null, 'endpoint': { 'id': 19, 'name': 'my endpoint', 'url': 'http://www.my-endpoint.com/' } } I would manage this with this serializer: class DownloadDetailedSerializer(DownloadSerializer): endpoint = EndPointSerializer(many = False, read_only=False) And now the actual question: how do i tell my generic view to use this last serializer for the returned data while keeping the original DownloadSerializer for the input? -
Django and Postgress Heroku deployment error
I have the following error in Heroku: at=error code=H10 desc="App crashed" method=GET path="/" host=psc-test.herokuapp.com request_id=c16bb8e0-a1e6-4905-ae79-56d105d71ef7 fwd="92.86.38.87" dyno= connect= service= status=503 bytes= protocol=https and I have no idea why -
How to pass an InMemoryUploadedFile as parameter to a celery task with json set as serializer?
I've just changed my celery settings to use json as serializer, I have to change some of my tasks with objects like querysets as parameters. I have one particular task with an InMemoryUploadedFile as parameter that can no longer be used with json as serializer. Do you have any advice since the file has no path please? The only thing I can think of would be to temporarily save the file, then pass the path as parameter, then reopen the file, and finally delete it. Thanks guys!