Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I extract a JSON payload string received on a subscribed topic of a Paho MQTT Javascript Client for consumption by django consumers?
Currently I have my own secure MQTT broker (Mosquitto) that I am connecting a Javascript Paho Client to in my django workflow. This client subscribes to a certain topic which my sensors on arduino are throwing some data. The subscribed client receives this incoming data message as a JSON payload string. My goal was to send this JSON string to the Paho JS client which in turn would send/expose it to my django consumers for specific information extraction and further processing. Right now I can console log that incoming data and surely the paho subscribed client is getting that information. I can't seem to figure out a way of sending the JSON message to django channels over the websocket. I understand that native Javascript websockets created using "vac socket = new WebSocket("ws://" + hostname ....." use functions like onmessage, onopen, onerror, onclose and they integrate perfectly with django channels. However, for the Paho websocket connection with the MQTT broker, the equivalent functions onMessageArrived, onConnected, onConnectionLost seem invisible to django. I know I am probably confusing some things here or doing something wrong. I need some help regarding this issue and please let me know if I should provide any more … -
Django. That IP address can't be assigned to
I am trying to deploy a Django app. I have a server with a public ip such as 194.61.xx.xxx but when I execute python3 manage.py runserver --noreload --nothreading 194.61.xx.xxx:8000 I get the error Error: That IP address can't be assigned to.. I have already set ALLOWED_HOSTS=["*"] and I can connect using ssh to my server with no problem. -
Onclick button does not call js function in django
I have a button that must call my js function, but nothing happens when i do (there is no get requests) My HTML: <button type="button" id="checker" id="button{{answer.id}}" onclick="mark_as_correct({{answer.id}});"> </button> My JS function: function mark_as_correct(qid) { var csrftoken = getCookie('csrftoken'); $.ajaxSetup({ beforeSend: function(xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } } }); $.ajax({ url: 'url answerajaxcorrect', type: 'post', data: {id: qid}, success: function(data) { document.getElementById('correct' + qid).innerHTML = "Correct!" var button = document.getElementById('button' + qid) button.parentNode.removeChild(button) }, failure: function(data) { alert('error') } }) } I do include my js to template: {% load static %} <script type="text/javascript" src="{% static 'js/main.js' %}"></script> And there is how my view looks like: @login_required def correct_ajax(request): qid = int(request.POST.get("id")) answer = get_object_or_404(Answer, id=qid) if answer.author == request.user: answer.is_correct = True answer.save() return JsonResponse({ "is_correct": True, }) else: return JsonResponse({ "is_correct": False, }) I am new to js and django, so it is hard for me to understand the source of my problem, please help. -
Django select all checkbox doesn't work for Microsoft Edge
I want to select all rows in a table by checking the header checkbox in my CheckBoxColumn. So far I have tried the following code select all rows in django_tables2 , which works fine for most browsers (e.g. Firefox, Chrome). However, when I open the website with Microsoft Edge and try to select all rows by clicking on the upper checkbox only the first row of the table will be checked, all other rows remain unchecked. This is my tables.py: class CRNTable(tables.Table): LinkModelColumn = tables.CheckBoxColumn(accessor='pk', attrs = {"th__input": {"onclick": "toggle(this)"}}, order_by='pk', verbose_name='Model') ... This is my JavaScript: <script language="JavaScript"> function toggle(source) { var checkboxes = document.getElementsByName('LinkModelColumn'); for(var i in checkboxes){ checkboxes[i].checked = source.checked;} } </script> -
Django - GeoDjango read coordinates in the wrong order
first of all thanks for your help. I'm making a form with Django which uses the OSMWidget to save coordinates (Polygons, Lines and Points) to a Geometry field in a PostgreSQL database. It works well, I can save the information in the database without any problem. And when I make a query with PgAdmin I can see the geometric fields data displayed in a Leaflet map correctly. Example of PgAdmin map with the geometric field data. Here's some of what I have in my forms.py: from django import forms from django_select2 import forms as select2_forms from django.contrib.gis import forms as osmforms from django.forms import ModelForm from .models import Dataset class SessionForm(forms.ModelForm): at_choices = [(item.title, item.title) for item in Dataset.objects.all()] key_choices = [(item.keywords_d, item.keywords_d) for item in Dataset.objects.all()] uuid = forms.CharField(label='', max_length=10 , widget=forms.TextInput(attrs={'class': "form-control left-half"})) title = forms.CharField(label='Title', max_length=65536 , widget=forms.TextInput(attrs={'class': "form-control full-size-field"})) abstract = forms.CharField(label='Abstract', max_length=65536 , widget=forms.Textarea(attrs={'class': "form-control full-size-field", 'title': 'Your name'})) keywords_d = forms.MultipleChoiceField(label='Keywords', widget=select2_forms.Select2MultipleWidget(attrs={'class': "form-control left-half",'style': 'width:100%'}), choices=key_choices) activity_type = forms.MultipleChoiceField(label='Activity type', widget=select2_forms.Select2MultipleWidget(attrs={'class': "form-control right-half",'style': 'width:100%'}), choices=at_choices) related_site_we = forms.CharField(label='Related Site', max_length=256 , widget=forms.TextInput(attrs={'class': "form-control full-size-field"})) bounding_box = osmforms.GeometryCollectionField(label='Bounding Box', widget=osmforms.OSMWidget(attrs={'class': "form-control full-size-field",'map_width': 992, 'map_height': 500})) class Meta: model = Dataset fields = ['uuid','title','abstract','keywords_d','activity_type','related_site_we','bounding_box'] And this … -
What do you think represents knowing Django?
Lately I've heard of people asking things like, do you know Django? can you work with Django? to kinda measure the things that you can do with it. As far as I understand, this can vary depending on the usage that you give to the framework. Not all the time you have to create a middleware or create an email back-end inside a Django app, however it seems like you have to know how to do that in order to be able to tell someone that you can work with Django and get a job as a back-end developer. What level of knowledge you believe it's required to say I know Django? What makes you know a framework or a language? -
Django Cms - wrong children url in menu when logged from admin
Hello I've a problem in my site menu. The django cms version is 3.7.2 I've four languages (en, it, de, fr) When an anonymous user use the site the menu is correct. When I'm logged from the admin panel i see some strange behaviors: when I've a second level page the url is composed with the parent slug in the wrong language (and if I do any change to the slug an publish it i still see the old slug) Here's the code for the menu.html {% load menu_tags %} {% for child in children %} <li class="child{% if child.selected %} selected{% endif %}{% if child.ancestor %} ancestor{% endif %}{% if child.sibling %} sibling{% endif %}{% if child.descendant %} descendant{% endif %}"> <a href="{{ child.attr.redirect_url|default:child.get_absolute_url }}" title="{{ child.get_menu_title }}">{{ child.get_menu_title }}</a> {% if child.children %} <ul> {% show_menu from_level to_level extra_inactive extra_active template "" "" child %} </ul> {% endif %} </li> {% endfor %} -
Quickly update django model objects from pandas dataframe
I have a Django model that records transactions. I need to update only some of the fields (two) of some of the transactions. In order to update, the user is asked to provide additional data and I use pandas to make calculations using this extra data. I use the output from the pandas script to update the original model like this: for i in df.tnsx_uuid: t = Transactions.objects.get(tnsx_uuid=i) t.start_bal = df.loc[df.tnsx_uuid==i].start_bal.values[0] t.end_bal = df.loc[df.tnsx_uuid==i].end_bal.values[0] t.save() this is very slow. What is the best way to do this? -
OPEN DJANGO AFTER INSTALLATION
Hello pls after installing django using pip on my command prompt pls how do i open django on my sytem -
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 …