Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How we can hold the user for a second for please wait msg in Django as we show in PHP with refresh tag?
How we can hold the user for a second for please wait msg in Django as we show in PHP with refresh tag ?enter image description here -
model fields are not created django
models.py from django.db import models class Blog(models.Model): title=models.CharField(max_length=50,default="") auther=models.CharField(max_length=100, default="") body=models.TextField(default="") 0001_inital.py operations = [ migrations.CreateModel( name='Blog', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ], ), ] cmd python manage.py migrate PS C:\Users\Dhiraj Subedi\Desktop\django-101> python manage.py makemigrations Migrations for 'first_app': first_app\migrations\0002_auto_20210531_1214.py - Add field auther to blog - Add field body to blog - Add field title to blog PS C:\Users\Dhiraj Subedi\Desktop\django-101> -
Cannot send array list from JavaScript to Django View
I have an array called tableData. But whenever I execute it I couldn't get the result on my python terminal. Since i already put print(pieFact), it should print me the output right? Other than that, when i put var data = {'test': '2', csrfmiddlewaretoken: '{{ csrf_token }}'};, i actually can get the 2 output in my terminal but not my array when I put 'test': tableData. Can anyone guide me what I'm doing wrong here? Thanks Javascript <script> //declare the array as a global var tableData = []; var URL="{% url 'test' %}" $(document).ready(function () { $(".button").on("click", function () { para = document.getElementById("Parameter").value; condi = document.getElementById("Condition").value; value2match = document.getElementById("valuetomatch").value; if (para && condi && value2match !== null) { var table = document.getElementById("myTable"); var row = table.insertRow(-1); var cell1 = row.insertCell(0); var cell2 = row.insertCell(1); var cell3 = row.insertCell(2); var cell4 = row.insertCell(3); cell1.innerHTML = document.getElementById("Parameter").value; cell2.innerHTML = document.getElementById("Condition").value; cell3.innerHTML = document.getElementById("valuetomatch").value; cell4.innerHTML = '<button class = "del_img "onClick="delSpec(this)"><img src="deleteimg.png" width="30" height="30"></button> </div>'; var myTab = document.getElementById("myTable"); // Only add the new row: tableData.push([ document.getElementById("Parameter").value, document.getElementById("Condition").value, document.getElementById("valuetomatch").value ]); modal.style.display = "none"; } else { alert("All the input box cannot be empty!"); } }); document.getElementById("buttonSubmit").onclick = function () { alert(tableData); var data … -
JSON parsing error in django post request
I'm trying to send data through POST request in django url = 'http://db-003:8013/v1/upgrade-ce' payload = { "cluster_name": cluster_name, "cec_id": cec_id, "new_version": new_version, "cr_number": cr_number, } response = requests.post(url, data=payload) On receiver end post method: cluster name = request.data.get('cluster_name') Data on receiver's end <QueryDict: {'cluster_name': ['abcd'], 'cec_id': ['abc'], 'new_version': ['8.0.23'], 'cr_number': ['6587657']}> The obtained data is a list, and not an individual string string. Tried json.dumps() , but on the receiver end, data is empty. How do i get an individual string -
getting object created thanks to TabularInline problem
My model A uses TabularInline, which creates objects of model A1. I want to output information about object A1 to the console when I save object A. I use the clean/save method. When I save an existing A object, it's fine, but if I create one, it outputs an error. How can I track the creation of object A1 in object A? Thank you. class A(models.Model): name = models.CharField(max_length=120) def save(self, *args, **kwargs): super().save(*args, **kwargs) print(self.a_name.all()) class A1(models.Model): description = models.CharField(max_length=120) name = models.ForeignKey(A, on_delete=models.CASCADE, related_name="a_name") -
DjangoQ Logged in user
I am using Django Q to schedule my python script which is inside views.py but when running my cluster it doesn't fetch the logged in user it gives an error 'str' object has no attribute 'user'.I am using request.user to get the detail of current logged in user it is working fine in another views what should i do please can someone help me? -
How to copy or read a file from the outside of the project file in Django?
I have created a basic ocr system. When a user uploads a PDF file to the system ocr read it and created an xlsm file with the same name. I am using remote control with Azure (Windows). I created a download button. When I click it, download the file with the same name, so it should work but appears an error because I want to read the file from the outside directory of the project. So, I should copy this file to my media dir, or I should read from there. This is my project: C:\Users\f-otc\PycharmProjects\otc This is the file that I want to download: C:\f\otc <a href= "{% static path %}" class="btn btn-outline-primary btn-sm" download>Download Report File</a> This is my button It gets the path correctly but gives an error when file downloaded. -
ListView isn't working in Django, Posts are not rendered
I am trying to render post_details and user_post HTML files but it is not rendering as expected. I can't see the post details or user posts in Django. It is rendering everything fine but not the post! Here is the code I am using: urls.py from django.contrib import admin from django.urls import path,include from . import views from .views import PostListView, UserPostListView, PostDetailView urlpatterns = [ path('', PostListView.as_view(), name='home'), path('user/<username>', UserPostListView.as_view(), name='user-post'), path('post/<int:pk>', PostDetailView.as_view(), name='post-detail'), path('login/',views.login_view, name='login'), path('logout/',views.logout_view, name='logout'), path('register/',views.register, name='register'), ] views.py from django.shortcuts import render,redirect from django.contrib.auth import login, logout,authenticate from django.shortcuts import render, get_object_or_404, HttpResponse from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from django.contrib.auth.models import User from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView from .models import Post # from .forms import PostForm from itertools import chain # Create your views here. def home(request): context = { 'posts': Post.objects.all() } return render(request, 'index.html',context) def login_view(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) if User is not None: login(request, user) return redirect('/') else: return render(request, 'login.html') return render(request, 'login.html') def logout_view(request): logout(request) return render(request, 'logout_view.html') def register(request): if request.method == 'POST': username = request.POST.get('username') email = request.POST.get('email') password = request.POST.get('password') user = … -
How to create file browser like google drive in django?
How to create a file browser like this in Django with Min.io or Amazon s3? -
Django : Changing settings in an exported csv file
I have implemented a button that will export the readings that are taken for a complex (to .csv) In the file that has been downloaded, the data is in the first cell only, separated by a coma. This is fixed in the .csv file by doing the following: Goint to data > get & transform data > from text/csv . 'select the file you wish to change' > transform data > save and close. Is there a way that I can change these settings in my exporting code. Views.py import csv def Avonleacsv(request): data =AvonleaClass.objects.all() response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="Avonlea_file.csv"' writer = csv.writer(response) writer.writerow(['Unit', 'Number of Units' ]) for avonleaclass in data: writer.writerow([ avonleaclass.unitNumber, avonleaclass.newReading, ]) return response -
type error module object is not iterable error in django
C:\IT Career\Python\shop>python manage.py runserver Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\THE KING\AppData\Local\Programs\Python\Python39\lib\site-packages\django\urls\resolvers.py", line 600, in url_patterns iter(patterns) TypeError: 'module' object is not iterable The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\THE KING\AppData\Local\Programs\Python\Python39\lib\threading.py", line 954, in _bootstrap_inner self.run() File "C:\Users\THE KING\AppData\Local\Programs\Python\Python39\lib\threading.py", line 892, in run self._target(*self._args, **self._kwargs) File "C:\Users\THE KING\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\THE KING\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "C:\Users\THE KING\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 419, in check all_issues = checks.run_checks( File "C:\Users\THE KING\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\checks\registry.py", line 76, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\THE KING\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\THE KING\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\THE KING\AppData\Local\Programs\Python\Python39\lib\site-packages\django\urls\resolvers.py", line 413, in check messages.extend(check_resolver(pattern)) File "C:\Users\THE KING\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\THE KING\AppData\Local\Programs\Python\Python39\lib\site-packages\django\urls\resolvers.py", line 412, in check for pattern in self.url_patterns: File "C:\Users\THE KING\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\functional.py", line 48, in get res = instance.dict[self.name] = self.func(instance) File "C:\Users\THE KING\AppData\Local\Programs\Python\Python39\lib\site-packages\django\urls\resolvers.py", line 607, in url_patterns raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) from e django.core.exceptions.ImproperlyConfigured: The included URLconf '<module 'products.urls' from 'C:\IT Career\Python\shop\products\urls.py'>' does not appear to have any patterns in it. If you see valid patterns in … -
table not allow to create and edit in django
Django table not allow to edit and create. Before editing the table I changed is active true and taken user illyas But after saving is active false and taken user None.... WHY??? models.py class SignupCupon(models.Model): offer_for = models.CharField(max_length=20, default="Referral offer") cupon_code = models.CharField(max_length=50, unique=True) offer_price = models.PositiveIntegerField() is_active = models.BooleanField(default=False) which_user = models.OneToOneField(User, related_name="which_user_signup", on_delete=models.CASCADE, null=True, blank=True) taken_user = models.ForeignKey(User, related_name="signup_cupon_taken_user", on_delete=models.CASCADE, null=True, blank=True) create_at = models.DateTimeField(auto_now_add=True) def __str__(self): return "User: " + str(self.which_user) + " - Cupon: " + str(self.cupon_code) def save(self, *args, **kwargs): if self.cupon_code == "": self.cupon_code = generate_cupon() super().save(*args, **kwargs) admin.py from django.contrib import admin from .models import CategoryOffer, ProductOffer, CuponOffer, SignupCupon, ReferralCupon admin.site.register([CategoryOffer, ProductOffer, CuponOffer, SignupCupon, ReferralCupon]) -
How to run django project using gunicorn with TLSv1_2
I have django project with version 1.11 ,python 2.7 and used gunicorn (19.6) to run https service. Is it possible to change ssl protocol to TLSv1_2 ? I found only gunicorn 20.x version can change ssl protocol to TLS_V1_2 but it needs python 3.4+ thanks -
why loop already started in pyttsx3
this is my program engine = pyttsx3.init() voices = engine.getProperty('voices') engine.setProperty('voice', voices[1].id) engine.setProperty('rate', 150) def voice_alert(engine): engine.say('please wear mask') engine.runAndWait() the function voice_alert is called when while loop is started to run while True: if mask < withoutMask: t = threading.Thread(target=voice_alert, args=(engine,)) t.start() error: raise RuntimeError('run loop not started') RuntimeError: run loop not started -
Connecting mongodb atlas through mongoengine in django after hosting on EC2 apache2
I am trying to host django project on EC2 usnig apache2 which is using mongodb atlas as database. When I am running this locally on EC2 after openning some port like 8000, it runs properly but on apache it's giving error. Below is some TLSFeature error, I am facing mod_wsgi (pid=67994, process='tracky', application='ip-IP_ADDRESS|'): Loading Python script file '/home/tracky/tracky-api/tracky/wsgi.py'. mongodb+srv://username:password@host/dbname?retryWrites=true&w=majority mod_wsgi (pid=67994): Exception occurred processing WSGI script '/home/tracky/tracky-api/tracky/wsgi.py'. Traceback (most recent call last): File "/home/ubuntu/anaconda3/envs/tracky/lib/python3.6/site-packages/pymongo/pool.py", line 1278, in _get_socket sock_info = self.sockets.popleft() IndexError: pop from an empty deque During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/ubuntu/anaconda3/envs/tracky/lib/python3.6/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/ubuntu/anaconda3/envs/tracky/lib/python3.6/site- File "/home/tracky/tracky-api/trackyapi/urls.py", line 2, in <module> from .views import Tracky File "/home/tracky/tracky-api/trackyapi/views.py", line 16, in <module> from .serializers import GoalsSerializer, GoalSerializer File "/home/tracky/tracky-api/trackyapi/serializers.py", line 9, in <module> class GoalSerializer(DocumentSerializer): File "/home/tracky/tracky-api/trackyapi/serializers.py", line 11, in GoalSerializer uid = ReferenceField(User, write_only=True) File "/home/ubuntu/anaconda3/envs/tracky/lib/python3.6/site-packages/rest_framework_mongoengine/fields.py", line 217, in __init__ self.queryset = model.objects File "/home/ubuntu/anaconda3/envs/tracky/lib/python3.6/site-packages/mongoengine/queryset/manager.py", line 38, in __get__ queryset = queryset_class(owner, owner._get_collection()) File "/home/ubuntu/anaconda3/envs/tracky/lib/python3.6/site-packages/mongoengine/document.py", line 215, in _get_collection db = cls._get_db() File "/home/ubuntu/anaconda3/envs/tracky/lib/python3.6/site-packages/mongoengine/document.py", line 193, in _get_db return get_db(cls._meta.get("db_alias", DEFAULT_CONNECTION_NAME)) File "/home/ubuntu/anaconda3/envs/tracky/lib/python3.6/site-packages/mongoengine/connection.py", line 363, in get_db db.authenticate( File "/home/ubuntu/anaconda3/envs/tracky/lib/python3.6/site-packages/pymongo/database.py", line 1492, in … -
How do I get the prev data of a many to many field incase there is an Update
I'm trying to maintain a history of updates, I need to know how to get the previous data of a many to many field in the serializer update function for field,value in validated_data.items(): new_value=value old_value=getattr(instance, field) for some reason I'm getting None So,I also tried this old_value=validated_data.get('groups', None) and I got the new value instead So, any help is much appreciated, ty!! -
getting column 'is_routed' cannot be null error. Even thought it is set to default=0 in database
Im inserting some values into database table using orm here is what im doing: placeorder_userorder=UserOrder(order_status='Processing',listing_id=all_response[0],actual_cost=total_original_prize,order_total=total_final_prize,total_without_dc=total_original_prize, discount=total_final_discount,gst=all_response[0]['gst']) placeorder_userorder.save() where as 'is_routed' is set to default value to 0(along with many column) So im not mentioning 'is_routed' into my code and it is supposed to be 0 when new row added But im getting this error: django.db.utils.IntegrityError: (1048, "Column 'is_routed' cannot be null") -
Django - Passing multiple parameters into raw queries with %s format
In the project I am working on before we used a custom connector for MariaDB but now I have to use the default connector for MySQL in Django. The previous MariDb connector used ? For parameterization but MySQL for Django uses %s instead. I create the queries dynamically in the following way: def create_update_query(interpretation, record_id, table): query = "UPDATE `db-dummy`."+table+" " for index, key in enumerate(interpretation): if index == 0: query = query + "SET {0} = %s".format(key) else: query = query + ", {0} = %s".format(key) query += " WHERE record_id = " + record_id return query And this is a sample of a query created dynamically (there could be up to 30 parameters): UPDATE `db-dummy`.s_data SET s_id = %s, h_loss = %s WHERE record_id = 5877 And here comes the problem. With the MariaDB you could something like this: sd_query = create_update_query(interpretation, record_id, tableName) cursor.execute(sd_query, tuple(interpretation.values()) ) But I do not know how to do it with a %s parameterization. I couldn't find anything in the official documentation. EXTRA INFO: If for example we print(tuple(interpretation.values())), this is the outcome: ('SIC0575', '1') -
Is there any way I can pass args Value to pass in django celery periodic tasks?
I got certain following task to be executed from apps.users.email import ConfirmationEmail @shared_task def send_email(receipt, **kwargs): return ConfirmationEmail(context=kwargs).send(to=[receipt]) and send email is called in below function. I am having problem on passing args in periodic task as I could not find any docs regarding this def _email(self): token = RefreshToken.for_user(user=self.user_instance).access_token # get current site current_site = get_current_site(self._request).domain # we are calling verify by email view here whose name path is activate-by-email relative_link = reverse('activate-by-email') # make whole url absolute_url = 'http://' + current_site + relative_link + "?token=" + str(token) self.context = { 'user': self._user.username, 'token': absolute_url } receipent = self._user.email send_email.delay(receipent, **self.context) Above code works fine with redis but I want to send email every 2 minutes but I am confused on passing args while passing the periodic task job. Is the approach wrong or I am missing something? -
Deploy camera in production for a django application in aws with docker
I have a web application made in django that requires the user's camera to work, when I run the application locally it works and in the browser I ask the user for permissions for the camera, but when I put it into production in a docker container inside a AWS EC2 instance, the application works with an ip http address but does not ask for permissions for the camera. Dockerfile FROM python:3.8.3 ENV PYTHONUNBUFFERED 1 RUN mkdir /my_app_dir WORKDIR /my_app_dir ADD requirements.txt /my_app_dir/ RUN pip install --upgrade pip && pip install -r requirements.txt ADD . /my_app_dir/ docker-compose.yml version: '3' services: web: build: . command: python manage.py runserver 0.0.0.0:80 volumes: - .:/my_app_dir ports: - "80:80" http://33.12.99.22/ (example) -
How to solve "can only concatenate str (not "FieldFile") to str"
I am trying to get the file that I store all the images. I have 2 html, editingclaims and submitclaim. I am storing the images in models.py receipt = models.FileField(upload_to='receipts/%Y/%m/%D') Submitclaims allows user to submit an image, while editicingclaims claims allows user to edit the image. If user submits a new image in the editingclaims.html, it will overwrite existing ones. If there isnt any submitted image, it will display the old image from submitclaims.html This is my views.py # Edit a claim def editclaims(request,id): context = initialize_context(request) user = context['user'] # get original object claims = SaveClaimForm.objects.get(id=id) if request.method == 'POST': # update original object claims.name = request.POST['name'] claims.email = request.POST['email'] claims.claim = request.POST['claim'] claims.claimtype = request.POST.get('claimtype') claims.description = request.POST['description'] old_file = claims.receipt if os.path.isfile('receipts/%Y/%m/%D'+old_file): os.remove('receipts/%Y/%m/%D'+old_file) claims.receipt = request.FILES.get('receipt') claims.cheque = request.POST.get('Cheque') claims.status = request.POST['status'] # save it with original `ID` claims.save() return render(request, "Login/editclaims.html", {'claims':claims, 'user':user}) -
How to include non-Python dependencies in a Python Django deployment?
I am deploying a Django application using Heroku. One of my application's dependencies is the 'ta-lib' library, which is a Python wrapper for a library written in C. To get this to work locally, I simply had to download the underlying C library and the program would pick up what it needed from /usr/local and I had no problems. Library reference: https://mrjbq7.github.io/ta-lib/install.html Now, when I'm trying to push my files to Heroku via Git, the build fails at this library. Here is the terminal output, starting from where the errors began: remote: Building wheel for TA-Lib (setup.py): started remote: Building wheel for TA-Lib (setup.py): finished with status 'error' remote: ERROR: Command errored out with exit status 1: remote: command: /app/.heroku/python/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-ya1rkeoc/ta-lib/setup.py'"'"'; __file__='"'"'/tmp/pip-install-ya1rkeoc/ta-lib/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /tmp/pip-wheel-e83ejfm_ remote: cwd: /tmp/pip-install-ya1rkeoc/ta-lib/ remote: Complete output (27 lines): remote: /tmp/pip-install-ya1rkeoc/ta-lib/setup.py:71: UserWarning: Cannot find ta-lib library, installation may fail. remote: warnings.warn('Cannot find ta-lib library, installation may fail.') remote: running bdist_wheel remote: running build remote: running build_py remote: creating build remote: creating build/lib.linux-x86_64-3.9 remote: creating build/lib.linux-x86_64-3.9/talib remote: copying talib/test_data.py -> build/lib.linux-x86_64-3.9/talib remote: copying talib/test_func.py -> build/lib.linux-x86_64-3.9/talib remote: copying talib/stream.py -> build/lib.linux-x86_64-3.9/talib remote: copying talib/__init__.py … -
Heroku passes the build but gives Application error
Hi I am trying to deploy a website on heroku. I successfully built it on heroku. When I try to deploy it gives me the Application Error when I check the log this is what I am getting: 2021-05-30T23:43:57.000000+00:00 app[api]: Build succeeded 2021-05-30T23:44:01.169958+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=cqthub.herokuapp.com request_id=1f7f7f68-028c-4101-a61c-dee410dc2429 fwd="75.157.7.173" dyno= connect= service= status=503 bytes= protocol=https 2021-05-30T23:44:10.322517+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=cqthub.herokuapp.com request_id=182f7faa-e19e-4693-919f-003e0600f42c fwd="75.157.7.173" dyno= connect= service= status=503 bytes= protocol=https I only mentioned 'favicon' in the footer: ..... </style> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.0.13/css/all.css" integrity="sha384-DNOHZ68U8hZfKXOrtjWvjxusGo9WQnrNx2sqG0tfsghAvtVlRW3tvkXWZh58N9jp" crossorigin="anonymous"> <link rel="icon" href="img/favicon.ico" type="image/x-icon"> <!-- Footer --> <hr> .... Can someone please tell me how to solve this issue? -
Django rest + React front
Currently, I am working with a group to try to create a website with a functional Django backend and a React frontend. We are using a user view set class UserViewset(viewsets.GenericViewSet, mixins.CreateModelMixin, mixins.RetrieveModelMixin, mixins.ListModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin): permissions_classes = (permissions.AllowAny,) serializer_class = UserSerializer queryset = User.objects.all() This is where I am stuck, I haven't used viewsets or serializers before and I am at an impasse on where to go from here. I was hoping to get some clarification of how to add in a create/register user plus login and logout functions so that we can start messing with our api. Any help would be appreciated. -
Can't deploy Django on Heroku due to static error
Hello I am trying to launch my django website on heroku. I downloaded the heroku CLI, and I am running the following code on fish to resolve the error: heroku config:set DISABLE_COLLECTSTATIC=1 however I am getting the following error › Error: Missing required flag: › -a, --app APP app to run command against › See more help with --help Can someone please tell me how to resolve this issue?