Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
bootstrap navbar not showing properly
I am beginning to learn django. This is my first bootstrap template to work on but navbar is not showing properly.I will continue learning django for the meantime but this propblem is irritating me. please help me solve it this is the template <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags --> <title>{% block title %}page one {% endblock %}</title> <!-- Bootstrap --> <link href="css/bootstrap.min.css" rel="stylesheet"> <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <nav class="navbar navbar-expand-md navbar-light bg-faded"> <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <a class="navbar-brand" href="#">Navbar</a> <div class="collapse navbar-collapse" id="navbarNavAltMarkup"> <div class="navbar-nav"> <a class="nav-item nav-link active" href="#">Home <span class="sr-only">(current)</span></a> <a class="nav-item nav-link" href="#">Features</a> <a class="nav-item nav-link" href="#">Pricing</a> <a class="nav-item nav-link disabled" href="#">Disabled</a> <form class="form-inline my-2 my-lg-0"> <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search"> <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button> </form> </div> </div> </nav> {% … -
How to group an array of objects by one of the model's attribute in Django?
I would like to do the something similar to this example How to group an array of objects by key but I couldn't find a solution for API Get in Django. Here's an example of what I have: [ { "id": 1, "nutrition_measurement_id": "1", "nutrition_type_id": "2", "feeding_time": "dinner" }, { "id": 2, "nutrition_measurement_id": "2", "nutrition_type_id": "1", "feeding_time": "dinner" }, { "id": 3, "nutrition_measurement_id": "3", "nutrition_type_id": "2", "feeding_time": "breakfast" }, { "id": 4, "nutrition_measurement_id": "2", "nutrition_type_id": "1", "feeding_time": "breakfast" } ] Here's an example of what i want to achieve: { "dinner": [ { "id": 3, "nutrition_type_id": 2, "nutrition_measurement_id": 1 } ], "dinner": [ { "id": 3, "nutrition_type_id": 1, "nutrition_measurement_id": 2 } ], "breakfast": [ { "id": 3, "nutrition_type_id": 2, "nutrition_measurement_id": 3 } ], "breakfast": [ { "id": 5, "nutrition_type_id": 1, "nutrition_measurement_id": 4 }, ] } Here are the models I have: class HorseNutrition(models.Model): horse = models.ForeignKey(Horse, models.DO_NOTHING) nutrition_type = models.ForeignKey('NutritionType', models.DO_NOTHING) nutrition_measurement = models.ForeignKey('NutritionMeasurement', models.DO_NOTHING) feeding_time = models.CharField(max_length=10, blank=True, null=True) class Meta: managed = False db_table = 'horse_nutrition' class NutritionMeasurement(models.Model): name = models.CharField(unique=True, max_length=30, blank=True, null=True) class Meta: managed = False db_table = 'nutrition_measurement' def __str__(self): return self.name def __unicode__(self): return self.name class NutritionType(models.Model): name = models.CharField(unique=True, max_length=30, blank=True, null=True) … -
temporarily save an image from HTTP get
I am trying to test a get response which fetches a filtered image (sepia, in this case). It would be nice to store the fetched data locally until the test is executed. I have tried the following: loc = join(dirname(__file__), 'image_file') def save_sepia(data): img_temp = NamedTemporaryFile(delete=True) img_temp.write(data.content) img_temp.flush() img = data.save(loc, File(img_temp), save=True) return img @pytest.fixture def image_sep(client): req = client.get('some url') save_sepia(req) return { 'id': 'test-image', 'image': open(loc[0], 'rb') } Is this the right approach? -
What happens with the existing data if Decimals decimal_places are changed in a Django model?
I need to change a DecimalField from having decimal_places=0 to decimal_places=7 while keeping max_digits=50. I think all numbers in this column are between 0 and 1,000,000,000. So the data migration could be unproblematic. However, I'm uncertain. I have seen the AlterField documentation and I think I found the source code. However, I would need an introduction to this. Is it possible to see the generated SQL queries? I could imagine several things going wrong: Data Dropping if Decimal(decimal_places=0) is different from Decimal(decimal_places=7) in a way that Django/Postgres does not take care of Data Change if the internal representation stays the same but the values are interpreted in a different way Overflow if values get out of bounds NaN / NULL if values get out of bounds The last two cases should not happen in my specific case, but I'm still interested how Django migrations would deal with out of bounds cases. -
Why can't I import an external package into my views.py file?
Normally I don't use StackOverflow and ask my questions on Reddit, however I think this might be a problem for other users as well, so here I am. I'm a beginning Django developer and I'm building my very first Feed reader so that I can display RSS data on my template. To get this to work I use the package called: 'feedparser'. And I installed it correctly following the steps: 'pip install feedparser'. However an error accurs when I want to import this package into my views.py file: 'import "feedparser" can not be resolved'. Because I'm still a beginner I work with tutorials to understand how I can create a feedreader. The very first step in every case is to install this package and to import it (ofcourse!) only using: import feedparser, unfortunately for me, it raises an error. I don't know how to fix it, I can see by using pip freeze that the package indeed is installed but why can't I import it? I hope someone can help me out because I have tried everything all day and nothing seems to work or to help. Views.py (import area): from django.shortcuts import render, get_object_or_404 from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin … -
I'm getting this JSONDecodeError at /vaccine/handle vaccine slots/ on heroku server but on my local server its working fine
Heroku log 2021-05-20T09:48:41.906814+00:00 app[web.1]: json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) 2021-05-20T09:48:41.907973+00:00 app[web.1]: 10.5.245.135 - - [20/May/2021:09:48:41 +0000] "POST /vaccine/handle_vaccine_slots/ HTTP/1.1" 500 82617 "https://systemofreckoning.herokuapp.com/vaccine/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36" 2021-05-20T09:48:41.909232+00:00 heroku[router]: at=info method=POST path="/vaccine/handle_vaccine_slots/" host=systemofreckoning.herokuapp.com request_id=d4a0b644-a44b-435f-963a-6cf8eaa9a5da fwd="103.88.217.153" dyno=web.1 connect=1ms service=141ms status=500 bytes=82877 protocol=https 2021-05-20T09:49:27.945441+00:00 app[web.1]: 10.97.195.7 - - [20/May/2021:09:49:27 +0000] "GET /logout/ HTTP/1.1" 302 0 "-" "Mozilla/5.0 (compatible; proximic; +https://www.comscore.com/Web-Crawler)" 2021-05-20T09:49:27.946900+00:00 heroku[router]: at=info method=GET path="/logout/" host=systemofreckoning.herokuapp.com request_id=fdeb198f-21c1-4d20-913d-ee93134c5b07 fwd="18.232.161.22" dyno=web.1 connect=0ms service=3ms status=302 bytes=395 protocol=https 2021-05-20T09:49:27.962588+00:00 app[web.1]: 10.97.195.7 - - [20/May/2021:09:49:27 +0000] "GET /accounts/login/ HTTP/1.1" 200 7748 "-" "Mozilla/5.0 (compatible; proximic; +https://www.comscore.com/Web-Crawler)" 2021-05-20T09:49:27.964058+00:00 heroku[router]: at=info method=GET path="/accounts/login/" host=systemofreckoning.herokuapp.com request_id=3fe99047-99a3-4d96-ad1f-087146838825 fwd="18.232.161.22" dyno=web.1 connect=0ms service=14ms status=200 bytes=8282 protocol=https 2021-05-20T09:50:05.878286+00:00 heroku[run.9390]: Client connection closed. Sending SIGHUP to all processes 2021-05-20T09:50:06.436547+00:00 heroku[run.9390]: Process exited with status 129 2021-05-20T09:50:06.537160+00:00 heroku[run.9390]: State changed from up to complete 2021-05-20T09:50:36.900551+00:00 heroku[router]: at=info method=POST path="/vaccine/handle_vaccine_slots/" host=systemofreckoning.herokuapp.com request_id=84aeeb06-fb0c-4802-910b-fc05d58fda52 fwd="103.88.217.153" dyno=web.1 connect=0ms service=126ms status=500 bytes=82891 protocol=https 2021-05-20T09:50:36.895526+00:00 app[web.1]: Internal Server Error: /vaccine/handle_vaccine_slots/ 2021-05-20T09:50:36.895536+00:00 app[web.1]: Traceback (most recent call last): 2021-05-20T09:50:36.895537+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner 2021-05-20T09:50:36.895537+00:00 app[web.1]: response = get_response(request) 2021-05-20T09:50:36.895547+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response 2021-05-20T09:50:36.895547+00:00 app[web.1]: response = wrapped_callback(request, *callback_args, **callback_kwargs) 2021-05-20T09:50:36.895548+00:00 app[web.1]: File "/app/vaccine/views.py", line 51, … -
Django : How can I display only the checked items from a model in a template?
Here is my Django Model: class InterviewAssessment(models.Model): topics = models.ManyToManyField(AdvocacyTopic, verbose_name="Topics", blank=True) They consist into a list of topics out of them one or several items can be selected. Therefore, when I want to create an object InterviewAssessment, I use this class: class InterviewForm(models.Model): class Meta: model = Interview fields = ['topics'] widgets = { 'topics': forms.CheckboxSelectMultiple(), } My workflow requires that another User, who conducts the interview, updates my form to make an assessment. Therefore I have created a form dedicated to the assessment, as only some fields are to be updated. I would like to display only the topics which have been checked. They are not to be updated. However, if through a widget: I disable the field with : self.fields['topics'].widget.attrs.update({'disabled': 'true'}) All the items are displayed in grey, however the field in the database is reset to 0 (which is normal with Django) I make the field readonly with: self.fields['topics'].widget.attrs.update({'readonly': 'true'}) The items are selectable and are implemented in the DB, which is worse. I directly act at the level of the template with: {{ form.topics }} Of course, I get all the topics, which I don't want. Therefore what would be the syntax to exclusively display … -
Angular Django Foreign Key Relationship
FYI: This question is probably not easily answered by someone, who doesn't know angular - I don't want to bait someone with django-rest-framework tag haha! In my Django models.py file I have two models with a Foreign Key relationship: class Work(models.Model): job = models.CharField(max_length = 200, blank = False) def __str__(self): return self.job class Personal(models.Model): name = models.CharField(max_length = 250) work = models.ForeignKey('Work', on_delete = models.CASCADE, null = True) def __str__(self): return self.name For these models I have also set up Django Rest Framework which is working perfectly fine I want this to work: User can add Personal name and job. Name is a basic text field but job should be a list, similar to how it works in Django backend. So my question is: How do I tell Angular to show me, when creating Personal, to display me a list of jobs I have set up in Django. This is what my html file is looking like right now: Name <input type="text" [(ngModel)]="selectedPersonal.name"/><br> Job <input type="text" [(ngModel)]="selectedPersonal.job"/><br> <button *ngIf="selectedPersonal.id != -1" (click)="updatePersonal()"> PUT </button> <button *ngIf="selectedPersonal.id == -1" (click)="createPersonal()"> CREATE </button> <button *ngIf="selectedPersonal.id != -1" (click)="deletePersonal()"> DELETE </button> This gives me a simple page, where I can see the … -
Is it safe to override queryset in a custom django-rest-framework action
Let's say I have a queryset like this class DataViewSet(viewsets.ModelViewSet): serializer_class = DataSerializer queryset = Data.objects.all() @action(detail=False, methods=['get'], url_path='viewers/sum') def viewers_sum(self, request): self.queryset = Data.objects.filter(foo="bar").order_by('-foo') return super().list(request) As you can see I override queryset in the custom action viewers_sum. My question is if this has risk to cause issue with other actions, like list(). I've had similar problems before with permission where I've overwritten some property that's hasn't been restored for the next request. I've tried to debug this and It seems like there's no problem, but I don't understand the reason behind it. And it might not behave the same on production server as in my dev-server. In the docs they're not using this method. But I would prefer this since it feels very clean (if it's safe). -
Problem with Google Maps Place autocomplete and django forms
I have a django form with this atribute: origin_address=forms.CharField(max_length=100,widget=forms.TextInput(attrs={"id":"autocomplete"})) I need to use Google Maps Place autocomplete in origin_address. In html file I am doing the following things: <form method="post"> {% csrf_token %} {{ form }} <script> function initAutocomplete() { var locat_input=document.getElementById('origin_address') var autocomplete=new google.maps.place.Autocomplete(locat_input); // { // types: ['address'], // componentRestrictions: {'country': ['es']}, // } // autocomplete.addListener('place_changed',onPlaceChanged); } </script> <script src='https://maps.google.apis.com/maps/api/js?key=AIzaSyCaR0xc4Xiv3rHEV-HkFD-4Dt7hsIx3aT0&libraries=place&callback=initAutocomplete'></script> <button>Enviar</button> </form> I am following this post: Django. Google Place Autocomplete Address Form . However, I cant see what its failing. Thank you -
Django Rest url page shown when reload react app
I have deployed my app using nginx and gunicorn, i have used Reactjs on front-end and django rest on backend, when my django server starts it loads react on front as template,everything works fine, but when i reload my react app instead of staying on react it moves to django rest pages, how it can be solved, it only giving issue whenenver i reload my app. urlpatterns = [ path("", index, name="index"), ] def index(request): return render(request, "build/index.html") -
django throttle rate limit for specific unauthenticated user based ip address
i have setup as given instructions https://www.django-rest-framework.org/api-guide/throttling/ and my setup code is setting.py """ REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.authentication.JWTAuthentication', ], 'DEFAULT_THROTTLE_CLASSES': [ 'rest_framework.throttling.AnonRateThrottle', 'rest_framework.throttling.UserRateThrottle', ], 'DEFAULT_THROTTLE_RATES': { 'anon': '5/min', 'anon_day': '10/day', 'user': '10/min', 'user_day': '20/day', } """ and custom throttle.py """ from rest_framework.throttling import AnonRateThrottle, UserRateThrottle class AnonDayThrottle(AnonRateThrottle): scope = 'anon_day' class UserDayThrottle(UserRateThrottle): scope = 'user_day' """ and assign to api class comparable_summary.py """ from rest_framework.throttling import AnonRateThrottle from rest_framework.views import APIView from .throttle import AnonDayThrottle LOGGER = logging.getLogger(__name__) class ComparablesSummaryAPI(APIView): """ apis performs for given response """ throttle_classes = [AnonDayThrottle, AnonRateThrottle] """ my question is i have checked two different ip_addresses but it consider unique ip_address for all request, please help me thank for your help -
How to disable Django cache view for superuser?
I use cache_page decorator for caching views in Django. How can I disable cache for superuser or authorized users ? -
how to disappear one page with popup of another page?
I have one sign in (pop up) page which has register tab in it for sign up, I supposed to make these 2 pages such that when i click on register the sign in page disappear and Registration(sign up) page pops up.But from few days i have been facing some issues as when i click on register the sign up page pops up properly but sign in page does not disappear properly instead it appears in backside of signup page(I have attached a screenshot for this). Here is my code: signin.html: {% load static %} <div class="modal fade" id="signin-modal" tabindex="-1" role="dialog" aria-labelledby="signin-modalLabel" aria-hidden="true" data-dismiss="modal"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h2>Sign in</h2> <button class="btn-black-border" type="button" data-toggle="modal" data-target="#register-modal" id="register">Register</button> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> {# A more "HTML" way of creating the login form#} <form method="post" action="{% url 'user_login' %}"> {% csrf_token %} <div class="form-group"> <label for="username">Email</label> <input type="email" name="username" placeholder="Username" class="form-control" pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$" required> </div> <div class="form-group"> <label for="password">Password</label> <input type="password" name="password" placeholder="Password" class="form-control" required> </div> <div class="check-data"> <div class="form-group"> <input type="checkbox" id="signin" name="signin" value="Sign In"> <label for="signin" class="checkbox-label">Stay signed in</label> </div> <a href="#" title="Forgot your password?" type="button" data-toggle="modal" data-target="#forgot-modal" id="forgot-psw">Forgot your password?</a> </div> … -
Custom tag doesn't render template completely
so here's my custom tag: @register.inclusion_tag('app/comments_list.html', takes_context=True) def show_comments(context): request = context['request'] comments_list = Comments.objects.all().order_by('-comment_time') paginator = Paginator(comments_list, 3) page = request.GET.get('page') try: comments = paginator.page(page) request.GET except PageNotAnInteger: comments = paginator.page(1) except EmptyPage: comments = paginator.page( paginator.num_pages) return {'comments': comments} and here's my template to render: {% for comment in comments %} {% if comment.commented_by.username == user.username %} <h6><font color="green">You</font></h6> <h7>{{ comment.comment_time }}</h7> {% else %} {{comment.commented_by}} {% endif %} <div class="comment"> {{comment}} </div> {% endfor %} My model: class Comments(models.Model): commented_by = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) comment = models.TextField(max_length=300) comment_time = models.DateTimeField(auto_now_add=True) def __str__(self): return self.comment For some reason it successfully renders {{comment.commented_by}} and {{ comment }} and completely ignores if condition and {{ comment.comment_time }}. And I have no idea why. Any help will be appreciated! Thank you! -
Sending data from C# script (in unity) to django web server
What I want: I have a Django web server with PostgreSQL database on Heroku, I want to store and display some data (like High Scores and similar) from my unity game. What I managed to do: I managed to create get and post requests in C# and get responds from them. My problem: The post requests only work if I have CSRF(I have some knowledge how it works and my assumption is that I should keep it on) turned off in my Django web server. My question: Can I, and how (preferably in a simple and easy way) send some simple data (strings) to my Django web server hosted on Heroku from a C# script run in my Unity game while having CSRF on (or if I don't need it to be on/use some other kind of protection). -
percentage of file uplaoded in django
I want to know how much percent of file is uploaded in djnago. This is my html. <form action="/contribute/" method="POST" enctype="multipart/form-data"> {% csrf_token %} <ul class="cform"> <li class="img_uplabel">Image:</li> <li class="img_up">{{ form.image }}</li> <button type="submit" class="up_btn">Go</button> </ul> </form> this is my models.py class Photo(models.Model): image = models.ImageField(upload_to="home/images", validators=(image_validator)) -
How do I authenticate/protect non api_views with DRF + JWT eg. rendering a private page
I understand how to protect this for example, get the token, store it as cookie, then get the access token via the cookie and send it via Ajax to /api/hello and I get my JSON @api_view() @permission_classes([IsAuthenticated]) def hello(request): return Response({'message': 'hello this is protected'}) But how would I protect this page where I want only people who are authenticated to see the page, eg. if they click this URL /secretmessage def secret_message(request): return render(request, 'secret_message.html') -
display variable with floatformat based on condition
i want to limit digits in numbers bigger than 1 by 2 digits. i want to find out if there is a short-syntax to simplify code from 5 lines to a one liner and learn from your experience. expected output : 100 10 1 0.00001 working code {% if number > 1 %} {{ number | floatformat:2 }} {% else %} {{ number }} {% endif %} im looking for a possible syntax like this pseudo code {{ number | if number > 1 floatformat:2 }} -
Django Integrity exception
Any of my exception is working. I couldn't figure out where I make mistake. Whatever is the exception, the else block is always executed. Any ideas please? def upload_road_type(request, pk): template = "networks/roadtype.html" roadnetwork = RoadNetwork.objects.get(id=pk) roadtypes = RoadType.objects.filter(network_id=pk) list_roadtype_instance = [] if request.method == 'POST': form = RoadTypeFileForm(request.POST, request.FILES) if form.is_valid(): datafile = request.FILES['my_file'] datafile = datafile.read().decode('utf-8').splitlines() datafile = csv.DictReader(datafile, delimiter=',', quoting=csv.QUOTE_NONE) for row in datafile: row = {k: None if not v else v for k, v in row.items()} try: road_type_id = row['id'] name = row['name'] except IntegrityError: messages.error(request, "id must be integer") return redirect('network_details', roadnetwork.pk) else: roadtype = RoadType( road_type_id=road_type_id, name=name, network=roadnetwork) list_roadtype_instance.append(roadtype) RoadType.objects.bulk_create(list_roadtype_instance) return redirect('network_details', roadnetwork.pk) else: form = RoadTypeFileForm() return render(request, template, {'form': form}) -
Django - Simple password reset using FormView, sending random string as password in email, without using tokens
How can I send random string as new password in email to reset password. I am having difficulty starting to write the code all other examples are using built-in views but I want to use form view. -
Django rest framework api - permission error - Access denied for this endpoint
I am using the following in my project: Django 3.2.3 djangorestframework 3.12.4 This is my first django project using DRF for an api to my project. I want only people with the correct credentials (membership of a particular Django group) to be able to use the api. I have created one such user, for manual testing. I am able to login to obtain a token from the Here are my files api/permissions.py class MyBasePermission(permissions.BasePermission): def has_permission(self, request, view): # TODO: Some common permissioning task return True class FooPermission(MyBasePermission): """Custom Permission Class for Foo Model """ def has_permission(self, request, view): if not super().has_permission(request, view): return False if request.user and (request.user.is_superuser or request.user.is_staff): return True if request.user and request.user.groups.filter(name="FooGroup"): return True return False api/views.py class FooViewSet(viewsets.ModelViewSet): """Endpoint for Foo Model""" authentication_classes = [authentication.TokenAuthentication] permission_classes = [IsAuthenticated, FooPermission] queryset = Foo.objects.all() serializer_class = FooSerializer def create(self, request, *args, **kwargs): pass def destroy(self, request, *args, **kwargs): pass def perform_create(self, serializer): pass api/urls.py router = routers.SimpleRouter() router.register( 'foo', FooViewSet, basename='foo-crud' ) urlpatterns = [ path('login/', UserLoginApiView.as_view(), name='login'), url('', include(router.urls)) ] myproject URLsConf urlpatterns = [ path('', TemplateView.as_view(template_name="homepage.html"), name='homepage'), path('api/v1/', include('api.urls') ), # ... ] httpie login http POST http://127.0.0.1:8000/api/v1/login/ username="user1" password="password1" HTTP/1.1 200 OK Allow: … -
Django is not rendering ListView
I had another post related to this but my code was complex so the communication was difficult. I completely stripped off the issue from the unnecessary details and came up with a very minimal example shown below: templates/base.html: <html> <body> <p>I am base.html</p> {% block content %} {% endblock content %} </body> </html> templates/blog.html: {% extends 'base.html' %} {% block content %} <p>I am blog.html</p> {{ blog_list }} {% for blog in blog_list %} {{ blog.title }} {% endfor %} {% endblock %} And blog/views.py from django.views import generic from .models import Blog class BlogList(generic.ListView): queryset = Blog.objects.filter() template_name = 'blog.html' # context_object_name = 'blog_list' class BlogDetail(generic.DetailView): model = Blog template_name = 'blog.html' That outputs this: [![enter image description here][1]][1] I was expecting the list of blog titles to be rendered there. I debugged the BlogList class and queryset value was this: <QuerySet [<Blog: First Page>, <Blog: Intro>]> So, the query is not empty. I have been completely frustrated by this issue. Anyone know what's going on? [1]: https://i.stack.imgur.com/qWAwR.png -
Django channels consumer
For django channels I have consumer file like this: from channels.generic.websocket import WebsocketConsumer from asgiref.sync import async_to_sync import json class chatConsumer(WebsocketConsumer): def connect(self): async_to_sync(self.channel_layer.group_add)( 'my_socket', self.channel_name ) self.accept() def receive(self, text_data): async_to_sync(self.channel_layer.group_send)( 'my_socket', { 'type': 'chat_message', 'data': text_data } ) def chat_message(self, event): json_data = json.loads(event['data']) # get received data as json respons_test = json.dumps(json_data) # make response text print("chat_message") # Sometimes this is printed few times self.send(text_data=respons_test) It seems chat_message method is running few times sometimes. I'm not sure how this exactly works but when I print into chat_message, it is printed sometimes once, sometimes more than once. (I don't change clients/browsers count, and also in front-end, receiver gets message correctly, only one time). Question: its normal few times running of chat_message? or I have something wrong in code? -
How to compress base64 decoded video data using ffmpeg in django
I want to upload the video/audio file in my django-channels project. So I uploaded video(base64 encoded url) from websocket connection. It is working fine. But now after decoding base64 video data I want to compress that video using ffmpeg.But it showing error like this. ''Raw: No such file or directory'' I used 'AsyncJsonWebsocketConsumer' in consumers.py file.Here is my code: consumers.py: async def send_file_to_room(self, room_id, dataUrl, filename): # decoding base64 data format, datastr = dataUrl.split(';base64,') ext = format.split('/')[-1] file = ContentFile(base64.b64decode(datastr), name=filename) print(f'file: {file}') # It prints 'Raw content' output_file_name = filename + '_temp.' + ext ff = f'ffmpeg -i {file} -vf "scale=iw/5:ih/5" {output_file_name}' subprocess.run(ff,shell=True) May be here ffmpeg can not recognize the file to be compressed. I also tried to solve this using post_save signal. signals.py: @receiver(post_save, sender=ChatRoomMessage) def compress_video_or_audio(sender, instance, created, **kwargs): print("Inside signal") if created: if instance.id is None: print("Instance is not present") else: video_full_path = f'{instance.document.path}' print(video_full_path) // E:\..\..\..\Personal Chat Room\media\PersonalChatRoom\file\VID_20181219_134306_w5ow8F7.mp4 output_file_name = filename + '_temp.' + extension ff = f'ffmpeg -i {filename} -vf "scale=iw/5:ih/5" {output_file_name}' subprocess.run(ff,shell=True) instance.document = output_file_name instance.save() It is also causing "E:..\Django\New_Projects\Personal: No such file or directory". How can I solve this issue? Any suggetions.It will be more helpful if it can be …