Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Ajax request call when new data is added in database
I want to create some kind of AJAX script or call that continuously will check the database if any new object is created (Django framework). I have tried using: setInterval(function()) It is working fine, but I want to know if it is the proper method, because there will be a lot of unnecessary requests which can increase server load. -
DRF ManyToManyFields with a Through Model
I have this M2M relation with through model as class Person(models.Model): name = models.CharField(max_length=128) def __str__(self): return self.name class Group(models.Model): name = models.CharField(max_length=128) members = models.ManyToManyField(Person, through='Membership') def __str__(self): return self.name class Membership(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) group = models.ForeignKey(Group, on_delete=models.CASCADE) date_joined = models.DateField() invite_reason = models.CharField(max_length=64) Please note that, I have extra fields date_joined and invite_reason in the through model. Now, I want to serialize the Group queryset using DRF and thus I choose the below serializer setup. class PersonSerializer(serializers.ModelSerializer): class Meta: model = Person fields = "__all__" class GroupSerializer(serializers.ModelSerializer): members = PersonSerializer(read_only=True, many=True) class Meta: model = Group fields = "__all__" and it is returning the following response, [ { "id": 1, "members": [ { "id": 1, "name": "Jerin" } ], "name": "Developer" }, { "id": 2, "members": [ { "id": 1, "name": "Jerin" } ], "name": "Team Lead" } ] Here, the members field returning the Person information, which is perfect. But, How can I add the date_joined and invite_reason field/info into the members field of the JSON response? -
Django-jsignature Fields Mixin
I have the below Model. class Job(models.Model): site_address=models.TextField() site_code=models.CharField(max_length=50) client=models.CharField(max_length=50) main_contractor=models.CharField(max_length=50) date_due=models.DateField() date_complete=models.DateField(null=True,blank=True) date_received=models.DateTimeField(auto_now_add=True) job_description=models.TextField() materials=models.TextField(blank=True) assigned_to=models.ForeignKey(User, on_delete = models.SET_NULL,null=True,blank=True) and also the below Django-signature model. class JSignatureModel(JSignatureFieldsMixin): name = models.CharField(max_length=50, blank=True, null=True) everything works ok and i can display, create a signature and save no problems. The issue is when i add the below. class JSignatureModel(JSignatureFieldsMixin): name = models.CharField(max_length=50, blank=True, null=True) sig = models.ForeignKey(Job, on_delete=models.CASCADE) when displayed it is asking me to manually select the job i want it to be related to instead of automatically been added when the job form is submitted. i have this working on another model which uses a foreign key link to the Job model. Is it because it's inheriting from JSignatureFieldsMixin and not models.Model? Im new to Django and Python and just trying to figure things out. Thanks -
Como fazer o deploy do python 32bits com django no Heroku?
Preciso utilizar a versão de 32bits do python para rodar a conexão com o Oracle, porem quando eu faço o deploy ele utiliza a versão do python 64 bits porem so funciona se for 32bits, alguem sabe como faço para rodar, pois não encontrei em nenhum lugar. -
Django template if condition on a key
I have a for loop through a dictionary. And I would like to have a condition on my key but I get an error. Here is my code : {% for key, value in price_list.items %} <li class="list-group-item"> <span style="margin-top: 7px;"> {{key}} </span> <span style="color: #F60;font-weight: bold;"> {{value}}€ </span> {% if {{key}} == 'Krefel' %} <a class="flux_cta gift__cta" href="#" style="font-size: 13px;height: 41px;float: right;padding-top: 11px;margin-right: 10%;" > Voir l'offre </a> {% endif %} I can't just check if the key is part of the dictonary as I am in a for loop. Any idea how I can adress the problem? Thanks -
Django form missing
So I'm trying to make a form to appear after user is authenticated. When the user authenticated then the form appears on the home page but it never appears. I'm pretty sure I'm doing something wrong ether in paths or view but can't figure this out. When I do the same code to external new template it works fine but I want form to appear on the same page. Here is the code: VIEWS.PY def vpn(request): form = vpn_form(request.POST or None) if form.is_valid(): form.save() context ={ 'form': form } return render(request, 'loginas/home.html', context) URLS.PY urlpatterns = [ # / path('', views.home, name='home'), # TEMPORARY path('signin', views.sign_in, name='signin'), path('signout', views.sign_out, name='signout'), path('callback', views.callback, name='callback'), path('', views.vpn, name='vpn'), models.py class VPN(models.Model): name = models.CharField(max_length=125) surname = models.CharField(max_length=125) description = models.TextField() date_to = models.DateField() date_from = models.DateField() forms.py from .models import VPN class vpn_form(forms.ModelForm): class Meta: model = VPN fields = ('name', 'surname', 'description', 'date_to', 'date_from') home template {% extends "loginas/layout.html" %} {% load static %} {% block content %} <div class="container"> <h1 class="d-flex justify-content-center"> </h1> <p class="d-flex justify-content-center"></p> {% if user.is_authenticated %} <form> {{form.as_p}} </form {% else %}<div class="d-flex justify-content-center"> <a href="{% url 'signin' %}" class="btn btn-primary btn-large ">Login</a> </div> {% endif … -
how to get data from different table using ajax in form of checkbox in django
Here i want to have my contactperson data in form of checkbox but using ajax call,I am able to bring in form of dropdown but after doing changes for converting it in form of checkbox its not working can anyone tell me how to change it views.py def add_project(request): error = "" if not request.user.is_staff: return redirect('admin_login') cpphone = '' cpemail = '' cust1 = Customer.objects.all() if request.method == 'POST': d = request.POST['customer'] c = request.POST['contactperson'] pn = request.POST['pname'] pl = request.POST['plength'] pt = request.POST['ptype'] pc = request.POST['pcost'] ptech = request.POST['ptechnologies'] psd = request.POST['psdate'] ped = request.POST['pedate'] pdesc = request.POST['pdescription'] d1 = Customer.objects.get(customer_id=d) contactperson1 = Contactperson.objects.get(person_id=c) cpphone = Contactperson.objects.get(person_id=c).person_phone cpemail = Contactperson.objects.get(person_id=c).person_email # print(cpphone, cpemail) try: Allproject.objects.create(customer=d1, contactperson=contactperson1, contactpersondetails=cpphone, contactpersonemail=cpemail, project_name=pn, project_length=pl, project_type=pt, project_cost=pc, project_technologies=ptech, project_startdate=psd, project_enddate=ped, project_description=pdesc) error = "no" except: error = "yes" d = {'error': error, 'cust': cust1} return render(request, 'projectfolder/add_project.html', d) def load_courses(request): cust_id = request.GET.get('customer') # print(cust_id) proj = Contactperson.objects.filter(customer_id=cust_id) return render(request, 'projectfolder/courses_dropdown_list_options.html', {'proj': proj}) add_project.html here i am only posting main fields that i want to be in form of checkbox See here i have contact person in form of select dropdown but i want that in checkbox format for each value <form class="row … -
Show Groupnames in a dropdown list
I am working on a studentresult website in Python and Django. Now I want to ask to the database to give me the names of the groups that are in the database. Using the standard db.sqlite3 database from django. In the Dropdown menu I get three white bars because I have three groups now. When I the Class DisplayGroups to id = Models.IntegerField(id, flat=True) change return.self.group_name to return self.id then the dropdownlist shows me the ID that the group has. But how can I show the name of the group. Tried a lot: Changed to group in the model Changed to groupname in the model Changed a few of the commands in the views.py Made a new database item Groepen and changed query to that. views.py from django.shortcuts import render, redirect from .models import DisplayGroups, DisplayUsername from django.contrib.auth.models import User, Group def index(request): response = redirect('/login') return response def home(response): return render(response, "home/home.html") def bekijk(request): DisplayGroup = Group.objects.all() print(DisplayGroup) DisplayNames = User.objects.all() print(DisplayNames) return render(request, "home/bekijk.html", {"DisplayGroups": DisplayGroup,"DisplayUsername":DisplayNames}) models.py from django.db import models # Create your models here. class DisplayGroups(models.Model): group_name = models.CharField(max_length=200) def __str__(self): return self.group_name class DisplayUsername(models.Model): username = models.CharField(max_length=100) def __str__(self): return self.username The html page {% … -
webpack-cli Running multiple commands at the same time is not possible
I am trying to made a full stack project using react and django from the tuto of bad traversy of react and django here react it is a django app i flow the tuto and when it coming to excute the flowing command npm run dev and dev it is "dev":" webpack --mode development ./leadmanager/frontend/src/index.js --output-path ./leadmanager/frontend/static/main.js", i have some errors they are (venv) youssef@youssef-HP-EliteBook-840-G3:~/Desktop/fullstack$ npm run dev > fullstack@1.0.0 dev /home/youssef/Desktop/fullstack > webpack --mode development ./leadmanager/frontend/src/index.js --output-path ./leadmanager/frontend/static/ [webpack-cli] Running multiple commands at the same time is not possible [webpack-cli Found commands: 'bundle', './leadmanager/frontend/src/index.js' webpack-cli Run 'webpack --help' to see available commands and options npm ERR! code ELIFECYCLE npm ERR! errno 2 npm ERR! fullstack@1.0.0 dev: webpack --mode development ./leadmanager/frontend/src/index.js --output-path ./leadmanager/frontend/static/ npm ERR! Exit status 2 npm ERR! npm ERR! Failed at the fullstack@1.0.0 dev script. npm ERR! This is probably not a problem with npm. There is likely additional logging output above. npm ERR! A complete log of this run can be found in: npm ERR! /home/youssef/.npm/_logs/2020-12-29T13_19_24_663Z-debug.log -
Introducing JavaScript events with my django template
I have develop quite numbers of web app with django but am seeking to improve UIs with JavaScript, I haven't done something like this before, but with my researches I have found somethings about events. But I will like if someone can just point me through how to implement it and get started easily, because I heard JavaScript is very hard to debug -
No ready() function when starting django with uvicorn
I have a problem because when starting a Django application by uvicorn, Django's AppConfig don't seem to be running ready() function. When I'm starting by Djnago's runserver command, ready function is correctly loaded. Can you help me to overcome this problem? settings.py """ Django settings for mtg_django project. Generated by 'django-admin startproject' using Django 3.1.3. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'pukj_o)6-!^i$oeh-9c1zik4w*v68!pkdux)nc_79fzjffp*j6' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # 'rest_framework', 'mtg.apps.MtgConfig' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'mtg_django.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'mtg_django.wsgi.application' # Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases # DATABASES = { … -
Django - queryset based on list interval
I have a Django model and want to get a Queryset based on the order_by clause which is set to a time field in descending order. I do NOT want to return all these objects. I just want to return the objects in the interval start to end. For now I get all the objects in Queryset list and manually slice the python list (list[start:end). The problem is that the list contains over 100k records. So it is a time consuming option. Is there any way in which I can pass this start and end parameter to Django and it only returns the queryset list after applying that slice. -
Serializing many to many relationship with attributes does not show attribute in the relationship
My conceptual model is that there are DemanderFeature objects which have LoadCurve objects linked to them in a many-to-many relationship, along with a single attribute indicating "how many times" the two are associated, using an attribute in the many-to-many relationship called number. I have been struggling for quite a while now, reading many answers on stackoverflow but I just cannot get it to work in exactly the way that I want. This is my desired output, when looking at the detail view of a DemanderFeature: HTTP 200 OK Allow: GET, POST, HEAD, OPTIONS Content-Type: application/json Vary: Accept [ { "name": "testdemander", "loadcurves": [ {"name": "lc", "number": 5}, {"name": "lc2", "number": 10} ], // Other DemanderFeature fields removed for brevity... } ] The closest I have been able to get to this is with this setup: Models class LoadCurve(models.Model): created = models.DateTimeField(auto_now_add=True) finalized = models.BooleanField(default=False) owner = models.ForeignKey('auth.User', on_delete=models.CASCADE) name = models.CharField(max_length=100) length = models.IntegerField(default=0) deleted = models.BooleanField(default=False) demanderfeatures = models.ManyToManyField("DemanderFeature", through="DemanderFeatureToLoadCurveAssociation") class Meta: ordering = ['name'] constraints = [ models.UniqueConstraint(fields=["owner", "name"], condition=models.Q(deleted=False), name="loadcurve_unique_owner_name") ] class DemanderFeature(models.Model): created = models.DateTimeField(auto_now_add=True) name = models.CharField(max_length=100) owner = models.ForeignKey('auth.User', on_delete=models.CASCADE) demanderfeaturecollection = models.ForeignKey(DemanderFeatureCollection, on_delete=models.CASCADE) loadcurves = models.ManyToManyField("LoadCurve", through="DemanderFeatureToLoadCurveAssociation") deleted = models.BooleanField(default=False) geom = gis_models.PointField(default=None) … -
does not show forms errors in django
I want show required errors but not showing. I made custom errors in form.py but it does not show either my current or default and why? When I submit a blank form I want it to appear, my created error this is my code --> home.html {% extends "home/base.html" %} {% block content %} <h2>Sign up Form</h2> <div class="frm"> <form method="post" novalidate> {% csrf_token %} {{form}} <button type="submit">sign up</button> </form> </div> {% endblock %} forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import get_user_model User = get_user_model() class SignUpForm(UserCreationForm): username = forms.CharField(max_length=30) username.error_messages['required'] = ('Username field is required') email = forms.EmailField(max_length=200) def __init__(self, *args, **kwargs): super(SignUpForm, self).__init__(*args, **kwargs) for field_name, field in self.fields.items(): field.widget.attrs['class'] = 'inp' for field in self.fields.values(): field.error_messages = {'required':'The field {fieldname} is required'.format( fieldname=field.label)} class Meta: model = User fields = ('username', 'email', 'password1', 'password2','mob', ) -
Why do I get conflicts while creating new Django app
tn_gram_backend is the main Django project folder. I created a new folder staging and inside that I am trying to create another Django app called ddc but it is throwing me the following error as show in the below image. Please suggest how to fix this. 'ddc' conflicts with the name of an existing python module and cannot be used as an app name -
Internal server error running Django on Heroku accessing from browser
I think this is a simple fix, but I've deployed quite a few Django apps to Heroku and I still can't figure out what's going on. Accessing https://dundjeon-finder.herokuapp.com/ gives me a 500 error when using the browser/curl, but if I shell into the app using heroku run ./manage.py shell I can render the views no problem. My logs aren't telling me anything (just that the response is 500), and Sentry isn't receiving an error (it has previously when the database env variable was set badly), so I'm assuming it's something to do with the way the request works. The repo is public, any help would be much appreciated! The settings file is here. -
Virtual environment for Django in ubuntu 20.04
After installing Django, I install virtual environment by using the command - pip3 install virtualenvwrapper-win.Also run sudo pip3 install virtualenv Added the following to the end of the .bashrc file export WORKON_HOME=~/virtualenvs export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python source ~/.local/bin/virtualenvwrapper.sh then source ~/.bashrc gets successfully executed. But when I run this command - mkvirtualenv test to create virtual environment, I am getting this- created virtual environment CPython3.8.5.final.0-64 in 94ms creator CPython3Posix(dest=/home/rudrakshi/.virtualenvs/test, clear=False, no_vcs_ignore=False, global=False) seeder FromAppData(download=False, pip=bundle, setuptools=bundle, wheel=bundle, via=copy, app_data_dir=/home/rudrakshi/.local/share/virtualenv) added seed packages: pip==20.3.1, setuptools==51.0.0, wheel==0.36.1 activators BashActivator,CShellActivator,FishActivator,PowerShellActivator,PythonActivator,XonshActivator Command '' not found, but can be installed with: sudo apt install mailutils-mh # version 1:3.7-2.1, or sudo apt install meshio-tools # version 4.0.4-1 sudo apt install mmh # version 0.4-2 sudo apt install nmh # version 1.7.1-6 sudo apt install termtris # version 1.3-1 I also installed the mailutils-mh but still getting this. -
Is it possible to use Azure Shared Access Signature outside of Azure?
Since Azures Shared Access Signatures (SAS) is an open standard I want to use it in my Django application which has no links to Azure whatsoever. I basically want to create a piece of code that creates read permission for the next 24 hours on a specific url I'm serving. So I've watched some video's on SAS and I installed the python library for it (pip install azure-storage-blob). I read over the README here on github but as far as I can see it always requires an Azure account. Is it also possible to use SAS in my own (Python) application? I imagine it to create the hashes based on a pre-defined secret key for. If this is possible, does anybody have any example code on how to create the url and how to validate it? Preferably in Python, but example code in other languages would be welcome as well. -
Python-Django-Heroku not able to locate images in heroku, images not visible
so I recently deployed my django/python website (that used sqllite as a database) to heroku which hosts websites for free, everything is functioning normally like when I used to run localhost in my browser, except that this project is using postgressql database with heroku and images aren't appearing on my website, I looked everywhere and I think it has to do with the uploads file in the database(the path of the image is still the same but the location of the image changed). local host image link: "http://localhost:8000/image/download/uploads/products/white_shirt_MERETfT.jpg" heroku image link: "https://supremelebanon.herokuapp.com/image/download/uploads/products/offwhite_shirt_tQWa19c.jpg" it says image not found for when I load the website on heroku hosting. Please anyone I'm still a newbie with heroku I dont really know how it works, if anyone can help it would be much appreciated, thanks in advance. settings.py file: import os from pathlib import Path import django_heroku # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'morrr7ht4t4m)j#%ws34ntr7mdq$pui)+uy2-#%tx^iznh_##6' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['supremelebanon.herokuapp.com', 'localhost', … -
Error when migrating a foreignkey in Django
When I run python .\manage.py makemigrations it gives me the following error in my app called store (this is for making blog posts). python .\manage.py makemigrations Migrations for 'store': store\migrations\0009_auto_20201229_1318.py - Remove field test from post - Add field author to post PS C:\Users\Lukas\Desktop\Projects\hiddenservice> python .\manage.py migrate store Operations to perform: Apply all migrations: store Running migrations: Applying store.0006_post_author...Traceback (most recent call last): File "C:\Users\Lukas\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "C:\Users\Lukas\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\sqlite3\base.py", line 413, in execute return Database.Cursor.execute(self, query, params) sqlite3.IntegrityError: NOT NULL constraint failed: new__store_post.author_id The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\Lukas\Desktop\Projects\hiddenservice\manage.py", line 22, in <module> main() File "C:\Users\Lukas\Desktop\Projects\hiddenservice\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\Lukas\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\Lukas\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Lukas\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Lukas\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 371, in execute output = self.handle(*args, **options) File "C:\Users\Lukas\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 85, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\Lukas\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\migrate.py", line 243, in handle post_migrate_state = executor.migrate( File "C:\Users\Lukas\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "C:\Users\Lukas\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "C:\Users\Lukas\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\executor.py", line 227, in apply_migration … -
How to pass object by id after saving from form using redirect?
I am sorry for asking this. I described a service that uploads an image through a form. The bottom line is that after a successful download (add_picture), I have to get to the image page (picture_detail). I don’t understand why I can’t transfer ID. I did the following: models.py: class Picture(models.Model): url = models.URLField(blank=True, verbose_name='Ссылка на изображение') image = models.ImageField(upload_to='pictures/%Y/%m/%d', width_field='image_width', height_field='image_height', blank=True, verbose_name='Изображение') def get_absolute_url(self): return reverse('home:picture_detail', args=[self.id]) views.py: def add_picture(request, id=None): picture = Picture.objects.filter(is_active=True) # picture_form = None # picture = get_object_or_404(Picture, id=id) if request.method == 'POST': form = PictureCreateForm(data=request.POST, files=request.FILES) if form.is_valid(): form.save() # picture = get_object_or_404(Picture, id=id) bb = Picture.objects.get(id=id) return HttpResponseRedirect(reverse('home:picture_detail', kwargs={'id': id})) else: return render(request, 'add_picture.html', locals()) else: form = PictureCreateForm() return render(request, 'add_picture.html', locals()) urls.py: urlpatterns = [ path('', views.home, name='home'), path('add_picture/', views.add_picture, name='add_picture'), path('picture_detail/<int:id>/', views.picture_detail, name='picture_detail'), ] As a result, I should get to a page of this kind: -
STARTTLS extension not supported by server while attaching more than 1 mb file
I am getting "STARTTLS extension not supported by server" while attaching more than 1 MB file with the mail. While attaching less than 1 MB file the exception is not being generated in python. if file_size <= ATTACHMENT_FILE_SIZE : print('in if condition') logger.info(f'{thread_name} : In If Condition') mailDetails.attach(MIMEText(body_to_be_sent, "html")) attachment = open(filepath, 'rb') payload = MIMEBase('application', 'octet-stream') payload.set_payload(attachment.read()) encoders.encode_base64(payload) payload.add_header('Content-Disposition', "attachment; filename= %s" % f'''{file_name}.xlsx''') mailDetails.attach(payload) try: connection = smtplib.SMTP(SMTPserver) connection.ehlo() connection.starttls() connection.set_debuglevel(False) connection.login(SMTPUSERNAME, SMTPPASSWORD) text = mailDetails.as_string() connection.sendmail(FROM_MAIL_ADDRESS,toAddress.split(",") + ccAddress.split(",")+bccAddress.split(","), text) logger.info(f'{thread_name} : Mail Sent successfully') # os.remove(filepath) -
Django : cannot access body after reading from request's data stream
Im working with REST API and currently sending data from fetch to my django view. Im getting cannot access body after reading from request's data stream. what is wrong? PS: i already tried using request.data but some other problems occuring views.py @csrf_exempt @api_view(['POST']) def createNew(request): data = json.loads(request.body) if request.method == 'POST': serializer = newsSerializer(data =data['title']) if serializer.is_valid(): serializer.save() # return Response(serializer.data) return redirect('http://127.0.0.1:8000/news_list/') my fetch method form.addEventListener("submit", function(e) { e.preventDefault() var url = 'http://127.0.0.1:8000/news_create/' var title = document.getElementById('title').value fetch(url, { method: 'POST', // or 'PUT' headers: { 'Accept': 'application/json, text/plain, */*', 'Content-Type': 'application/json', 'X-CSRFToken': csrftoken, }, body: JSON.stringify({ 'title': title }), }) .then(response => response.json()) .then(data => { console.log('Success:', data); }) .catch((error) => { console.error('Error:', error); }); }); -
How to add multiple popup form in one page in django
I want to create three tables(In HTML) as follow : Medical School PG University(Name of university and pass-out year) Privilege state to practice(Name of state, License expiry year) I want to add a popup form to information in those three tables on one page(In HTML). -
Database-Query in DjangoChannels Consumer returns coroutine object instead of query-set
I am using an AsyncConsumer from wich an async task calls a syncronous function via the asgiref sync_to_async function. In this function the result of a database query is supposed to be saved to a variable and later iterated over, but instead of the resulting queryset, the variable just saves the coroutine object. a simplified version of the code: class ChatConsumer(AsyncConsumer): ... async def collect_votes_task(self): await sync_to_async(self.process_sessions()) def process_sessions(self): current_session = self.get_current_session(self.room_name) print(current_session) # do other stuff with the query-set @database_sync_to_async def get_current_session(self, current_session_code): current_session = Session.objects.filter( session_code=current_session_code) return current_session prints: <coroutine object SyncToAsync.__call__ at 0x000001B1CBBF03C0> I am fairly new to DjangoChannels, so excuse me if the reason this happens is obvious.