Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
getting the count of titles opened by a user only if the first entry also belongs to the same user
Title model: class Title(models.Model): first_author = models.CharField(max_length = 150) title = models.CharField(max_length = 150, unique = True) created_date = models.DateTimeField(auto_now=True) title_url= models.CharField(max_length = 150) Entry model: class Entry(models.Model): title = models.ForeignKey("titles.title", on_delete= models.CASCADE) user = models.ForeignKey("auth.user", on_delete= models.CASCADE) created_date = models.DateTimeField(auto_now_add=True) updated_date = models.DateTimeField(auto_now=True) content = models.TextField(max_length=10000,) In my blog, when a user opens a title the user also has to write the first entry. When the first entry is deleted if there are no other entries in the title, the title also get deleted. So I want to count titles opened by the user only if the first entry of the title still belongs to the same user. The only idea I have is to get all the titles opened by the user: titles= Title.objects.filter(first_author=user.username) Then iterate over titles and check whether the first title still belongs to the same user and if so add it to the count. But since it requires iterating over the queryset the query object is no longer lazy and it takes too much time end effort. I wonder if there is a way of achieving it by only one ORM. -
id gets undefined on click event
I am getting value in details and it also have id in it. But while fetching it shows Id is Undefined html </tr> <script type="text/ng-template" id='display'> <button type="button" class="btn btn-danger btn-sm" ng-click="delete(detail.id)">delete</button></td> </script>``` angular $scope.delete= function(id) { console.log($scope.id); } }); -
Sending images from Django(Server A) to Django-rest-api(Server B)
I built two Django servers. One is for image-processing and the other one is for front-page with forums. I designed like: If users post images to front-server(Django), then it send them to api-server(Django-rest-framework). Is there any ways to implement it? Thanks. -
Query user in Django
first post here. Im trying to query the user so i from the form so i can save the user in my database. This is my code form = lageBruker(request.POST) bruker = User.objects.create(format(request.POST['username'])) print() if request.method == 'POST': if form.is_valid(): fornavn = request.POST['first_name'] etternavn = request.POST['last_name'] email = request.POST['email'] kunde = Kunde.objects.create( #bruker = bruker, fornavn=fornavn, etternavn=etternavn, email=email ) kunde.save() context = {'form': form} return render(request, 'ebutikk/registrer.html', context)``` -
Django signals + channels: message not going through to client
I want a signal to be sent every time a .save() is made from django.db import models from django.forms.models import model_to_dict from django.db.models.signals import post_save from channels.layers import get_channel_layer from django.core.serializers.json import DjangoJSONEncoder from asgiref.sync import async_to_sync import json class DeribitFundingData(models.Model): time = models.DateTimeField() rate = models.FloatField() def __str__(self): return str(self.time) def save_post(sender, instance, **kwargs): channel_layer = get_channel_layer() data = model_to_dict(instance) json_data = json.dumps(data, cls=DjangoJSONEncoder) async_to_sync(channel_layer.group_send)( "echo_group", {"type": "stream", "data": json_data}, ) post_save.connect(save_post, sender=DeribitFundingData) My consumer looks as follows, where stream is supposed to receive the data from save_post: class StreamConsumer(AsyncConsumer): groups = ["echo_group"] async def websocket_connect(self, event): print("connected", event) await self.send({ "type": "websocket.accept" }) async def stream(self, event): data = event["message"] await self.send({ 'type': 'websocket.send', 'text': data }) My .js: <script> var loc = window.location var wsStart = "ws://" if (loc.protocol == 'https:'){ wsStart = 'wss://' } var endpoint = wsStart + loc.host + "/websockets/" console.log(endpoint) socket = new WebSocket(endpoint); socket.onopen = function(message) { console.log("open", message); } socket.data_stream = function(message) { console.log("stream", message); } socket.onerror = function(message) { console.log("error", message); } socket.onclose = function(message) { console.log("close", message); } </script> In the shell I see that the websockets connection was established. Although the messages I'm sending from post_save are not … -
Error sending POST from React front end to Django,error status 401
I am using Token authentication for Django & React integration. The below POST method fails in React with status 401,however same method give status 200 ok from POSTMAN(with same token,url and id) axios .post(`songs/${id}/like`, { headers: { Authorization: `Token ${token}` }}) .then() .catch(); }; I have ensured that I passed all parameters to axios but something got wrong. Other interaction with backends like login,signup,GET methods work fine. What are the possible causes for the error ? I have set CORSORIGINALLOWALL=True. -
How to implement 2 Boolean Fields conditional OR in django filters?
I am using django-filters. I want to filter my model with 2 boolean fields "men" & "women". From the image below you can see I have 3 records. 2 records have "men" field checked. In my template where I have the filter implemented, when I check "men" checkbox, it returns only one record because it is checking AND conditional. How do I implement conditional OR for those Boolean Fields so that is returns the 2nd record as well where it has "men" checked as well? class UserProductFilter(django_filters.FilterSet): SUB_CATEGORY_CHOICES=Products.objects.values_list('sub_category',flat=True).order_by('sub_category').distinct('sub_category') sub_category=django_filters.ModelChoiceFilter(label='Sub Category',field_name='sub_category',to_field_name='sub_category',queryset=SUB_CATEGORY_CHOICES) men=django_filters.BooleanFilter(label='Men',field_name='men', widget=forms.CheckboxInput) women=django_filters.BooleanFilter(label='women',field_name='women', widget=forms.CheckboxInput) class Meta: model = Products fields = ['sub_category', 'men', 'women'] The Image with records. -
how to use django inlineformset with javascript
i tired of trying many ways but non of them worked in my case . whenever i save my inlineformset it only save the last form , if count=3 then from my front end it will generate 3 fields to add books , but it only the save the last one. i appreciate any helps , and even i'm ready to pay to the solution my models.py class Book(models.Model): book = models.CharField(max_length=20,unique=True) author = models.ForeignKey(Author,on_delete=models.CASCADE) class Author(models.Model): author = models.CharField(max_length=30,unique=True) count = models.IntegerField() this is my forms.py class AuthorForm(ModelForm): class Meta: model = Author fields = ['author','count'] class BookForm(ModelForm): class Meta: model = Book fields = ['book'] InlineFormset_Author = inlineformset_factory(Author,Book,form=BookForm,extra=1) and also this is my views.py class CreateBookView(LoginRequiredMixin,SuccessMessageMixin,CreateView): model = Author form_class = AuthorForm def get_context_data(self,*args,**kwargs): context = super(CreateBookView,self).get_context_data(*args,**kwargs) if self.request.POST: context['book'] = InlineFormset_Author(self.request.POST) context['book'] = InlineFormset_Author() return context def form_valid(self,form): context = self.get_context_data() context = context['book'] with transaction.atomic(): self.object = form.save() if context.is_valid(): context.instance = self.object context.save() return super(CreateBookView,self).form_valid(form) and this is my template <form method="POST">{% csrf_token %} {{book.management_form}} {{form.author | add_class:'form-control col-12 col-sm-10 mx-auto'}} {{form.count | add_class:'form-control col-12 col-sm-10 mx-auto' | attr:'id:count'}} <button class="col-4 mx-auto shadow-lg border-right border-left">insert</button> <div id="BOOK" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="my-modal-title" aria-hidden="true"> <div class="modal-dialog" … -
Installing collected packages: twisted, daphne, channels Running setup.py install for twisted ... error
''' ERROR: Command errored out with exit status 1: 'c:\users\vikas bahuguna\appdata\local\programs\python\python38-32\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\Users\Vikas Bahuguna\AppData\Local\Temp\pip-install-mm65vrjl\Twisted\setup.py'"'"'; file='"'"'C:\Users\Vikas Bahuguna\AppData\Local\Temp\pip-install-mm65vrjl\Twisted\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' install --record 'C:\Users\Vikas Bahuguna\AppData\Local\Temp\pip-record-os___wbn\install-record.txt' --single-version-externally-managed --compile --install-headers 'c:\users\vikas bahuguna\appdata\local\programs\python\python38-32\Include\Twisted' Check the logs for full command output. ''' -
How can i make replies on comments in Class DetailView
hi im very new in django, and i want to figure out how to handle replies on comments in class Based View, if anyone can help i really gonna be thankfull models.py class Comment(models.Model): ... reply = models.ForeignKey('self', null=True, blank=True, on_delete=models.CASCADE, ... views.py class PostDetailView(FormMixin, DetailView): model = Post template_name = 'blog/post_detail.html' form_class = CommentForm def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['comments'] = Comment.objects.filter(post=self.object) context['form'] = self.get_form() field_value = Post.objects.get(title=self.object.title) context['title'] = field_value return context how can i make it work? -
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