Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django import export update field before export signal
I want to update my field before exporting the csv. I just found out about https://django-import-export.readthedocs.io/en/latest/getting_started.html#signals. Say i have a field named totalstudents that stores the total number of students in an empty coloumn before export, how will i do it? I get really confused everytime I have to use signals, so any help would be appreciated -
Why won't this Django TestCase test pass?
I am trying to write tests for an API. I'm having trouble with a couple of User model methods. The methods all work in development and production environments, but the test does not. Here is the test: def test_delete_user(self): USER_DELETED = 1 self.u = self.setup() result = User.delete_user(self.u, self.u.pk) # response self.assertEqual(result, USER_DELETED) # functionality self.assertIsNone(self.u) print(self.u) When I run this test, the return value USER_DELETED is correct, but the user object is not actually deleted. self.setup() returns a single created user. I can post this if it is needed, but the setup and teardown both work with various other tests in the UserTest class. Here is the model method being tested: @staticmethod def delete_user(requesting_user, user_id): # static variables USER_DELETED = 1 NOT_AUTHORIZED = 0 NO_USER = -1 user_to_be_deleted = User.get_user_from_user_id(user_id) if user_to_be_deleted == NO_USER: return NO_USER # check for authorization to delete if requesting_user != user_to_be_deleted: return NOT_AUTHORIZED user_to_be_deleted.delete() return USER_DELETED I also tried creating the user with the setup and then calling self.u.delete() instead of the custom method I have. This gives the same result: AssertionError: <User: test_user> is not None Can someone explain what I am doing wrong here? Thanks. -
User deletion in Django
I created a custom Account table in Django. I even created an email-based activation to activate an account. It is working fine. The problem arises when, while new registration, the user enters an email ID which does not belong to him, or when he enters an invalid email id, or when he doesn't receive any verification mail and is trying to register again. While doing so, Error pops up showing that the email already exists. So what I want is like if the account hasn't been activated, the account details must be removed completely from the table rather than just making is_active=False. Is there any method to do this? -
The view didn't return an HttpResponse object. It returned None instead error when video recording through HTML and Javascript
I have the following function in my view that is doing some background images treatment when we click on the SCAN button. The template is loaded correctly at first before clicking the SCAN Button. In the template (shown below) I have a <video> tag along with js that does webcam recording (even without the SCAN clicked). When I click on the scan button, I face the "The view didn't return an HttpResponse object. It returned None instead". I tried commenting everything related to the webcam recording (that is being done initially without clicking on SCAN), then clicked on scan and did not face this error. I found that the problem is caused by the javascript, since after commenting out the <script> tag, no errors appeared (video tag remained uncommented) Can you please help with this ? Kind regards, view.py def verifyContent(request): matched = False error = False context = { 'matched' : matched } if request.method == "POST": if request.POST.get("scan"): result = frame_detection() if result: search(request) return redirect('main:search') context = {'matched': matched, 'error': error} return render(request=request, template_name="main/verifyContent.html", context=context) verifyContent.html <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <input type="file" id="myFile" name="infos"> <input type="submit" name="upload"> <input type="submit" name="scan" value="Scan"> </form> <h1>Webcam recording</h1> <video … -
Django TabularInline need search list sorted based on date to search faster
Please check the attached image. It has a Video page and a Target (Person) a TabularInline. So one video can have multiple persons associated with it. What I need to do is, whenever I will assign a Person to the Video it should appear first in the Select Person list. Basically every time I am selecting videos related to same Person and perform this operation but every time I have to search for Person. Instead if it appears on top of the list by job will be easy. This data is getting saved in Target model where there is created_at field from which we can sort it. Model details are below, Model: class Target(DFModel): person = models.ForeignKey( Person, models.DO_NOTHING, blank=True, null=True) video = models.ForeignKey( 'Video', models.DO_NOTHING, blank=True, null=True) reviewed = models.TextField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True, help_text=datetime_help_text) class Meta: db_table = 'target' admin.py class TargetTabularInline(admin.TabularInline): model = Target raw_id_fields = ("person",) fields = ('person',) extra = 1 class VideoAdmin(BaseAdmin): inlines = [TargetTabularInline] readonly_fields = ('page_link', 'page_url', 'views', 'likes', 'dislikes', 'tags', 'video_url', 'thumb_url') list_display = ['title', 'targets', 'source', 'video_link', 'reviewed', 'category', 'sfw', 'upload_date', 'created_at'] search_fields = ('title', 'category', 'source__name', 'target__person__name', 'reviewed',) raw_id_fields = ("creator",) def video_link(self, obj): return format_html( "<a … -
Django singal update field when model objects are created in bulk
I have a model named FinancePending class FinancePending(models.Model): amountPaid=models.IntegerField TotalAmount=models.IntegerField AmountPending = models.IntegerField I will populate them using a csv which means that the objects will be creaeted in bulk. Now i want to update the amountpending field for all the objects respectively in a post_save method. But I cannot seem come up with the proper logic @reciever(post_save, sender = FinancePending) def createAmountPending(sender,instance, **kwargs): finance_pending = FinancePending.objects.update() amount_paid = FinancePending.objects.values_list('amountPaid', flat=True) amount_paid = list(amount_paid) total_amount = FinancePending.objects.values_list('TotalAmount', flat=True) total_amount = list(total_amount) # total - paid TotalFee = [float(s.replace(',', '')) for s in total_amount] AmountPaid = [float(s.replace(',', '')) for s in amount_paid] def Diff(li1, li2): return (list(set(li1) - set(li2))) amount_pending = Diff(TotalFee, AmountPaid) i = 1 while i <= len(amount_pending): FinancePending.objects.filter(invoiceNumber=i).update(AmountPending=str(amount_pending[i])) i = i + 1 instance = FinancePending.objects.all() instance.refresh_from_db() instance.post.save() -
Django - compare user objects by field
I have a Dictionary view that shows the list of words created by a specific (special) user: class Dictionary(FilterView): model = Word template_name = 'vocab/dictionary.html' context_object_name = 'dict_list' paginate_by = 15 filterset_class = WordFilter strict = False def get_queryset(self): qs = self.model.objects.filter(user__username__iexact='special_user') return qs def get_object(self): queryset = qs pk = self.kwargs.get('pk') if pk is None: raise AttributeError('pk expected in url') return get_object_or_404(queryset, pk=pk) Now I want any user to be able to come to this page and add any word that they want to, like this: def custom_create_word(request, object): if request.method == 'POST': pass if request.method =="GET": from .forms import WordForm from .models import Word word = Word.objects.get(pk=object) user = request.user target_word = word.target_word source_word = word.source_word deck_name = "My Words" fluency = 0 new_word, created = Word.objects.get_or_create(user=user, target_word=target_word, source_word=source_word, deck_name=deck_name, fluency=fluency) return HttpResponseRedirect(reverse('vocab:dict')) Everything works as expected. But in the template I want the button to look different depending on whether the logged in user already has this word in their own list (which should be judged by if target_word is the same). My template looks like this: <tr> {% for word in dict_list %} <td>{{word.target_word}}</td> <td>{{word.source_word}}</td> <td> {% if user_word %} <a href="" class="btn btn-success btn-sm" >Added</a> … -
proto.teacher.MultipleObjectsReturned: get() returned more than one TeacherReport -- it returned 2
i'm trying to fetch data from a django model and then store it into another django model but i'm getting this error, can anyone tell how to resolve it. i'm uploading the code with it. lt, created = TeacherReport.objects.get_or_create( Teacher_ID=teacher[i], ) if not created: lt.Teacher_Name = tname[i] lt.save() -
Issue with Django: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet
Any idea what's causing this error? I've tried commenting out each app in INSTALLED_APPS one by one to see which one isn't loading, but I get the same error no matter which one is commented out. Traceback (most recent call last): File "/Users/ColeHoward/PycharmProjects/Face_Recognition_App/main.py", line 18, in django.setup() File "/Users/ColeHoward/PycharmProjects/Face_Recognition_App/venv/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/ColeHoward/PycharmProjects/Face_Recognition_App/venv/lib/python3.7/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/Users/ColeHoward/PycharmProjects/Face_Recognition_App/venv/lib/python3.7/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 1006, in _gcd_import File "", line 983, in _find_and_load File "", line 953, in _find_and_load_unlocked File "", line 219, in _call_with_frames_removed File "", line 1006, in _gcd_import File "", line 983, in _find_and_load File "", line 967, in _find_and_load_unlocked File "", line 677, in _load_unlocked File "", line 728, in exec_module File "", line 219, in _call_with_frames_removed File "/Users/ColeHoward/PycharmProjects/Face_Recognition_App/venv/lib/python3.7/site-packages/django/contrib/auth/models.py", line 2, in from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/Users/ColeHoward/PycharmProjects/Face_Recognition_App/venv/lib/python3.7/site-packages/django/contrib/auth/base_user.py", line 47, in class AbstractBaseUser(models.Model): File "/Users/ColeHoward/PycharmProjects/Face_Recognition_App/venv/lib/python3.7/site-packages/django/db/models/base.py", line 107, in __new__ app_config = apps.get_containing_app_config(module) File "/Users/ColeHoward/PycharmProjects/Face_Recognition_App/venv/lib/python3.7/site-packages/django/apps/registry.py", line 252, in get_containing_app_config self.check_apps_ready() File "/Users/ColeHoward/PycharmProjects/Face_Recognition_App/venv/lib/python3.7/site-packages/django/apps/registry.py", line 135, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. -
Django foreign key relation do not conserve object identity
I have a model Message with a foreign key to AUTH_USER_MODEL (users model). class Message(models.Model): SUBJECT_MAX_LENGTH = 120 recipient = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='received_messages', null=True, blank=True, verbose_name=_("recipient")) simple so far. Question is, when I add a message to a given user by using the related_name: m=Message.objects.create() user1.received_messages.add(m) then: m.recipient is user1 # True however: user1.received_messages.first() is m # False I don't understand why the identity is not conserved both ways. Thanks -
API request from Angular App to Django REST API - blocked by CORS
I have a working Angular app that gets data from a Django REST api. The api requests are successful when I make requests to some endpoints but fail due to being blocked by CORS on other endpoints. My CORS configuration in django app: Whitelist: CORS_ORIGIN_WHITELIST = ( 'http://localhost:4200', # my angular app 'http://localhost:8080', ) Middleware: MIDDLEWARE = [ ... 'corsheaders.middleware.CorsMiddleware', ] Installed Apps: INSTALLED_APPS = [ ... 'corsheaders', ] When I make this get request in my angular app, it succeeds and i get back the result i expect Angular request: public getProviders(searchParams: ProviderSearchParams): Observable<ProviderSearchResult> { const p = this.serializeParams(searchParams, new HttpParams()); return this.http.get<any>(`${this.base_url}/providers/`, {params: p}) .pipe(map(this.deserializeAs(ProviderSearchResult))); } Django Endpoint # urls path('', views.ProviderList.as_view(), name="api_provider_list"), # views class ProviderList(generics.ListAPIView): """ View all providers. """ queryset = Provider.objects.filter(is_accepted=True) filter_backends = [DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter] filterset_fields = ['name', 'branches__city', 'branches__area'] search_fields = ['name', 'branches__name', 'branches__city', 'branches__area'] ordering_fields = ['name', 'created_date'] pagination_class = PageNumberPagination def get_serializer_class(self): if self.request.user.is_staff: return AdminProviderSerializer return PublicProviderSerializer However, it seems to fail with error blocked by CORS when i make a request to a generics.RetrieveUpdateDestroyAPIView. Here is an example: Angular request: public getProviderBySlug = (slug: string): Observable<Provider> => this.http.get<any>(`${this.base_url}/providers/${slug}`) .pipe(map(this.deserializeAs(Provider))) Django Endpoint # urls path('<slug:slug>/', views.ProviderDetail.as_view(), name="api_provider_details"), # views … -
What is the best way to set ModelAdmin defaults in Django?
ModelAdmin.list_max_show_all defaults to 200. ModelAdmin.list_per_page to 100. Say I want to change those defaults to 500 and to 25. I also want all my ModelAdmin classes to have access to js/admin.js and css/admin.css. Is the best way to do that to create my own MyModelAdmin class and then have all my other ModelAdmin classes inherit from that one? class MyModelAdmin(admin.ModelAdmin): list_max_show_all = 500 list_per_page = 25 class Media: js = ( settings.STATIC_URL + 'js/admin.js' ) css = { 'all': (settings.STATIC_URL + 'css/admin.css',) } @admin.register(Book) class BookAdmin(MyModelAdmin): model = Book ... @admin.register(Author) class AuthorAdmin(MyModelAdmin): model = Author ... # This also inherits from django.contrib.auth.admin.UserAdmin @admin.register(CustomUser) class CustomUserAdmin(MyModelAdmin, UserAdmin): model = CustomUser ... Is there any downside to doing this? -
Django error where the form.as_p does not work [closed]
http://dpaste.com/1FZQE3S this is the traceback from the code, I dont think code needs to be posted -
Error Using Crispy Form on my Django projects
I got an Error Using Crispy Form on my Django projects. I added 'crispy-forms' in the INSTALLED_APPS under setting here is the code INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'employee_register', 'crispy_forms', ] Also added to setting CRISPY_TEMPLATE_PACK = 'bootstrap4' and on my html as {% extends 'employee_register/base.html' %} {% load crispy_forms_tags %} {% block content %} <form method="post" action="" autocomplete="off" class="uniForm"> {% csrf_token %} {{ form|crispy }} </form> {% endblock content %} Here is the error OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: '<frozen importlib._bootstrap>' What could be the problem please? Thank You. -
Django Logger not logging but all other loggers work
I have configured my Django application to run in production but I cannot get anything out of the django logger. The root logger is writing out to file and Azure logging so I can see my elasticsearch and opencensus logs writing fine but nothing is coming out of django. At the moment I am using INFO level just to see if anything comes out but I'll be adjusting those once I know things are writing out. DEBUG = False LOGGING = { "disable_existing_loggers": False, "filters": { "require_debug_false": { '()': 'django.utils.log.RequireDebugFalse', }, 'require_debug_true': { '()': 'django.utils.log.RequireDebugTrue', }, }, 'formatters': { 'simple': { 'format': '[%(asctime)s] %(levelname)s %(message)s', 'datefmt': '%Y-%m-%d %H:%M:%S' }, 'verbose': { 'format': '[%(asctime)s] %(levelname)s [%(name)s.%(funcName)s:%(lineno)d] %(message)s', 'datefmt': '%Y-%m-%d %H:%M:%S' }, }, "handlers": { "file": { "class": "logging.FileHandler", "filename": os.path.join(APP_ROOT, 'logs', 'app.log'),#"/warden/logs/arches.log", "level": "INFO", "formatter": 'verbose', 'filters': ['require_debug_false'], #,'require_debug_true'], }, 'console': { # writes to the console 'class': 'logging.StreamHandler', 'level': 'INFO', 'filters': ['require_debug_true'], 'formatter': 'verbose' }, 'azure':{ 'level': 'INFO', 'filters': ['require_debug_false'], #,'require_debug_true'], 'class': 'opencensus.ext.azure.log_exporter.AzureLogHandler', 'formatter': 'verbose' }, }, "loggers": { 'django': { 'handlers': [ 'azure', 'file', ], 'level': 'INFO', }, '': { 'handlers': [ 'azure', 'file', ], 'level': 'INFO', }, }, "version": 1 } -
Import django model class into Plotly-Dash stateless app
I'm trying to build a dashboard app using django-plotly-dash. I was able to get the app up and running when pulling the data from a .CSV file but this is slow. To speed things up I imported the data into my backend Postgresql server and created a model in the pages app in my Django project. The problem comes when I attempt to import a specific table from my model into my stateless DjangDash app in a different folder. The error I keep getting is "unable to import pages.models" Folder Structure: DjangoProject >dash_apps >finished_apps -appOne.py >pages -__init__.py -admin.py -apps.py -models.py -test.py >base -__init__.py -asgi.py -routing.py -settings.py -urls.py -wsgi.py -manage.py The app is named appOne.py and the table or class is in the models.py file and is named general_finance_metrics So far I have tried the following in my appOne.py file with no luck: from pages.models import general_finance_metrics (error is: unable to import 'pages.models' pylint (import-error)) from DjangoProject.pages.models import general_finance_metrics (error is: unable to import 'DjangoProject.pages.models' pylint (import-error)) from .models import general_finance_metrics (error is: attempted relative import beyond top-level package pylint (relative-beyond-top-level)) from base.models import general_finance_metrics (error is: unable to import 'base.models' pylint (import-error)) from base import models (error is: unable to … -
Django saving data from a template into the admin panel
I am creating basically a site where a user will fill out 5 fields on a page and then the data that the user entered get stored in the admin panel for me to view. I am not sure if this is possible. I have tried searching for what I am trying to accomplish and either my searching is bad or this isn't possible. -
Combine Latitude and Longitude figures together in real time
I modified my code after looking at at Romas post (GeoDjango: Can't save a model with PointField(), Error: SpatialProxy (POINT) with value of type: <class 'users.models.Point'>). I calculate Location by doing self.Location = Point(self.Longitude, self.Latitude). The problem with this approach is that the location is only updated when I click save (at the moment I am modifying the table via the admin page and not the front end). Is there a way of getting the Location value to be updated in real time? class Property(models.Model): id = models.AutoField(primary_key=True) User = models.ForeignKey(User, on_delete=models.CASCADE) Latitude = models.FloatField(blank=True, null=True, verbose_name='Latitude', default="00.0000000") Longitude = models.FloatField(blank=True, null=True, verbose_name='Longitude', default="00.0000000") Location = models.PointField(blank = True, null=True, srid=4326) City = models.CharField(max_length=50, default="") Street = models.CharField(max_length=60, default="") PostCode = models.CharField(max_length=60, default="") Residential = models.CharField(choices=NO_OF_HRS, max_length=60, default='1') def save(self, *args, **kwargs): self.Location = Point(self.Longitude, self.Latitude) super(Property, self).save(*args, **kwargs) -
django local static file configuration
Somehow in a Django project, I changed my config for static files. Now I have to run python manage.py collectstatic --noinput before I run python manage.py runserver. Otherwise whatever changes I made to my project will not show up. Does anyone know how to fix this? Thanks -
How to serve static files in django-tenants?
I am getting trouble configuring static files. please help. The templates are served correctly for each tenant. The directory /tenants/<schema>/ contains two folders 'static' and 'templates'. I have two schemas 'public' and 'tenant1'. So naturally, the static files are copied to /staticfiles/<schema> ie, /staticfiles/public and /staticfiles/tenant1 The problem im getting is, the server searches for static files for tenant1 in the folder /tenants/public/static/, and not /staticfiles/tenant1 or even /tenants/tenant1/static/. I am using django server and not HTTP server like apache2 or nginx. What am i doing wrong here? The following are my settings: STATIC_URL = "/static/" MEDIA_URL = "/media/" MEDIA_ROOT = os.path.join(BASE_DIR, "media") STATIC_ROOT = os.path.join("F:\dev\django\\sitename", "staticfiles") MULTITENANT_STATICFILES_DIRS = [ os.path.join("F:\dev\django\\vislr", "tenants\%s\\static"), ] DEFAULT_FILE_STORAGE = "django_tenants.files.storage.TenantFileSystemStorage" MULTITENANT_RELATIVE_MEDIA_ROOT = "" # (default: create sub-directory for each tenant) STATICFILES_STORAGE = "django_tenants.staticfiles.storage.TenantStaticFilesStorage" MULTITENANT_RELATIVE_STATIC_ROOT = "" # (default: create sub-directory for each tenant) REWRITE_STATIC_URLS = False REWRITE_MEDIA_URLS = False SITE_ID = 1 STATICFILES_FINDERS = ( "django_tenants.staticfiles.finders.TenantFileSystemFinder", "django.contrib.staticfiles.finders.FileSystemFinder", "aldryn_boilerplates.staticfile_finders.AppDirectoriesFinder", "django.contrib.staticfiles.finders.AppDirectoriesFinder", ) MULTITENANT_TEMPLATE_DIRS = [ os.path.join("F:\dev\django\\sitename\\tenants\%s\\templates"), ] -
Can't serve Django Static folder with Nginx, GUnicorn and Docker
I am trying to deploy an django project and to finalize the development I need to access the /admin path that is on port 8000 (localhost:8000/admin/). However, the the css files are not being loaded on nginx. The way that is now, /static/ is on port 80 (localhost:80/static/) but if you open the "inspect" on admin page you will see that the static folder has to be on 8000 too. docker-compose version: '3' services: djangoservice: build: . restart: always ports: - 8000:8000 volumes: - ./django:/srv/djangoproject - ./config:/srv/config networks: - testnetwork nginx: build: context: . dockerfile: nginx.dockerfile restart: always ports: - 80:80 - 443:443 depends_on: - djangoservice networks: - testnetwork networks: testnetwork: driver: bridge nginx.dockerfile FROM node:13 as build-stage RUN mkdir -p /srv/src COPY frontend /srv/src WORKDIR /srv/src RUN rm -rf node_modules RUN npm install RUN npm run build || npm run build FROM nginx RUN mkdir -p /srv/www COPY --from=build-stage /srv/src/dist /srv/www RUN mkdir -p /srv/static COPY ./django/static /srv/static COPY config/nginx/conf.d /etc/nginx/conf.d website.conf upstream djangoserver { server djangoservice:8000; } server { listen 0.0.0.0:80 default_server; #teste server_name _; #teste root /srv/www; index index.html index.htm index.nginx-debian.html; location /static/ { alias /srv/static/; autoindex on; } location /api { proxy_pass http://djangoserver; } location / … -
Django: Sort Items in Dropdown (via field_order?)
I am using a dropdown on a template. I do want an alphabetical order in that dropdown and don't know how to get this. template.html: <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <fieldset> {{ form|crispy }} </fieldset> <div> <button type="submit">OK</button> </div> </form> The context comes from views.py: def my_view(request): if request.method == 'POST': form = MyForm(request.POST) if form.is_valid(): … return render(request, 'xxx/template.html', {'form': form}) The form is defined in forms.py: from django import forms from .models import Project class MyForm(forms.Form): project = forms.ModelChoiceField(queryset=Project.objects) field_order = ['name', ] models.py: class Project(models.Model): name = models.CharField() … The documentation talks about field_order. The line field_order = ['name', ] in form.py has no effect. What's wrong? -
!Push rejected, failed to compile Python app. -Heroku
I am getting an error when I try to deploy heroku django app. Any suggestion please, The Error is, remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to djlms. remote: To https://git.heroku.com/djlms.git ! [remote rejected] master -> master (pre-receive hook declined) requirements.txt is asgiref==3.2.7 dj-database-url==0.5.0 Django==2.2 django-ckeditor==5.9.0 django-crispy-forms==1.9.1 django-heroku==0.3.1 django-js-asset==1.2.2 gunicorn==20.0.4 Pillow==7.1.2 psycopg2==2.8.5 pytz==2020.1 sqlparse==0.3.1 whitenoise==5.1.0 And python runtime is python3.7.0. -
How to get the SMTP server response code in Django?
Goal: Hi! How can I get the SMTP response codes through Django, similar to return values given from the smtplib module??? I want to use Django's api instead of having to use that, and I see nothing in Django's email docs. I know send_mail(), send_mass_mail() , and EmailMessage.send_messages(...) all have return values that show the number of successfully delivered messages... But I want the response codes for all of them. The point is to get proof that an email is sent, bad email address, etc, like smtp response codes show. And it's looking to me like I'd have to make a custom email backend for this, and subclass from BaseEmailBackend... It's using smtplib anyway. Example code for smtplib's response code import smtplib obj = smtplib.SMTP('smtp.gmail.com', 587) response = obj.ehlo() print(response) # Obviously this doesn't send a message yet, but I want response[0] (250, b'smtp.gmail.com at your service, [111.222.33.44]\nSIZE 31234577\n8BITMIME\nSTARTTLS\nENHANCEDSTATUSCODES\nPIPELINING\nCHUNKING\nSMTPUTF8') -
Django Rest Framework link logged user to app model
When I add a new Article, I have a dropdown with a list of all registered users. I want to link the current user to the new Article. models.py from django.db import models from django.conf import settings User = settings.AUTH_USER_MODEL class Article(models.Model): title = models.CharField(max_length=100) user = models.OneToOneField(User, related_name='Article', on_delete=models.CASCADE) def __str__(self): return self.title serializers.py from rest_framework import serializers from .models import Article class ArticleSerializer(serializers.ModelSerializer): class Meta: model = Article fields = ['id', 'title', 'user']