Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
FileNotFoundError while Running Bash Script with Django
I'm pretty new to Django but really trying to do one simple thing at this point. I'm trying to run a bash script when someone clicks on a page hosted by my Django server. This was attempted by adding the following few lines into my views.py: from django.shortcuts import render from .models import Scenario import subprocess def index(request): [this page works so code not included] def deploying (request, scenario_id): subprocess.call('/home/ubuntu/test.sh') return render( request, 'deployment/deploying.html') So.. first time I try this with no execute permissions set on the file, I get this error: [Errno 13] Permission denied: '/home/ubuntu/test.sh' I give it chmod 777 test.sh and it now gives me: [Errno 2] No such file or directory: '/home/ubuntu/test.sh' whaaaaat...?! How did giving it permissions make the file "disappear"? Makes no sense to me.. -
Concurrent request in django
Concurrent request to Django API from vue returns the response from the last request for both. Here is my snippet from vue component methods:{ users(){ axios.get('users').then((response) => { this.sers = response.data; }).catch((error) => { console.log(error); }); }, new_users(){ axios.get('users', { params: {type:'new'}, }).then((response) => { this.new_users = response.data; }).catch((error) => { console.log(error); }); } }, mounted(){ this.users(); this.new_users(); } and my python snippet from the Django view def list_objects(request): if 'type' in request.GET and request.GET['type'] =='new' : #return new users else: #return users The problem is the new_users() and users() methods respond with new users data(the one which called last, if we call the users() method last both methods get users data ) -
Django- Video Encoding Package Not working while uploading videos
I installed this django-video-encoding package and followed the documentation as mentioned. But the code isn't running it seems. The videos I upload gets uploaded as it is without getting converted. There might be errors in the way I implemented it. Can anyone tell me how to properly use this code? This is the link for the package: https://github.com/escaped/django-video-encoding THis is my model class VideoPost(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True) title = models.TextField(max_length=1000) height = models.PositiveIntegerField(editable=False, null=True, blank=True) width = models.PositiveIntegerField(editable=False, null=True, blank=True) duration = models.FloatField(editable=False, null=True, blank=True) post_date = models.DateTimeField(auto_now_add=True, verbose_name="Date Posted") updated = models.DateTimeField(auto_now_add=True, verbose_name="Date Updated") slug = models.SlugField(blank=True, unique=True, max_length=255) file = VideoField(width_field='width', height_field='height', duration_field='duration', upload_to='videos/') format_set = GenericRelation(Format) signals @receiver(post_save, sender=VideoPost) def convert_video(sender, instance, **kwargs): enqueue(tasks.convert_all_videos, instance._meta.app_label, instance._meta.model_name, instance.pk) views. class CreateVideoPostView(LoginRequiredMixin, BSModalCreateView): def get(self, *args, **kwargs): form = VideoPostForm() context = { 'form':form, } return render(self.request, 'videos/video/create_video.html', context) def post(self, *args, **kwargs): form = VideoPostForm(self.request.POST or None, self.request.FILES or None) if form.is_valid(): video = form.save(commit=False) video.user = self.request.user video.save() create_action(self.request.user, 'posted a new video', video) return redirect('videos:my_video_home') -
How to render ManyToMany Extra Fields for each element of Foreign Key?
Django beginner here and I would really appreciate a bit of help or a bit of guidance into the right direction. I wish to develop a tool to make a product configuration for a quotation and one of the key elements is to have a list of optional accessories as checkboxes and have inputs fields for each available item to insert how many will be ordered. What I have so far is this: class Accessory(models.Model): name = models.CharField(max_length=200, null=True, blank=True) price = models.DecimalField(max_digits=8, decimal_places=2) class Offer(models.Model): offer_num = models.UUIDField(default=uuid.uuid4, editable=False) product = models.ForeignKey(Product, null=True, blank=True, on_delete=models.SET_NULL) accessories = models.ManyToManyField(Accessory, through='OfferAccessory') class OfferAccessory(models.Model): offer = models.ForeignKey(Offer, on_delete=models.CASCADE) accessory = models.ForeignKey(Accessory, on_delete=models.CASCADE) quantity = models.IntegerField() when it comes to the rendering part, it just displays 1 field in total instead of 1 field for each item: #forms.py class OrderForm(forms.Form): amount = forms.IntegerField() accessories = forms.ModelMultipleChoiceField( widget=forms.CheckboxSelectMultiple(), queryset=OfferAccessory.objects.all()) What I have so far: https://ibb.co/mC9s1QX What I want to achieve: https://ibb.co/6PrtrHG Thanks in advance! -
Django: Method name conflicts with model field
We have the following mixin to add a status field to many different models: class StatusFieldModelMixin(models.Model): """ Abstract class to add status field to a model. """ class Status(models.TextChoices): ACTIVE = 'active', _('Active') ARCHIVED = 'archived', _('Archived') DELETED = 'deleted', _('Deleted') status = models.CharField( verbose_name=_('Status'), max_length=25, choices=Status.choices, default=Status.ACTIVE, ) class Meta: abstract = True def is_active(self): return self.status == self.Status.ACTIVE def is_archived(self): return self.status == self.Status.ARCHIVED def is_deleted(self): return self.status == self.Status.DELETED The three methods at the bottom exist so we can do things like: if project.is_active(): instead of: if project.status == 'active': The main reason for that is in case we expand the values of what is considered "active" at some point in the future - like "active", "pending", "in-progress", etc. Much better to change that one method instead of having to change it in many places in our code. This mixin was added to our User model, which has all the fields added by the classes in Django auth, including the "is_active" field. We simply make it mirror the value of our status field. The problem is, after I added the is_active() method, I got this error when I tried to import fixtures: django.core.exceptions.ValidationError: ['“<bound method StatusFieldModelMixin.is_active of … -
Daphne + Django Channels gives error 503 on Heroku
I've been trying to make my Django Channels app work on Heroku for the past 2 days but can't seem to make it work. I recently couldn't even run the app but after some digging I managed to start it up. The app works fine on localhost. I went from having error 404, to 500 and now 504. I've been trying to understand the Heroku logs but can't seem to find a solution. Hopefully someone can give me a hint on how to fix it. Here are the different files and logs. Settings: CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [os.environ.get('REDIS_URL', 'redis://localhost:6379')], }, }, } Requirements: Django==3.0.7 gunicorn==19.9.0 pytz==2019.3 sqlparse==0.3.0 whitenoise==5.0.1 tweepy==3.8.0 dj-database-url==0.5.0 psycopg2-binary==2.8.5 discord.py==1.3.3 requests==2.23.0 channels-redis==2.4.2 channels==2.4.0 daphne==2.5.0 asgi.py import os import django from channels.routing import get_default_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'APPNAME.settings') django.setup() application = get_default_application() Procfile: web: daphne APPNAME.asgi:application --port $PORT --bind 0.0.0.0 -v2 Heroku Logs: 2020-06-09T14:37:43.770650+00:00 app[web.1]: 2020-06-09 14:37:43,770 DEBUG HTTP response complete for ['10.32.231.221', 20064] 2020-06-09T14:37:43.770759+00:00 app[web.1]: 10.32.231.221:20064 - - [09/Jun/2020:14:37:43] "GET /static/img/favicon.png" 200 10836 2020-06-09T14:37:47.782543+00:00 app[web.1]: 2020-06-09 14:37:47,782 WARNING dropping connection to peer tcp4:10.11.131.158:15868 with abort=True: WebSocket opening handshake timeout (peer did not finish the opening handshake in time) 2020-06-09T14:37:47.783124+00:00 app[web.1]: 2020-06-09 14:37:47,783 DEBUG WebSocket … -
Django looks for media files in wrong directory with DEBUG = False and Nginx
My 2 Django apps are running with Nginx and Gunicorn on mysite.com and mysite.com/app2. App1's media files are working just fine. And for the app2 with DEBUG=False I get 404 when trying to download a media file, though the url it makes for the file is correct (it matches the directory on the server). From nginx error log I found that it is probably looking for it in the media directory of app1. How can I make app2 look for media in the correct directory? Nginx log error: *2020/06/09 13:24:51 [error] 9378#9378: 1 open() "/home/user/app1/media/attach_1/attach.pdf" failed (2: No such file or directory), client: 134.94.7.210, server: mysite.com, request: "GET /media/attach_1/attach.pdf HTTP/1.1", host: "mysite.com", referrer: "mysite.com/app2/" Nginx conf: server { listen 80; server_name server_domain; location = /favicon.ico { access_log off; log_not_found off; } location = /static/ { root /home/user/app1; } location = /app2/static/ { root /home/user/app2; } location = /media/ { root /home/user/app1; } location = /app2/media/ { root /home/user/app2; } location / { include proxy_params; proxy_pass http://unix:/run/app1.sock; } location /secondapp/ { include proxy_params; proxy_pass http://unix:/run/app2.sock:/; } } app2.settings: STATIC_URL = '/static/' PROJECT_DIR = os.path.dirname(os.path.abspath(__file__)) STATIC_ROOT = os.path.join(PROJECT_DIR, 'static') STATICFILES_DIRS = ( os.path.join(BASE_DIR, "static"), ) MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = 'media/' … -
Serving Django-NGINX content from private subnet to AWS application Load Balancer
We have hosted Django application on NGINX in EC2 private subnet, we are not able to access it via AWS application load balancer end point. Below is the configuration file from location /etc/nginx/sites-enabled/myserver.conf We are getting 504 Gateway timeout using port 80 in configuration file and 502 bad Gateway using 443 in configuration file. upstream my_server { #server 0.0.0.0:80; server unix:/home/ubuntu/Desktop/star/star.sock fail_timeout=0; } server { listen 443; # default_server server_name 0.0.0.0; client_max_body_size 4G; access_log /home/ubuntu/Desktop/star/logs/nginx-access.log; error_log /home/ubuntu/Desktop/star/logs/nginx-error.log; location /static/ { root /home/ubuntu/Desktop/star/dashboard/static/; } location / { proxy_hide_header X-Frame-Options; include proxy_params; proxy_pass http://unix:/home/ubuntu/Desktop/star/star.sock; } # Error pages error_page 500 502 503 504 /500.html; location = /500.html { root /home/ubuntu/Desktop/star/dashboard/static/; } location ^~ /(css|js) { root /home/ubuntu/Desktop/star/dashboard/static/; } } server { if ($host = 0.0.0.0) { return 301 https://$host$request_uri; } if ($host = 0.0.0.0) { return 301 https://$host$request_uri; } listen 443; server_name 0.0.0.0; return 404; } -
how fix NoReverseMatch at x?
I am getting the error NoReverseMatch at /post/(post number) when I am trying to enter post_detail.html the error is Reverse for 'post_remove' not found. 'post_remove' is not a valid view function or pattern name. I guess I should change url of post_remove in urls.py but I don't know how It is views.py from django.shortcuts import render, get_object_or_404, redirect from django.utils import timezone from django.views import generic from django.views.generic.edit import DeleteView from .models import Post from .forms import PostForm # Create your views here. def post_list(request): posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date') return render(request, 'blog/post_list.html', {'posts': posts}) def post_detail(request, pk): post = get_object_or_404(Post, pk=pk) return render(request, 'blog/post_detail.html', {'post': post}) def post_new(request): if request.method == "POST": form = PostForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.author = request.user post.save() return redirect('post_detail', pk=post.pk) else: form = PostForm() return render(request, 'blog/post_edit.html', {'form': form}) def post_edit(request, pk): post = get_object_or_404(Post, pk=pk) if request.method == "POST": form = PostForm(request.POST, instance=post) if form.is_valid(): post = form.save(commit=False) post.author = request.user post.save() return redirect('post_detail', pk=post.pk) else: form = PostForm(instance=post) return render(request, 'blog/post_edit.html', {'form': form}) def post_draft_list(request): posts = Post.objects.filter(published_date__isnull=True).order_by('created_date') return render(request, 'blog/post_draft_list.html', {'posts': posts}) def post_publish(request, pk): post = get_object_or_404(Post, pk=pk) post.publish() return redirect('post_detail', pk=pk) def post_remove(request, pk): post = get_object_or_404(Post, pk=pk) post.delete() … -
How to put optional parameters in url using django
I need to put only optional paramaters using django, here my code : urlpatterns = [ url(r'^getdoclist/(?P<creationdate>[^/]+)/(?P<modificationdate>[^/]+)$',Get_DocumentList.as_view()) "creadtiondate" and "modificationdate" are my parameters -
How can I set min_length to django charfield?
I want to create a social media and for example person's username must be longer than 5charecters and shorter than 30 char's -
Django on IIS into production
Does anyboby have (present- actual) documentation about how to configure DJango o IIS. I have tried some tutorials on youtube but they are old and some things have changed. THanks you very much -
Django signals - how do I send what was saved in the model using post_save?
Triying to use signals to send through websockets the last record that was saved using .save(). What do I put in data? #models.py from django.db import models from django.db.models.signals import post_save from channels.layers import get_channel_layer from asgiref.sync import async_to_sync class DataModel(models.Model): time = models.DateTimeField() value = models.FloatField() def __str__(self): return str(self.time) def save_post(sender, instance, **kwargs): channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)( "echo_group", {"type": "on.message", "data": data}, ) post_save.connect(save_post, sender=DataModel) -
Many to Many with extra field in Django ModelForms
I'm on Django 2.2 and here are my simplified models: class Course(CustomModelClass): name = models.CharField(max_length=200, null=False, unique=True) components = models.ManyToManyField('Component', through='CourseComponent') class Component(CustomModelClass): name = models.CharField(max_length=200, null=False, unique=True) class CourseComponent(CustomModelClass): course = models.ForeignKey(Course, on_delete=models.CASCADE) component = models.ForeignKey(Component, on_delete=models.CASCADE) quantity = models.IntegerField(default=0, null=False) My relationships work well no problem on that. Now arrive the moment I do a ModelForm to manage that. Here is my form for now: class CourseForm(ModelForm): class Meta: fields = ['name', 'group', 'components'] model = Course And same it works quite well if my quantity has a null=True parameter but of course when I put it at False, it obviously doesn't work anymore. What I wanted to do is to have in my form a way to select components and set a quantity. I don't really care how it looks like it can be a chackbox with the name of the component and a numberfield or many select list to select the component and a number field, it's not the important part. My problem right now is that of course I have no access to the quantities in the form. Any idea? -
How to update database on successful payment in django through paytm
https://dev.to/iiits-iota/paytm-payment-gateway-integration-in-django-1657 I referred this to setup my payment gateway -
Verify OAuth 2.0 token
I have a token from Microsoft OAuth 2.0 with PKCE that in is sent to my Django server from a front-end. How can I verify the integrity of this token? I want to allow users to sign in with their Microsoft accounts. -
How to limit ForeignKey users in custom groups in django
How to limit number of ForeignKey users in custom groups in django ? for example to 3? class Group(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) choice = models.ForeignKey(Choice, on_delete=models.CASCADE) -
Comparison in Django template using request.GET and choices is not properly evaluated
I have this in my models: class Task(Record): class Status(models.IntegerChoices): OPEN = 1, "Open" COMPLETED = 2, "Completed" status = models.IntegerField(choices=Status.choices, db_index=True, default=1) Then in my template I want to show all the statuses, so I do this in views.py: context = { "statuses": Task.Status.choices, } And in my template I loop through it: {% for label,name in statuses %} {{ label }}: {{ name }} {% endfor %} This leads to: 1: Open 2: Completed So far, so good. But now if I use a GET parameter, I can't get things to work as I want. Say I open ?id=2 and then I run: {% for label,name in statuses %} {{ label }}: {{ name }} {% if label == request.GET.id %} YES {% else %} Sorry, not equal to {{ request.GET.id }} {% endif %} {% endfor %} Then I expect this to show YES for the first item. But it doesn't! Somehow this evaluates to: 1: Open Sorry, not equal to 1 2: Completed Sorry, not equal to 1 I do not understand why the first item does not evaluate to true. -
Slow query using Django and PostgreSQL with > 40 million rows
I'm working with a model (table) with more than 40 million rows and queries are very slow (> 2 min), using PostgreSQL. The models: class ModelA(...): source = models.ForeignKey(ModelB, related_name='source', ...) target = models.ForeignKey(ModelB, related_name='target', ...) class ModelB(...): c = models.ForeignKey(ModelC, ...) ... The Django filter: ModelA.objects.filter(source__isnull=True, target__c=my_c) The query: SELECT "model_a"."id", ... FROM "model_a" INNER JOIN "model_b" T3 ON ("model_a"."target_id" = T3."id") WHERE ("model_a"."removed" = False AND "model_a"."source_id" IS NULL AND T3."c_id" = 389) How can I optimize it? I am having optimization problems and I would like to know different solutions, etc. -
Channels - how do I send data through websocket when signal is received?
I want to stream data from a database through websocket. Basically a new record is being inserted into DataModel at every second and I want to send this new record through websocket as soon as it's inserted. Someone recommended me to use signal when the model's save() method is called. So to my models.py I just added this: def save_post(sender, instance, **kwargs): print('signal') post_save.connect(save_post, sender=DataModel) What to I put inside of save_post and also on my consumers.py so that the data goes through? -
how can i define User Groups and permissions on django to control a news model?
i have News model. i want to manage news by users who belongs from these Groups? class News(models.Model): title = models.CharField(max_length=255, help_text="Short title of news") content = models.TextField(blank=True) author = models.ForeignKey(User, on_delete=models.CASCADE) created_on = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now=True) status = models.BooleanField(default=True) how can i define these user permissions? Users Groups Permissions Reporters # create a news CopyEditors # read and update Poducers # read, update, aprove and revoke Rundown # list of aproved articles Anchors # read only aproved articles -
Why can't I filter on one new field in Django Rest Framework?
So I'm editing an existing codebase using Django Rest Framework, and I added a new field to a model: class MyModel(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=150, null=True) the_new_field = models.IntegerField(null=True, default=None) I've got a serializer, which is fairly basic: class MyModelSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = MyModel fields = ( 'id', 'name', ) So to the serializer I simply added the new field: class MyModelSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = MyModel fields = ( 'id', 'name', 'the_new_field', ) I can call the endpoint using name using ?name=awesomename, which actually filters based on awesomename, but when I call the endpoint using ?the_new_field=123456 it simply returns all the records in the database. What am I missing here? How can I make it filter based on this new field? -
Django / Wagtail: trying to add new children content to present on template
CandlePage and CandleIndexPage. the CandlePage is defined to describe the candle details the CandleIndexPage should present a list of Candles (CandlePage objects). i need to add to the CandleIndexPage template a 'label' property for each CandlePage object. i tough that it can be done with overriding the get_context method, but i was not able to do it on the 'children's level'. happy to get any advice. -
I got a KeyError when i try to use request.META['CSRF_COOKIE']
I want to use the mako template in django2, but when I set up the render function of mako and tried to set the template to bring the csrf token, I found that I could not get the CSRF__COOKIE in request.META #coding:utf-8 from mako.lookup import TemplateLookup from django.template import RequestContext from django.conf import settings from django.template.context import Context from django.http import HttpResponse def render_to_response(request, template, data=None): context_instance = RequestContext(request) path = settings.TEMPLATES[0]['DIRS'][0] lookup = TemplateLookup( directories=[path], output_encoding='utf-8', input_encoding='utf-8' ) mako_template = lookup.get_template(template) if not data: data = {} if context_instance: context_instance.update(data) else: context_instance = Context(data) result = {} for d in context_instance: result.update(d) result['csrf_token'] = '<input type="hidden" name="csrfmiddlewaretoken" value="{0}" />'.format(request.META['CSRF_COOKIE']) return HttpResponse(mako_template.render(**result)) django reports error: KeyError "CSRF_COOKIE", what shoud i do? -
Product image loads on all products page, but not on individual product page (Django)
For a little bit of context, when you add a new product to my website, you are required to add an image as well. I can get the product images to load just fine when viewing the main products page, but when you try to view an individual product on a new product details page, the image won't load. The product image is pulled in via the following code: <div class="product" style="background-image: url('{{ MEDIA_URL }}{{ product.image }}')"></div> Here is the HTML used on the main products page: <div class="album"> <div class="container"> <div class="product-row"> {% for product in products %} <div class="col-xl-4 col-md-6"> <div class="card mb-4 shadow-sm"> <div class="product" style="background-image: url('{{ MEDIA_URL }}{{ product.image }}')"></div> <div class="product-card-body"> <p class="product-title">{{ product.name }}</p> <p class="text-muted">{{ product.category }}</p> <div class="d-flex justify-content-between align-items-center"> <div class="btn-group"> <form method="post" action="{% url 'add_to_cart' product.id %}"> {% csrf_token %} <div class="text-center"> <span class="input-group-btn"> <button class="product-btns btn-success" type="submit">Add to Cart</button> </span> </div> </form> <form class="ml-2" method="post" action="{% url 'product_details' product.id %}"> {% csrf_token %} <div class="text-center"> <span class="input-group-btn"> <button class="product-btns btn-info" type="submit">Find out more</button> </span> </div> </form> </div> <p class="product-price">£{{ product.price }}</p> </div> </div> </div> </div> {% endfor %} </div> </div> </div> Here is the HTML used on the product …