Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to properly catch POST request in a Django serializer when using the JSON Web token authentication?
I customized the AUTH_USER_MODEL variable in settings.py to implement JSON Web Token authentication in Django, and everything works perfectly to login as superuser in the admin section. However, when I try to register a new user with the REST API, the line request.data.get('user', {}) in the serializer returns an empty dictionary, so I need to convert the object of type QueryDict into a Dict. Then I need to unlist the dictionary's values to finally have valid data. I'm afraid there is something wrong in my code, what is the proper way to do that ? I followed the tutorial from Thinkster here. views.py from rest_framework import status from rest_framework.permissions import AllowAny from rest_framework.response import Response from rest_framework.views import APIView from authentication.serializers import RegistrationSerializer class RegistrationAPIView(APIView): permission_classes = (AllowAny,) serializer_class = RegistrationSerializer def post(self, request): # user = request.data.get('user', {}) # <- returns {} user = dict(request.data) user = {k:v[0] for k,v in user.items()} serializer = self.serializer_class(data=user) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) settings.py AUTH_USER_MODEL = 'authentication.User' AUTHENTICATION_BACKENDS = [ 'graphql_jwt.backends.JSONWebTokenBackend', 'django.contrib.auth.backends.ModelBackend', ] GRAPHQL_JWT = { "JWT_ALLOW_ARGUMENT": True, } REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'authentication.backends.JWTAuthentication', ] } -
How do I view movies in descending order of average score? django
What we want to achieve. I want to display the score (stars) of a movie in descending order. Present condition The tmdb API is used to retrieve movie information. And the model movie and TV have only ID and stars(score). From here, only those with stars are returned to html. I want to ask a question. And if score is selected, how can I make it appear in descending score order? data = requests.get (f "https://api.themoviedb.org/3/tv/{tv_id}?api_key={TMDB_API_KEY}&language=en-US"). Now you can get the information of tv. def index(request): movie = reversed(Movie.objects.order_by('stars')) tv = reversed(TV.objects.order_by('stars')) context = { "movie": movie, "tv" : tv, } return render(request, 'Movie/index.html', context) class Movie(models.Model): id = models.CharField(primary_key=True, editable=False, validators=[alphanumeric],max_length = 9999) stars = models.FloatField( blank=False, null=False, default=0, validators=[MinValueValidator(0.0), MaxValueValidator(10.0)] ) def get_comments(self): return Comment_movie.objects.filter(movie_id=self.id) def average_stars(self): comments = self.get_comments() n_comments = comments.count() if n_comments: self.stars = sum([comment.stars for comment in comments]) / n_comments else: self.stars = 0 return self.stars class TV(models.Model): id = models.CharField(primary_key=True, editable=False, validators=[alphanumeric],max_length = 9999) stars = models.FloatField( blank=False, null=False, default=0, validators=[MinValueValidator(0.0), MaxValueValidator(10.0)] ) def get_comments(self): return Comment_tv.objects.filter(tv_id=self.id) def average_stars(self): comments = self.get_comments() n_comments = comments.count() if n_comments: self.stars = sum([comment.stars for comment in comments]) / n_comments else: self.stars = 0 return self.stars class … -
Django: How to save javascript auto-increment to django database?
I am incrementing a value from my database evey 3.5 sec using javascript, but the value that i am incremeting is coming dynamically from the database, now i want to save the newly incremented value to the database as the increment keeps going, i don't know how to achieve this using django and javascript. When i refresh the page, the value resets to the default value that i have in my database and doesn't update the value with the new increments <span id="generated">{{total_points}}</span> <!-- This is the js doing the increment function --> <script> var i = {{total_points}}; function increment() { i++; document.getElementById('generated').innerHTML = `₦` + Number(i).toLocaleString('en') + `.00`; } setInterval('increment()', 3140); </script> how do i save the new increments to the database? Do i need to provide my models.py? -
How to make divisions go on a new line? html/css
So, I want maximum of 3 div's per row, so when I use "for" loop after 3 instances it would automatically go to a new line. I have very little knowledge in js, so it'll be better if you can suggest me something not connected with it. Thank you in advance. (Making this template for my first django project). .main-section{ background: white; text-align: center; border: solid 1px #D1BEA8; } .book-list-main{ display: table; table-layout: fixed; border-spacing: 30px; } .single-book{ display: table-cell; width: 310px; height: 400px; margin: 0 20px 20px 10px; grid-column-start: 1; border: solid 1px #D1BEA8; height: fit-content; } .img-description-container{ display: flex; } .single-book h1{ font-size: 20px; } .img-description-container img{ max-width: 180px; max-height: 240px; float: left; } .img-description-container p{ float: right; font-size: 12px; overflow-y: scroll; margin-top: 50px; } .author-display{ display: flex; flex-direction: column; } .author-display span{ font-size: 14px; margin-top: 30px; background-color: #f1efe5; } .votes-total { position: relative; } .votes-total:before { content: attr(data-hover); visibility: hidden; opacity: 0; width: 60px; color: black; background-color: aliceblue; text-align: center; border-radius: 5px; padding: 5px 0; position: absolute; font-size: 11px; z-index: 1; left: 0; top: -110%; } .votes-total:hover:before { opacity: 1; visibility: visible; } .single-book-footer{ margin-top: 15px; margin-left: 17px; display: flex; flex-direction: row; } .single-book-footer button{ height: 30px; … -
CSS file references a file which could not be found. (Fieldsets forms and Heroku)
I am using fieldsets for my django forms. Everything works fine on local. I wanted to uploaded onto Heroku and started running into problem. When running "python manage.py collectstatic", I am getting the following error: The CSS file 'forms_fieldset\css\main.css' references a file which could not be found: forms_fieldset/img/sorting-icons.svg The message is correct. The file forms_fieldset/img/sorting-icons.svg is not mentioned in main.css. I suppose there is two questions: How does it know a file does not exist, if it actually not mentioned anywhere? How and where can I add this file? Below is my settings.py, just in case someone wants to look at it: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', "crispy_forms", 'main.apps.MainConfig', 'register.apps.RegisterConfig', 'import_export', 'forms_fieldset', ] ... STATIC_URL = 'static/' #IMAGE STUFF# MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR,'media') #Staticfiles_storage to make it compatible with Heroku SATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' #storing static files VENV_PATH = os.path.dirname(BASE_DIR) STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = ( os.path.join(BASE_DIR, "static"),) -
Customizing authentication backend for multi users in Django
So my question is that you have a custom user 'Account' and I'm trying to use Loginview but with only one specific backend but the class does not care about the value passed. from django.contrib.auth import views as auth_views from .lists import ProjectCreateView , ProjectUpdateView , ProjectDeleteView class ClientLogin(auth_views.Loginview): def form_valid(self, form): """Security check complete. Log the user in.""" auth_login(self.request, form.get_user(),'CREA.models.ClientBackend') return HttpResponseRedirect(self.get_success_url()) urlpatterns = [ path('', ClientLogin.as_view(template_name='authentification/client_login.html', redirect_authenticated_user=True,next_page='client-home'), name='client-log-in'), NB: note that the backend works fine if it's the only one specified in the settings but other than that the loginview use all backends one by one, and yes I know that this is the default behaviour but then whats the point of this variable in auth_login here is the buld in function in django : def login(request, user, backend=None): """ Persist a user id and a backend in the request. This way a user doesn't have to reauthenticate on every request. Note that data set during the anonymous session is retained when the user logs in. """ session_auth_hash = "" if user is None: user = request.user if hasattr(user, "get_session_auth_hash"): session_auth_hash = user.get_session_auth_hash() if SESSION_KEY in request.session: if _get_user_session_key(request) != user.pk or ( session_auth_hash and not constant_time_compare( request.session.get(HASH_SESSION_KEY, … -
django import_export | data not exported from database
I am using Django-import_export for exporting data. I have used the code given below that's not working correctly. It exported only dehydrated data instead of given fields. class MemberResource(resources.ModelResource): Brand=Field() class meta: model = model fields=('title','Brand') def dehydrate_Brand(self, obj): return str(obj.Brand.title) class modelAdmin(ImportExportModelAdmin): resource_class = MemberResource list_display=['title','Model_code','Chipset','chipset_description','Brand','categories'] search_fields = ['title','Model_code','Chipset',] fields=('title','Model_code','Chipset','chipset_description','image','Brand','Cat') admin.site.register(model,modelAdmin) -
in decorator assert not existing_data, "swagger_auto_schema applied twice to method"
I have added three input fields as headers but coming swagger_auto_schema applied twice to method issue and other one when I'm adding one swagger_auto_schema with given header input field than working fine where as when I'm adding three swagger_auto_schema with adding thier object than getting this error This is my code from rest_framework.generics import GenericAPIView from drf_yasg.utils import swagger_auto_schema from drf_yasg import openapi class ProductDataView(GenericAPIView): serializer_class = ProductSerializer permission_classes = (IsValidConsumer,) categories = openapi.Parameter('categories', in_=openapi.IN_HEADER, description='categories', type=openapi.TYPE_STRING, required=True) productName = openapi.Parameter('product_name', in_=openapi.IN_HEADER, description='product_name', type=openapi.TYPE_STRING) CustomerName = openapi.Parameter('customer_name', in_=openapi.IN_HEADER, description='customer_name', type=openapi.TYPE_STRING) @swagger_auto_schema(manual_parameters=[productName]) @swagger_auto_schema(manual_parameters=[categories]) @swagger_auto_schema(manual_parameters=[CustomerName]) -
how to pass 2 pks of different models in the same url django
how do i add primary keys of 2 different models of post model and comment model in the same url of editing comments when im adding 2 int pks in the same url it shows an error and when im giving 1 custom name then it doesnt work views.py class EditCommentView(UpdateView): model = Comment form_class = EditCommentForm template_name = "edit_comment.html" urls.py urlpatterns = [ path("post/<int:pk>/comments/", login_required(CommentsView.as_view(), login_url='signin'), name="comments"), path("post/<int:pk>/comments/add/", login_required(AddCommentView.as_view(), login_url='signin'), name="add-comment"), path("post/<int:pk>/comments/<int:pk>/edit/", login_required(EditCommentView.as_view(), login_url='signin'), name="edit-comment"), ] template {% extends "base.html" %} {% block content %} <section class="text-gray-600 body-font overflow-hidden"> <div class="container px-5 py-24 mx-auto"> <div class="flex flex-col text-center w-full mb-12"> <h1 class="sm:text-3xl text-2xl font-medium title-font mb-4 text-gray-900">Comments</h1> <p class="lg:w-2/3 mx-auto leading-relaxed text-base"> <a class="text-indigo-500 inline-flex items-center mt-4" href="{% url 'add-comment' post_id %}">Add Comment </a> </p> </div> <div class="-my-8 divide-y-2 divide-gray-100"> {% for comment in object_list %} <div class="py-8 flex flex-wrap md:flex-nowrap"> <div class="md:w-64 md:mb-0 mb-6 flex-shrink-0 flex flex-col"> <!-- <span class="font-semibold title-font text-gray-700">CATEGORY</span> --> <span class="mt-1 text-gray-500 text-sm">{{comment.date_created}}</span> </div> <div class="md:flex-grow"> <h2 class="text-2xl font-medium text-gray-900 title-font mb-2">{{comment.user.username}}</h2> <p class="leading-relaxed">{{comment.body}}</p> <a class="text-indigo-500 inline-flex items-center mt-4" href="{% url 'edit-comment' post_id comment.id %}"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-pencil-square" viewBox="0 0 16 16"> <path d="M15.502 1.94a.5.5 0 0 1 0 .706L14.459 3.69l-2-2L13.502.646a.5.5 … -
Show an Alert Message before saving the page Django
I am trying to create an alert message before saving the page, i tried to it Django Forms , But did not worked def clean(self): cleaned_data = super(CountryForm, self).clean() cc_myself = cleaned_data.get("registrations") subject = cleaned_data.get("calendar") if cc_myself and subject: # Only do something if both fields are valid so far. if "help" not in subject: raise forms.ValidationError( "You can edit the values" ) -
DRF Add multiple annotated fields to nested serializer
In my queryset i have few annotate fields. I want group those fields to nested serializer. For example views.py class PostViewSet(viewsets.ModelViewSet): queryset = Post.objects.all().prefetch_related( Prefetch('comments', queryset=Comment.objects.filter(parent__isnull=True).order_by('-pub_date') .annotate(likes=Count('votes', filter=Q(votes__choice=True)), dislikes=Count('votes', filter=Q(votes__choice=False))))) So there is two additional fields 'likes', 'dislikes' serializers.py class CommentVoteSerializer(serializers.Serializer): likes = serializers.IntegerField(source='comments.likes') dislikes = serializers.IntegerField(source='comments.dislikes') class Meta: fields = ['likes', 'dislikes'] class CommentSerializer(serializers.ModelSerializer): rating = CommentLikesSerializer(read_only=True, many=True) class Meta: model = Comment fields = ['id', 'text', 'pub_date', 'rating'] I tried different ways but can't understand how to fix it. Thanks for help -
convart raw sql to django query
I want to convert qs = Category.objects.raw('SELECT y.id,y.name,y.parent_id FROM core_category y INNER JOIN (SELECT name,parent_id, COUNT(*) AS CountOf FROM core_category GROUP BY name,parent_id HAVING COUNT(*)>1 ) dt ON y.name=dt.name AND y.parent_id=dt.parent_id') this raw sql to django sql query -
spotify api "player/currently-playing" enpoint is not return currently playing song data
I am trying to get data about a song playing on one of my devices from the spotify API. I have created a view that fetches data from the API and part of it looks like this: class Song(viewsets.ModelViewSets): .... room_code = request.data['room_code'] room = Room.objects.filter(code=room_code)[0] host = room.host endpoint = 'player/currently-playing' response = execute_spotify_api_request(host, endpoint) item = response.get('item') duration = item.get('duration_ms') progress = response.get('progress_ms') album_cover = item.get('album').get('images')[0].get('url') return Response(response, status=status.HTTP_200_OK) The execute_spotify_api_request(host, endpoint) is a utility function and it looks like this: def execute_spotify_api_request(session_id, endpoint, post_=False, put_=False): tokens = get_user_tokens(session_id) headers = {'Content-Type': 'application/json', 'Authorization': "Bearer " + tokens.access_token} if post_: post(BASE_URL + endpoint, headers=headers) if put_: post(BASE_URL + endpoint, headers=headers) response = get(BASE_URL, {}, headers=headers) try: return response.json() except: return {'error': 'Could not retrieve a response'} The full url from which im fetching is ""https://api.spotify.com/v1/me/player/currently-playing" The problem is with the response that im getting from the API, the response is not an error but data that im not expecting to get. Im getting a response that looks like this: response = { "display_name": "Tanatswamanyakara", "external_urls": { "spotify": "https://open.spotify.com/user/dlnsysel6bndktbvduz6cl79w" }, "followers": { "href": null, "total": 0 }, "href": "https://api.spotify.com/v1/users/dlnsysel6bndktbvduz6cl79w", "id": "dlnsysel6bndktbvduz6cl79w", "images": [], "type": "user", "uri": "spotify:user:dlnsysel6bndktbvduz6cl79w" } I … -
Restricting User to have one one-to-one relationship with any one of the given models Django
I am having two model classes named as Leader and Member, both have a OnetoOne relationship with User, as you can see below: from django.db import models from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.DO_NOTHING) # Abstract model class for common fields in Leader and Member class Meta: abstract = True class Leader(Profile): # attributes # def save(self) -> None: # if Member.objects.filter(user=self.user).first() == None: # return super().save() # else: # raise ValidationError("User is already a member, migrate it to make it leader.") class Member(Profile): # attributes But if a user is already having a relation with anyone, among both of them, then it should not be allowed to have a relation with the other one. For example: If a user1 is referenced by Leader model, then it is not allowed to be referenced by Member model, if needed there should be a process by which we can remove and add user from Leader model to Member model, i.e. transferring Profile abstract model data from Leader model to Member model and receiving remaining data manually or vica versa. By searching over the internet, I got to know that to solve this there is a way of raising ValidationError, … -
Images disappear when Django debug=False
When preparing to deploy my Django website to production, of course I turn the "debug" flag to "false" in my settings file. For some reason, all my images stop appearing. Here is my call to the image(s) in my template(s): <div id='photo1'> <img src="{% static 'app/image.png' %}" alt="Image Text"> </div> Appreciate suggestions for formatting my image links so they survive transition to production! -
Write to CSV file with manytomany field in Django
I have a model that includes two fields many to many from the model of plants and I would like to write in a CSV file, thanks to the library panda, the name of the plants and the associated plants of the model. Here is function to write a CSV file but I don't know how to write the fields in many to many with the name of the plants : class UploadLinkPlantData(generics.CreateAPIView): serializer_class = FileUploadSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) file = serializer.validated_data['file'] reader = pd.read_csv(file) for _, row in reader.iterrows(): LnkPlantPlant.objects.update_or_create( custom_id=row['Custom Id'], defaults={ "custom_id": row['Custom Id'], "link": row['Link'], "description": row['Description'] }) return Response({"status": "Succès : plante(s) crée(s) ou mise(s) à jour."}, status.HTTP_201_CREATED) class LnkPlantPlant(models.Model): class MAGNET_CHOICES(models.TextChoices): NONE = None IDEAL = 'ideal', GOOD = 'good', MEDIOCRE = 'mediocre', BAD = 'bad' custom_id = models.IntegerField(primary_key=True, unique=True) plant = models.ManyToManyField('perma_plants.Plant', related_name='%(class)s_plant') plant_associated = models.ManyToManyField('perma_plants.Plant', related_name='%(class)s_plant_associated') link = models.CharField(max_length=10, choices=MAGNET_CHOICES.choices, default=MAGNET_CHOICES.NONE, blank=True, null=True) description = RichTextField(max_length=255, blank=True, null=True) Here is Plant model : class Plant(models.Model): custom_id = models.IntegerField(primary_key=True, unique=True) name = models.CharField(max_length=150) def __str__(self): return self.name -
Displaying data using datatbales through django rest framework
https://www.youtube.com/watch?v=ntH6Fb9Rdkw I've followed this tutorial on how to fetch data to datatables using django(that person used core django while i wanna fetch and display data through django rest framework ) this is how my json structure is "results": [ { "book": "1", "author": "1", "status": 1 }, while on the frontend #datatables script part <script> $(document).ready(function () { $('#data').DataTable({ "processing": true, "serverSide": true, "ajax": { "type": "GET", "url": 'http://localhost:8000/api/books/', data: function ( data ) { console.log(data) } }, "columns":[ {"results":"book"}, {"results":"author"}, {"results":"status"} ] }); }); </script> #html part <table id="data"class="table table-striped table-hover"> <thead> <tr> <th>Books</th> <th>Author</th> <th>Status</th> </tr> </thead> where i could get a 200 request in the console #in console results: [{book: "1", author: "1", status: 1},…] 0: {book: "1", author: "1", status: 1} yet the table isnt fetching any data and i dont understand what exactly is wrong -
Responsive Navbar Link is not working on mobile device
I developed my first website using django. It works perfect on desktop, but on mobile device the category submenu links are not working. When clicked they act like I clicked on white space and close the navbar. Note: the Intital links work on mobile too. The children of the categories are not working. I though about z-index but the parent links are working. Here are the codes: <div id="responsive-nav"> <!-- category nav --> {% if page %} <div class="category-nav"> {% else %} <div class="category-nav show-on-click"> {% endif %} <span class="category-header">{% trans "Categories" %} <i class="fa fa-list"></i></span> {% load myapptags %} {% categorylist as category %} {% load mptt_tags %} <ul class="category-list"> {% recursetree category %} <li class="dropdown side-dropdown"> <a href="{% url 'category_products' node.id node.slug %}" class="dropdown-toggle" {% if not node.is_leaf_node %} data-toggle="dropdown" aria-expanded="true" {% endif %}>{{ node.title }} <i class="fa fa-angle-right"></i></a> <div class="custom-menu"> {% if not node.is_leaf_node %} <ul class="children"> {{ children }} </ul> {% endif %} </div> </li> {% endrecursetree %} </ul> </div> my apptag @register.simple_tag def categorylist(): return Category.objects.all() css of mobile @media only screen and (max-width: 991px) { #responsive-nav { position: fixed; left: 0; top: 0; bottom: 0; max-width: 270px; width: 0%; overflow: hidden; background-color: #FFF; -webkit-transform: … -
path('', views.IndexView.as_view(), name='index'), AttributeError: module 'polls.views' has no attribute 'IndexView'
how to solve this : i am using generic views method in django and facing this error while creating my first poll app ... path('', views.IndexView.as_view(), name='index'), AttributeError: module 'polls.views' has no attribute 'IndexView' my urls.py : urlpatterns = [ path('', views.IndexView.as_view(), name='index'), # ex: /polls/5/ path('<int:pk>/', views.DetailView.as_view(), name='detail'), # ex: /polls/5/results/ path('<int:pk>/results/', views.ResultsView.as_view(), name='results'), # ex: /polls/5/vote/ path('<int:question_id>/vote/', views.vote, name='vote'), ] -
venv dependencies are being added without being downloading
I use virtual environments in my django projects. I create my projects like this python3 -m venv <name of venv> After I pip install django in the venv, I use the pip list command. At this point the list only contains the default django packages. Then I start my django project like this. django-admin startproject <name of project> After that when I add the venv folder to my project folder, and run pip list again, all dependencies from previous projects are being added to the list. I can't figure out why this is happening. -
How can I enter numbers in the bar on the django form?
What you want to achieve I want to input numbers in the django form like this. Current code class Comment_movie_CreateForm (ModelForm): class Meta: model = Comment_movie fields = ('comment','stars') comment = forms.CharField (required = False, label ='comment', max_length = 1000) stars = forms.FloatField (required = False, label ='stars', widget = forms.TextInput ( attrs = {'type':'number','id':'form_homework', "class": "no_resize",'min': '0','max': '10','step': '0.1' }))) def clean (self): cleaned_data = super (). clean () return cleaned_data def clean_stars (self): stars = self.cleaned_data ['stars'] if stars! = None: if stars <0 or stars> 10: raise forms.ValidationError ("The rating input is incorrect.") return stars else: else: raise forms.ValidationError ("The rating input is incorrect.") def clean_comment (self): comment = self.cleaned_data ['comment'] if len (comment)> 1000: raise forms.ValidationError ("There are too many characters.") elif len (comment) == 0: raise forms.ValidationError ("Please enter the characters.") return comment def __init__ (self, * args, ** kwargs): super () .__ init__ (* args, ** kwargs) self.label_suffix = "" <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ form }} {% if comment_tv %} <button type="submit">Edit Comment</button> <button type="submit" name="action" value="delete">Delete Comment</button> {% else %} <button type="submit">Post Comment</button> {% endif %} </form> What you want to ask How would you change it to look like … -
Django admin panel: How to show Form instead of the data list?
I have a simple project built with Django, and I need to add some settings to my project. I have created the settings model, but what I want is to hide the data, and when a user opens the settings page it shows the form to add or update the settings data, without showing the date list, because settings are always one object that will be created once and updated as needed. This is my simple settings model. class ConfigSettings(models.Model): """ This model is used to store the configuration settings for the application. """ use_invoice_terms = models.BooleanField( default=False, help_text=_('Add your terms & conditions at the bottom of invoices/orders/quotations') ) and this is how I registered the model class in the admin file. @admin.register(ConfigSettings) class ConfigSettingsAdmin(admin.ModelAdmin): pass -
how to set non-database field on a model in django
i want to set / update calculated field on a model, with a different value on each object. for example, i have a User model, and i want to set a name property on each user, where name is not a column on the DB and it can't be edited by the user. the names can come from get_all_users_names() or from get_name_by_user_id(id). where should i set it and how should i set it? im new with python so please share some code :) thanks -
How to save media files to Heroku local storage with Django?
Im having a Django REST app with React for client. Im recording a file with React and sending in to Django. When i save it i modify it with ffmpeg and save it again in the same folder with a new name, the ffmpeg command looks like this: os.system(f"ffmpeg -i {audio_path} -ac 1 -ar 16000 {target_path}") Because i need a path for my audio both for opening and saving, i can't use cloud stores like "Bucket S3, Cloudinary etc.". And the fact that im using it only for a few seconds and then deleting it makes Heroku (the app is deployed there) the perfect place to save it non-persistent. The problem is that the file isn't getting saved in my library with media files. It saves in the postgre db but doesn't in my filesystem and when i try to access it my program returns that there isn't a file with that name. My question is How can i save media files in Heroku file system and how to access them? settings.py MEDIA_ROOT = os.path.join(BASE_DIR,'EmotionTalk/AI_emotion_recognizer/recordings') MEDIA_URL = '/' urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', include('EmotionTalk.emotion_talk_app.urls')), path('auth/', include('EmotionTalk.auth_app.urls')), path('api-token-auth/', views.obtain_auth_token), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) \ + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) views.py def … -
AttributeError: module 'django.db.models' has no attribute 'Aqtau'
I work with django first time. And fced with this error. Can You help me to solve. Erro like this, I have many models and data in there, and I put this data to html like table, after I want to change values in data, but in views I cant search my models My models py like this: (in city_name I put name of Model there it is Aqtau ) from django.db import models class Aqtau(models.Model): city_name = models.CharField(max_length=255) KT_by_projects_10g = models.CharField(max_length=255) KT_by_projects_100g = models.CharField(max_length=255) KT_on_facts_10g = models.CharField(max_length=255) KT_on_facts_100g = models.CharField(max_length=255) My views to put data to html: def index(request): Aqtau_city = Aqtau.objects.all().values() template = loader.get_template('index.html') context = { 'Aqtau_city': Aqtau_city, } return HttpResponse(template.render(context, request)) HTML looks like: <tr> {% for x in Aqtau_city %} <td>Aqtau</td> <td>{{ x.KT_by_projects_10g }} </td> <td>{{ x.KT_by_projects_100g }} </td> <td>{{ x.KT_on_facts_10g }} </td> <td>{{ x.KT_on_facts_100g }} </td> <td><a href="update/{{ x.city_name }}/{{ x.id }}">update</a></td> {% endfor %} </tr> urls.py looks like: urlpatterns = [ path('', views.index, name='index'), path('update/<str:city_name>/<int:id>', views.update, name='update'), And views update like: There i want to get model by getattr, but django db.models don't search Aqtau class. def update(request, city_name, id): model = getattr(models, city_name) mymember = model.objects.get(id=id) template = loader.get_template('update.html') context = { …