Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How change the Connection Arguments (after, before) in graphene-python (relay)?
Using: Django 3.x [ Django-Filters 2.2.0, graphene-django 2.8.0, graphql-relay 2.0.1 ] Vue 2.x [ Vue-Apollo ] After applying some filters (iContains etc.) on my graphQL search i tried to change or manipulate the connection_args like firstor after. I can fetch a Dictionary on my resolver like {'first': 2, 'name__icontains': 'eagle'} with values i put in the IDE. As you can see (Example 1 /def resolve_all_birds2) i use that already for a logic. But i do not understand where do manipulate the GraphQLArgument states of the before. after first. last function which comes with relay? Example 1 class ExtendedConnection(Connection): class Meta: abstract = True total_count = Int() edge_count = Int() def resolve_total_count(root, info, **kwargs): return root.length def resolve_edge_count(root, info, **kwargs): return len(root.edges) class Birds2Node(DjangoObjectType): class Meta: model = Birds filter_fields = { 'id': ['exact', 'icontains'], 'name': ['exact', 'icontains', 'istartswith', 'iendswith'], } interfaces = (relay.Node, ) connection_class = ExtendedConnection # --- CUSTOM FIELDS --> # pkey = _db primary key pKey = Int() def resolve_pKey(parent, info): return parent.pk # qRank = Item Rank in Edge Array qRank = Int() def resolve_qRank(parent, info, **kwargs): return info.path[2] class Birds2Query(ObjectType): birds2 = relay.Node.Field(Birds2Node) all_birds2 = DjangoFilterConnectionField(Birds2Node) def resolve_all_birds2(self, info, **kwargs): if 'name__icontains' in kwargs: nameIcon … -
Django Add Choices Directly From Admin Not Working
When I try to add a subject from admin into the Subject model's name field, I am getting an error when I try to save the entry (see admin image below). I'm using the latest Django 3 and Python 3. This code used to work with Django 2 but since the upgrade, it does not populate anything into a blank SUBJECT_CHOICES() from admin. What I want to do is directly add subjects from admin into the database so that these subjects will populate the subjects dropdown menu in my forms.py. In other words, I want my dropdown menu from forms.py for the subjects to populate all of the subjects that I add directly from admin (see image below for an example dropdown menu with all the subjects entered). I see two different ways of solving this but I am unsure how to code them. Either just use a ForeignKey with SubjectName model, or a simple CharField without choice and customize the input widget into a dropdown. I might still need something custom for the form if I were to have dropdown-select and also type-in new choice from admin. Models.py: from django.db import models from django.urls import reverse from memberships.models import … -
Filter inheritance django and graphene
im trying to use django-graphene and having hard time to filter by foreign key's fields. class Country(SupplierProduct): name = models.CharField(max_length=100) class City(SupplierProduct): name = models.CharField(max_length=100) country = models.ForeignKey(Country, on_delete=models.CASCADE) class Location(models.Model): city = models.ForeignKey(City, on_delete=models.CASCADE) street = models.CharField(max_length=200) number = models.IntegerField('House Number') class Hotel(SupplierProduct): name = models.CharField('hotel name', max_length=500) rate = models.IntegerField('number of stars') location = models.ForeignKey(Location, on_delete=models.CASCADE) and i'm trying to make queries easier by renaming fields and create my own Filter Class. class LocationFilter(df.FilterSet): country_name = df.CharFilter(field_name='city__country__name', lookup_expr='icontains') city_name = df.CharFilter(field_name='city__name', lookup_expr='icontains') class Meta: model = Location fields = ['country_name', 'city_name'] now i wanted to know if there is a way for me to make hotel's filter class to use this filter also for its location field? like somekind of inheritance that every model that has location in it could filter easily by its fields -
Template shows custom ModelForm but data is not being saved through views.py
I'm trying to build a book-tracker app where users can login and submit books they've read and rate each book on a 5-star scale. I'm using 2 forms and they show up in the template home.html, but I'm not sure how to pass that data through in views.py and save it in the database. The HomeForm data is saved, but RatingForm data is not. forms.py: from django import forms from home.models import Post, Rating class HomeForm(forms.ModelForm): post = forms.CharField() rating = forms.IntegerField() class Meta: model = Post fields = ( 'book_title', 'book_author', 'book_review', ) class RatingForm(forms.ModelForm): rating = forms.IntegerField() class Meta: model = Rating fields = ( 'stars', ) views.py: from django.views.generic import TemplateView from home.forms import HomeForm, RatingForm from django.shortcuts import render, redirect from home.models import Post, Rating class HomeView(TemplateView): template_name = 'home/home.html' def get(self, request): form = HomeForm() rating_form = RatingForm() posts = Post.objects.all() args= {'form': form, 'posts': posts, 'rating_form': rating_form,} return render(request, self.template_name, args) def post(self, request): form_a = HomeForm(request.POST, prefix='home') form_b = RatingForm(request.POST, prefix='rating') if form_a.is_valid() and form_b.is_valid(): post = form_a.save(commit=False) rating = form_b.save(commit=False) text = form_a.cleaned_data['post'] post.user = request.user post.save() rating.user = request.user rating.save() rate = form_b.cleaned_data['stars'] return redirect('home') args = {'form_a': form_a, 'form_b': form_b, … -
Counting 2 Querysets Deep within Django Template
Is there a way to count within a Django template on a 2nd deep queryset connected via FK's/M2M's? For instance, Model A is FK'd to Model B, and Model B is M2M'd to Model C {% for C in Cs %} {% for B in C %) {% if B.A.all.count >= 2 %} B Has multiple A's! {% else %} B only has 1 A! {% endif %} {% endfor %} {% endfor %} Basically, I want to count the number of A's within B, and if it's 2 or more, just display "Multiple," as actually listing them out is disrupting my template. But I can't seem to get it to work. At the same time, the below DOES work for me: {% for C in Cs %} {% if C.B.all.count >= 2 %} C has multiple B's! {% else %} C only has 1 B! {% endif %} {% endfor %} I just can't get it to go one queryset deeper. Any help? Do I have to do this within the views? -
Pagination not working with Django Class Based Generic ListView as expected
I'm having issues with paginating the data for all other views, apart for the first view present in the same views.py file. For the first view (JobList) pagination works completely fine, whereas for the second view (JobSearchView) pagination doesn't work at all. I'm not sure, what's preventing the JobSearchView from paginating. I have another 2 views present within the same views.py file, which are identical to the JobSearchView, even for those views the pagination isn't working. Here is my code within the views.py file. class JobList(ListView): model = Job template_name = "jobs/job_listings.html" context_object_name = "job_list" # ordering = ['-published_date'] ordering = ['-id'] paginate_by = 3 def get_context_data(self, **kwargs): context = super(JobList, self).get_context_data(**kwargs) jobs_expiring_soon = Job.objects.filter(application_last_date__gte=datetime.now(), application_last_date__lte=lookup_date) state_list = State.objects.order_by('name') profession_list = Profession.objects.order_by('name') context['jobs_expiring_soon'] = jobs_expiring_soon context['state_list'] = state_list context['profession_list'] = profession_list return context class JobSearchView(ListView): model = Job template_name = 'jobs/job_search_results.html' ordering = ['-published_date'] context_object_name = 'search_results' paginate_by = 3 def get_context_data(self, **kwargs): context = super(JobSearchView, self).get_context_data(**kwargs) search_results = [] distinct_search_results = [] query = self.request.GET.get('search_term') keyword_list = query.split(" ") keyword_list = [x for x in keyword_list if len(x.strip()) > 0] for keyword in keyword_list: posts = Job.objects.filter( Q(title__icontains=keyword) | Q(organization__name__icontains=keyword) | Q(type__icontains=keyword) | Q(address__icontains=keyword) | Q(city__name__icontains=keyword) | Q(state__name__icontains=keyword) | … -
Adjusting current code to be able to add items from new table to the basket
My website is currently adapted to deal with things like adding to the cart, removing from the cart and creating an order, only on one Item table. I wanted to add different products to the site, so I need to create a new table, that will handle other items. The thing is, that I am not really sure how to properly implement that to my website, so things like adding to the cart and creating order would work with that new table as well. So thats the model of the first Item table: class Item(models.Model): title = models.CharField(max_length=100) price = models.FloatField() discount_price = models.FloatField(blank=True, null=True) category = models.ManyToManyField(Category) label = models.CharField(choices=LABEL_CHOICES, max_length=1) slug = models.SlugField() description = models.TextField() image = models.ImageField() def __str__(self): return self.title def get_absolute_url(self): return reverse("core:product", kwargs={ 'slug': self.slug }) def get_add_to_cart_url(self): return reverse("core:add-to-cart", kwargs={ 'slug': self.slug }) def get_remove_from_cart_url(self): return reverse("core:remove-from-cart", kwargs={ 'slug': self.slug }) When you add item to the cart it goes to this table: class OrderItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ordered = models.BooleanField(default=False) item = models.ForeignKey(Item, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) def __str__(self): return f"{self.quantity} of {self.item.title}" def get_total_item_price(self): return self.quantity * self.item.price def get_total_discount_item_price(self): return self.quantity * self.item.discount_price def get_amount_saved(self): return self.get_total_item_price() - … -
Django markdown/wysiwyg with global css support
I am looking for a post editor for Django Admin which will incorporate my sites css classes / styles. I installed Martor markdown editor, which I think is fantastic, but It does not seem possible to add css to the rendered markdown when using: {{ post.content|safe_markdown }} This is also the case with CKeditor, which I can't get to match my sites style in fonts, colors etc. Anyone have any tips for me for an easy to use solution which will adapts site css classes, and has an editor with code snips, images, h1, h2, h3, quote and paragraph etc? -
Foreign key POST in Django
I have some problems with my app . I need to make task with relations to user. Here is my code: bug ValueError at / Cannot assign "(<SimpleLazyObject: <function AuthenticationMiddleware.process_request.<locals>.<lambda> at 0x04C54E38>>,)": "Task.usertask" must be a "UserMembership" instance. models.py class UserMembership(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, null=True,blank=True) image=models.FileField(upload_to='photos/%Y/%m/%d/',null=True,blank=True) class Task(models.Model): title=models.CharField(max_length=200) date = models.DateTimeField(default=datetime.now,blank=True) is_published=models.BooleanField(default=True) usertask=models.ForeignKey(UserMembership, on_delete=models.PROTECT, null=True, blank=True) views.py if request.method == 'POST': usertask = request.user, title = request.POST['title'] task = Task(usertask=usertask,title=title) task.save() task = Task.objects.order_by('-date').filter(is_published=True, usertask=request.user.id) context={ 'task':task, } return render(request,'index.html',context) html form <form action="" method="POST"> {% csrf_token %} <input name="title" type="text" class="form-control" id="usr"> <button type="submit" class="btn btn-primary">add</button> -
How can I skip deleted models during a loop doing expensive operations in Django?
I have a model called device. Each device has a data_downloaded() and data_uploaded() method, which look through the database for all records associated with that device, and sum up the data they've used. Each device can potentially have thousands of records that need to be aggregated to calculate its usage. My models look like this: class Device(models.Model): ... mac_address = models.CharField(...) data_downloaded_cached = models.BigIntegerField(...) data_uploaded_cached = models.BigIntegerField(...) def data_downloaded(self): return DataRecord.objects.filter(mac_address=self.mac_address, direction="download").aggregate(data=Sum('data')).get("data", 0.00) or 0.00 def data_uploaded(self): return DataRecord.objects.filter(mac_address=self.mac_address, direction="upload").aggregate(data=Sum('data')).get("data", 0.00) or 0.00 class DataRecord(models.Model): timestamp = models.DateTimeField(...) mac_address = models.CharField(...) direction = models.CharField(...) data = models.BigIntegerField(...) Since device.data_downloaded() and device.data_uploaded() are expensive operations that can take a minute to calculate (a lot of database rows need to be aggregated), I can't call those methods directly when a template is loading, so I cache the values. A background process runs the following code to update these cached values every few minutes: for device in Device.objects.all(): device.data_downloaded_cached = device.data_downloaded() device.data_uploaded_cached = device.data_uploaded() device.save() When templates are displaying a list of devices, along with download and upload values for each devices, they can just use the cached values instead of trying to run these expensive operations on-the-fly, which would cause templates to … -
how to use set_cookie in context processors?
I have the following code in context_prcessors.py def company(request): … context = { ‘company’: company } response = render(request, ‘company.html’, context) response.set_cookie(‘company’, current_company return response and the following error: RecursionError at / maximum recursion depth exceeded while calling a Python object -
Nginx failure: (111: Connection refused) while connecting to upstream, client
I am running a django app with nginx in a docker container and everything was running perfectly fine up until I rebuild the container. Suddenly I get a 502 (Bad Gateway) error and the logs say (111: Connection refused) while connecting to upstream, client: 216.245.221.82, I have no idea what changed. I am pulling the lates nginx image so maybe there was a change which doesn't work well with my config. But I don't know. I am deploying my app on an EC2 instance with nginx in a docker container. Here are my configs and my compose file: server { listen 443 ssl; server_name mywebsite.de; client_max_body_size 0; charset utf-8; ssl_stapling off; ssl_stapling_verify off; ssl_certificate /etc/letsencrypt/live/mywebsite.de/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/mywebsite.de/privkey.pem; set $my_host $http_host; if ($http_host = "mywebsite.de") { set $my_host "mywebsite.de"; } location / { proxy_pass http://django:5000; proxy_set_header Host $my_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } } server { listen 80 ; server_name mywebsite.de; return 301 https://mywebsite.de$request_uri; } server { listen 80 ; server_name www.mywebsite.de; return 301 https://mywebsite.de$request_uri; } server { listen 443 ; server_name www.mywebsite.de; return 301 https://mywebsite.de$request_uri; ssl_stapling off; ssl_stapling_verify off; ssl_certificate /etc/letsencrypt/live/mywebsite.de/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/mywebsite.de/privkey.pem; } My docker-compose file: version: '3' services: django: build: context: . dockerfile: ./compose/production/django/Dockerfile image: my_website_production_django … -
Calling function in function using Django causes NameError
to keep my project clean I have module with my CalculationLogic class. I call this class in my views.py file, like: def method_in_views_file(request): cl = CalculationLogic() return cl.method_in_calculation_logic() In my CalculationLogic: def other_function(self,x): # some logic here # return result def method_in_calculation_logic(self,args): # some logic here # x = ['x','y','z'] data = other_function(x) return render(request,'file.html',{'data':data}) Unfortunately after calling this view in my browser I get NameError that other function is not defined. Which part can be wrong here? -
Get all the inputs that has been used in the search fields (historic) and display in the template in Django
I research a lot but did not found any answers to my question - hope anyone can help me. I made a simple view to search some points from my DB: class SearchResults(LoginRequiredMixin, ListView): model = Points template_name = 'search_results.html' def get_queryset(self): # new query_x = self.request.GET.get('query_x') query_y = self.request.GET.get('query_y') points_returned = self.request.GET.get('points_returned') distance_condition = self.request.GET.get('distance_condition') if distance_condition == 'Nearest': object_list = Points.objects.filter( geom_point__distance_lte=('POINT({0} {1})'.format(query_x, query_y), D(km=10000000000000)) ).order_by('geom_point')[:int(points_returned)] return object_list else: object_list = Points.objects.filter( geom_point__distance_lte=('POINT({0} {1})'.format(query_x, query_y), D(km=10000000000000)) ).order_by('-geom_point')[:int(points_returned)] return object_list The search works well and I get the right values. But what I need now (and didn`t find the solution) is to display in the home.html (home page from the search) all the inputs that has been made by the user in the query_x and query_x search fields, like a search historic. The inputs that the user put need to be recorded in his profile if possible. I already tried some stuff like using MiddleWare, JSON Response but did not have success. -
Django context returned by get_object
class ListDetailView(DetailView): context_object_name = 'aaaa' def get_object(self, queryset=None): return List.objects.get(unique_list_id=self.kwargs['unique_list_id']) In template I have to equal contexts: {{ object.list_name }} {{ aaaa.list_name }} How to override get_object() to return only context specified by context_object_name = 'aaaa'? Why I have 2 contexts? -
Django: interacting with multiple databases in a centralized way and in read only mode
I'm trying to understand what is the best solution to make Django interact with more databases. I need to use one db as the Django models backend, and I need also to interface Django apps with another legacy db but, in this case, only to read data. More context: I can just connect to the legacy db with a user with read and write permissions, but I want to be sure that the legacy db is used in read only mode (at least implicitly). Moreover, I need to query the legacy db from many apps and views, so a centralized connection management would be the optimal solution, both to manage the configuration in one place and to optimize resources (connections, cursors and so on) At first, I tried to create a connection object with a python library and to share it across the project apps and views, but I realized I was reinventing the wheel. Indeed, Django natively supports more databases connections in a centralized way. E.g., settings.py from Django doc: DATABASES = { 'default': { 'NAME': 'app_data', 'ENGINE': 'django.db.backends.postgresql', 'USER': 'postgres_user', 'PASSWORD': 's3krit' }, 'legacy_db': { 'NAME': 'user_data', 'ENGINE': 'django.db.backends.mysql', 'USER': 'mysql_user', 'PASSWORD': 'priv4te' } } As far as … -
how to serialize list of form object to JSON in django
I'm trying to serialize the form objects and return to the AJAX call so that I can display them in the template, but I'm not able to serialize them unlike serializing the model objects don't we have an option for form objects if request.method == 'POST': temp_data_form = TemplateDataForm(request.POST) if request.POST.get('temp_id'): # getting id of the current template existing_template = Template.objects.filter(id=request.POST.get('temp_id'))[0] if request.POST.get('item'): item_query = existing_template.tempdata_set.filter(item=request.POST.get('item')) if item_query: item_query = item_query[0] and True # we only edit the existing object of the template always as we create the object by default on GET request if existing_template and existing_template.title != request.POST.get('title') and request.POST.get('title')!= None: existing_template.title = request.POST.get('title') existing_template.save() if temp_data_form.is_valid() and item_query != True: # Template items alias data td_obj = temp_data_form.save(commit=False) td_obj.template = existing_template td_obj.save() values_form = [] for item in existing_template.tempdata_set.all(): values_form.append(TemplateDataForm(instance=item)) return JsonResponse(values_form, safe=False) I'm getting the below error. raise TypeError(f'Object of type {o.__class__.__name__} ' TypeError: Object of type TemplateDataForm is not JSON serializable -
Requesting /admin but return to the same page
Hello there i m looking to fix a problem i m working on django right now the issue is that when i try to go to the admin area login it returns me to the same index.html page my code: urls.py on main folder from django.conf.urls import url,include from django.contrib import admin from first_app import views urlpatterns = [ url('',views.index,name="index"), url('first_app/',include('first_app.urls')), url('admin/', admin.site.urls) ] urls.py on first_app folder urlpatterns = [ url('',views.index,name="index") ] the views.py on first_app folder def index(request): my_dic = {'insert_me':"Hello Jinja"} return render(request,'index.html',my_dic) index.html file {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="{% static 'css/style.css'%}"> <title>Django Page</title> </head> <body> <p>{{ insert_me}}</p> <h1>a picture </h1> </body> </html> -
connecting multiple create-react-apps with django
I have one big Django project consisting out of several small apps, independent from each other but partly sharing the same database or/and models. All the apps are created with python manage.py startapp appa so they have their own urls.py and views.py. I started using create-react-app for the front end for two of those apps and connected them successfully by turning the index.html of the react project into a template and serve it through the views.py (more here). Now each one of these create-react-app projects has its own build folder which's path I include in the STATICFILES_DIRS in settings.py to collect the static files. It looks like this: static/ templates/ appa/ build/ static/ index.html ... appb/ build/ static/ index.html ... Now, I was wondering if there is a way to have only one build folder that contains all built files respectively to their projects something like: appa/ appb/ static/ templates/ build/ appa/ static/ index.html ... appb/ static/ index.html ... I'm imagining that this folder would live on the same level as the the static folder and the appa and appb folders. One way, since by default I can't have the build folder outside the project folder structure(?) and I don't … -
Is there a way to retrieve the value of object instead of the id?
What I like to know is if there is a way to retrieve the object instead of the id (pk) when using django.core.serializers.serialize. I have a model named MenuItem with a ManyToManyField releated to a MenuSubItem. When I execute this code serializers.serialize('json', MenuItem.objects.all()) I got {'model': 'support.menuitem', 'pk': 2, 'fields': {'type': 2, 'app_label': None, 'label': 'Intranet Administration', 'sub_item': [**3**]}} But what I really wanna get is {'model': 'support.menuitem', 'pk': 2, 'fields': {'type': 2, 'app_label': None, 'label': 'Intranet Administration', 'sub_item': [**objects or objects_attribute**]}} Or if there is a workaround using other libs -
Howdo you create a Multipolygon field in GeoDjango from geojson objects
I'm new to GeoDjango and noticed some weird behavior when I was trying to convert a geojson object to a MultiPolygon object which is a field on the model. The geojson I upload is different than what the geojson property on the MultiPolygon field returns. Either I am not understanding what a MultiPolygon in GeoDjango is compared to a geojson MultiPolygon or I am creating the object improperly. I'm showing an example below with some real outputs and sudo code. Any direction would be appreciated including tell me I'm not creating the object properly, or that it is correct and I need to distinguish things differently. import json geojson = { "type": "MultiPolygon", "coordinates": [ [ [ [ [-77.62939453125, 38.53097889440024], [-76.70654296875, 38.53097889440024], [-76.70654296875, 39.32579941789298], [-77.62939453125, 39.32579941789298], [-77.62939453125, 38.53097889440024], ] ] ], [ [ [-77.783203125, 39.58875727696545], [-77.178955078125, 39.58875727696545], [-77.178955078125, 40.153686857794035], [-77.783203125, 40.153686857794035], [-77.783203125, 39.58875727696545], ] ], ], } my_model = MyModel.objects.first() my_model.multipolygon_field = json.dumps(geojson) my_model.save() my_model.multipolygon_field.geojson # return which contains different coords than I entered. '{ "type": "MultiPolygon", "coordinates": [ [ [ [ -77.783203125, 39.588757276965453 ], [ -77.178955078125, 39.588757276965453 ], [ -77.178955078125, 40.153686857794035 ], [ -77.783203125, 40.153686857794035 ], [ -77.783203125, 39.588757276965453 ] ] ] ] }' -
table services_parceiros has no column named user_id, DJANGO
thanks for your time. i've been trying to set a model to his creator user. although i'm getting this error and would like to know if am'i doing anything wrong before try a AbstractUser. i'did my user app just in the forms.py i don't know if thats the reason. Error: table services_parceiros has no column named user_id accounts/forms.py: from django import forms from django.contrib.auth import get_user_model, authenticate User = get_user_model() class LoginForm(forms.Form): username = forms.CharField() password = forms.CharField(widget=forms.PasswordInput()) def clean (self, *args, **kwargs): username = self.cleaned_data.get('username') password = self.cleaned_data.get('password') if username and password: user = authenticate(username=username, password=password) if not user: raise forms.ValidationError('usuario não encontrado') if not user.check_password(password): raise forms.ValidationError('senha incorreta') if not user.is_active: raise forms.ValidationError('usuario desativado') return super(LoginForm, self).clean(*args, **kwargs) class RegisterForm(forms.ModelForm): first_name = forms.CharField(max_length=100) last_name = forms.CharField(max_length=100) email = forms.EmailField(label='Email address') email2 = forms.EmailField(label='Confirm Email') password = forms.CharField(widget=forms.PasswordInput) class Meta: model = User fields = [ 'first_name', 'last_name', 'username', 'email', 'email2', 'password' ] def clean(self, *args, **kwargs): email = self.cleaned_data.get('email') email2 = self.cleaned_data.get('email2') if email != email2: raise forms.ValidationError("Emails must match") email_qs = User.objects.filter(email=email) if email_qs.exists(): raise forms.ValidationError( "This email has already been registered") return super(RegisterForm, self).clean(*args, **kwargs) services/models.py: from django.db import models from phone_field import PhoneField from datetime … -
How can i post a mp4 using moviepy without saving in local storage?
I'm trying to make a serve that concatenate two videos in one. But i need the server don't save the temp file in my local folder or any folder, only using the memory. clip1 = VideoFileClip(videoBegin) clip2 = VideoFileClip(videoEnd) final_clip = concatenate_videoclips([clip1, clip2]) # final_clip.write_videofile('video.mp4') files = {'file': final_clip} hea = {'Authorization': 'Token ' + token} import requests res = requests.post(url, files=files, headers=hea) But the problem is the request can't send the moviepy object, because it needs a bytes-like. *** TypeError: a bytes-like object is required, not 'VideoClip'. Is there a way to send a video from moviepy without saving in folder? And only use the memory? I'm using Django as a server. I don't know if it helps. -
How to create a virtual pdf file to be used in Django unit tests
I have this function in my viewset to upload a pdf file to A @api_view(['POST', 'DELETE']) @permission_classes((AllowAny,)) def upload_file_pdf(request): # Uploading and saving the file if the request is a POST - Validating the extension of the file as well if request.method == 'POST': try: upload = Upload(file_pdf=request.FILES["filepond"]) upload.full_clean() except ValidationError as e: return Response(e, status=status.HTTP_400_BAD_REQUEST) upload.save() return Response(upload.pk, status=status.HTTP_200_OK) # Deleting the file if the request is DELETE if request.method == 'DELETE': file_pk = str(json.loads(request.body)) return Response(file_pk, status=status.HTTP_200_OK) When I want to test it, I don`t know how to create a sample pdf file in unit tests def test_create(self): self.pdf_file = .... self.client.post('/api/v1/file/pdf/', data={"filepond": self.pdf_file}) self.assertEqual(response.status_code, 200) What should I put in front of self.pdf_file -
Saving Generated PDF to Django Model
Just want to create a pdf using pdfgen and then save it to my model with a file field, then return the link to the file. Getting error saying memoryview object has no attribute '__committed' views.py def pdf_creator(request): import io from django.http import FileResponse from reportlab.pdfgen import canvas from .models import Invoice # create buffer to hold pdf buffer = io.BytesIO() # create canvas with buffer as file c = canvas.Canvas(buffer) # draw on canvas c.drawString(0,300,"Hello") # save pdf c.save() # create instance of new invoice with pdf in buffer as its pdf file i = Invoice.create(buffer) # save instance of model i.save() models.py class Invoice(models.Model): def invoice_path(self): from datetime import date file = self.pdf today = date.today() return f'invoices/{today}/'+file @classmethod def create(cls, file): invoice = cls(pdf = file) return invoice pdf = models.FileField(upload_to=invoice_path) created_date = models.DateField(auto_now=True)