Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Status: Select a valid choice. 1 is not one of the available choices Django 3
Here i am using Django 3.0 and Python 3.7. When i am trying to update the user phone number or email id i am getting this issue. Here is my views.py: class ClientUserInfoUpdate(CustomAdminMixin, UpdateView): model = ClientUser template_name = "core/user_info_mutiple_edit_form.django.html" form_class = ClientUserInfoUpdateForm user = None methods = None def get_success_url(self): return reverse("admin_user_update", args=[self.user.pk]) def get_form_kwargs(self): kwargs = super(ClientUserInfoUpdate, self).get_form_kwargs() self.user = kwargs['instance'] self.methods = self.user.get_userinfodata() kwargs['user'] = self.user kwargs['methods'] = self.methods return kwargs def get_context_data(self, **kwargs): context = super(ClientUserInfoUpdate, self).get_context_data(**kwargs) context['user'] = self.user context['methods'] = self.methods context['countries'] = countries_sorted for method in ContactInfoMethod.objects.all(): context['types_' + method.name.lower()] = ContactInfoMethodType.objects.types_by(method.name) return context Here is my forms.py: class ClientUserInfoUpdateForm(forms.ModelForm): user = None methods = None # sort of a copy of fieldsets, but utilising the dynamic capabiliities of the form #formsections = [] new_info = [] def __init__(self, *args, **kwargs): self.user = kwargs.pop('user') self.methods = kwargs.pop('methods') super(ClientUserInfoUpdateForm, self).__init__(*args, **kwargs) #self.formsections = [] # auto generate the form based upon self.methods (!!!) for dm in self.methods: methodtypes = ContactInfoMethodType.objects.types_by(dm['method'].name) methodtypes_choices = methodtypes.values_list('pk', 'type__name') if(dm['method'].use_dialling_code): dialling_code_choices = countries_sorted_with_dial_choices i = 1 methodname = "" for info in dm['items']: fn = info.dynamic_form_field_name() self.fields[fn] = forms.CharField() if(dm['method'].name.lower() == "email"): self.fields[fn] = forms.EmailField() self.fields[fn].name = fn self.fields[fn].verbose_name … -
Why doesn't it return the messages?
I'm trying to retrieve all messages in the chat, the messages are saved in the ChatMessage template. The insertion of a new message does not create problems for me, the recovery yes, in the send_message() function I use the send() with the correct data. {'command': 'messages', 'messages': [{'id': 204, 'author': 'C12VC08213@are.it', 'content': 'Ciao da tutti', 'timestamp': '2022-06-06 13:57:37.103215'}, {'id': 236, 'author': 'CCCVC08213@are.com', 'content': 'Ciao da tutti quanti', 'timestamp': '2022-06-07 07:59:50.818133'}, {'id': 269, 'author': 'C11VC0@are.it', 'content': 'Ciao da tutti quanti1', 'timestamp': '2022-06-07 08:51:58.980090'}]} I don't understand why it doesn't send it, the websocket restiusce nulls me or it doesn't respond. from concurrent.futures import thread from django.contrib.auth import get_user_model # from asgiref.sync import await from asgiref.sync import async_to_sync, sync_to_async from channels.db import database_sync_to_async import json from chat.models import ChatMessage, ChatRoom from users.models import Operator from chat.utils import ( get_chatmessages, get_operator_info, # get_current_chatroom, # get_operator, ) from channels.generic.websocket import AsyncWebsocketConsumer from chat.api.v1.serializers import ChatMessageSerialiser, ChatRoomSerializer class ChatConsumer(AsyncWebsocketConsumer): async def receive(self, text_data): print("------------------ receive") text_data_json = json.loads(text_data) if text_data_json["command"] == "fetch_messages": await self.fetch_messages(data=text_data_json) # self.send(text_data=fetch['messages']) # await self.channel_layer.group_send( # self.room_group_name, # {"type": "chat_message", "message": messages}, # ) if text_data_json["command"] == "new_message": message = text_data_json["message"] await self.new_message(data=text_data_json) self.send(text_data=message) await self.channel_layer.group_send( self.room_group_name, {"type": "chat_message", "message": message}, … -
serializer error for list field when i run tests in Django
I have a weird problem when using TestCase and Client in Django. from django.test import TestCase, Client data is: data = { "match_status": MatchStatus.FINISHED, "winner_side": Side.CITY, "end_time": get_now(), "players": [ { "uuid": self.player.uuid, "role": self.role, "success_acts": [self.act1.id], "failed_acts": [self.act2.id, self.act3.id] } ] } from django.test import Clien as client self.client.post(reverse("match-finish", args=[self.match_create.uuid]), data=data) this is a custom serializer: class MatchFinishPlayerSerializer(BaseSerializer): uuid = UUIDField() role = IntegerField() success_acts = ListField() failed_acts = ListField() class MatchFinishSerializer(BaseSerializer): match_status = IntegerField() winner_side = IntegerField() end_time = DateTimeField() players = MatchFinishPlayerSerializer(many=True) Part of view.py: @action(methods=["POST"], url_path="finish", url_name="finish", detail=True) def finish(self, request, uuid: UUID = None): serializer = self.get_serializer_class()(data=request.data) serializer.is_valid(raise_exception=True) return Response(serializer.validated_data) and when I run python manage.py test I got an error: {'players': ['This field is required.']} -
How to use default logger and custom logger in django but avoid duplicate logs
I have two sets of APIs in a Django project that I want to use my custom logger. So in every viewset I will be doing logger.info(...) or logger.error(...) before the responses. Everywhere else in the project, like Admin pages and other tools, I'd like to leave the logging as it is for now. This is how I have defined my LOGGING in settings.py. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'standard': { 'format': 'ts=%(asctime)s level=%(levelname)s caller=%(filename)s:%(funcName)s:%(lineno)s %(message)s', 'datefmt': '%Y-%m-%d %H:%M:%S', }, }, 'handlers': { 'console': { 'class': 'logging.StreamHandler', 'formatter': 'standard', }, }, 'loggers': { 'django': { 'handlers': ['console'], 'level': os.getenv('DJANGO_LOG_LEVEL', 'INFO'), }, }, } The problem is that the way it is, the logging in the APIs is duplicated for every request, my logger and the existing django logger. How can I "disable" the default django logger in the APIs but keep it everywhere else? -
Testing a django `post_save` signal that includes function calls that occur after db transaction is committed
When django tests are running, database transactions are not committed. How do I test an event triggered by object creation but that happens after the db transaction has been committed? I have a Campaign model and the below post_save signal. Using Django TestCase it is difficult to assert that the functions within transaction.on_commit are called in the case when a new Campaign object is created. When the signal runs in the test context, it always thinks that an existing campaign object is being edited, not that one has been newly created. Therefore I cannot test the else branch of the if statement. How could I test the case when Campaign.objects.filter(pk=instance.pk).exists() is False? Signal: @receiver(post_save, sender=Campaign, dispatch_uid="apps.writing.signals.create_handwriting") def create_handwriting(sender, instance, **kwargs): """Whenever a campaign is created or updated, trigger the handwriting cloud function to (re)generate the handwriting image. """ if Campaign.objects.filter(pk=instance.pk).exists(): transaction.on_commit( lambda: log_campaign_progress(pk=instance.pk, status="t2h-edited", stage="campaign") ) transaction.on_commit(lambda: delete_campaign_pages(campaign_pk=instance.pk)) else: transaction.on_commit( lambda: log_campaign_progress(pk=instance.pk, status="t2h-created", stage="campaign") ) transaction.on_commit(lambda: enqueue_handwriting_generation(campaign_pk=instance.pk)) Test: class TestSignals(TestCase): def setUp(self): self.factory = RequestFactory() @mock.patch("lettergun.apps.writing.signals.log_campaign_progress") @mock.patch("lettergun.apps.writing.signals.enqueue_handwriting_generation") @mock.patch("lettergun.apps.writing.signals.delete_campaign_pages") def test_create_handwriting_edit_existing_campaign( self, delete_campaign_pages, enqueue_handwriting_generation, log_campaign_progress ): # disconnected in the factory so we need to reconnect it here signals.post_save.connect( sender=Campaign, dispatch_uid="apps.writing.signals.create_handwriting", receiver=create_handwriting, ) enqueue_handwriting_generation.return_value = True log_campaign_progress.return_value = True with self.captureOnCommitCallbacks(execute=True) … -
Share Django authentication for FastAPI
I have working Django project. Now i want to add FastAPI so at existing django templates i can make API requests to refresh data without reloading whole template (like tables for example). The question is how to connect FastAPI to existing django authentication system, so it can use sessions from db, so that user authenticate only once, when logging in to django project. Here some options i have investigated: Change django base authentication to oauth2, also set fastapi to oauth2 (though i desire to configure fastapi, not changing django) Fetch django sessions from db on each api request and verify user Both django and fastapi on the same server and can share the same db. Maybe some better options are possible. Please advice what would be the best approach to use django already authenticated user data with fastapi? Thx -
How to import images ImageField from excel, using Django import_export?
I am using django-import-export, Excel file as file.xlsx when importing an ImageField the image is saved as a link "C:\Users\hp\Desktop\images\gallery\29.jpg" and not an actual image into database. models.py class Product(models.Model): name = models.CharField( max_length=200, verbose_name='Nom') slug = models.SlugField( max_length=150, unique= True, verbose_name='URL') reference = models.CharField( max_length=200, verbose_name='Référence', unique=True, blank=True, null=True) def __str__(self): return self.name class PhotoProduct(models.Model): image = models.ImageField(upload_to='images/produits') actif = models.BooleanField(verbose_name='actif', default=True) product = models.ForeignKey(Product, related_name="photos", on_delete=models.CASCADE) def __str__(self): return str(self.product) ########### ressources.py class PhotoProductAdminResource(resources.ModelResource): product = fields.Field(column_name='product', attribute='product', widget=ForeignKeyWidget(Product, field='id')) class Meta: model = PhotoProduct fields = ( 'id', 'product', 'actif', 'image', ) ########### admin.py @admin.register(PhotoProduct) class PhotoProductAdmin(ImportExportModelAdmin): list_display = ('id', 'product', 'actif') list_display_links = ('id','product', ) list_editable = [ 'actif'] resource_class = PhotoProductAdminResource form = PhotoProductModelForm -
Why in DJANGO the Templates are not updated when I refresh the page with new data in the DB?
The problem is that when I change data through a form or by the django admin if it is saved in the database, but when redirecting to another view or refreshing the screen with f5 it does not show the changes in the user views unless I start session again or delete the cookies, something that for each change you have to perform this operation, however in the django admin views if everything is updated normally with a simple f5. This is very rare since the page has been working for more than 1 year without this problem and suddenly this happened. I'm using: Stevedore Nginx gunicorn 20.0.4 Django 3.1.4 python 3.9 sqlite 3 and bootstrap 4.6 for user views I thought it was just the update of my browser but in any browser the same thing happens I did not find a similar problem in any forum, I hope you can help me or give me an indication of what is causing this -
modelize schema procede withdjango
Is it possible to draw a dynamic schema procede with django ? i tried to draw shapes with #svg in HTML/CSS but it is a static solution ... And I need to do dynamic modification in the schema , hypertext for exemple Any help please ? -
Manytomay field is None or can't call field in a view in django
I have a problem in my code,I'm Trying to querying to my course model, I have a many to may field of course in user model,now I need to query to course model that course title or id is equal to user's courses My course model is: class Courses(models.Model): title = models.CharField(max_length=100, null=False, blank=False) description = models.TextField(null=False, blank=False) active = models.BooleanField(default=False) default_course = models.BooleanField(default=False) My user model in another app is: class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=255, unique=True, db_index=True) courses = models.ManyToManyField('academy.Courses', related_name='user_courses', blank=True) is_verified = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_author = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) is_adviser = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) auth_provider = models.CharField( max_length=255, blank=False, null=False, default=AUTH_PROVIDERS.get('email')) I have to say my user model and course model are in different app This is my view: class CoursesListView(mixins.ListModelMixin, viewsets.GenericViewSet): serializer_class = UserSerializer def get_queryset(self, **kwargs): user = self.request.user course = Courses.objects.filter(title__in=user.courses.title) I tried so many code but none of them worked,please any one can help me how can I write this view? as I said I want to call courses that have same id or title with user courses -
Django can't get form to load in browser 404
I've got my LAMP setup with Ubuntu and MariaDB. The Django code managed to create some tables for me in the database but I just get 404 when I try to load my form in my browser. This is my first Django app. Maybe my urls.py is wrong. Maybe it's my settings.py. I've trying all sorts of things so my code has probably got a bit mangled. From TEMPLATES in settings.py I've hardcoded the path to my .html I've experimented with this a lot. 'DIRS': [ '/opt/vcm_project/vcm/templates/vcm' ], urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('create_unit', views.create_unit, name='create_unit'), ] models.py from django.db import models # Create your models here. class Unit(models.Model): unit_code = models.CharField(max_length=15) unit_name = models.CharField(max_length=255) unit_sector = models.CharField(max_length=255) unit_application = models.TextField(max_length=65535) unit_url = models.URLField(max_length=255) superseded_equivalent = models.CharField(max_length=15) def __str__(self): return self.unit_name class Element(models.Model): element_number = models.CharField(max_length=100) element_name = models.CharField(max_length=255) def __str__(self): return self.element_name forms.py from django import forms from .models import Unit class UnitForm(forms.ModelForm): class Meta: model = Unit fields = ('unit_code', 'unit_name', 'unit_sector', 'unit_application', 'unit_url', 'superseded_equivalent') widgets = { 'unit_code': forms.CharField(label='Unit code', max_length=15) 'unit_name': forms.CharField(label='Unit name', max_length=255) 'unit_sector': forms.CharField(label='Unit sector', max_length=255) 'unit_application': forms.CharField(label='Unit application', max_length=65535) 'unit_url': forms.URLField(label='Unit URL', max_length=255) … -
Django: Override 404 template in some views
I have a custom 404 template for my whole django application but I would like to show a different one for specific views. Is there a way to overrride the 404 template at runtime for one specific view? -
Email sending through Gmail is not working in Django. Gmail less secure apps disabled
From May 30 2022 onwards Gmail removed Less Secure apps access in gmail. Is there any alternative email provider we can use or is there any solution for it? EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'mail@gmail.com' EMAIL_HOST_PASSWORD = 'password' EMAIL_PORT = 587 if request.method == "POST": name = request.POST['form_name'] email = request.POST['form_email'] subject = request.POST['form_subject'] message = request.POST['form_message'] send_mail(subject,message,email,['mail@gmail.com'] ) return render(request, 'pages/contact.html', {'name': name}) else: return render(request, 'pages/contact.html', {}) Need help, Thanks in advance. -
Prevent User from creating instance for other users
I have 4 models each related to each other with ForeignKey. class User(models.Model): name = models.CharField() class Business(models.Model): name = models.CharField() //business name created_by = models.ForeignKey(User,related_name=businesses,on_del=models.CASCADE) class ProdCategory(models.Model): business = models.ForeignKey(Business,related_name=categories,on_del=models.CASCADE) name = models.CharField() class Product(models.Model): category = models.ForeignKey(ProdCategory,related_name=products,on_del=models.CASCADE) name = models.ForeignKey() price = models.DecimalField() Now If I try to get all the Products of the current authenticated user I get the Correct List of products (that coming from the same User>Business>ProdCategory>Product) But if I try to create a Product with authenticated user, I can create a Product with providing the id of ProdCategory(already created by different users) (User of Business>ProdCategory) != self.request.user In Short I can create product for other users. Which is not what I want. I want to prevent the current user from creating products if ProdCategory id provided is of different users. It should return error. User must provide the id of ProdCategory that was created by the same user. Serializer classes are defined with all fields using ModelSerializer. Here goes the View for creating and listing products: class ProductListCreateView(generics.ListCreateAPIView): serializer_class = ProductListCreateSerializer def get_queryset(self): return Product.objects.filter(category__business__created_by=self.request.user) -
Django How to Select One Foriegn Key Among Multiple Foriegn Keys
I have two models know i created a third one in which i want to link any one between these two forign keys but not both of them and i want to show both of them while linking then we choose one of them -
Must supply api_key with django app deployed on heroku
hello guys i've got a django app, and i'm using cloudinary to save images, on my localhost it working perfectly but once i deployed to heroku i keep getting this error message Must supply api_key and ive added the api_key to my config list -
Running a django project with documentation based in linux on windows
I want to run this project https://github.com/sajib1066/django-event-management in windows but its documentation is for linux. Please simplify the instructions for windows because I'm having trouble in setting this up. Especially since the source command is not in powershell. -
Object of type RefreshToken is not JSON serializable
I would like to trigger user_logged_in after a user is authenticated through rest_framework_simplejwt This is the code I have written: class CustomTokenObtainPairSerializer(TokenObtainPairSerializer): def validate(self, attrs): authenticate_kwargs = { self.username_field: attrs[self.username_field], "password": attrs["password"], } try: authenticate_kwargs["request"] = self.context["request"] except KeyError: pass user = authenticate(**authenticate_kwargs) user_logged_in.send(sender=user.__class__, request=self.context['request'], user=user) if not api_settings.USER_AUTHENTICATION_RULE(user): raise exceptions.AuthenticationFailed( self.error_messages["no_active_account"], "no_active_account", ) return { self.get_token(cls, user) } @classmethod def get_token(cls, user): token = super().get_token(user) token['username'] = user.username token['first_name'] = user.first_name token['last_name'] = user.last_name token['country'] = user.profile.country token['city'] = user.profile.city token['bio'] = user.profile.bio token['photo'] = json.dumps(str(user.profile.profile_pic)) return token When I try to authenticate a user I get the error: Object of type RefreshToken is not JSON serializable -
Django 4.0 getting many to many field objects in List View
I'm really new to Django and have been stuck....I have a book model and a genre model that have a many to many relationship. How would I go about getting all the books for a specific genre in a list view. I'm assuming its faster to get a Genre object and get all the books from it using a query such as "genre.objects.book_set.all" rather than going through all books and seeing if they have the specified genre. However I'm not sure how I would do that in a ListView? I wanna take the genre name from the url and then use that to get the genre object. here is what I have URL: path('genre/<string:name>', GenreListView.as_view(), name='book-genre'), Models: class Genre(models.Model): name = models.CharField(max_length=50, unique=True) def __str__(self): return self.name class Book(models.Model): name = models.CharField(max_length=150, unique=True) description = models.TextField() user_count = models.IntegerField() pages = models.IntegerField() genres = models.ManyToManyField(Genre) image = models.ImageField(default='book_imgs/default.jpg', upload_to='book_imgs') def __str__(self): return self.name View? class GenreListView(ListView): model = Genre def get_queryset(self): Not sure what to put here.... return Any help is appreciated, thanks. -
Vue Js and Django get fields from ForeignKey Objects
I am using Django Rest Framework with Vue JS and currently unable to get the foreignkey fields from the actual model of the api. I want to be able to get the store name of a particular product. Whenever I try to call [[ product.store.name ]] in my vue template it returns nothing. Also my href does not return the slug of a store. This could be an easy fix, but I am hopeful to get a solution. Below is my code, thanks. models.py class Store(models.Model): owner = models.ForeignKey("account.Profile", null=True, on_delete=models.SET_NULL) category = models.ForeignKey("store.Category", null=True, on_delete=models.SET_NULL) name = models.CharField(max_length=30, unique=True) slug = AutoSlugField(populate_from='name', unique=True, editable=True) description = models.CharField(max_length=255, blank=True) def __str__(self): return str(self.id) class Product(models.Model): store = models.ForeignKey("store.Store", null=True, on_delete=models.SET_NULL, related_name='product_store') category = models.ForeignKey("store.Category", related_name='product_category', on_delete=models.CASCADE) sub_category = models.ForeignKey("store.SubCategory", related_name='product_sub_category', on_delete=models.SET_NULL, blank=True, null=True) created_by = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='product_creator') title = models.CharField(max_length=255) description = models.TextField(blank=True) slug = AutoSlugField(populate_from='title', unique=True) price = models.DecimalField(max_digits=10, decimal_places=0) serializer.py class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = '__all__' views.py class ProductListAPIView(generics.ListAPIView): pagination_class = MyCustomPagination queryset = Product.objects.all().order_by('-date_created') # queryset = Product.objects.all() serializer_class = ProductSerializer products.js <script> new Vue({ el: "#blog", delimiters: ['[[', ']]'], data() { return { products: [], currentPage: 1, hasNext: true, loading: true, … -
Django ManyToMany MultipleChoice Field Edit Values Not Getting Checked
trying to show already selected items from Django many-to-many relationship in multiple choice field, but selected values aren't checked. this is what i've tried so far // models.py class Person(models.Model): name = models.CharField(max_length = 100, help_text = _('name required! maximum 100 characters')) class Team(models.Model): name = models.CharField(max_length = 100, help_text = _('name required! maximum 100 characters')) members = models.ManyToManyField(Member, related_name = 'teams') // forms.py class TeamForm(forms.ModelForm): teams = forms.MultipleChoiceField(choices = Team.objects.all(), widget = forms.CheckboxSelectMultiple) def __init__(self, *args, **kwargs): super(TeamForm, self).__init__(*args, **kwargs) if kwargs.get('instance'): initial = kwargs.setdefault('initial', {}) initial['teams'] = [t for t in kwargs['instance'].teams.all()] // views.py class PersonEditView(View): team_form = TeamForm template_name = 'persons/edit.html' def get(self, request, person_id): """ """ person = get_object_or_404(Person, pk = person_id) return render(request, self.template_name, { 'team_form': self.team_form(instance = member, initial = {'teams': person.teams.all()}), }) // edit.html template <div class=""> <p class="">Team Information</p> {% for team in team_form.teams.field.choices %} <div class=""> <input id="{{ team.id }}" type="checkbox" value="{{ team.id }}" class=""> <label for="{{ team.id }}" class="">{{ team.name|title }}</label> </div> {% endfor %} </div> how do i get to show selected teams checked in the list of teams when editing the details of a Person? -
Django - Is it possible to prefetching multiple filters for queryset?
I know you can prefetch a single filtered queryset E.g. Parent.objects.all() .prefetch_related( Prefetch("child_set", queryset=Child.objects.filter(type="A") ) That way running obj.child_set.all().count() will return the count of related A Childs without running another query. But what if I wanted to have the B count too? So the following would take 2 queries - can I somehow prefetch them both? return { "a_count": obj.log_set.filter(type="A").all().count(), "b_count": obj.log_set.filter(type="B").all().count(), } -
Set inital value on django many to many fields
I would like to start a form with a default value sent on a request, but it seems not to be working: views.py """ ADD A NEW FILE IN CLIENT DETAIL """ @login_required def new_file_detail(request, id): user = request.user client = get_object_or_404(ClientPerson, pk=id) form = FilesForm(request.POST or None, request.FILES or None, user=user, instance=client, initial={'person_client': client}) if form.is_valid(): form = form.save(commit=False) form.user = request.user form.save() return redirect('files_list') return render(request, 'file_form.html', {'form': form, 'client': client}) Expected: Result: -
Why does my ModelFormSet keeps updating the same record instead of creating a new one?
I have these Models, this is all part of an app that registers events which have images through an ImageAlbum: class EventAlbum(models.Model): uuid = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False, unique=True) event = models.ForeignKey(Event, on_delete=models.CASCADE, related_name='eventos') def get_main_image(self): return self.images.get(main=True) class EventImage(models.Model): uuid = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False, unique=True) image = models.FileField('imagen', upload_to=upload_path) main = models.BooleanField('principal', default=False) album = models.ForeignKey(EventAlbum, related_name = 'images', on_delete=models.CASCADE) And this FormSet for the Images: class BaseImageFormSet(BaseModelFormSet): def clean(self): """Checks that there is only one main image""" if any(self.errors): return boolean_arr = [] for form in self.forms: if self.can_delete and self._should_delete_form(form): continue main_data = form.cleaned_data.get('main') main = main_data if main_data is not None else False if sum(boolean_arr) > 1: raise ValidationError('There can only be one main image.') boolean_arr.append(main) Here is in my Views: class NewEventView(BaseView): def get(self, request, *args): ImageFormSet = modelformset_factory( EventImage, fields=('image', 'main'), extra=5, max_num=5, formset= BaseImageFormSet) image_formset = ImageFormSet(prefix='images') context = {'forms': {'image_formset': image_formset, } return render(request, "events/events_add.html", context) def post(self, request): new_album = EventAlbum(event=new_event) ImageFormSet = modelformset_factory( EventImage, fields=('image', 'main'), extra=5, max_num=5, formset= BaseImageFormSet) image_formset = ImageFormSet(request.POST, request.FILES, prefix='images') if image_formset.is_valid(): new_album.save() images = image_formset.save(commit = False) for image in images: image.album = new_album image.save() image_formset.save() return HttpResponse('Ok', content_type='text') else: return Response((image_formset.errors, image_formset.non_form_errors()), … -
SES email being consistently hacked
I'm using Amazon SES email from the django-ses module. I have two SES-verified addresses; SES is restricted to sending only to those addresses. There's a DKIM string on my domain's DNS configuration. SES is accessed using django-ses from a contact form on my website that's protected by Recaptcha. Recently I've begun getting spam sent to those verified addresses coming from SES. Messages in Russian, messages containing website links, messages starting with "Hey guys...". I get about one per day. There are many questions on the net about SES emails going to the spam directory. That is NOT the issue here. The emails are received by my InBox; they are just bogus, hacked emails. I changed the SES API key and Secret key, to no avail. Where do I look next? (I don't have AWS Support, and find nothing in their Knowledge Base.)