Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django cannot save to to second database
i've tried using multiple database in my django projects, then i create a models with foreign key to User, it can't save to second database this is the UserData models class UserData(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='user', related_query_name='user') is_controller = models.BooleanField(default=False) phone_number = models.CharField(max_length=255, blank=True, null=True) then in views instance = UserData( user=request.user, nim=nim, phone_number=phone ) after that, i save the instance >>> instance.save() #it works on default database (sqlite) >>> instance.save(using='db_alias') # return an error the error said it was cannot add or update child row because of the foreign key (1452, 'Cannot add or update a child row: a foreign key constraint fails (labs.presence_userdata, CONSTRAINT presence_userdata_user_id_4b3dfc56_fk_auth_user_id FOREIGN KEY (user_id) REFERENCES auth_user (id))') can anyone help me solve this problem -
Django, create table or page just to join all other tables into one and show it. is it possible?
I want to show info from different tables together in another page or table. But I don't want create another table with duplicate info. Is it possible to Join many tables and show in some admin page? -
How to get value of a nested serializer field from its parent serializer class?
Consider the followings two serializers: class SerializerA(BaseSerializer): field_1 = serializers.IntegerField() field_2 = SerializerB() class SerializerB(BaseSerializer): field_3 = serializers.IntegerField() The input JSON for SerializerB will not contain field_3 and it has to obtained from field_1 of SerializerA. I have tried this class SerializerB(BaseSerializer): field_3 = serializers.IntegerField() def __init__(self, instance=None, data=empty, **kwargs): if data is not empty and isinstance(data, dict): _data = data.copy() _data['field_3'] = self.parent.initial_data.get('field_1') super(SerializerB, self).__init__(instance, _data, **kwargs) super(SerializerB, self).__init__(instance, data, **kwargs) But it is not working as data is always empty and it never passes the if statement. -
The admin isn't submitting data in django
I have written this code using django: in models.py(in the app): class Feature2(models.Model): name = models.CharField(max_length=100) detail = models.CharField(max_length=500) in URLs.py(in the app) urlpatterns = [ path('2', views.index, name='index2'), ] in admin.py(in the app): 'admin.site.register(Feature2)' in app's templates (index2.html): <div class="row icon-boxes"> {% for feature in xfeatures %} <div class="col-md-6 col-lg-3 d-flex align-items-stretch mb-5 mb-lg-0" data-aos="zoom-in" data-aos-delay="200"> <div class="icon-box"> <div class="icon"><i class="ri-stack-line"></i></div> <h4 class="title"><a href="">{{feature.name}}</a></h4> <p class="description">{{feature.details}}</p> </div> </div> {%endfor%} </div> </div> in views.py (in app): def index2 (request): xfeatures = Feature2.objects.all() return render(request,'myapp/index2.html', {'xfeatures': xfeatures}) in urls.py in project: urlpatterns = [ path('admin/', admin.site.urls), path('myapp/', include("myapp.urls")) ] when I run admin in the browser and enter data in features2 this appears to me: in this photo so what is wrong in my code? -
Django template filter remove image
My Problem I was making posts and postdetail page using summernotes. I using summetnote made 2 pictures and sentences I use truncatechars_html:100|safe I want to image remove in the post page I want to show photos uploaded to summernote only when I go to postdetail. post.html content code without using safe I just want the image to be invisible <div style="text-align: center;">Make post and two image</div> <div style="text-align: center;"><br></div><div style="text-align: center;">wdljawlkdjkawd</div> <div style="text-align: center;"><img src="/media/django-summernote/2022-08-06/31910af9-4366-48ad-aae1-8fc523d87181.jpg" style="width: 698.011px;"><br></div> <div style="text-align: center;"><img src="/media/django-summernote/2022-08-06/3c7f7804-a5d7-4cd3-b69b-bea66fd6b121.png" style="width: 698.011px;"><br></div> post.html <div class="container mt-5"> <div class="row"> <div class="col-lg-12"> <!-- Post content--> <article> <!-- Post header--> {% for post in Post_list %} <header class="mb-4"> <!-- Post title--> <h1 class="fw-bolder mb-1"><a href="{% url 'post_detail' post.id %}"> {{ post.title }}</a></h1> <!-- Post meta content--> <div class="text-muted fst-italic mb-2">{{ post.create_time }}</div> </header> <section class="mb-5"> <p class="fs-5 mb-4">{{ post.content|truncatechars_html:100|safe }}</p> </section> {% endfor %} </article> </div> </div> </div> post_detail.html <div class="container mt-5"> <div class="row"> <div class="col-lg-12"> <!-- Post content--> <article> <!-- Post header--> <header class="mb-4"> <!-- Post title--> <h1 class="fw-bolder mb-1"><a href=""> {{ post.title }}</a></h1> <!-- Post meta content--> <div class="text-muted fst-italic mb-2">{{ post.create_time }}</div> </header> <section class="mb-5"> <p class="fs-5 mb-4">{{ post.content|safe }}</p> </section> </article> </div> </div> </div> -
python manage.py migrate: ValueError: too many values to unpack (expected 2)
i just create django project and run python manage.py migrate and receive this error ValueError: too many values to unpack (expected 2) ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀ python 3.10⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀ django 4.1 -
Shoud I must delare global in python when i change list in function?
This is my code. my_list = [{"id": 1, "data": "Python"}, {"id": 2, "data": "Code"}, {"id": 3, "data": "Learn"}] def this(): for index in range(len(my_list)): if my_list[index]["id"] == 2: del my_list[index] break this() print(my_list) >>> [{'id': 1, 'data': 'Python'}, {'id': 3, 'data': 'Learn'}] I can see that my_list[1] has removed. But I have a problem. I don't declare global my_list , but why I can change a list outside of function in function? -
django.db.utils.IntegrityError: NOT NULL constraint failed: user.id
I don't know why the error is caused even though I designated the author. I'd appreciate your help. model & form class SuperTitle(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='debate_author') super_title = models.CharField(max_length=100) liker = models.ManyToManyField(User, related_name='debate_liker') def __str__(self): return self.super_title class SuptitForm(forms.ModelForm): class Meta: model = SuperTitle fields = ['super_title'] views.py def create(request): ... dic = {'super_title' : request.POST.get('sup_title')} sup_form = SuptitForm(dic) if sup_form.is_valid(): sup_form.author = request.user sup_form.super_title = ... sup_form.save() ... return IntegrityError at /polls/debate/create/ NOT NULL constraint failed: polls_supertitle.author_id -
How to apply lookups in django filter query according to conditions?
I want to make a query where i can apply lookups only when some conditions satisfy. e.g A customer can pick only that food from stall for which he paid for class Customer(models.Model): food_type = models.CharField() fruit_id = models.ForeignKey(Fruit, null=True) vegetable_id = models.ForeignKey(Vegetable, null=True) is_paid = models.BooleanField() class Food(models.Model): fruit_id = models.ForeignKey(Fruit, null=True) vegetable_id = models.ForeignKey(Vegetable, null=True) So i need to do something like: q = Food.objects.all() if Customer.objects.filter(id=(id of customer), food_type='fruit', is_paid=True).exists(): q = q.filter(fruit_id__in=Customer.objects.filter(id=(id of customer), food_type='fruit', is_paid=True).values_list('fruit_id', flat=True)) if Customer.objects.filter(id=(id of customer), food_type='vegetable', is_paid=True).exists(): q = q.filter(vegetable_id__in=Customer.objects.filter(id=(id of customer), food_type='vegetable', is_paid=True).values_list('vegetable_id', flat=True)) How can i optimize this as this is a small example, in my case there are many more conditions. I want to reduce the number of times it is hitting the database. Also is there any way i can use conditional expressions here? e.g When() Any help will be appreciated. -
ModuleNotFoundError: No module named 'html.entities'; 'html' is not a package
Newbie coder here. So im trying to pipenv install django but i keep getting this error : $ pipenv install django Creating a virtualenv for this project... Pipfile: C:\Users\wesleyromero308\Desktop\Pipfile Using C:/Users/wesleyromero308/AppData/Local/Programs/Python/Python38/python.exe (3.8.0) to create virtualenv... [= ] Creating virtual environment...ModuleNotFoundError: No module named 'html.entities'; 'html' is not a package Failed creating virtual environment [pipenv.exceptions.VirtualenvCreationException]: 2022-08-06 01:08:46.004 ERROR root: ModuleNotFoundError: No module named 'html.entities'; 'html' is not a package Failed to create virtual environment. I then went and did pip install htmlentities and it was successful. Then i did pip install html and got this error: $ pip install html Collecting html Using cached html-1.16.tar.gz (7.6 kB) Preparing metadata (setup.py): started Preparing metadata (setup.py): finished with status 'error' error: subprocess-exited-with-error python setup.py egg_ifo did not run successfully. exit code: 1 [1 lines of output] ERROR: Can not execute `setup.py` since setuptools is not available in the build environment. [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: metadata-generation-failed Encountered error while generating package metadata. See above for output. Please help, i just want to install django lol i been stuck for days now -
Fail to enable Smartsheet webhook (502 Bad Gateway)
Django: 4.0.6 Smartsheet Python SDK: 2.105.1 Ngrok: 3.0.6 I have a Django server running on localhost, forwarded my localhost through Ngrok, have setup a callback route for accepting/responding to the Smartsheet-Hook-Challenge, and created a webhook instance using Python SDK. However, when I try to enable my webhook by running the following (documented here): Webhook = smartsheet_client.Webhooks.update_webhook(webhook_id,smartsheet_client.models.Webhook({'enabled': True})) Ngrok immediately returns 502 bad gateway, and my webhook instance's disabledDetails attribute becomes Request returned HTTP status code 502 (ref id: wtegm9). And I have no clue what's the cause of this 502. PS: While I'm writing this question, I was able to successfully enable my webhook using cURL command, so I can go ahead and start working. But enabling the same webhook instance with update_webhook python method still gives 502. Since updating webhook with cURL worked, could it be a bug in the Python SDK method itself? -
DRF - The serializer field might be named incorrectly and not match any attribute or key on the `str` instance
I'm trying to save my update serialize. The predict field is changed to the value predicted by Inference code(Image Classfication model). But I get the error: AttributeError at /predict/product/1/ Got AttributeError when attempting to get a value for field image on serializer ProductSerializer. The serializer field might be named incorrectly and not match any attribute or key on the str instance. Original exception text was: 'str' object has no attribute 'image'. AttributeError at /predict/product/1/ Got AttributeError when attempting to get a value for field image on serializer ProductSerializer. The serializer field might be named incorrectly and not match any attribute or key on the str instance. Original exception text was: 'str' object has no attribute 'image'. I checked migrations. Views.py from django.shortcuts import render from rest_framework.response import Response from .models import Product from rest_framework.views import APIView from .serializers import ProductSerializer from django.http import Http404 from rest_framework import status, viewsets #from .inference_code import predict from .apps import ProductConfig import json class ProductListAPI(viewsets.ViewSet): serializer_class = ProductSerializer queryset = Product.objects.all() def get(self, request): queryset = Product.objects.all() print(queryset) serializer = ProductSerializer(queryset, many=True) return Response(serializer.data) def post(self,requset): serializer= ProductSerializer( data=requset.data) return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST) class ProductPredictAPI(APIView): def get_object(self, pk): try: return Product.objects.get(pk=pk) except Product.DoesNotExist: raise Http404 def … -
Django pull list of all users, but shows list of multiple users with only current users credentials
In Django, I am trying to get a list of all users. I use the following query: users = User.objects.all().order_by('id') I am able to get a list of all the users, but it outputs a list of all users, but only showing the current users credentials? If I have 20 users, it will show 20 users but only the information for the currently logged in user. For example, I want to see a table like: User | Email ------------ User1 | user1@test.com User2 | user2@test.com User3 | user3@test.com But if the current user that is logged in is User1, It shows: User | Email ------------ User1 | user1@test.com User1 | user1@test.com User1 | user1@test.com Or if User2 is logged in, it shows: User | Email ------------ User2 | user2@test.com User2 | user2@test.com User2 | user2@test.com Here is my view.py: def portal_users(request): users = User.objects.all().order_by('id') return render(request, 'portal/users.html', {"users": users}) templates {% for users in users %} <tr> <td>{{user.username}}</td> <td>{{user.email}}</td> </tr> {% endfor %} -
Django.db.models.field.CharField
I have a Django project that I'm trying to cobble together for a very basic survey that needs to be entered for demographic information. I've dummied up some data through the admin site in order to get my ListView working for the time being. Unfortunately I'm getting a strange response. I built the models.py to be a drop down of a full spelled out and then to keep it small, I've made the actual storage in the db 1-3 characters. When I get my list view, one that uses 1 character to store for gender presents as (<django.db.models.fields.CharField>,), I would like for it to present as as the larger name of "Male", "Female", "Non-binary". However for my race and ethnicity fields which are 2 & 3 characters, those are returning as the actual storage for the DB (i.e, 'AA', 'NHP'). I'm more comfortable with SQL, so I'm not opposes to adding a table for a key as there would only be 11 entries for now, but its possible that more things could be added down the line. models.py: from django.db import models from django.contrib import admin from django.contrib.auth.models import User # Create your models here. class StuData(models.Model): id_num = models.IntegerField(primary_key=True) … -
How to get the pid of a subprocess created by Process?
So i am trying to get the pid of a subprocess running inside celery worker. The problem is that the process is blocking and when i print os.getpid() inside the subprocess i am getting the pid of the worker. I am developing a monitoring project for training nlp model using farm-haystack and celery. p = Process(target=Reader_Training()) p.start() -
How does work import in python project (django) or issue with import models from tests in django project
I have an issue with import models from tests in django project. That is structure of my project: D:\learn_django\mysite | db.sqlite3 | manage.py | test.txt | tree.txt | +---catalog | | admin.py | | apps.py | | forms.py | | models.py | | urls.py | | views.py | | __init__.py | | | +---tests | | | test_forms.py | | | test_models.py | | | test_views.py | | | __init__.py | | | | | \---__pycache__ | | test_forms.cpython-39.pyc | | test_models.cpython-39.pyc | | test_views.cpython-39.pyc | | __init__.cpython-39.pyc | | And test_models.py file (which have problem with improt) look like: from catalog.models import Author from django.test import TestCase class AuthorModelTest(TestCase): @classmethod def setUpTestData(cls): # Set up non-modified objects used by all test methods Author.objects.create(first_name='Big', last_name='Bob') def test_first_name_label(self): author = Author.objects.get(id=1) field_label = author._meta.get_field('first_name').verbose_name self.assertEquals(field_label, 'first name') If I wirte import like this: from ..models import Author It will be work. But if I write import like says in mozilla lesson: from catalog.models import Author Pycharm report errors: Unresolved reference 'catalog' If I try import by absolute path: from mysite.catalog.models import Author Test fails with error: ModuleNotFoundError: No module named 'mysite.settings' Here you can clone my project - https://gitlab.com/Galoperidol/learn_django3 So my … -
What is the best approach of using django and ajax?
I'm now working on my first big project and can't understand how to use Django with ajax. On my website there are several services which works separately and are written on javascript, but soemtimes I have to send some information to the server. Also I have custom admin interface which contains of different changing database operations. All these actions should be done without reloading the page (using ajax post and get requests). So, I think I have two ways of doing it: Using ajax and classic Django views for each operation. Using ajax and integrated into my website Django REST Framework API methods. The stumbling block is that I wouldn't use this API methods from any other types of clients, just call them from users' browsers via ajax. What is the best approach in my situation? It seems to me that the second way is more "serious", but I don't have much experience of making projects like this and can't speak directly. -
How Can I Get A Dictionary Value From Python?
I was trying to convert a look up today to a data dictionary...for performance reasons... It's almost working...Except that it's duplicating the entries on my output... Here is my code in question... class Calendar(HTMLCalendar): def __init__(self, year=None, month=None, user=None): self.user = user self.year = year self.month = month super(Calendar, self).__init__() # formats a day as a td # filter events by day def formatday(self, day, requests): requests_per_day = DailyPlannerRequest.objects.filter(Q(created_by=self.user)).distinct().order_by('start_time') daily_planner_events1 = [] for requests in requests_per_day: requests_per_day_dict = model_to_dict(requests) daily_planner_events1.append(requests_per_day_dict) daily_planner_events1 = dict() events = add_event_dates(requests_per_day) all_event_dates = [] for event in events: for date in event.dates: if date not in all_event_dates and date.month == self.month and date.year == self.year: all_event_dates.append(date) for event in events: for date in event.dates: if date in all_event_dates and date not in daily_planner_events1 and date.month == self.month and date.year == self.year: daily_planner_events1[date] = [event] else: if date.month == self.month and date.year == self.year: daily_planner_events1[date].append(event) # daily_planner_events[date].append(events) d = '' for requests in requests_per_day: for event in daily_planner_events1: if event.day == day: d += f'<li> {requests.get_html_url} </li>' if day != 0: return f"<td><span class='date'>{day}</span><ul> {d} </ul></td>" return '<td></td>' The code above works...Except it's giving me incorrect output...The problem piece in particular is this... for requests in … -
project() missing 1 required positional argument: 'pk'
am confuse right now...i want to pass in a key value but i kept on getting error my code urls from django.urls import URLPattern, path from . import views urlpatterns = [ path('', views.projects, name="projects"), path('project/', views.project, name="project"), ] and the function i created def project(request, pk): projectObj = None for i in projectslist: if i['id'] == pk: projectObj = i return render(request, 'projects/single-project.html', {'project': projectObj}) -
error: no such column: blog_marketreview.name even when i have a field named name
i get the error no such column: blog_marketreview.name even when i clearly have a field named name in my app blog and model marketreview. I HAVE done makemigrations and migrate but the error persists. here is my models.py class MarketReview(models.Model): post = models.ForeignKey(MarketPost, related_name="mreviews", on_delete=models.CASCADE) name = models.CharField(max_length=255) body = models.TextField() date_added = models.DateTimeField(auto_now_add=True) rate = models.PositiveSmallIntegerField(choices=RATE_CHOICES) def __str__(self): return '%s - %s' % (self.post.title, self.name) here is the marketpost model that i connect to using foreignkey: class MarketPost(models.Model): title = models.CharField(max_length=100) price = models.DecimalField(default=0, max_digits=9, decimal_places=2) post_image = models.ImageField(null=True, blank=False, upload_to='marketplace_images/') content = models.TextField() #content = RichTextField(blank=True, null=True) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title + ' | ' + str(self.author) def get_absolute_url(self): return reverse('marketplace-detail', args=(str(self.id))) and here the template that had an error during rendering: <hr> 27 <br><br> 28 29 {% if not post.mreviews.all %} 30 <h4>No reviews yet... Be the first one!</h4> 31 <a href="{% url 'add-marketreview' post.pk %}">Add a Review</a> 32 33 {% else %} 34 <a href="{% url 'add-marketreview' post.pk %}">Add a Review</a> 35 <br><br> 36 **{% for review in post.mreviews.all %} this line is in red** 37 <h4>{{ user.name }}</h4> 38 <b>{{ review.name }} - {{ review.date_added }}</b> 39 <br> … -
handling courses with multiple languages in database design
I have to handle courses available in multiple languages, and also keep track of the user progress for each language available class Language(models.Model): code = models.CharField(primary_key = True) name = models.CharField() class TextContent(models.Model): textId = models.UUIDField(default = uuid4, primary_key = True,editable = False) language = models.OneToOneField(Language) class OriginalText(models.Model): originalText = models.CharFIeld() language = models.ForeignKey(Language) class Product(models.Model): name = models.OneToOneField() title = models.OneToOneField(OriginalText) class Course(models.Model): languages = models.ManyToManyField(Language) class Chapter(models.Model): title = models.OneToOneField(OriginalText) ........... class Lesson(models.Model): title = models.OneToOneField(OrigianlText) class LessonContent(models.Model): lesson = models.ForeignKey(Lesson) language = models.ForeignKey(Language) textContent = models.TextField() videoContent = models.FielField() class CourseEnrollment(models.Model): course = models.ForeignKey(Course) user = models.ForeignKey(User) in LessonContent class I have textContent and videoContent fields that's because the lesson could be a video or simply an article I want to track the user's progress in terms of chapters and video time progress to continue if he got interrupted and specially that each lesson video can be different in length depending on the language, I am still struggling to find a way to achieve this class UserProgress(models.Model): ...... so is my way of handling multiple-language courses right and if anyone can help me with tracking the user progress any help would be really appreciated -
How to set User's password in django with async, or create User
i have telegram bot(aiogram) for django-site registration, and here is problem. Django have a lot of async methods but i didn't find method for setting user password. Main idea here, but with aupdate_or_create i can't set password. Maybe i need use async to sync or something like this. but I'm almost sure that it is easy to solve with async, but I don't know how user, is_created = await User.objects.aupdate_or_create( username=message.from_user.username, email=data['email'], ) await user.set_password(data['password']) user.save() -
django migrate: ValueError: too many values to unpack (expected 2)
i write this model in models.py from django.db import models class Article(models.Model): title = models.CharField(max_length=255) text = models.TextField() pub_date = models.DateField(auto_now_add=True) and i run python manage.py migrate and receive this error Operations to perform: Synchronize unmigrated apps: messages, staticfiles Apply all migrations: admin, auth, contenttypes, news, sessions Synchronizing apps without migrations: Creating tables... Running deferred SQL... Running migrations: Applying auth.0001_initial...Traceback (most recent call last): File "/home/ilya/code/Project1/app/manage.py", line 22, in <module> main() File "/home/ilya/code/Project1/app/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/ilya/code/Project1/venv/lib/python3.10/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/home/ilya/code/Project1/venv/lib/python3.10/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/ilya/code/Project1/venv/lib/python3.10/site-packages/django/core/management/base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "/home/ilya/code/Project1/venv/lib/python3.10/site-packages/django/core/management/base.py", line 448, in execute output = self.handle(*args, **options) File "/home/ilya/code/Project1/venv/lib/python3.10/site-packages/django/core/management/base.py", line 96, in wrapped res = handle_func(*args, **kwargs) File "/home/ilya/code/Project1/venv/lib/python3.10/site-packages/django/core/management/commands/migrate.py", line 349, in handle post_migrate_state = executor.migrate( File "/home/ilya/code/Project1/venv/lib/python3.10/site-packages/django/db/migrations/executor.py", line 135, in migrate state = self._migrate_all_forwards( File "/home/ilya/code/Project1/venv/lib/python3.10/site-packages/django/db/migrations/executor.py", line 167, in _migrate_all_forwards state = self.apply_migration( File "/home/ilya/code/Project1/venv/lib/python3.10/site-packages/django/db/migrations/executor.py", line 249, in apply_migration with self.connection.schema_editor( File "/home/ilya/code/Project1/venv/lib/python3.10/site-packages/django/db/backends/sqlite3/schema.py", line 39, in __exit__ self.connection.check_constraints() File "/home/ilya/code/Project1/venv/lib/python3.10/site-packages/django/db/backends/sqlite3/base.py", line 289, in check_constraints for column_name, ( ValueError: too many values to unpack (expected 2) ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀ ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀ ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀ ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀ ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀ ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀ -
Django EmailMessage how to send html message
Good day,how can I send html when I use django EmailMessage from django.shortcuts import render, HttpResponse from django.core.mail import EmailMessage def send_email(request): msg = EmailMessage( subject='this is the title', body='this is the content', from_email='test@gmail.com', to=['anothertest@yahoo.com'] ) msg.attach_file('t2.xls') msg.send(fail_silently=False) return HttpResponse('OK') I tried html_message but still not work: msg = EmailMessage( subject='this is the title', body='this is the content', from_email='test@gmail.com', to=['anothertest@yahoo.com'] html_message = '<p>this is an automated message</p>' ) Any friend can help ?Thanks! -
Django overridden choices failing validation
I am overriding the choices option defined in the model, which is just a blank tuple. Here's my models.py #For assigning Ciena loopbacks class Dia_Address(models.Model): order_reference = models.ForeignKey(Order, null=True, on_delete=models.CASCADE) equipment_hostname = models.CharField(max_length=500, null=True, verbose_name="Equipment Hostname", help_text="Hostname of the DIA device.") subnet = models.CharField(max_length=200, null=True, choices=DIA_SUBNETS, help_text="Subnet in which the DIA device requires an address.") Contents of my forms.py, which overrides the model choices. class Dia_AddressForm(ModelForm): class Meta: model = Dia_Address fields = ['equipment_hostname', 'subnet'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) #order_id = str(order_reference.id) dcn_address_handler = AddressHandler subnet_id = "94806" DIA_SUBNETS = () NEW_SUBNETS = dcn_address_handler.get_subnet_data(dcn_address_handler, subnet_id) DIA_SUBNETS = NEW_SUBNETS + DIA_SUBNETS self.fields['subnet'].choices = DIA_SUBNETS Contents of my views.py def addDia_Address(request, pk_test): order = Order.objects.get(id=pk_test) dia_address_form = Dia_AddressForm() if request.method == 'POST': dia_address_form = Dia_AddressForm(request.POST) dia_address_form.instance.order_reference = order if dia_address_form.is_valid(): dia_address_form.save() return redirect('order', pk_test) context = {'dia_address_form':dia_address_form} return render(request, 'orchestration/dia_address_form.html', context) The issue I have is this form is failing validation. I am able to select the appropriate option from the form dropdown menu. Is there any way I can disable this validation for just this one charfield?