Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django export-import use both ExportActionModelAdmin and ExportMixin together
In admin.py, using either: from django.contrib import admin from import_export.admin import ExportActionModelAdmin, ExportMixin class BookAdmin(ExportActionModelAdmin, admin.ModelAdmin): # stuff or from django.contrib import admin from import_export.admin import ExportActionModelAdmin, ExportMixin class BookAdmin(ExportMixin, admin.ModelAdmin): # stuff works well, but I'm not able to have both together: from django.contrib import admin from import_export.admin import ExportActionModelAdmin, ExportMixin class BookAdmin(ExportActionModelAdmin, ExportMixin, admin.ModelAdmin): # stuff In this latter case, the top right 'Export' button is missing (but the drop-down menu is OK). How could I use both ExportActionModelAdmin and ExportMixin from import_export.admin in my admin classes in order to have both the drop-down menu for a fine grain selection, and the 'Export' button for exporting all the model in one click? Doc URL: https://django-import-export.readthedocs.io/en/latest/getting_started.html#exporting-data -
why I am getting 401 error while sending a post request to auth/users in android studio but same request works in browser? wrong with my request?
I have an API which allows post request to register new users. It works in browser but when I try making this post request in my android project.I get 401 unauthorized response, I don't know what is wrong with my request!? private static String makeHttpRequest(URL url, String info) throws IOException { String jsonResponse = ""; if (url == null) { return jsonResponse; } HttpURLConnection urlConnection = null; OutputStream outputStream = null; InputStream inputStream = null; try { urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("POST"); urlConnection.setRequestProperty("Content-Type", "application/json"); urlConnection.setRequestProperty("Accept", "application/json"); urlConnection.setDoOutput(true); //write to the stream outputStream = urlConnection.getOutputStream(); byte[] input = info.getBytes(Charset.forName("UTF-8")); outputStream.write(input, 0, input.length); urlConnection.connect(); //read the response if (urlConnection.getResponseCode() == 200) { authenticated = true; inputStream = urlConnection.getInputStream(); jsonResponse = readFromStream(inputStream); } else { Log.e(LOG_TAG, "Error response code: " + urlConnection.getResponseCode()); } } catch (IOException e) { Log.e(LOG_TAG, "Problem retrieving the JSON results.", e); } finally { if (urlConnection != null) { urlConnection.disconnect(); } if (inputStream != null) { inputStream.close(); } if (outputStream != null) { outputStream.close(); } } return jsonResponse; } -
Fetch Nested Data Using Ajax
I am having difficulties in fetching data which leads the output in this "[object Object]" Here is the sample data that I am fetching: { "id": 1, "logs": [ { "id": 1, "login_time": "2022-09-24T08:43:48.988768Z", "logout_time": "2022-09-24T08:43:48.988768Z", "work_hours": 0, "user": 1 }, { "id": 2, "login_time": "2022-09-24T10:24:59.564850Z", "logout_time": "2022-09-24T10:24:59.564850Z", "work_hours": 0, "user": 1 } ] } And here is the AJAX Code that I am using: function userlist(){ var wrapper = document.getElementById(`userlist`) var url = 'http://127.0.0.1:8000/userapi/' fetch(url) .then((resp) => resp.json()) .then(function(data){ console.log('Data:', data) var list = data for (var i in list){ var item = ` <div id="data-row-${i}"> ${list[i].logs} </div> ` wrapper.innerHTML += item } }) } -
Online registration form with Django/Python
I need to create an online registration form. with the possibility of recording at your leisure, (with an interval of 1 hour), for example, recording at 12, then automatically close the possibility (selection) of recording from 12:00 to 13:00. at the same time, it is necessary to give the opportunity to sign up only for free hours. Please, recommend how to implement this problem in Django/Python -
Watail is not showing features for RichTextField in wagtail admin page edit form
wagtail RichTextField is not showing the features I gave (bold, italic, etc..) on the wagtail admin page edit. How can I add that? am I missing something? I also tried with admin.FieldPnale("banner_subtitle") which also did not work for me. HomePage class HomePage(Page): template = "home/home_page.html" banner_title = models.CharField(max_length=100, blank=False, null=True) max_count = 1 banner_subtitle = RichTextField(features=['bold', 'italic']) banner_image = models.ForeignKey( to="wagtailimages.Image", null=True, blank=False, on_delete=models.SET_NULL, related_name="+" ) banner_cta = models.ForeignKey( to="wagtailcore.Page", null=True, blank=True, on_delete=models.SET_NULL, related_name="+" ) content_panels = Page.content_panels + [ FieldPanel("banner_title"), FieldPanel("banner_subtitle"), ImageChooserPanel("banner_image"), PageChooserPanel("banner_cta"), ] pip freeze output anyascii==0.3.1 asgiref==3.5.2 beautifulsoup4==4.11.1 certifi==2022.9.14 charset-normalizer==2.1.1 Django==4.1.1 django-filter==22.1 django-modelcluster==6.0 django-permissionedforms==0.1 django-taggit==3.0.0 django-treebeard==4.5.1 djangorestframework==3.14.0 draftjs-exporter==2.1.7 et-xmlfile==1.1.0 html5lib==1.1 idna==3.4 l18n==2021.3 openpyxl==3.0.10 Pillow==9.2.0 pytz==2022.2.1 requests==2.28.1 six==1.16.0 soupsieve==2.3.2.post1 sqlparse==0.4.2 tablib==3.2.1 telepath==0.3 urllib3==1.26.12 wagtail==4.0.1 webencodings==0.5.1 Willow==1.4.1 xlrd==2.0.1 XlsxWriter==3.0.3 xlwt==1.3.0 wagtail admin edit page -
Django Amazon Ses E-mail address is not verified
i'm a django developer, I'm doing a project but I have a problem I have a recording section in my project that works when an approved user tries for an amazon ses account, but I get errors when unapproved users register how can I solve this https://prnt.sc/m0lZBh9Xtpo5 -
How to make user specific forms?
So I want to make it so a "Tutor" can select a "Student", now each tutor has a different set of Students so the drop down list needs to be unique. So this is the part of forms where question comes from, tutor1 get's passed through by response into views, then from views it needs to be passed into the form so Students.objects.all displays all of the students that tutor1 has. (The query set part is fine and I believe the Field is also correct) the part that doesn't work is passing in response or passing in the tutor1 into the form and so far I can't find anywhere how to do this. student = forms.ModelChoiceField(queryset = Students.objects.all(tutor=tutor1.id)) This is the last piece of the hard part of my website so I'd be so grateful if anyone knows how to fix this. -
how can I save docker's database data locally on my server?
I'm running an app inside a docker container. That app uses docker Postgres image to save data in a database. I need to keep a local copy of this database's data to avoid losing data if the container is removed or purged somehow ..so I am using volumes inside my `docker-compose.YAML file,, but still the local DB folder is always empty .. so whenever I move the container or purge it the data are lost docker-compose.yaml version: "2" services: db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data ports: - '5433:5432' restart: always command: -p 5433 environment: - POSTGRES_DB=mydata - POSTGRES_USER=mydata - POSTGRES_PASSWORD=mydata@ - PGDATA=/tmp django-apache2: build: . container_name: rolla_django restart: always environment: - POSTGRES_DB=mydata - POSTGRES_USER=mydata - POSTGRES_PASSWORD=mydata@ - PGDATA=/tmp ports: - '4002:80' - '4003:443' volumes: - ./www/:/var/www/html - ./www/demo_app/static_files:/var/www/html/demo_app/static_files - ./www/demo_app/media:/var/www/html/demo_app/media # command: sh -c 'python manage.py migrate && python manage.py loaddata db_backkup.json && apache2ctl -D FOREGROUND' command: sh -c 'wait-for-it db:5433 -- python manage.py migrate && apache2ctl -D FOREGROUND' depends_on: - db as you can see i used ./data/db:/var/lib/postgresql/data , but locally the ./data/db directory is always empty !! -
Why this Javascript code is not working. Jquery already added in inter file. HTML and Javascript code below here. Django Project, Tailwind CSS
/** JavaScript Code **/ $(".changeQuantity").click(function (e) { e.preventDefault(); var product_id = $(this).closest(".product_data").find(".prod_id").val(); var product_qty = $(this).closest(".product_data").find(".qty_input").val(); var token = $('input[name="csrfmiddlewaretoken"]').val(); $.ajax({ method: "POST", url: "/update-cart", data: { product_id: product_id, product_qty: product_qty, csrfmiddlewaretoken: token, }, success: function (response) { console.log(response); alertify.success(response.status); }, }); }); /- ---"HTML CODE"--/ <span class="flex flex-row h-10 w-32 rounded-lg relative bg-transparent mt-1"> <button data-action="decrement" class=" changeQuantity text-gray-600 bg-gray-300 hover:text-gray-700 hover:bg-gray-400 h-full w-20 rounded-l cursor-pointer outline-none"> <span class="m-auto text-2xl font-thin">−</span> </button> <input type="text" class=" qty_input focus:outline-none text-center w-full font-semibold text-md md:text-basecursor-default flex items-center outline-none" name="custom-input-number" value="{{ item.product_qty }}"></input> <button data-action="increment" class=" changeQuantity bg-gray-300 text-gray-600 hover:text-gray-700 hover:bg-gray-400 h-full w-20 rounded-r cursor-pointer"> <span class="m-auto text-2xl font-thin">+</span> </button> </span> -
Want to download the file which was recently uploaded by user in django?
This is my models.py from django.db import models import os # Create your models here. class Fileupload(models.Model): file=models.FileField( upload_to='media') date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.file def filename(self): return os.path.basename(self.file.name) This is my Views.py from msilib.schema import File from urllib import response from django.shortcuts import render,HttpResponse from .models import Fileupload from .encryptfile import encrypt # import required module import os from cryptography.fernet import Fernet # Django file encrytion process from https://pypi.org/project/django-encrypted-files/ # Import mimetypes module import mimetypes # def index(request): # return render(request, 'index.html') def base(request): if request.method == 'POST': file2 =request.FILES["file"] # name = request.FILES["file"].name # path = "media/"+name document = Fileupload.objects.create(file=file2) document.save() fname = Fileupload.filename(document) global path1 path1 ="media/"+fname # print(fname) #encrypting the uploaded file which is file2 # opening the key key = Fernet.generate_key() with open("thekey.key","wb") as thekey: thekey.write(key) # opening the original file to encrypt with open(path1, 'rb') as file: original = file2.read() # encrypting the file encrypted = Fernet(key).encrypt(original) # opening the file in write mode and # writing the encrypted data with open(path1, 'wb') as encrypted_file: encrypted_file.write(encrypted) return render(request,'download.html') else: return render(request, 'base.html') def download(request): # Define Django project base directory BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Define text file name # filename = Fileupload.filename() # … -
create tables according to the multiple schema from django model
How to create tables according to the multiple schema on a postgresql from model. However , I am not familiar with django. Can anyone point me in the right direction ? -
Resolving names of all Django related models when exporting a table to a text file (csv)
I have a simple Django (4.1/Python3.9) table with textual and numerical fields. In this table, four of these are ForeignKeys: 1 is referencing itself 1 is referencing an other table through a OneToMany relationship (aka simple ForeignKey) 2 are referencing 2 other tables through a ManyToMany relationship Django is kind enough, when using the model._meta.get_fields() method, to retrieve all related fields along with the usual fields of the model. And that's what I want. Within the admin page of that model, I can see all these related fields as "resolved", e.g. their name is displayed instead of their ids, this is because of the usual __str__(self) method we can use in the model classes: from django.db import models class Foo(models.Model): name = model.CharFields( max_length=100, unique=True, verbose_name="Foo name" ) # here are some other usual data fields self_relation = models.ForeignKey( "self", on_delete=models.CASCADE, null=True, blank=True ) bar = models.ForeignKey( "Bar", on_delete=models.CASCADE, null=True, blank=True ) baz = models.ManyToManyField(Baz) qux = models.ManyToManyField(Qux) def __str__(self): return self.name class Bar(models.Model): name = model.CharFields( max_length=100, unique=True, verbose_name="Bar name" ) # ... def __str__(self): return self.name class Baz(models.Model): name = model.CharFields( max_length=100, unique=True, verbose_name="Baz name" ) # ... def __str__(self): return self.name class Qux(models.Model): name = model.CharFields( max_length=100, … -
Why do I get AttributeError: 'NoneType' object has no attribute 'email'
I am trying to verify otp. The table in db for otp contains email and otp_no. I am getting the expected outcome if the otp provided by the user is correct but get "AttributeError: 'NoneType' object has no attribute 'email'" if the otp is wrong. Following is the code: @api_view(['POST']) def verifyOtp(request): email = request.data.get('email') otp_no = request.data.get('otp_no') res = dict() if email!= None and otp_no!= None: result = Otp.objects.filter(email=email, otp_no = otp_no).first() if len(result.email)> 0: res['isOtpVerified'] = True if otp_no == result.otp_no else False return JsonResponse(res) else: res['emailExist'] = False return JsonResponse(res) what am I missing in the code? -
Staticfiles not loading on Django
My static files are not loading on Django. I'm running this on my local machine. The location of example.png is main/static/main/example.png. main is an app. Here's my settings.py: """ Django settings for tutorials project. Generated by 'django-admin startproject' using Django 4.1.1. For more information on this file, see https://docs.djangoproject.com/en/4.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.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/4.1/howto/deployment/checklist/ # 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', ] 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 = 'tutorials.urls' TEMPLATE_DIR = os.path.join(BASE_DIR,'templates') TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_DIR, ], '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 = 'tutorials.wsgi.application' # Database # https://docs.djangoproject.com/en/4.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/4.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': … -
Comparing and updating two lists containing dictionaries with unique keys in Python
I have two lists, both contain dictionaries.I want to compare list_1 with list_2, If any values changes in the list_1 according to list_2 we can update that values to list_2. While comparing both lists, if new dictionary is found on list_1 we can add that dict to list_2. While comparing both lists, if a dict is missing in list_1 according to list_2, we can delete that dict from list_2 also. list_1 list_1 = [{'unique_id': 'ABC001', 'key_1': 'Apple_New', 'price': 100.00}, {'unique_id': 'ABC003', 'key_3': 'Grapes', 'price': 80.00] list_2 list_2 = [{'unique_id': 'ABC001', 'key_1': 'Apple', 'price': 80.00}, {'unique_id': 'ABC002', 'key_2': 'Orange', 'price': 70.00}] Expected Result list_2 = [{'unique_id': 'ABC001', 'key_1': 'Apple_New', 'price': 100.00}, {'unique_id': 'ABC003', 'key_3': 'Grapes', 'price': 80.00}] -
Django real time variable assignment and get value from real time variable?
I have database table which have parameter name. I am getting parameter names and assigning it as input box like this. Everything is real time. Number of parameters are changing at every radio button. Now i want to get values of input box when user submit form.enter image description here enter image description here enter image description here enter image description here -
how to send email using djnago
I have a situation where using API android app will POST the user Data to my django website and a entry is created in my backend .I want to send email to the user after the entry has been created in django. I have created a indicator which will get true when Data is POST. ANy suggestion how to use that indicator for sending email to every new entry created . -
Even After Deleting the migrations in django, old app name shows up?
The login_user app, was never created for this project. And when I run makemigrations for, I get the following error ValueError: The field admin.LogEntry.user was declared with a lazy reference to 'login_user.user', but app 'login_user' isn't installed. Full stacktrace to migrate command (skincurate) ➜ python manage.py migrate admin /home/sshivaditya/Projects/Updated_code_3/Skincurate_Research Operations to perform: Apply all migrations: admin Running migrations: Applying admin.0004_auto_20220825_1517...Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/sshivaditya/miniconda3/envs/skincurate/lib/python3.8/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/sshivaditya/miniconda3/envs/skincurate/lib/python3.8/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/sshivaditya/miniconda3/envs/skincurate/lib/python3.8/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/home/sshivaditya/miniconda3/envs/skincurate/lib/python3.8/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/home/sshivaditya/miniconda3/envs/skincurate/lib/python3.8/site-packages/django/core/management/base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "/home/sshivaditya/miniconda3/envs/skincurate/lib/python3.8/site-packages/django/core/management/commands/migrate.py", line 232, in handle post_migrate_state = executor.migrate( File "/home/sshivaditya/miniconda3/envs/skincurate/lib/python3.8/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 "/home/sshivaditya/miniconda3/envs/skincurate/lib/python3.8/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 "/home/sshivaditya/miniconda3/envs/skincurate/lib/python3.8/site-packages/django/db/migrations/executor.py", line 245, in apply_migration state = migration.apply(state, schema_editor) File "/home/sshivaditya/miniconda3/envs/skincurate/lib/python3.8/site-packages/django/db/migrations/migration.py", line 124, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/home/sshivaditya/miniconda3/envs/skincurate/lib/python3.8/site-packages/django/db/migrations/operations/fields.py", line 249, in database_forwards schema_editor.alter_field(from_model, from_field, to_field) File "/home/sshivaditya/miniconda3/envs/skincurate/lib/python3.8/site-packages/django/db/backends/sqlite3/schema.py", line 137, in alter_field super().alter_field(model, old_field, new_field, strict=strict) File "/home/sshivaditya/miniconda3/envs/skincurate/lib/python3.8/site-packages/django/db/backends/base/schema.py", line 507, in alter_field new_db_params … -
How to make a triple sub-layers Choicefiled in Django?
I noticed that the official document has mentioned two-layer choiceFiled only. When I code a three-layer data structure, a notification pops out. (fields.E005) 'choices' must be an iterable containing (actual value, human readable name) tuples. .e.g.: choices=( ("city", ( ("USA", "USA"), ("Canada", "Canada"), ("UK", ( ("England": "England",) ("Scotland": "Scotland"), )), )), ), Can you give me an example how to customer a widget to address this job? -
How to get innerhtml of dragged element on button onclick?
Basically I have created a drag and drop html template with javascript,what I want is get the inner html of dragged element in button onclick('') automatically to run a function, means what ever is dragged add name of element in button onclick(''). please help me with this.. <button class="btn btn-primary pull-right" id="show_graph">SHOW</button> JavaScript code $('.drag').draggable({ appendTo: 'body', helper: 'clone' }); $('#dropzone').droppable({ activeClass: 'active', hoverClass: 'hover', accept: ":not(.ui-sortable-helper)", drop: function (e, ui) { var $el = $('<div class="drop-item"><details><summary>' + ui.draggable.text() + '</summary><div><label>More Data</label><input type="text" /></div></details></div>'); $el.append($('<button type="button" class="btn btn-default btn-xs remove"><span class="fa-solid fa-trash text-white "></span></button>').click(function () { $(this).parent().detach(); })); $(this).append($el); } }).sortable({ items: '.drop-item', sort: function () { $(this).removeClass("active"); } }); Here is for loop used with help of Django and these are the draggable elements. {% for item in head %} <div class="col-12"> <a class="border border-light btn att1 btn-default drag text-white my-2">{{item}}</a> </div> {% endfor %} -
Django model.objects.get() isn't looking by param that I specify
I'm trying to get object from db. That's my model: class Employee(models.Model): class EmployeeRole(models.TextChoices): DEFAULT = 'Default' PM = 'PM' ADMINISTRATOR = 'Administrator' name = models.CharField(max_length=127, blank=False, null=False) surname = models.CharField(max_length=127, blank=False, null=False) login = models.CharField(max_length=127, blank=False, null=False) password = models.CharField(max_length=1023, blank=False, null=False) email = models.EmailField() employee_role = models.CharField(max_length=31, choices=EmployeeRole.choices, blank=False, null=False) salary = models.DecimalField(max_digits=10, decimal_places=2) department = models.ForeignKey(Department, on_delete=models.SET_NULL, null=True, blank=True) last_login_date = models.DateField(auto_now=True) created_date = models.DateField(auto_now_add=True) def __str__(self): return f"{self.name} {self.surname} - {self.employee_role}" That's my urls: urlpatterns = [ path('employees/<int:pk>', views.employee_details), path('employees/', views.employee_list_or_add), ] And that's my views: @csrf_exempt def employee_list_or_add(request): if request.method == 'GET': employees = Employee.objects.get(id=4) serializer = EmployeeSerializer(employees) print(serializer) return JsonResponse(serializer.data, safe=False) elif request.method == 'POST': data = JSONParser().parse(request) serializer = EmployeeSerializer(data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status=400) I'm learning with REST documentation, I'm on first chapter - serialization. But I can't get any objects from db. No matter if I use Employee.objects.all() (with many=True in serializer) like in documentation or Employee.objects.get(pk=4) like currently in my code - I'm always getting error invalid literal for int() with base 10: b'17 21:19:04.767380' That's the time of last_login_date of first record in Employee db. But in .get() function I specified 'pk' so why it's … -
Accessing a parent model attribute within Django template
I have an app that has a list of projects, and each project has a number of posts, and when you click on a project, it shows all of the posts in that project, but I can't figure out how to make it display what project the user is currently on, sample of it not working It should say "Posts for project 1" for example. Here is the relevant code of what I have so far. <h1 class="mb-3">Posts for {{ post.project.title }}</h1> {% for post in posts %} <article class="media content-section"> <img class="rounded-circle article-img" src="{{ post.author.profile.image.url }}"> <div class="media-body"> <div class="article-metadata"> <a class="mr-2">{{ post.author }}</a> <small class="text-muted">{{ post.date_posted|date:"F d, Y" }}</small> </div> <h2><a class="article-title">{{ post.title }}</a></h2> <p class="article-content">{{ post.description }}</p> </div> </article> {% endfor %} class Project(models.Model): title = models.CharField(max_length=100) description = models.TextField(default='') date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('project-detail', kwargs = {'pk': self.pk}) class Post(models.Model): def get_default_action_status(): return Project.objects.get(title="bruh") project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name='posts', default=get_sentinel_exam_id) title = models.CharField(max_length=100) description = models.TextField(default='') date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) LOW = '!' MED = '!!' HIGH = '!!!' YEAR_IN_SCHOOL_CHOICES = [ (LOW, '!'), (MED, '!!'), (HIGH, '!!!'), ] severity = models.CharField( max_length=3, … -
I need to send mail for more than one member in django
I need to send an email to the users associated to the Shop when a purchase is done in the shop. If two users was associated for two of them also email should go. Note: shop_user is the feild name and it is a many to many feild def generate_invoice(request): if request.user.is_authenticated: billingshop = shop.objects.all() Product = product.objects.all() if request.method == 'POST': form = Invoicing(request.POST) if form.is_valid(): user = form.save(commit=False) Billing_shop = form.cleaned_data['Billing_shop'] Supplier = form.cleaned_data['Supplier'] Payment_mode = form.cleaned_data['Payment_mode'] Upi_transaction_id = form.cleaned_data['Upi_transaction_id'] products = form.cleaned_data['Product'] Quantity = form.cleaned_data['Quantity'] shoping_product = product.objects.filter(Product_name= products).first() sub_total = shoping_product.product_price * Quantity user.Gst = (18 / 100)*sub_total user.Price = sub_total + user.Gst user.save() shoppingcartuser= shop.objects.get(shop_name= Billing_shop) // Match the shop name shoppingcartemails= shoppingcartuser.shop_users.all().values_list('email', flat=True) // Retriving the email address associated with the shopname in the feild name shop_users. date = datetime.today() html_content = render_to_string("invoices/invoice_email.html", {'title':"test mail","date":date,"invoiceuser":Billing_shop,"supplier":Supplier,"payment":Payment_mode,"transactionid":Upi_transaction_id}) text_content = strip_tags(html_content) email = EmailMultiAlternatives( "Congratulations! Invoice generated successfully", text_content, settings.EMAIL_HOST_USER, [shoppingcartemails] // this place is the to email ) email.attach_alternative(html_content,"text/html") email.send() messages.success(request, 'Registration successful.') return redirect('home') else: form = Invoicing() return render(request, 'invoices/create_invoice.html', context={'form': form,'shop':billingshop,'Product':Product}) else: messages.error(request, 'Please login into your account.') return render("login") The feild shop_users consists of two mail addresses and i am facing this … -
Django Testing Using AsyncClient and Authentication
I have a basic Asynchronous Class Based View: class AsyncAuthenticationView(View): async def post(self, request, *args, **kwargs): authenticated: bool = await sync_to_async(lambda: request.user.is_authenticated)() if not authenticated: return HttpResponse('Unauthorized', status=401) return HttpResponse('Success', status=200) And two simple tests: @pytest.fixture def authenticated_async_client(user) -> AsyncClient: client = AsyncClient() client.force_login(user) return client class TestAsyncAuthenticationView: @pytest.mark.asyncio async def test_with_async_client(self, authenticated_async_client: AsyncClient): """This test fails, with response code 401 instead of 200""" response = await authenticated_async_client.post( reverse('auth-test'), 'abc', content_type="text/html", ) assert 200 == response.status_code # fails with 401 @pytest.mark.asyncio async def test_with_async_request_factory(self, async_rf: AsyncRequestFactory, user): """This test succeeds correctly with response code 200""" r = async_rf.post('/fake-url', 'abc', content_type='text/html') r.user = user r.session = {} response = await AsyncAuthenticationView().post(r) assert 200 == response.status_code The first test which uses the AsyncClient always fails to authenticate returning status code 401 while the second test is passing just fine with status code 200. Based on the docs the AsyncClient has all the same methods, so I am not not why the test is failing. Perhaps there is a different authentication method that needs to be used? The AsyncRequestFactory that is being used in the second test is from the pytest-django package. Any help would be much appreciated. Thank you. -
Get user's operating system in Django & Docker
Operating system is always set to Ubuntu even in my localhost. I don't know if this is related to Docker or something else but here is my code. I have a utility function to get user's operating system (I am using httpagentparser) def get_operating_system(request): agent = request.META.get("HTTP_USER_AGENT") operating_system = httpagentparser.detect(agent).get("os").get("name") return operating_system and calling this function in my auth (sign up) view. class SignUp(FormView): form_class = SignUpForm template_name = "project1/registration/signup.html" def form_valid(self, form): user = form.save(commit=False) user.username = form.cleaned_data.get("username") user.operating_system = get_operating_system(self.request) user.save() send_email_confirmation(user, user.email) notifications.info( self.request, _( "some text here" ), ) return redirect("login") and here is my user model ... operating_system = models.CharField(_("operating system of the user"),max_length=150, default=OperatingSystem.WINDOWS) ... class User(AbstractUser): class OperatingSystem(models.TextChoices): UBUNTU = "UBUNTU",_("ubuntu") DEBIAN = "DEBIAN",_("debian") FEDORA = "FEDORA",_("fedora") MINT = "MINT",_("linux mint") WINDOWS = "WINDOWS",_("windows") MACOS = "MACOS",_("macos") ... I am running my project in a Docker in a Ubuntu server and when I sign up to my site, my operating system is always Ubuntu even I am using different operating systems such as Windows and MacOS.