Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python Django send post request from vue app using axios to django app
I am trying to send a post request from a vue app to a django app. The project structure is something like: - MyProj (main project file) - myproj (django main folder with settings.py) - myapp (django app with urls.py) - vueapp (vue app that has no django related files in it) I am trying to use axios to post data from 'vueapp' to 'myapp' basically. In axios I am posting to "{% url 'frontend:add_to_basket' %}" which seems to be an error. Any suggestions to how to make the two apps communicate with each other? There may be a better method to do it, but here's mines (I added some code snippets) urls.py where i need to post data: app_name = "frontend" urlpatterns = [ path("add_to_basket/", views.add_to_basket, name="add_to_basket"), ] And the view to go with it: def add_to_basket(request): if request.method == "POST": quantity = request.POST['quantity'] return JsonResponse({"quantity":quantity}, status=201) return HttpResponse('') The script in the html/vue file: Assume bagCount takes an integer value correctly. function sendRequest(method, data) { var r = axios({ method: method, url: "{% url 'frontend:add_to_basket' %}", data: data, xsrfCookieName: 'csrftoken', xsrfHeaderName: 'X-CSRFToken', headers: { 'X-Requested-With': 'XMLHttpRequest' } }) return r } export default { name: "purchase-coffee", data(){ return{ … -
django comment form on post detailview
i am still learning django. trying to create a comment form in my blogdetail view.. i am following a tutorial from youtube.. https://www.youtube.com/watch?v=An4hW4TjKhE&t=40s this tutorial has form which takes users from django users .. but in my form i want user to enter his name ,email and content.. following this tutorial i made form model but i have no idea how to get data from my own html form by this.. i have reached to a stage where in admin i can add comments and display them in my html file but now i am getting an error.. name 'post' is not defined my files are.. forms.py from django import forms from.models import Comment class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('content', 'email', 'name' ,) models.py class BlogPost(models.Model): title = models.CharField(max_length=500) writer = models.CharField(max_length=150,default='my dept') category =models.CharField(max_length=150) image = models.ImageField(upload_to='images') post = models.TextField(max_length=2000) Date = models.DateField( default=datetime.date.today) def __str__(self): return self.title class Comment(models.Model): post = models.ForeignKey(BlogPost , on_delete=models.CASCADE) name = models.CharField (max_length = 150) email = models.CharField (max_length = 150) content = models.TextField () def __str__(self): return self.email views.py def detailview(request, id=None): blg = get_object_or_404(BlogPost, id=id) comments = Comment.objects.filter( post=blg).order_by('-id') if request.method == 'POST': comment_form = CommentForm(request.POST or … -
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) while loading a json file
I am trying to load a json file as below but getting the above error. Any idea why am getting this error, thanks. import json with open(settings.NEWS_JSON_PATH, 'w+') as news: articles = json.load(news) the file is this path defined in my settings.py file: NEWS_JSON_PATH = os.path.join(BASE_DIR, 'news.json') -
Django Forms - How to combine Form (CreateView) into ListView Class
My application has User model, to whom I assign different programs. Each program contain different exercises, for each exercise, the user needs to fill up results according to his exercise. So basically, my HTML page for the exercise need to contain another form that provide the user inputs areas. My code contain: User Model, Program Model, Exercise Model, Data Model. Program Model: class Program(models.Model): patient = models.ForeignKey(User, on_delete=models.CASCADE, default=0) program_name = models.CharField(max_length=1000, default="") date_posted = models.DateTimeField(default=timezone.now) def __str__(self): return str(self.id) + " - " + self.patient.username + " - " + self.program_name + " - " + str(self.date_posted) def get_absolute_url(self): return reverse('program-detail', kwargs={'pk': self.pk}) Exercise Model: class Exercise(models.Model): program = models.ForeignKey(Program, on_delete=models.CASCADE, default=0) date_posted = models.DateTimeField(default=timezone.now) name = models.CharField(max_length=1000, default="") description = models.TextField(default="") load_share = models.TextField(default="") breath_method = models.TextField(default="") recovery_method = models.TextField(default="") measure_method = models.TextField(default="") notes = models.TextField(default="") extra_info = models.TextField(default="") reps = models.PositiveSmallIntegerField(default=0) sets = models.PositiveSmallIntegerField(default=0) def __str__(self): return str(self.program_id) + " - " + str(self.pk) + " - " + " - " + self.name + " - " + str(self.date_posted) Data Model: class Data(models.Model): exercise = models.ForeignKey(Exercise, on_delete=models.CASCADE, default="0") set_number = models.PositiveSmallIntegerField(default=0) spo2 = models.PositiveSmallIntegerField(default=0) hr = models.PositiveSmallIntegerField(default=0) physical_level = models.PositiveSmallIntegerField(default=0) breath_level = models.PositiveSmallIntegerField(default=0) sys = models.PositiveSmallIntegerField(default=0) … -
Change the name of output of form-variables Django
I have a form for creating a new recipe using Django - the problem is, that it displays by variable names i.e n_persons, prep_time etc. but I would like to make it Number of persons, Preperation time. Is there a way to do so? {% extends "indkoeb/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="OPSKRIFT"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">New</legend> {{form|cripsy}} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Save</button> </div> </form> </div> {% endblock content %} -
Django models save field prohibited
I'm new to Django, I'm tring to save an entry on the history model with the code below. This are my models class Actius(models.Model): id = models.ObjectIdField() name = models.CharField(max_length=255) ric = models.CharField(max_length=255) pais = models.CharField(max_length=255) index = models.CharField(max_length=255) sector = models.CharField(max_length=255) class History(models.Model): actiu = models.ForeignKey( Actius, on_delete=models.CASCADE ) time = models.DateTimeField() price = models.FloatField(max_length=255) What I'm tring to do actiu = Actius.objects.filter(ric='EUR_USD').get() print(actiu) # output: Actius object (None) entry = History( actiu = actiu, price = 12 ) entry.save() print( actiu.history_set.all() ) # output # ValueError: save() prohibited to prevent data loss due to unsaved related object 'actiu'. The actiu field i already created... Why says it's not saved? -
Changing website currency based on user selection Django
I want to implement multiple currency in my Django website. I have used the django-money app for currency conversion. The website allows the user to select currency using a dropdown. When the user selects a currency, I want the entire website (every page) to show the product prices converted in the selected currency. How can I do that? -
Django-auth-ldap problem while trying to login to a Django web-app
Specifications: The web-app runs on Apache 2.4.6 server which runs on a VM with CentOS 7. The LDAP server which I test this app on is ldap.forumsys.com (https://www.forumsys.com/tutorials/integration-how-to/ldap/online-ldap-test-server/). The error: When I try to login in the aforementioned Django app, the authenticate() function returns None. When I look at the Django-auth-ldap logs I see this error: Caught LDAPError while authenticating euler: SERVER_DOWN({'result': -1, 'desc': "Can't contact LDAP server", 'errno': 107, 'ctrls': [], 'info': 'Transport endpoint is not connected'},) What works: From my Centos 7 VM I am successfully able to use ldapsearch on the LDAP server (I can connect from my VM to the LDAP server). This makes me think that the problem is not within Centos itself. The LDAP authentication works when running on my Windows 10 computer with the basic Django development server. The code is the same and I can login without any problems. This makes me think that the problem is not within Django. My counclusion: I think that the problem must be in the communication between the Apache server and the LDAP server. It could perhaps be connected to the httpd configuration (I have not made any changes to any .conf in regards to LDAP, … -
How to solve cannot unpack non-iterable bool object error in Django?
if i put below condition in my view file id=request.POST['id'] #post data which i am sending from html file name=request.POST['name'] #post data which i am sending from html file if MyModel.objects.filter(id=id,name!=name).exists(): print('data available') else: print('data is not available') its showing below error cannot unpack non-iterable bool object if request.POST['name'] is available in my requested id(request.POST['id']),then i want to print print('data available'). Otherwise i want to print print('data is not available') How to Do that? -
How can I visualize data in realtime with Influxdb, django and d3js?
I have developped a little project with django + Influxdb I send data every 15 minutes to influxdb. I have succeeded on displaying that data through D3.js. However, I don't know how to visualize it in "real time". I need to find the way of sending to django the changes in a specific measurement in Influxdb. After that i will send through websockets that data to d3js chart. Any tip? Thanks in advance -
Do for Loop in Django models.py file affect performance?
i plan on using for loops to auto-generate a choices parameter for my field SIZE=[] # to be generated with a for loop to avoid me writing extra lines of code e.g (0, '32'),(1, '33') ... old_price = models.PositiveIntegerField() shoe_varient = models.IntegerField('SIZE', choices=SIZE) Do for loops in the models.py file cause any performance issues, because I assume that the models.py file is just for the building (structuring) of the database.. In other words does the model.py file get called after every request? -
django vs node.js.which is better?
(sorry for my bad english) I know django medium-high level and I know js medium-high level(with jquery and vue.js). Now I have been developing with django. But lately, I liked searching node.js more on the internet for some reason. At the same time, I thought it was better than django node.js. (speed performance, asynchronous etc). I wanted to get advice from experienced people first, that is, from you. Do you think this is the right decision? I should learn node.js after django? I would be glad if you could help. -
Sort weekdays from datetime objects
I want to get the weekdays for each week from a list of datetime objects. Example: For the list [2020-08-17 07:00:00, 2020-08-28 05:00:00, 2020-08-17 09:00:00, 2020-08-18 09:00:00, 2020-08-24 02:00:00, 2020-08-27 02:00:00] The result should be as : list_1 = ['Mon', 'Tue'] list_2 = ['Mon', 'Thu', 'Fri'] -
Can't get images in django
I have vue app and django app. I build them separately and I use vue's index.html as a template. When I go to the image directory. For example: http://localhost:8000/media/posts/images/image.png. Instead of getting the image, I get a static file. Here is my urls.py file. TemplateView responds to the root URL. I use index.html as a template. It comes from vue build. from django.conf import settings from django.conf.urls.static import static from django.contrib import admin from django.urls import path, re_path from django.views.generic import TemplateView urlpatterns = [ path('api/admin/', admin.site.urls), ## I use index.html as template. It comes from vue dist directory re_path('', TemplateView.as_view(template_name='index.html')) ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I included vue build files in static files directories. STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static/') STATICFILES_DIRS = ['/home/sam/Documents/Projects/vue/flow/dist/static'] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') And I use index.html from vue build as a template TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['/home/sam/Documents/Projects/vue/flow/dist'], ... }, ] I tried different ways to fix it. If I remove re_path('', TemplateView.as_view(template_name='index.html')) line from urlpatterns, the image problem disappears. However I miss static files. I tried to use path instead of re_path. Like this: path('', TemplateView.as_view(template_name='index.html')). In this case, I get both images and static files. But … -
How can I change the default value of db in django?
I would like to change the value of itemCnt stored as 0 in db to None if the value of serializer.data[item] comes in as None.So I tried to write and post code as follows, but the default value of db does not change. What should I do? Here's my code. views.py class makeVoteView (GenericAPIView) : serializer_class = makeVoteSerializer permission_classes = [IsAuthenticated] def post (self, request) : serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) serializer.save(organizer=request.user) user = User.objects.get(username=serializer.data['organizer']) Vote = vote.objects.get(pk=serializer.data['pk']) if serializer.data['item3'] == None : Vote.item3Cnt = None if serializer.data['item4'] == None : Vote.item4Cnt = None if serializer.data['item5'] == None : Vote.item5Cnt = None if user.identity == 'teacher' : Vote.is_consent = True return Response({'message': '투표 등록이 완료 되었습니다.'}, status=201) return Response({'message': '대기열 등록이 완료 되었습니다.'}, status=200) serializers.py class makeVoteSerializer (serializers.ModelSerializer) : organizer = serializers.CharField(source='organizer.username', read_only=True) class Meta : model = vote fields = ['pk', 'organizer', 'subject', 'item1', 'item2', 'item3', 'item4', 'item5'] -
Randomly Can't connect to MariaDB from Python & Django
I'm running windows server 2016 vm with Diango 3.1.1, Python 3.7.9 (mysqlclient 2.0.1) and MariaDB 10.5.4. After a few hours/minutes randomly django web pages do not connect for a few seconds with the error: OperationalError at / (2002, "Can't connect to MySQL server on '127.0.0.1' (10060)") django page error screenshoot Other python scripts connecting the database fail with the same error. File "c:\Python37\lib\site-packages\MySQLdb\__init__.py", line 130, in Connect return Connection(*args, **kwargs) File "c:\Python37\lib\site-packages\MySQLdb\connections.py", line 185, in __init__ super().__init__(*args, **kwargs2) MySQLdb._exceptions.OperationalError: (2002, "Can't connect to MySQL server on '127.0.0.1' (10060)") I have no errors in MariaDB logs or in event viewer. With "SELECT * FROM information_schema.processlist" I have less than 15 processes My.ini [mysqld] datadir=C:/Program Files/MariaDB 10.5/data port=3306 innodb_buffer_pool_size=1023M slow_query_log=1 long_query_time=5.0 bind-address = 0.0.0.0 max_allowed_packet=64M Can anybody help me solve this? Any reply will be appreciated. -
Migration problem in related models with Django
i'm getting some problems migrating my models with Django. I have 2 models in 2 differents apps: authentication model page import datetime from consumptions.models import Platform from django.contrib.auth.models import User from django.db import models from logs.mixins import LogsMixin class Client(LogsMixin, models.Model): """Model definition for Client.""" user = models.OneToOneField(User, on_delete=models.CASCADE) cif = models.CharField("CIF", null=False, default="", max_length=50) platforms = models.ManyToManyField(Platform, verbose_name=("Plataformas")) dateadded = models.DateTimeField("Fecha de inserción", default=datetime.datetime.now) class Meta: """Meta definition for Client.""" verbose_name = 'Cliente' verbose_name_plural = 'Clientes' def __str__(self): """Representación de cliente.""" cif = "Sin empresa" if self.cif: cif = self.cif string = "{} {} ({})".format(self.user.first_name, self.user.last_name, cif) return string And then I have consumption model page import datetime from authentication.models import Client from django.contrib.auth.models import User from django.db import models from django.utils.timezone import now from logs.mixins import LogsMixin from rules.models import Rule class Consumption(LogsMixin, models.Model): """Definición del modelo de Consumos""" STATES = [ ('not-prevalidated', 'No prevalidado'), ('prevalidated', 'Prevalidado'), ('pendant', 'Pendiente validación cliente'), ('accepted', 'Aceptado'), ] client = models.ForeignKey(Client, verbose_name=("Cliente"), null=True, default=None, on_delete=models.SET_DEFAULT) course = models.ForeignKey(Course, verbose_name=("Curso"), null=True, default=None, on_delete=models.SET_DEFAULT) class Platform(LogsMixin, models.Model): """Definición del modelo para plataforma""" name = models.CharField("Nombre de la plataforma", max_length=100, null=False, blank=False) url = models.CharField("URL de la plataforma", max_length=100, null=False, blank=False) As you can see, … -
local variable 'comment_form' referenced before assignment
hi i am trying to make a comment form in my post detailview .. but getting this error.. local variable 'comment_form' referenced before assignment views.py file def detailview(request, id=None): blg = get_object_or_404(BlogPost, id=id) comments = Comment.objects.filter( post=blg).order_by('-id') if request.method == 'POST': comment_form = CommentForm(request.POST or None ) if comment_form.is_valid(): content = request.POST.get('content') comment_form.save() else: comment_form = CommentForm() context = {'blg': blg, 'comments': comments, 'comment_form' : comment_form , } return render(request, 'blog/blogdetail.html', context) i think the problem is with the context.. forms.py from django import forms from.models import Comment class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('content',) -
Skype API connection issue
I try to develop an django app that collect everything in skype and pass to mysql. I deployed my app and mysql db on to azure. The app run perfectly fine locally, i can login to skype, retrieve messages etc. also pass all of those into mysql that i setup in azure. But the app on azure is unable to connect to skype though skpy(skype api for python). Do anyone know how to solve it? Or know the problems? -
How can I start Gunicorn without disabling SELinux?
I'm trying to make a tiny website with Django + Gunicorn + Nginx on CentOs. But the only problem is that I can't start Gunicorn without changing SELinux to disabled or permissive mode. Many articles say that I'd rather to turn off the SELinux, but I'm worried about some security problems that can happen as I'm almost new to Django and Gunicorn. Is there a way to use Gunicorn with SELinux successfully? -
When React requests to Django API, net::ERR_SSL_PROTOCOL_ERROR is occured
Stack : AWS Lightsail, React, DRF, Django, Gunicorn, NGINX I created certificate using Let's Encrypt. ※ I followed this site : https://www.digitalocean.com/community/tutorials/how-to-secure-nginx-with-let-s-encrypt-on-ubuntu-16-04 So, I can access https://mydomain without error. But when React calls Django API, net::ERR_SSL_PROTOCOL_ERROR is occured. I think there's something I need to set up in React, DRF, Django. Cause no error logged in syslog and /var/log/nginx/error.log. I googled but couldn't find what I wanted. Can I ask for advice? Thank you. -
Modal form initial field
In my app a have form to update item. User updates it using dropdown fields. If there is no required value on dropdown he can add his own. It is done through the popup bootstrap modal form. Problem is that if the modal form is submitted user is redirected to form view but all values that we had already entered disappears. I'm not looking for ready solution but a hint how to make it, because I am learning and I would like to now how it should be done properly. Clicking "new person" opens the modal form. I don't want to make use choose subsidiary twice as a person belongs to the subsidiary. If the new user is added all values filled by user disappears because I'm redirecting from modal to the point where the user is starting the update. The modal form opens when the user chooses a new person form dropdown list: jquey: $("#id_salesPersonDistributor").change(function () { var url = $("#subsidiaryForm").attr("data-salesPersonsDistributorContact-url"); var salesPersonDistributorId = $(this).val(); var id_sales = $(this).children(":selected").attr("id"); if (id_sales == "new") { $("#id_salesPersonDistributor").modalForm({ formURL: "{% url 'new_sales_person_distibutor' VCIUpdate %}" }); } else { $.ajax({ url: url, data: { 'salesPersonDistributor': salesPersonDistributorId }, success: function (data) { $("#salesPersonsDistributorContact").html(data); } … -
Django {% translate "Log out" %} does not follow translation literally
I am internationalizing my app and need to translate the string "Log out". However, Django does not follow my translation literally but translates "Log out" in its own way. In my specific example, I am trying to translate "Log out" to "Esci", its Italian equivalent. However, when I render the templates I get the translation "Annulla accesso", which roughly translates to "Undo access" in English. Additionally, I found that if I use {% translate "Logout" %} or even {% translate "Log Out" %} everything works as I would expect. Is there something particular about the string "Log out" that I should know? How can I override this behavior? Here is my HTML: {% load i18n %} {% block body %} <h1>{% translate "Hello" %}, {{ user.username }}</h1> <ul> <li>{% translate "Currently logged in as" %}: {{ user.username }}</li> <li><a href="{% url 'users:logout' %}">{% translate "Log out" %}</a></li> </ul> {% endblock %} And here is my .po file: #: users/templates/users/user.html:9 msgid "Log out" msgstr "Esci" Again, despite this, when rendered, "Log out" is translated "Annulla accesso". -
How to choose which web hosting service to use?
I am building an e-learning platform with Django, but I am not sure how and where to host it when finished. I don't fully understand the difference between the hosting services offered by Hostinger and AWS, and why Heroku is so popular in the Django community. How can I decide what is the best service to use? And, if the topic is too complex, where can I learn it? -
Django doesn't save on db with Crispy Forms
I'm trying to save on db but it doesn't work. Here's my Models.py from django.db import models # Create your models here. class Persona(models.Model): name = models.CharField(max_length=50) birth_date = models.DateTimeField() reg_date = models.DateTimeField(auto_now_add=True, blank=True) address = models.CharField(max_length=30) phone_number = models.CharField(max_length=10) email = models.EmailField(max_length=254) Here's my Views.py from django.shortcuts import render, redirect from .forms import insert_values from .models import Persona from django.views.generic import TemplateView # Create your views here. class HomeView(TemplateView): def post(self, request, *args, **kwargs): try: form = insert_values(request.POST) if form.is_valid(): p = Persona( name=form.cleaned_data['name'], birth_date=form.cleaned_data['birth_date'], address=form.cleaned_data['address'], phone_number=form.cleaned_data['phone_number'], email=form.cleaned_data['email'], ) p.save() return redirect('home') except Exception as err: errore = err.__str__() The post call works and the request is redirected, but in the object p I got the exception "AttributeError: Manager isn't accessible via 'Persona' instances". How can I solve this?