Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Login-error page not displayed when using python-social-auth
I am using social-app-django (part of python-social-auth) to implement Facebook login for the users of my Django site. I have a requirement that users must be found in the local user database before they can log in with Facebook. I have replaced the auth_allowed-part of the authentication pipeline, to perform this check: def auth_allowed(backend, details, response, *args, **kwargs): if not backend.auth_allowed(response, details) or not is_registered_user(response, details): raise AuthForbidden(backend) where is_registered_user() is a custom function that checks whether the user exists locally. My problem is that the users are not redirected to the login error URL, if this check fails and the AuthForbidden exception is thrown. Instead, the site returns a 500. The error-page URL is configured as follows in settings.py: LOGIN_ERROR_URL = "/" I am using Django CMS, so I have also tried implementing middleware that overwrites SocialAuthExceptionMiddleware (which is supposed to handle the AuthForbidden exception in a standard setup) to return a CMS-page instead of an URL from settings.py but this middleware is not invoked in the process, as far as I can see. Any ideas on how to fix this? Am I missing some configuration? -
In django, creating a randomized object list with paging
I've been trying to get a list of model objects, randomize their order and paginate them in the template. I thought I've done it until I realize that in each next page call I had been re-randomizing objects rather than using the previously randomized list. Is there anyway I can randomize the object list only while opening the page first time and after that use the same list without randomizing it while going to the next page? Thanks. Views.py class index(View): def get(self, request): all_items = list(Electronics.objects.all()) random.shuffle(all_items) paginator = Paginator(items, 24) page = request.GET.get('page') items = paginator.get_page(page) return render(request, 'home.html', {'items':items, 'header':'Homepage'}) home.html <div class='container'> <div class='row'> {% for item in items %} <div class='col-xs-6 col-sm-8 col-lg-4'> <img src='{{ item.image.url|cut:"%22"|thumb}}'> <h4>{{item.name}}</h4> <p>$ {{item.price}}</p> <form method='get'> <input value='Add to cart' type='submit' formaction= "{% url 'addtocart' item.id %}"> <input value='View Details' type='submit' formaction= "{% url 'detail' item.id %}"> </form> <div><br><br> {% endfor %} </div> </div> <div class='pagination' align='center'> <span class='step-links'> {% if items.has_previous %} <a href="?page=1{% if request.GET.q %}&q={{request.GET.q}}{% endif %}">&laquo; first</a> <a href="?page={{items.previous_page_number}}{% if request.GET.q %}&q={{request.GET.q}}{% endif %}">previous</a> {% endif %} <span class="current"> Page {{items.number}} of {{items.paginator.num_pages}} </span> {% if items.has_next %} <a href="?page={{items.next_page_number}}{% if request.GET.q %}&q={{request.GET.q}}{% endif %}">next</a> <a … -
File not found with qgis2threejs and django
I've used the plugin QGIS2Threejs on 2.18 QGIS version and with that version was very simply to serve the 3D map on a Django site, becouse the only thing that I do was insert a Django static file tag( for example something like this {% static 'my_path/index.js' %} ) inside the html script tag, after creation of a TemplateView. With the new version there isn't index.js but there is the directory "index" and the new core of the 3D map is scene.json that is inside this directory. Here there is e little demo 3D map created with the default parameters of qgis2threejs. It is very simple to understand: there is index.html inside it there is the javascript for load the scene: // load the scene app.loadJSONFile("{% static 'data/index/scene.json' %}", function () { app.start(); Inside the json there are three paths for serve other parts of the scene as the satellite image(b0.png), vectors(a0.json) and the DEM(b0.bin). I need to change that paths for initialize the scene but if I do this the consolelog show 404 error related to a0.json, b0.bin and b0.png. What do you suggest for solve this problem? I've tried to set the paths manually but nothing is change. -
How do I run migrations on GCloud SQL instance?
I want to run a migration on the GCloud MySQL instance for my site. I have already tried making a new bucket on the GCloud console and importing my local MySQL dump into that and then adding that to the MySQL instance. It didn't work. I also saw someone recommending to connect to the GC using the GC proxy and Google Compute Engine. I am new to this so I couldn't follow along very well, and I found out that App and Compute Engine are two different things. Here's my requirements file; asn1crypto==0.24.0 cffi==1.12.2 cryptography==2.6.1 Django==2.1.7 django-crispy-forms==1.7.2 freeze==1.0.10 mysql==0.0.2 mysqlclient==1.4.2.post1 Pillow==6.0.0 psycopg2==2.8.1 pycparser==2.19 PyMySQL==0.9.3 pytz==2018.9 six==1.12.0 -
How to make a reverse relate between two models in one application?
How to make a reverse relate between two models in one application? class User(AbstractUser): user_status = models.ForeignKey(Status) class Status(models.Model): users = models.ManyToManyField(User, blank=True) -
Django prefetch related of prefetched related
I have a few models that are in the fashion of parent - child - child of child. In my views.py I did swsallsteps = sws_dcoument_step.objects.filter().prefetch_related(my various models) The issue I'm having is how can I prefetch the related information from the related information? I'm getting lost in this portion. Example I have this in my views.py swsallsteps = SWS_Document_Step.objects\ .filter(document_number=document_id)\ .prefetch_related('swes_step_set', 'sws_step_hazard_set', 'sws_step_ppe_set') This is returning exactly what I'd expect. The SWES_Step_Set associated to SWS_Document_Step like my first 2 models below. How though, can I pull the SWES_Step_Picture model associated to SWES_Document_Step? I imagine it's much more simple than I'm making it. Models for example below. class SWS_Document_Step(models.Model): STEP_TYPE_CHOICES = ( ('People', 'People'), ('Quality', 'Quality'), ('Velocity', 'Velocity'), ('Cost', 'Cost'), ) document_number = models.ForeignKey(SWS_Document, on_delete=models.CASCADE) sws_sequence_number = models.PositiveIntegerField(editable=True, null=True) sws_work_element_description = models.CharField(max_length=500) sws_step_type = models.CharField(max_length=30, choices=STEP_TYPE_CHOICES, null=True, blank=True) pub_date = models.DateTimeField(auto_now=True) class Meta: verbose_name = 'SWS Document Step' verbose_name_plural = '005 SWS Document Steps' def __str__(self): return str(self.document_number) + " " + str(self.sws_sequence_number) + " " + str(self.sws_work_element_description) class SWES_Step(models.Model): STEP_TYPE_CHOICES = ( ('People', 'People'), ('Quality', 'Quality'), ('Velocity', 'Velocity'), ('Cost', 'Cost'), ) sws_document_id = models.ForeignKey(SWS_Document_Step, on_delete=models.CASCADE, null=True) swes_description = models.CharField(max_length=500) swes_step_type = models.CharField(max_length=8, choices=STEP_TYPE_CHOICES, blank=True) pub_date = models.DateTimeField(auto_now=True) class Meta: … -
How can I call other css file based on other lang selected ex. arabic
I just want to call other style.css file when the website language is changed from english to arabic. Of course for arabic, the content has to also be from right to left. I've placed an if condition on my base.html but still its not working. Also Ive heard about using LANGUAGE_BIDI lately, but I cant see a better tutorial or anything for how to implement it. Let me also tell you that the language translation is pretty much working fine once I change the language from en to ar. <!-- Style CSS --> {% if LANG == ar %} <link rel="stylesheet" href="{% static 'style_ar.css' %}"> {% else %} <link rel="stylesheet" href="{% static 'style.css' %}"> {% endif %} Here's the base.html if condition, but no success. Its only calling up the else condition. Just wanted to know the best possible way to implent this or otherwise any other solution. such as the use of LANGUAGE_BIDI or any other best practice. Thank you.. -
nested serializers with junction sql table : a proper way to create/update/delete
I pretty new to django and django rest framework... I still learning so excuse me if I am asking silly question... I am sorry in advance... That said ! Here are the models that I am working on: class Targets(models.Model): first_name = models.TextField() last_name = models.TextField() email = models.TextField() position = models.TextField() class Groups(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user_id') name = models.TextField(unique=True, null=False) modified_date = models.DateTimeField(auto_now_add=True) targets = models.ManyToManyField(Targets, through='Group_Targets') class Group_Targets(models.Model): group = models.ForeignKey(Groups, on_delete=models.CASCADE, related_name='groups') target = models.ForeignKey(Targets, on_delete=models.CASCADE, related_name='targets') Groups extends the core User models So a User can have multiple Groups. Groups have multiple Targets Targets can be part of multiple Targets Here are the endpoints: urlpatterns = [ path('groups/', GroupsAPIView.as_view()), path('groups/<int:pk>/', GroupsIDAPIView.as_view()) ] Here are the serializers: class GroupsSerializer(serializers.ModelSerializer): targets = TargetsSerializer(many=True) class Meta: model = Groups fields = ('id', 'name', 'modified_date', 'user_id', 'targets', ) def create(self, validated_data): user = None request = self.context.get("request") if request and hasattr(request, "user"): user = request.user targets = validated_data.pop('targets') group = Groups.objects.create(user_id=user.id, **validated_data) for target in targets: trgt = Targets.objects.create(**target) Group_Targets.objects.create(group_id=group.id, target_id=trgt.id) return group class GroupsIDSerializer(serializers.ModelSerializer): targets = TargetsSerializer(many=True) class Meta: model = Groups fields = ('id', 'name', 'modified_date', 'user_id', 'targets', ) def create(self, validated_data): user = None request … -
Using UniqueConstraint to solve "get() returned more than one" error in Django admin
I'm trying to access an (unmanaged) model via Django administration dashboard. The model doesn't have a primary key, but instead is unique across three fields. class MyObjectView(models.Model): solution_id = models.IntegerField(blank=True, null=True) scenario_id = models.IntegerField(blank=True, null=True) object_id = models.CharField(max_length=256, blank=True, null=True) description= models.CharField(max_length=1000, blank=True, null=True) year_of_creation = models.DateField(blank=True, null=True) def __str__(self): return "SolID - {0} -- CogID {1}".format(self.solution_id, self.cityobjectgroup_id) class Meta: managed = False # Created from a view. Don't remove. db_table = 'myobject_view' While I am able to access the list of all items in the admin dashboard, as soon as I try to view one specific item I get the error: get() returned more than one MyObjectView -- it returned 4! As per the documentation, I tried adding a UniqueConstraint in the Meta class, but the constraint doesn't seem to have any effect, and the error above persists: class Meta: managed = False # Created from a view. Don't remove. db_table = 'myobject_view' constraints = [ models.UniqueConstraint(fields=['solution_id', 'scenario_id', 'object_id '], name='unique_object'), ] Is this the proper way to solve the get() returned more than one error? Should the constraint work even on an unmanaged model? -
Django 1.10 Print values in same line in Templates
i want in same line print two value look like "1. Question ...". but first {{ }} after set new line. look like this, "1." "Question ..." {% for q in question %} <p> {{ forloop.counter }}. {{ q.question|safe }}</p> {% endfor %} How can i print two value in same line in template ? -
Long fetch time from firebase realtime database
I am using Firebase Realtime Database with Django using pyrebase. When I make multiple queries in the same view it takes long time to retrieve data. I have tried fetching the database all at once which makes loading considerably faster but database has a child "Transactions" which stores past transactions. So,fetching the whole database will fetch data(increasing overtime) that is not required. def post_menu(request): vendors = database.child('Vendors').shallow().get().val() curr_vendor_list = [i for i in vendors if database.child('Vendors').child(i).child('email').get().val() == request.user.email] if curr_vendor_list: curr_vendor = curr_vendor_list[0] else: error_msg = {'msg': "You are not a registered Vendor!"} return render(request, 'Authentication/login.html', error_msg) if request.method == 'POST': category = request.POST.get('category') if category == 'new': category_name = request.POST.get('category_input') elif category == 'existing': category_name = request.POST.get('category_select') else: return redirect('Vendor:reviews') item_name = request.POST.get('item') ingredients = request.POST.get('ingredients') mark = request.POST.get('mark') price = request.POST.get('price') dict_item_properties = {'ingredients': ingredients, 'mark': mark, 'price': price} if category == 'new': dict_item = {item_name: dict_item_properties} database.child('Menus').child(curr_vendor).child(category_name).set(dict_item) elif category == 'existing': database.child('Menus').child(curr_vendor).child(category_name).child(item_name).set(dict_item_properties) return redirect('Vendor:menu') return redirect('Vendor:reviews') -
How to serialize nested of nested object in a serializer?
I'm working on django rest framework with writable nested serializers. Using the documentation (https://www.django-rest-framework.org/api-guide/relations/#writable-nested-serializers) i'm able to do a nested relationships using serializer as a field. Here comes my problem. I got the error below when I'm trying to do a nested relation using a serializer as a field when this serializer has also a nested relation. TypeError: Direct assignment to the reverse side of a related set is prohibited. Use info_object.set() instead. Here are a part of my serializer: class BuildMessageSerializer(serializers.ModelSerializer): class Meta: model = models.BuildMessageInfo fields = '__all__' class BuildSerializer(serializers.ModelSerializer): info_object = BuildMessageSerializer( many=True, required=False, allow_null=True) class Meta: model = models.Build fields = '__all__' def create(self, validated_data): infos_result = validated_data.pop('info_object') build_res = models.Build.objects.create(**validated_data) for info_result in infos_result: models.BuildMessageInfo.objects.create( build_res=build_res, **info_result) build_res.labels.set(infos_result) return build_res class JobResultSerializer(serializers.ModelSerializer): class Meta: model = models.JobResult fields = '__all__' class JobBuildResult(JobResultSerializer): build_result = BuildSerializer(many=True) def create(self, validated_data): builds_data = validated_data.pop('build_result') job_result = models.JobResult.objects.create(**validated_data) for build_data in builds_data: models.Build.objects.create(job_result=job_result,**build_data) return job_result You can find here the payload for my unit test: self.build_payload = { 'daily_key': '365v4a9e8fv4s9efb8', 'computer': 'SOPBAMBOO01', 'branch_name': 'branch', 'plan_key': 'key', 'build_number': 25, 'pull_request': False, 'build_result': [ { 'name': 'app', 'project': 'ble', 'platform': 'board', 'mode': 'release', 'os': 'bm', 'ide': 'iar', 'result': 'pass', 'warning': 0, … -
Linking Django with MSSQL error: The database driver doesn't support modern datatime types
I have been trying to link my mssql database to Django. I am using windows 10 on my machine. When I run the Django server there is no problem. However, when I want to use InspectDB I am getting this error: File "C:\ProgramData\Anaconda3\lib\site-packages\sql_server\pyodbc\base.py", line 365, in init_connection_state "The database driver doesn't support modern datatime types.") django.core.exceptions.ImproperlyConfigured: The database driver doesn't support modern datatime types. My Django settings looks like this: DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'HOST': 'my_host', 'PORT': '1433', 'NAME': 'database_name', 'OPTIONS': { 'driver': 'SQL Server', 'extra_params': "Persist Security Info=False;server=my_host" }, }, } I don't really understand this engine idea. However, I tried other engines non of them worked. Error pops up when I run the server. With this engine not error araise when I run the server but it gives me the above mentioned error when I want to run: python manage.py inspectdb any insght would be greatly appreciated. -
ValueError: I/O operation on closed file . Python, Django , Boto3
I have a post method in my views.py : def post(self, request): author = User.objects.get(id=request.data.get('user_id')) new_article = Article.objects.create(author=author, title=request.data.get('title'), text=request.data.get('text'),img=File(request.data.get('image[0]'))) new_article.save() for i in range(20): img_key = 'image[{}]'.format(i) img = request.data.get(img_key) if img: article_img = ArticleImage(article=new_article,img=File(img), is_main=False ) article_img.save() else : break images = ArticleImage.objects.filter(article=new_article) return Response({ 'article': ArticleSerializer(new_article, context=self.get_serializer_context()).data }) It creates a new article which contains img files. The image files I save in AWS S3 bucket . Saving main image of article using new_article.save() method works fine , but article_img.save() returns an error: **File "C:\Users\Arcvi\AppData\Local\Programs\Python\Python36-32\lib\site-packages\storages\backends\s3boto3.py", line 520, in _save_content content.seek(0, os.SEEK_SET)* ***ValueError: I/O operation on closed file.**** I guess I do something wrong in my for loop. If you need more information about code , I will share it . Please any help. -
Django: can't load CSS files that are in /static
Since I finished the backend of my Django website I started adding some style. My html files are displayed but it seems no css has been linked to them however the path is correct when I show the source code in Firefox. mywebsite/ ----blog/ ----mywebsite/ ----static/ --------css/ ------------struct.css ----templates/ --------layouts/ --------errors/ ------------404.html --------html/ ------------struct.html Django version: 2.1.7 settings.py: DEBUG = False ALLOWED_HOSTS = ['*'] INSTALLED_APPS = [ # other apps... 'django.contrib.staticfiles', ] STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] urls.py: from django.conf import settings from django.conf.urls.static import static urlpatterns = [ # ... ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) struct.html: {% load static %} <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width; initial-scale=1.0;"> <link rel="stylesheet" href="{% static 'css/struct.css' %}"> <title>test</title> </head> <body> <p>test</p> </body> </html> struct.css: p{ color:red: } body{ background-color:black: } -
django-sass-processor: load sass_tags and load static
I'm wondering if {% load sass_tags %} is only for scss files, scss and css or all static files. For example which of those two examples would be correct: Example 1: {% load static %} {% load sass_tags %} <link href="{% sass_src 'scss.path' %}" rel="stylesheet" type="text/css"> <img src="{% static 'img.path' %}"> Example 2: {% load sass_tags %} <link href="{% sass_src 'scss.path' %}" rel="stylesheet" type="text/css"> <img src="{% sass_src 'img.path' %}" The latter seems to be working but I'd like to have a confirmation and a little bit more informations if anyone knows, I couldn't find much about this on the documentation. -
How to check the name of a model in a Django Template
I'm trying to get the name of a model in my template so i can give it a different design in the template #views.py class PostListView(ListView): model = Post template_name = 'blog/home.html' context_object_name = 'posts' paginate_by = 15 def get_queryset(self): posts = [] shared_post = [] if self.request.user.is_authenticated: user_id = self.request.user.id view_user_post = Post.objects.filter(user=self.request.user) user_profile = User.objects.get(id=user_id).profile # print(user_profile) for profile in user_profile.follower.all(): for post in Post.objects.filter(user=profile.user): posts.append(post) for profile in user_profile.follower.all(): for share in Share.objects.filter(user=profile.user): shared_post.append(share) chain_qs = chain(posts, view_user_post, shared_post) print(chain_qs) return sorted(chain_qs, key=lambda x: x.date_posted, reverse=True) else: posts = Post.objects.all().order_by('?') return posts #models.py class Share(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) content = models.TextField(max_length=140, null=True, blank=True) date_posted = models.DateTimeField(default=timezone.now) def __str__(self): return '{}- {}'.format(self.post.title, str(self.user.username)) class Post(models.Model): title = models.CharField(max_length=140) content = models.TextField(validators=[validate_is_profane]) likes = models.ManyToManyField(User, related_name='likes', blank=True) date_posted = models.DateTimeField(default=timezone.now) user = models.ForeignKey(User, on_delete=models.CASCADE) image = models.ImageField(upload_to='post_pics', blank=True) image_2 = models.ImageField(upload_to='post_pics', blank=True) image_3 = models.ImageField(upload_to='post_pics', blank=True) restrict_comment = models.BooleanField(default=False) saved = models.ManyToManyField(User, related_name='saved_post', blank=True) I need a way to check the name of the model in the template possibly an if/ else statement to check properly. thanks -
How to pass an SVG file from a views function to a template?
Within my views.py file I have a function that when called via a request, generates an .svg file. I then want this function to render the template and display said .svg file. Code I have so far (simplified): views: def home(request): # --------------------------------------- # generate test.svg file and save to a buffer # --------------------------------------- svg_data = open("buffer/test.svg", "rb").read() data = { 'image': svg_data } return render(request, 'blog/home.html', data) template: {% extends "blog/base.html" %} {% block content %} <svg> {{ image }} </svg> {% endblock content %} Unfortunately when I attempt to access the {{ image }} tag within the template, it displays nothing. So I ask, is there a way that I can load an .svg file in my views function and have it displayed within my template? -
Django: Get one key and value from queryset dictionary
I have this query: item = Item.objects.filter(id=3) It is returning a queryset with its the keys and values. Now I need to extract a particular value from the queryset, like this: item_name = item['name'] But it does not work. How can I achieve this? Send the most simple way if possible, please. Thanks! -
How can I override how rest-auth saves users?
My site has a django backend and it uses django-rest-auth package for authentication. I want to change this function inside rest-auth serializers: path_to_my_virtenv/lib/python3.7/site-packages/rest_auth/registration/serializers.py class RegisterSerializer(serializers.Serializer): def get_cleaned_data(self): return { 'username': self.validated_data.get('username', ''), 'password1': self.validated_data.get('password1', ''), 'email': self.validated_data.get('email', '') } I tried editing it directly and everything worked as I wanted, however I have a suspicion that it's not a good idea to edit files inside virtenv site-packages. Is there a way to override them from my django app? What is the best thing to do in my situation? -
Calculate sum of items in a date_range queryset if matched by foreign_key_id and skip the rest
I have a 100k entries per day and I am using them to output in an API(i have a limit and and offset by default). I want to calculate values in my queryset if they have a common owner_id and leave the rest as it is if no common owner for the date delta What i am doing now but doesnt look to be correct( it doest calculate some data correct tho, but some data is increased as well for some reason, which should have not been) TrendData.objects.filter(owner__trend_type__mnemonic='posts').filter( date_trend__date__range=[date_from, date_to]).values('owner__name').annotate( views=(Sum('views') / date_delta), views_u=(Sum('views_u') / date_delta), likes=(Sum('likes') / date_delta), shares=(Sum('shares') / date_delta), interaction_rate=( Sum('interaction_rate') / date_delta), ) date_delta = date_to - date_from #<- integer my models are: class Owner(models.Model): class Meta: verbose_name_plural = 'objects' TREND_OWNERS = Choices('group', 'user') link = models.CharField(max_length=255) name = models.CharField(max_length=255) owner_type = models.CharField(choices=TREND_OWNERS, max_length=50) trend_type = models.ForeignKey(TrendType, on_delete=models.CASCADE) def __str__(self): return f'{self.link}[{self.trend_type}]' class TrendData(models.Model): class Meta: verbose_name_plural = 'Trends' owner = models.ForeignKey(Owner, on_delete=models.CASCADE) views = models.IntegerField() views_u = models.IntegerField() likes = models.IntegerField() shares = models.IntegerField() interaction_rate = models.DecimalField(max_digits=20, decimal_places=10) mean_age = models.IntegerField() source = models.ForeignKey(TrendSource, on_delete=models.CASCADE) date_trend = models.DateTimeField() Source parent model doesn't really help in that case, it's a csv file data was loaded from, … -
Have a blog with a max of 5 items
Is it possible to create a Django blod which only allows a maximum of 5 items and anything that is added after the 5th item should overwrite the oldest item? If so how is it done? -
Django - Cannot perform another query while using a queryset iterator()
I'm using Django 1.11 with MySQL. Upgrading to 2 isn't feasible in the short term so isn't an acceptable solution to my immediate problem, but answers referring to Django 2 may help others so feel free to post them. I need to perform a data migration on all rows in a table. There are less than 40000 rows but they are quite big - two of the columns are ~15KB of JSON which get parsed when the model is loaded. (These are the rows I need to use in the data migration so I cannot defer them) So as not to load all the objects into memory simultaneously, I thought I'd use queryset.iterator which only parses rows 100 at time. This works fine if all I do is read the results, but if I perform another query (eg to save one of the objects) then once I reach the end of the current chunk of 100 results, the next chunk of 100 results are not fetched and the iterator finishes. It's as if the result set that fetchmany fetches the rows from has been lost. To illustrate the scenario using ./manage.py shell (Assume there exist 40000 MyModel with sequential ids) … -
Testing Django FileResponse
I have a Django view that returns a file. The FileResponse is built for that purpose. However, I do not understand how to test this. Right now I use the HttpResponse and test it like this: response = client.get(url) io = io = BytesIO(response.content) The io object can now be used for further testing. However, if I try the following with FileResponse (which is derived from StreamingHttpResponse and thus has streaming_content instead of content), I get the following exception: TypeError: a bytes-like object is required, not 'map' If I cast the map object to bytes like this: response = client.get(url) io = io = BytesIO(bytes(response.streaming_content)) I get another exception: TypeError: 'bytes' object cannot be interpreted as an integer How can I get an BytesIO object from FileResponse.streaming_content? -
Create corresponding models on ViewSet save
I have a simple model that is serialized and created. The Viewset for this is as follows: class OrderViewset(viewsets.ModelViewSet): depth = 1 serializer_class = OrderSerializer ... def perform_create(self, serializer): serializer.save(user=self.request.user) populate_ing(serializer) Once the user saves and creates the model, I aim to shoot of and call 'populate_ing(xxx)' which takes the model (in this case an order) and creates a number of related objects using a foreign key relationship. Is it possible to handle this on save? Believe, as above, by overriding the perform_create I should do so. And, most importantly, how can I access the model which has just been created?