Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ZipFile to response not working in python 2.7.9
Has anybody come across with the issue that the ZipFile(response, 'w') is not working with python 2.7.9? The same code works with python 2.7.0 and 2.7.6. from django.http import HttpResponse ... response = HttpResponse(content_type='application/zip') response['Content-Disposition'] = 'attachment; filename="file.zip"' with ZipFile(response, 'w') as output: outzip.writestr('output.txt', 'data to write') return response AttributeError: 'HttpResponse' object has no attribute 'seek' -
django overwrite db entries
I've a MySQL db table like this: id, field1, field2, field3 id is the primary key and auto increment I'm writing a button that allows user to update field1, however, it ends up overwriting all entries that share the same field2, here's my code to do the update in views.py: my_model = MyModel.objects.get(id=id) my_model.field1= request.POST.get('new_field1_value') my_model.save() So, I used the primary key to get the only entry from my db and then do the update, however, it's overwriting all entries in my db that share the same value of field2, I'm very confused, any help is really appreicated! -
How Do I Include ForeignKey in django-rest-framework POST
So I have tried to make a browsable API via django-rest-framework (DRF), but I have had some issues nesting serializers. So far, I am able to include the Sport and Category fields/foreignkeys into my Article, but when I try to POST via the API, I get an error saying as follows: Got a TypeError when calling Article.objects.create(). This may be because you have a writable field on the serializer class that is not a valid argument to Article.objects.create(). You may need to make the field read-only, or override the ArticleSerializer.create() method to handle this correctly. Original exception text was: int() argument must be a string, a bytes-like object or a number, not 'ArticleSport'. Here are my files: models.py class ArticleSport(TimeStampedModel): title = models.CharField(max_length=20, blank=False) slug = AutoSlugField(populate_from='title', unique=True, always_update=True) parent = models.ForeignKey('self', blank=True, null=True, related_name='children') # TODO: Add on_delete? uuid = models.UUIDField(default=uuid.uuid4, unique=True, editable=False) def __str__(self): return '{0}'.format(self.title) #class Meta: # TODO: Migrate live #unique_together = ('title', 'parent') class ArticleCategory(TimeStampedModel): title = models.CharField(max_length=20, blank=False) slug = AutoSlugField(populate_from='title', unique=True, always_update=True) parent = models.ForeignKey('self', blank=True, null=True, related_name='children') # TODO: Add on_delete? uuid = models.UUIDField(default=uuid.uuid4, unique=True, editable=False) def __str__(self): return '{0}'.format(self.title) class Meta: verbose_name_plural = 'article categories' #unique_together = ('title', 'parent') # TODO: … -
Django - iframe in template
I have a template in which I want to display an iframe. However then I call iframe object from my dictionary the code is displayed as. I have never worked with iframes before so I am not sure what is goign wrong here. This is my code: view def get(self, request, *args, **kwargs): # code context.update({ 'preview': preview, 'ad': ad, }) return render(request, 'preview.html', context) template <div> {{ preview }} </div> This displays the iframe code on the template as is: <iframe src="https://www.server.com/api/preview_iframe.php?d=AQJX8krvqFUdi1fti2whFYPuTwhqufTjXz5XHL58PKMdBgNfv4d-YOMR56B02YSKskZZsKDlo0djLHBuwRjKvdQsjU94KO75foPR-rcgfT0qVQ-67Y69pxpA_vPGEQpLDbBfJBOYpqwiFs5nu6D5XCmyAW_B877lkvHbO-mXbx1lmy2EiYfDnABRcs8WynK77ZdxgsjEWHbBvVeofhh3gpQ&amp;t=AQItBadwOTQ_GS3b" width="274" height="213" scrolling="yes" style="border: none;"></iframe> If I try {{ preview | safe }} I dont see anything , aka template is blank -
Django - Sort Queryset by Date instead of Datetime
I have a model (representing a 'job') that contains a DateTimeField called date_created. I have another called date_modified. I would like to sort by -date_modified so that the most recently modified 'jobs' are at the top of my list. The problem is that multiple running jobs will keep getting reordered each time the timestamp gets updated. If the date_modified field was sorted as if it was a DateField, then I could sort all 'jobs' that have been modified 'today' first, and then sort off of a second value (like date_created) so that they would not change places in the list as the timestamps are modified. This is what I have now: queryset = DataCollection.objects.all().order_by('-date_modified','-date_created') I found a related article, but seems outdated with version 1.9: Django sorting by date(day) I saw something that mentioned using Coalesce? Thank you! -
importing data into a GeoDjango model
I have a GeoDjango model that I created with a particular field : mpoly of type models.MultiPolygonField() class GeoEntity(models.Model): name = models.CharField(max_length=50) file_name = models.CharField(max_length=64) country_code = models.CharField(max_length=2) iso2 = models.CharField('2 Digit ISO', max_length=2) iso3 = models.CharField('3 Digit ISO', max_length=3) un = models.IntegerField('United Nations Code') collection_date = models.DateField(auto_now=False) corner_coords = models.CharField(max_length=255) sensor = models.CharField(max_length=128) #probably ultimately layer info targetName = models.CharField(max_length=64) # this will probably need to be far less once I figure out the formatting of this. fileSize = models.IntegerField() polarization = models.CharField(max_length=128) #accessLevel = models.CharField(max_length=255) #some roll field created_at=models.DateField(auto_now_add=True) updated_at=models.DateField(auto_now=True) mpoly = models.MultiPolygonField() def __str__(self): return self.name I am not sure how that mpoly datatype looks in python code? I ultimately have a json file that I want to load, parse and save the data to this model. Just not sure how to approach this. I do have the postgis extension installed on the postgresql database in the backend. A snippet of the json I want to load is: { "target_name": "", "mpoly": "{ \"type\": \"Polygon\", \"coordinates\": [ [ [ 39.285833333333329, 36.037777777777777, 0.0 ], [ 39.221666666666671, 35.776111111111113, 0.0 ], [ 38.68055555555555, 35.861666666666665, 0.0 ], [ 38.742777777777782, 36.123055555555553, 0.0 ] ] ] }", "f_size": 340, "collection_dt": "20160201033033", "polarization": "SIDD: … -
Django: Print out all choices for a models.Model class
Im trying to write an algorithm that prints out all choices in a Django model class. For example: I have a model: class SomeModel(models.Model): field_a = models.SmallIntegerField(choices=[(1, "a"), (2, "b"), (3, "c")] field_b = models.CharField(max_length=255) The expected output is something like this: "field_a": [(1, "a"), (2, "b"), (3, "c")] Please note the algorithm should ignore field_b because of the missing choices attribute. Any idea on how this functionality can be achieved? -
json.loads fails with this array - DJango
I'm wrapping a html table into a javascript array, later I parse it into json and send it trough a hidden CharField for submit. I have been used this method before, but now I have an error in json loads in the view. The first code that I used to wrap a previous table, and the one that is working, is this: var tbl = $('table#tabla_productos tr').get().map(function(row) { return $(row).find('td').get().map(function(cell) { return $(cell).html(); }); }); $.each(tbl, function(key,value) { value.pop(); }); tbl.shift(); var tblJson=JSON.stringify(tbl); The table that I used with that code had 3 int columns, one of pure text and the last one was a float. If I send that data I don't have problems with jsonloads, but with the new data, the one with problmes, looks like this (is the wrapped array): [["1","2","1","100"],["1","10","1","200"]] The code that I used to produce that array is this one: var tbl = $('table#tabla_productos tr').get().map(function(row) { return $(row).find('td').get().map(function(cell) { return $(cell).html(); }); }); $.each(tbl, function(key,value) { value.splice(3,1); }); tbl.shift(); var tblJson=JSON.stringify(tbl); I don't know what is happening, is almost the same code, the first code works fine, but the second one don't loads with json.loads in the view, what is happening? -
Django Rest-Auth giving 403 when doing a GET /user/
I am trying to test some Angular 2 app code that calls the rest-auth package on my local Django server. Using Chrome to see the header information I see the following when the GET is issued: OPTIONS /rest-auth/user/ HTTP/1.0 Host: 127.0.0.1:8000 Accept: */* Accept-Encoding: gzip, deflate, sdch Accept-Language: en-US,en;q=0.8 Access-Control-Request-Headers: x-csrftoken Access-Control-Request-Method: GET Origin: http://localhost:8100 Referer: http://localhost:8100/ User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36 HTTP/1.0 200 OK Access-Control-Allow-Headers: x-requested-with, content-type, accept, origin, authorization, x-csrftoken Access-Control-Allow-Methods: GET, POST, PUT, PATCH, DELETE, UPDATE, OPTIONS Access-Control-Allow-Origin: * Access-Control-Max-Age: 86400 Content-Type: text/html; charset=utf-8 Date: Mon, 22 Aug 2016 17:31:43 GMT Server: WSGIServer/0.2 CPython/3.4.3 X-Frame-Options: SAMEORIGIN And here is what the 403 result looks like: GET /rest-auth/user/ HTTP/1.0 Host: 127.0.0.1:8000 Accept: */* Accept-Encoding: gzip, deflate, sdch Accept-Language: en-US,en;q=0.8 Origin: http://localhost:8100 Referer: http://localhost:8100/ User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36 X-CSRFToken: HTTP/1.0 403 Forbidden Access-Control-Allow-Origin: * Allow: GET, PUT, PATCH, HEAD, OPTIONS Content-Type: application/json Date: Mon, 22 Aug 2016 17:31:43 GMT Server: WSGIServer/0.2 CPython/3.4.3 X-Frame-Options: SAMEORIGIN Do I need to do something special to get rid of the 403 error? -
Pre-populating Django-REST endpoints with empty data?
In Ruby on Rails, endpoints are automatically create with an empty list. I was wondering if there is equivalent behavior in the Django-REST framework because my ember.js frontend is looking for these endpoints to have some data (could be null), but the interface is not rendering because there is no data at the endpoints. -
Add Many2Many object list in Django Admin
I have the following models: class Book(models.Model): user = models.ForeignKey('users.User', related_name='usuário') title = models.CharField('nome do livro', max_length=200) author = models.CharField('autor', max_length=200) categories = models.ManyToManyField('categories.Category', verbose_name='categorias') class Category(models.Model): name = models.CharField('categoria', max_length=200) def __str__(self): return self.name What I am trying to do is add a list of Books in the Category entry in my Admin, so I can see all books from a specific category. I tried to do: class BooksInLine(admin.TabularInline): model = Book.categories.through class CategoryAdmin(admin.ModelAdmin): model = Category list_display = ('name',) search_fields = ('name',) inlines = (BooksInLine,) But this didn't have the effect I was hoping for, since it added drop-downs, and I am thinking in something closer to a table. How can I achieve this? -
Multilingual issue using django
Im Using python3 and django1.10 for my application , and kinnda new to django. Im planning to have many languages for django admin panel. as i follow the rules in Django documantion, i find out that i have to use a middleware for localization... here is my setting apps 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', I also add this LANGUAGES = ( ('fa', ugettext('Farsi')), ('en', ugettext('English')), ) and LOCALE_PATHS = ( os.path.join(BASE_DIR, 'locale'), ) And of course i installed the GNU gettext and create my locale folders with django-admin.py makemessages -l fa command , then i translate the .po file and compile it so i get the .mo file. so far every things looks good i think, and when i just change the language in setting file just by typing it,every thing works. Now here is my question, How can i add the feature to change the application language from admin panel, or view ? i add the url((r'^i18n/', include('django.conf.urls.i18n'))), in my urls file. But i just dont know what to do now. please help me. What is the next step ? How can i add this form or where sholud i add this form to change language ? <form action="/i18n/setlang/" method="post"> <input … -
Django - create custom tag to acces variable by index in template
I have a HTML template in django. It get's two variables: list of categories (queryset, as it it returned by .objects.all() function on model in django) and dictionary of contestants. As a key of the dictionary, I'm using id of category, and value is list of contestats. I want to print name of the category and then all the contestants. Now I have this: {% for category in categories_list %} <h1>category.category_name</h1> {% for contestant in contestants_dict[category.id] %} {{ contestant }} </br> {% endfor %} {% endfor %} However, when I run it, I get error: TemplateSyntaxError at /olympiada/contestants/ Could not parse the remainder: '[category.id]' from 'contestants_dict[category.id]' What I know so far is that I can't use index in template. I thought that {% something %} contains pure Python, but it shoved up it's just a tag. I know that I have to create my own simple_tag, but I don't know how. I read the docs Writing custom template tags, but there is such a little information and I wasn't able to fiqure out how to create (and mainly use in a for loop) a tag, that will take dict, key and return the value. What I tried is: templatetags/custom_tags.py: from … -
Access queryset values while setting up modelform
Is it possible to access a value from the queryset that was used to create the form class. For example I have the following view: class MyView(View): position = Position() form_class = PortfolioForm PositionModelFormSet = modelformset_factory(Position, fields=('symbol', 'direction', 'size'), form=form_class) def get(self, request): positions = self.position.get_user_positions_qs(user=request.user) portfolio = self.PositionModelFormSet(queryset=positions) What I need is to be able to access the values that are passed to the PortfolioForm when creating the form. In other words, for each form in the formset there is a queryset that is used when instantiating it. I need to access the values in that queryset while setting up the form. For example the PortfolioForm would be something like: class PortfolioForm(forms.ModelForm): value = get_value_from_queryset # eg: access symbol field do_something_with_value(value) class Meta: model = Position fields = ['symbol', 'direction', 'size'] -
List item template Django
I'm dealing creating a template on Django to show a list of items with 2 buttons that make actions. My form class it's: class AppsForm(forms.Form): def __init__(self, *args, **kwargs): policiesList = kwargs.pop('policiesList', None) applicationList = kwargs.pop('applicationList', None) EC2nodesList = kwargs.pop('amazonNodesList', None) super(AppsForm, self).__init__(*args, **kwargs) self.fields['appsPolicyId'] = forms.ChoiceField(label='Application Policy', choices=policiesList) self.fields['appsId'] = forms.ChoiceField(label='Application', choices=applicationList) self.fields['ec2Nodes'] = forms.ChoiceField(label='Amazon EC2 Nodes', choices=EC2nodesList) Now, I do the form with: <form method="post" action="" class="form-inline" role="form"> <div class="form-group"> {% for field in form %} { field.label }}: {{ field}} {% endfor %} </div> {% csrf_token %} <input type="submit" class="btn btn-default btn-success" name="deployButton" value="Deploy"/> <input type="submit" class="btn btn-default btn-danger" name="undeployButton" value="Undeploy"/> And the result it's: Application Policy - Choicefield ; Application - Choicefield ; Amazon EC2 Nodes - Choicefield [Button Deploy] [Button Undeploy] And what I'm looking for it's a way to render the form and show the list like this: Application Policy - Choicefield ; Application - Choicefield [Button Deploy] [Button Undeploy] Amazon EC2 Nodes - Choicefield [Button Deploy] [Button Undeploy] <more items if I add them in forms.py...> How I can get the proper way to render like that? Thanks and regards. -
Django rest framework allow BOTH Api-Token and username/password
So I have a confusing use-case which I'm not sure as to how to go about. I have a RESTful API implemented using Django rest framework, which is the backend for some web app implemented in react.js (served via some other fileserver). Front-end authentication uses username/pass using DRF TokenAuthentication and django-rest-auth. Once authenticated, User is then limited by some rules on an Account model. So far : User has a flag to mark if he was a bad boy (and broke the rules related to the Account (for example, made too many posts in one day), and the Account has a 1-to-many relation to all Users under that Account (something along the lines of django-oganizations) Now, I need to expose the api to 3rd parties, via some secret key (Api-Token), and allow that Account api access with a different set of restrictions. So what I think I need, is a method to allow for both authentication methods to co-exists. As far as I can see, easiest way to do this is: create a "dummy" user named '{account_id}-api_user', maybe even flag it as a special user. override/duplicate the TokenAuthentication to allow for it search bot 'Token' in Authorization header and 'Api-Token' … -
How to login in a user using Django
I have made the registration part of the login system but i am unable to make a registered user login. Can someone help me with the code to make a registered user login. Here's my code : Views.py from django.shortcuts import render, redirect from django.contrib.auth import authenticate, login from django.views.generic import View from .forms import UserForm # def Success(request): # return render(request, 'success.html') class UserFormView(View): form_class = UserForm template_name = 'form.html' def get(self, request): form = self.form_class(None) return render(request, self.template_name, {'form': form}) def post(self, request): form = self.form_class(request.POST) if form.is_valid(): user = form.save(commit=False) # cleaned data username = form.cleaned_data['username'] password = form.cleaned_data['password'] user.save() return redirect('success.html') return render(request, self.template_name, {'form': form}) Urls.py from django.conf import settings from django.conf.urls import include, url from django.conf.urls.static import static from django.contrib import admin from .views import UserFormView urlpatterns = [ url(r'^$', UserFormView.as_view(), name='registraion'), url(r'login/', LoginView.as_view(), name='login'), #url(r'success/', Success, name='sccuess') ] Forms.html Registration Form <br> <form action="" method="POST"> {% csrf_token %} {{form.as_p}} <button type="submit">SUBMIT</button> </form> What i want is another view for Login which will be linked to login.html and after logging-in the user the user is redirected to home.html. I have tried a lot and read the documentation as well but i wasn't able to … -
Django reverse foreignkey relationship failing
I have set up two models where one has a foreign key relationship to the other. Since I have multiple databases I also set up a routers.py file as both databases live in the same application. I have been reading and following the documenation found here and here and as far as I can tell I am following the documentation to the letter. models.py class Customers(models.Model): customer_id = models.AutoField(primary_key=True) name = models.CharField(max_length=100) active = models.IntegerField() class Meta: db_table = 'customers' app_label = 'db1' class Users(models.Model): user_id = models.AutoField(primary_key=True) customer = models.ForeignKey(Customers, models.CASCADE) role = models.ForeignKey(Roles, models.CASCADE) active = models.IntegerField() class Meta: db_table = 'users' app_label = 'db1' routers.py class BackendRouter(object): def db_for_read(self, model, **hints): if model._meta.app_label == 'db1': return 'default' elif model._meta.app_label == 'db2': return 'db2' return None def db_for_write(self, model, **hints): if model._meta.app_label == 'db1': return 'default' elif model._meta.app_label == 'db2': return 'db2' return None def allow_relation(self, obj1, obj2, **hints): if obj1._meta.app_label == 'db1' or \ obj2._meta.app_label == 'db1': return True elif obj1._meta.app_label == 'db2' or \ obj2._meta.app_label == 'db2': return True return None def allow_migrate(self, db, app_label, model_name=None, **hints): if app_label == 'db1': return db == 'default' elif app_label == 'db2': return db == 'db2' return None Ignore … -
Django SMTP library generates wrong smtp auth plain authentication string
I encounter a strange, reproducible issue on different setups (localhost, production systems) with Django's smtp library: the auth plain authentication string is totally of the mark. This is what the python console returns: sys.version_info sys.version_info(major=3, minor=5, micro=0, releaselevel='final', serial=0) from email.base64mime import body_encode as encode_base64 encode_base64(("\0%s\0%s" % ("User Name", "1234123241-23421334")).encode("ascii"), eol='') 'AFVzZXIgTmFtZQAxMjM0MTIzMjQxLTIzNDIxMzM0' However when I send email through python's smtplib.py this is the auth plain authentication string that is generated by smtplib.py: AFVzZXIgTmFtZQBiJzEyMzQxMjMyNDEtMjM0MjEzMzQn It's generated here: https://github.com/python/cpython/blob/master/Lib/smtplib.py#L629 Example: https://gist.github.com/macolo/bf2811c14d985d013dda0741bfd339e0 I am in dire need of a clue regarding this, thank you. -
Django relation error when running make migrations
Hey I am attempting to initialize a new database, but I am running into some issues setting up the migrations. The error I am getting appears to stem from setting up my forms. In a form I am using, I am creating a choice field as so: from django import forms from ..custom_admin import widgets, choices class MemberForm(forms.Form): provinces = forms.ChoiceField(label='Provinces', choices=choices.PROVINCE_CHOICES, required=True) where PROVINCE_CHOICES comes from here: from ..base.models import ProvinceStateRegionCode PROVINCE_CHOICES = [] for province in ProvinceStateRegionCode.objects.filter(country_code_id=1).order_by('code'): PROVINCE_CHOICES.append((province.code, province.code)) The issue seems to be that this loop is being called before the migrations occur, giving me an error stating that the Province model does not exist. Commenting out the reference to this file allows the migrations to work, however, that seems like an impractical solution for continued use. Is there a way to get around this error? For reference, here is the error I get when I run manage.py makemigrations: ./manage.py makemigrations Traceback (most recent call last): File "/Users/js/Documents/VirtualEnvironments/pcenv/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) psycopg2.ProgrammingError: relation "pc_psr_code" does not exist LINE 1: ...escription", "pc_psr_code"."country_code_id" FROM "pc_psr_co... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "./manage.py", line … -
Elegant fallback for html5 video using JS
I have a Django website where users are meant to upload videos for others to playback. All videos are encoded solely as mp4 format. In certain cases where browsers can't play this format (e.g. Firefox), I need to program an elegant fallback. For me, that would be an option to download the video instead of streaming it. Looking at the simple example here, I've tried to program a fallback in my Django template, but to no avail. Perhaps the JS snippet needs tweaking? Below is what my template code basically looks like. Can someone help me vis-a-vis troubleshooting this? Thanks in advance. {% extends "base.html" %} {% block content %} <div class="margin"> <table> {% for video in object_list %} <tr><td> <a name="section{{ forloop.counter }}"></a> <a href="{% url 'videocomment_pk' video.id %}"> {{ video.caption }} <button> Comment </button> </a> <br> <video width="500" height="350" controls autoplay> <source src="{{ video.url }}" type='video/mp4; codecs="mp4v.20.8, samr"'> <a href="{{ video.url }}"> <img src="xyz.jpg" title="Your browser does not support the <video> tag"> </a> <p>Your browser does not support the <video> tag</p> </video> <br> </td></tr> {% endfor %} </table> <script> var v = document.querySelector('video'), sources = v.querySelectorAll('source'), lastsource = sources[sources.length-1]; lastsource.addEventListener('error', function(ev) { var d = document.createElement('div'); d.innerHTML = … -
Dynamically adding many to many relationships in the save method in Django
My Content model has a many-to-many relationship to the Tag model. When I save a Content object, I want to add the relationships dynamically. Im doing this the following way. # models.py def tag_content(content_id): obj = Content.objects.get(content_id) print obj # Checking obj.tags = [1, 2, 3] # Adding the relationships using the Tag IDs class Tag(models.Model): name = models.CharField(max_length=255) class Content(models.Model): title = models.CharField(max_length=255) is_tagged = models.BooleanField(default=False) tags = models.ManyToManyField(Tag, blank=True) def save(self, *args, **kwargs): super(Content, self).save(*args, **kwargs) if not self.is_tagged: tag_content(self.pk) # calling the tagging method In other words, when a Content object is saved, its tags field is related to 3 different Tag object models. Just to let you know, I do have the Tags with pks = 1, 2, and 3 in database. However, this simply doesn't work. The save method calls the tag_content method, since the print obj statement works. However, the many-to-many field is not set and remains empty. The funny thing is, If I run the following commands in shell, the tags field is set perfectly. # python manage.py shell from myapp.models import * obj = Content.objects.get(pk=1) tag_content(obj.pk) So how come the shell version works, but the other one doesn't? Any help is appreciated. -
How to customize the response of Django REST Framework GET request?
I have a model Foo which I use as the model for my vanilla DRF serializer. # models.py class Foo(models.Model): name = models.CharField(max_length=20) description = models.TextField() is_public = models.BooleanField(default=False) # serializers.py class FooSerializer(serializers.ModelSerializer): class Meta: model = Foo # views.py class FooRetrieveAPIView(RetrieveAPIView): queryset = Foo.objects.all() serializer_class = FooSerializer Now the result of this endpoint is being used by front-end code, which is then the basis on how the next page to show is identified. Anyway, I need to change the structure of the results returned for both status 200 (existing record) and 404 (non-existent record). Actual result (from vanilla DRF): $ curl localhost:8000/foo/1/ # existing record {"id": 1, "name": "foo", "description": "foo description", is_public=false} $ curl localhost:8000/foo/2/ # non-existent record {"detail": "Not found."} How I want the results to be: $ curl localhost:8000/foo/1/ {"error": "", "foo": {"id": 1, "name": "foo", "description": "foo description", is_public=false}} $ curl localhost:8000/foo/2/ {"error": "Some custom error message", "foo": null} I've mostly used vanilla DRF so things are pretty straightforward so this customization of the response structure is a bit new to me. Django version used: 1.9.9 DRF version used: 3.3.x -
DRF list of objects sharing a common relation
My model involves CashFlow and ThirdParty. One CashFlow has one ThirdParty. One ThirdParty has many CashFlow. I have a DRF API running with this serializer: class CashFlowSerializer(serializers.ModelSerializer): third_party = ThirdPartySerializer(allow_null=False, required=True, many=False) class Meta: model = CashFlow fields = ('id', 'date', 'forecasted_value', 'edited_value', 'third_party') It is OK for a POST request with a JSON like: { "date": "2016-10-01", "forecasted_value": null, "edited_value": 5000, "third_party": { "label": "APIRA", "categories": [ { "label": "Produit", "parent": null, "user": 1 }, { "label": "Beacon", "parent": 1, "user": 1 } ], "user": 1 } } Now, I want to add MANY CashFlow in one POST request with a JSON like this: { "cashflow_list": [ { "date": "2016-10-01", "forecasted_value": null, "edited_value": 5000 }, { "date": "2016-12-01", "forecasted_value": 10000, "edited_value": null } ], "third_party": { "label": "APIRA", "categories": [ { "label": "Produit", "parent": null, "user": 1 }, { "label": "Beacon", "parent": 1, "user": 1 } ], "user": 1 } } Of course I don't want something like serializer_class = CashFlowSerializer(many=true), which would induce a repetition of the "ThirdParty" data. -
Django allauth Redirect to email verification after social signup
I use Twitter for main signup/login and I would like to redirect to 'accounts/email' link after social signup because I want to force new user to provide their emails. I've found same question and answer from @Anzel from allauth.socialaccount.adapter import DefaultSocialAccountAdapter class SocialAccountAdapter(DefaultSocialAccountAdapter): def save_user(self, request, sociallogin, form=None): super(DefaultSocialAccountAdapter, self).save_user(request, sociallogin, form=form) return redirect('/accounts/email/') but the answer didn't work for me and got this AttributeError at /accounts/twitter/login/callback/ 'super' object has no attribute 'save_user' Request Method: GET Request URL: http://localhost:8000/accounts/twitter/login/callback/?oauth_token=HSowSgAAAAAAuTblAAABVrLCOpE&oauth_verifier=cVrwyB2Vfk2Lgsrwg5fqE0wyzrfnwJ3H Django Version: 1.9.2 Exception Type: AttributeError Exception Value: 'super' object has no attribute 'save_user'