Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework - & on method field not working as expected
In my filterset I am doing the below: class ItemFilter(FilterSet): entry_date__gte = DateTimeFilter(field_name='entry_date', method=entry_gte_filter) entry_date__lte = DateTimeFilter(field_name='entry_date', method=entry_lte_filter) class Meta: model = Item fields = ('name', 'qty', 'entry_date__gte', 'entry_date__lte') For some reason I have to use the method field here and cannot give the lookup expr directly My methods look like below: def entry_gte_filter(queryset, name, value): name = f"{name}__gte" queryset = Item.objects.annotate( detail=models.Exists(Detail.objects.filter( **{name: value, 'id': models.OuterRef('id')}))).filter(detail=True) return queryset and def entry_lte_filter(queryset, name, value): name = f"{name}__lte" queryset = Item.objects.annotate( detail=models.Exists(Detail.objects.filter( **{name: value, 'id': models.OuterRef('id')}))).filter(detail=True) return queryset However, when I execute the below API: GET /api/items?entry_date__gte=2021-06-29&entry_date__lte=2021-07-04 I get the responses with below entry dates: 2021-06-30T00:00:00 2021-06-11T00:00:00 2021-07-02T00:00:00 I am unclear why a response with 2021-06-11 is being returned when the API mentions entry_date__gte=2021-06-29 To me it looks django filters is not working as expected when method type is used. Could anyone please help me here why djangorestframework is behaving like this and if there is any way to fix this and get the expected behavior? -
problems logging in with Django custom backend
I have been trying to get my Django custom backend to work and it refuses to accept my credentials, which are correct in the database (I have verified this). It just keeps saying email and password are incorrect. I am lost and don't know where to go from here with this. I really need help at this point. VIEWS.PY class MyLogin(LoginView): template_name = 'employees/login.html' success_url = 'employees:emp-home' authentication_form = LoginForm def get_success_url(self): return super().get_success_url() def form_valid(self, form): user = self.request.POST['username'] password = self.request.POST['password'] authenticate(EmpBackend, self.request, user, password) return HttpResponseRedirect(self.get_success_url()) MODELS.PY class EmpUserManager(BaseUserManager): def create_user(self, email, password=None): if not email: raise ValueError("Users must have an email address") user = self.model(email=self.normalize_email(email)) user.set_password(password) user.save() return user def create_staffuser(self, email, password): """ Creates and saves a staff user with the given email and password. """ user = self.create_user( email, password=password, ) user.staff = True user.save(using=self._db) return user def create_superuser(self, email, password): user = self.create_user(email, password=password) user.staff = True user.save() return user class Emp(AbstractBaseUser): user = models.OneToOneField(User, on_delete=models.CASCADE) email = models.CharField(max_length=100, default=None, unique=True) first_name = models.CharField(max_length=100, default=None, null=True) last_name = models.CharField(max_length=100, default=None, null=True) username = models.CharField(max_length=100, default=None, null=True) password = models.CharField(max_length=100, default=None) phone = models.CharField(max_length=20, default=None, null=True, blank=True) address1 = models.CharField(max_length=100, default=None, null=True, blank=True) address2 … -
How to to do Mask input in django?
I am working on a little app so I hope you will never mind if I ask some noob questions. I am taking a NIC number from a user but with proper format. Format: xxxxx-xxxxxx-x It means that when a user click in the input field, all the xx should remove and only - will be remains, so if a user types 17301, the - should be appear automatically and then user continue to write 362775 then a - should appear automatically and finally last digit entered by the user 6. This was the complete scenario, I hope I defined it very simple. Input Field Code <div class="col-md-3 mb-3"> <label for="validationCustom10">CNIC</label> <input type="number" class="form-control" id="validationCustom10" placeholder="xxxxx-xxxxxxx-x" name="contact" required> </div> -
Django - Adding custom class to label_tag
I am trying to figure out a way to add a class to my tag on my form. I want to accomplish this without something like crispyforms and if possible not having to edit the html. Based on my knowledge and googling I have spent a few hours trying to figure this out but I cannot haha. I basically just want to output a class in the label element like so: <label class='text-muted' for="id_street_address">Street Address:</label> My model is as follows: class CheckoutForm(forms.Form): street_address = forms.CharField(widget=forms.TextInput( attrs={ 'class': 'form-control' } )) apartment = forms.CharField(required=False, widget=forms.TextInput( attrs={ 'class': 'form-control' } )) country = CountryField(blank_label='(select country)') zip_code = forms.CharField(widget=forms.TextInput( attrs={ 'class': 'form-control' } )) same_billing_address = forms.BooleanField(widget=forms.CheckboxInput()) save_info = forms.BooleanField(widget=forms.CheckboxInput()) payment_option = forms.BooleanField(widget=forms.RadioSelect()) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['street_address'].label = 'Street Address' self.fields['apartment'].label = 'Address 2 (optional)' self.fields['zip_code'].label = 'Zip Code' I render my form in the template like this: <form> {% csrf_token %} {% for field in form %} <div class="form-group px-3 my-3"> {{ field.label_tag }} {{ field }} {{ field.help_text }} {{ field.errors }} </div> {% endfor %} </form> Is it possible to do this? Any help is greatly appreciated -
stop Django admin actions from showing project wide
I've got a project with quite a few admin-actions. Currently I'm registering them like so: @admin.action(description='Some admin action description') def do_something_action(self, request, queryset): pass Some of these are being added to the admin-class of another app so I cannot simply add the function directly on the class where they are needed. The problem is that these actions are shown project-wide, on every admin-screen. How can I stop this behaviour, and manually set them where they are wanted? If it matters, it's Django3.2. -
DRF & Pillow: Error: The submitted data was not a file. Check the encoding type on the form
I wrote CreateAPI for Member model. The model contains "photo" ImageField. I need insert onto the photo the watermark and save the result to the field. I do it and add to the request (so serializer can work and save Member with the "updated" photo with the watermark). class MemberCreateView(CreateAPIView): #... def create(self, request, *args, **kwargs): if request.data.get('photo'): # insert watermark img = Image.open(request.FILES['photo'], mode='r') watermark = Image.open('static/members/watermark.png'),mode='r') img.paste(watermark, (0, 0)) # add to request request.data['photo'] = img serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) I got this error in Postman json (testing API): { "photo": [ "The submitted data was not a file. Check the encoding type on the form." ] } -
Getting unexpected error while using Django signals
Models.py ROLES = ( ('1', 'student'), ('2', 'creator'), ('3', 'mentor') ) class User(AbstractUser): role = models.CharField(max_length=2, choices=ROLES, default=1) class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(max_length=40) signals.py from django.db.models.signals import post_save, pre_delete from django.dispatch import receiver from student.models import Student, User @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: Student.objects.create(user=instance) @receiver(post_save, sender=User) def save_profile(sender, instance, **kwargs): instance.student.save() I am trying to add a student in the database whenever a new user registers, for this purpose i am using Django signals but it is giving a strange error that i am not able to understand, error that i am facing is User has no student -
when i start a app in djago with docker-compose it makes its folder under root user whats the problem?
when I want to make changes to files of that app it doesnt let me and wants root password. I tried to change access permissions with chmod and it work but still I think this must be a way so I dont have to do that every time make a app. I use this command to start a app: docker-compose exec web python manage.py startapp appname -
Is it possible to get the value of a Factory boy Faker object for use in another field while making a DjangoModelFactory
I am trying to use factory boy to create a model instance for events, but I am needing to see if I can access the result of a Faker declaration in another field. In the code below, I want to access the start_time field in the end_time field so I can create a datetime that is 1 hour from the start_time. It complains that start_time is a faker object, and not a datetime object. How do I get the Faker class to render its information so I can use it in the end_time field? class EventFactory(DjangoModelFactory): class Meta: model = Event client = factory.SubFactory( ClientFactory, ) customer = factory.SubFactory( CustomerFactory, ) resource = factory.SubFactory( ResourceFactory, ) title = Faker("sentence", nb_words=5) start_time = Faker( "date_time_between_dates", datetime_start=datetime.datetime.now(), datetime_end=datetime.datetime.now() + datetime.timedelta(days=30), ) end_time = start_time + datetime.timedelta(hours=1) all_day = False background_color = None border_color = None text_color = None duration = datetime.timedelta(hours=1) -
Django unit testing: applied to JSON and excel files
first of all i'm sorry if i made English mistakes. I'm new to Django tests, i'm trying to make automation tests for file application. accessed files are (excel, zip, pickle or csv file). Views.py def create(self, request, *args, **kwargs): project_owner = request.POST.get('project_owner') if project_owner is None: return Response('error', status=500) try: # project = Project.objects.filter(id=request.POST.get('project_owner')) project_owner = request.POST['project_owner'] file = request.FILES.get('input_file') project_id = request.POST['projectId'] except (AttributeError, TypeError, Exception): raise AssertionError('The project does not exist') logger.warning('The project does not exist, please create a project!') return Response({'msg': str(e)}, status=500) project = Project.objects.filter(id=project_id).first() if project is None: return Response('project id for filter doesn\'t exist', status=500) if file is None: messages.error(request, 'Upload one of these files: ' '[excel, zip, pickle or csv file]') return HttpResponseRedirect(reverse('project-detail', args=(project_id,))) logger.info(f'Creation of the file: {file.name}') was_handle = False if file.name.endswith(('.zip', '.rar', '.7Z', '.zipx')): was_handle = handle_zip_file(file, project) elif file.name.endswith(('.xlsx', '.xlsm', '.xls', '.xlsb', '.xlt', '.xlr', '.csv')): was_handle = handle_file(file, project) if was_handle: messages.success(request, f'{file.name} successfully uploaded!') else: messages.error(request, 'Upload one of these files: ' '[excel, zip, pickle or csv file]') module_name = project.task.get_module_name() ModuleManager.execute(module_name, 'reloading_properties', request.user.id, project_id) logger.info(f'The file "{file.name}" was created') return HttpResponseRedirect(reverse('project-detail', args=(project_id,))) ---------------- Test_creation view ------------------------- ----------creation file Method-------- def create_file(self, file): csrf_client = Client(enforce_csrf_checks=True) context = … -
How i can filter the query Django form with relations
seniors! Please help with filtering the selection in the fields, how can this be done? using basic creatingView to create a form (ModelForm) Help me please, i have Models: class Filials(models.Model): Fullname=models.CharField(max_length=30,blank=False) Entity=models.CharField(max_length=20,blank=True) City=models.CharField(max_length=15,blank=True) INN = models.IntegerField(max_length=20,blank=True,null=True) def __str__(self): return self.Fullname def get_absolute_url(self): return f'/{self.id}' class Department(models.Model): Filial=models.ForeignKey(Filials, on_delete=models.CASCADE, blank=True) Fullname = models.CharField(max_length=30,blank=False) def __str__(self): return f'{self.Filial}|{self.Fullname}' class SubDepartment(models.Model): Department=models.ForeignKey(Department, on_delete=models.CASCADE, blank=True) Fullname = models.CharField(max_length=30, blank=False) def __str__(self): return self.Fullname class Employee(models.Model): Fullname=models.CharField(max_length=60,blank=False) Position = models.CharField(max_length=30,blank=False) Filial= models.ForeignKey(Filials, on_delete=models.CASCADE, blank=True) Department=models.ForeignKey(Department,on_delete=models.CASCADE, blank=True) SubDepartment=models.ForeignKey(SubDepartment,on_delete=models.CASCADE, blank=True) Fired=models.BooleanField(default=False) Fired_date=models.DateField(blank=True,null=True) Created_date=models.DateField(auto_now=True) Login = models.CharField(max_length=20,blank=False) Password=models.CharField(max_length=15,blank=False) Phone = models.CharField(max_length=12,blank=False) Wordkey=models.CharField(max_length=40,blank=True) def __str__(self): return self.Fullname def get_absolute_url(self): return f'/{self.id}' and forms.py : class CreateEmployee(forms.ModelForm): Fullname = forms.CharField(max_length=60, required=True, widget=TextInput(attrs={ 'class': "form-control", "placeholder": "Fullaname" })) Position = forms.CharField(max_length=60, required=True, widget=TextInput(attrs={ 'class': "form-control", "placeholder": "Position" })) Filial = forms.ModelChoiceField(empty_label=None, queryset=Filials.objects.all(), required=True, widget=Select(attrs={ 'class': "form-control", "placeholder": "Filial" })) Department = forms.ModelChoiceField(queryset=Department.objects.all(), required=True, widget=Select(attrs={ 'class': "form-control", "placeholder": "Department" })) SubDepartment = forms.ModelChoiceField(queryset=SubDepartment.objects.all(), required=True, widget=Select(attrs={ 'class': "form-control", "placeholder": "SubDepartment" })) Fired = forms.BooleanField(required=False) Login = forms.CharField(max_length=60, required=True, widget=TextInput(attrs={ 'class': "form-control", "placeholder": "Login" })) Password = forms.CharField(max_length=60, required=True, widget=TextInput(attrs={ 'class': "form-control", "placeholder": "Password" })) Phone = forms.CharField(max_length=60, required=True, widget=TextInput(attrs={ 'class': "form-control", "placeholder": "Phone" })) Wordkey = forms.CharField(max_length=60, required=False, widget=TextInput(attrs={ 'class': "form-control", "placeholder": … -
Django update_or_create throws an error, but works properly from shell
Say I have two models which are bound by OneToOne relation. class Person(models.Model): ... class Pear(models.Model): consumer = models.OneToOneField( Person, on_delete=models.CASCADE ) color = models.CharField() ... Person ModelSerializer nests Pear ModelSerializer. Person ModelSerializer also has update method which calls update_or_create for Pear. It looks like this. class PearSerializer(serializers.ModelSerializer): class Meta: model = Pear fields = '__all__' class PersonSerializer(serializers.ModelSerializer): pear = PearSerializer(required=False) class Meta: model = Person fields = '__all__' def update(self, instance, validated_data): pear_data = validated_data.pop('pear') ... if pear_data is not None: obj, created = Pear.objects.update_or_create( consumer=pear_data.get('consumer'), defaults={'color': pear_data.get('color')} ) ... So it throws an error saying that the consumer field value should be unique. At the same time update_or_create with the same parameters and absolutely same data works perfectly if called through shell. What am I missing? Thanks. -
Show posts liked by users
I am building a BlogApp and I am stuck on a Problem. I have a two models named Post and FavoriteUsers. Post for creating posts. FavoriteUsers for adding favorite users through ManyToManyField. What i am trying to do :- I am trying to see posts which are liked by favorite users of request.user. user_1 can add favorite multiple users. AND user_1 can see all the posts liked by favorite users. First i am accessing posts which are created by favorite users (which is successfully working) and then i am accessing posts which are liked by favorite users (which is not working). BUT when i try to show the posts which are liked by favorite users then nothing is showing. models.py class BlogPost(models.Model): blog_post_owner = models.ForeignKey(User,default='',null=True,on_delete = models.CASCADE) blog_post_title = models.CharField(max_length=500,default='') likes = models.ManyToManyField(User, related_name='post_like', blank=True) class FavoriteUsers(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE,related_name='parent_user') favorite_users = models.ManyToManyField(User, related_name='favorite_users', blank=True) views.py def show_favourite_users(request): objects = FavoriteUsers.objects.filter(favorite_users=request.user) context = {'objects':objects} return render(request, 'show_favourite_users.html', context) show_favourite_users.html {% for obj in objects %} {% for users in obj.favorite_users.all %} <!-- For access favorite users --> {% for posts in users.blogpost_set.all %} <!-- For access the blogpost title through blogpost_set --> {{ posts.blog_post_title }} {% for like in posts.favorite_users.likes.all … -
timyMCE allowed tags in django
In django I am using tinyMCE field for admin. I need to add a set of tags allowed by me, how can I do this? 'paste_as_text': True, not suitable, need to write a list and make it universally -
MySQL replication for Graphene Django
I'm using Graphene as a GraphQL server in Django. I set up a MySQL replica in Django. My setting is pretty simple. Read requests -> Replica. Write requests -> Source Mutations works in the next way: They modify data and then return modified/new data. Graphene modifies data in Source and immediately selecting them from Replica. The problem is that updated data is not immediately appearing in Replica DB (because of Replication delay). As result, some mutations simply do not work. I have a solution - specifying the Django database in every mutation. Didn't tried it yet. But the project is huge, and this requires a lot of changes in the codebase. I'm looking for simpler solutions. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'db_name', 'USER': 'root', 'HOST': MYSQL_HOST, 'PORT': '3306', }, 'read_replica': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'db_name_replica', 'USER': 'root', 'HOST': MYSQL_HOST_REPLICA, 'PORT': '3306', } } DATABASE_ROUTERS = ['app.db_router.DatabaseRouter'] class DatabaseRouter: def db_for_read(self, model, **hints): return 'read_replica' def db_for_write(self, model, **hints): return 'default' def allow_relation(self, obj1, obj2, **hints): return True def allow_migrate(self, db, app_label, model_name=None, **hints): return True -
Django Allauth - Facebook Login does not produce email
I have issues with the django-allauth facebook login. I have configured the facebook login successfully and I am able to send a request to facebook and get the user's information back to my console to create the user to login. I have met an unusual issue in this process however. When I print the results I obtain from the facebook API to inspect the results, I manage to get a dictionary with "first_name", "last_name" and "name" populated with the facebook user's information but the field "email" and "username" carry a value of None. This is problematic because instead of being able to move forward with the account creation, the user is shown an allauth default html page with a form to enter the email/username. I would like to skip this page altogether and I could if I had the email in the first place. The dictionary that I get is the "data" coming out of allauth/socialaccount/adapter.py function populate_user(populate_user(self, request, sociallogin, data). Maybe I should have the email at the different step? My settings are set up as such: LOGIN_URL = 'login' LOGIN_REDIRECT_URL = '/' LOGOUT_URL = 'logout' LOGOUT_REDIRECT_URL = 'login' SOCIAL_AUTH_RAISE_EXCEPTIONS = False ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_USERNAME_REQURIED = True ACCOUNT_AUTHENTICATION_METHOD … -
Django not saving forms data in database
I am getting forms success message in my html template but forms data not saving. here is my code: views.py: class BlogDetailsAccount(FormMixin,DetailView): model = Blog template_name = 'blog/my-account-blog-details.html' form_class = CommentFrom def get_success_url(self): return reverse('blog:my-account-blog-details', kwargs={'slug': self.object.slug}) def get_context_data(self, **kwargs): #my context data........ return data def post(self, request, *args, **kwargs): self.object = self.get_object() form = self.get_form() if form.is_valid(): messages.add_message(self.request, messages.INFO, 'Your Comment pending for admin approval') return self.form_valid(form) else: messages.add_message(self.request, messages.INFO, 'Somethings Wrong. Please try again') return self.form_invalid(form) def form_valid(self, form): return super(BlogDetailsAccount, self).form_valid(form) my models.py: class BlogComment(models.model): .......#my models fields.... ............. post_save.connect(BlogComment.user_comment, sender=BlogComment) #using signals -
Filtering on a Window function in Django
I have the following model: class Foobar(models.Model): foo = models.IntegerField() And I figured out how to calculate the delta of consecutive foo fields by using window functions: qs = Foobar.objects \ .annotate( delta=F('foo') - Window(Lag('foo'), partition_by=F('variant'), order_by=F('timestamp').asc()) ) Now I only want the records from this where delta is negative: qs.filter(delta__lte=0) But as you might expect, this gives an error: django.db.utils.NotSupportedError: Window is disallowed in the filter clause. How can I do this filtering with the Django ORM? -
Uvicorn + Django + NGinx - Error 404 while handlind websocks
I am setting up a server with Nginx and Uvicorn to run a Django app with websockets. Everything goes well with normal http request and I can get my webpage but my websockets handshakes always end up with a 404 error. Everything goes well running with runserver. here is my asgi.py file import os import django django.setup() from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from django.core.asgi import get_asgi_application import AERS.routing import Stressing.routing os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'AERS.settings') application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": AuthMiddlewareStack( URLRouter( Stressing.routing.websocket_urlpatterns ) ), # Just HTTP for now. (We can add other protocols later.) }) my settings.py ASGI_APPLICATION = 'AERS.asgi.application' redis_host = os.environ.get('REDIS_HOST', '127.0.0.1') CHANNEL_LAYERS = { 'default': { 'CONFIG': { 'hosts': [(redis_host, 6379)], }, 'BACKEND': 'channels_redis.core.RedisChannelLayer', }, } my nginx config file server { listen 80; server_name aers.box 10.42.0.1; location = /favicon.ico { access_log off; log_not_found off; } location ~ ^/static { autoindex on; root /home/AERS; } location ~ ^/ { include proxy_params; proxy_pass http://unix:/home/AERS/AERS.sock; } location @proxy_to_app { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; proxy_buffering off; proxy_pass http://unix:/home/AERS/AERS.sock; } location ~ ^/ws/ { proxy_pass http://unix:/home/AERS/AERS.sock; proxy_http_version 1.1; proxy_redirect off; proxy_buffering off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Upgrade … -
Why do errors differ when I interchange the order of the members of url patterns
Note: I'm not requesting for a help to fix the errors, but to ask the reason why they differ by interchanging the order of url patterns. The following is how my urls.py of my django application (basic_app) looks like: from django.urls import path, re_path from basic_app import views app_name = 'basic_app' urlpatterns = [ path('', views.SchoolListView.as_view(), name='list'), re_path(r'^(?P<pk>[-\w]+)/$', views.SchoolDetailView.as_view(), name='detail'), path('create/', views.SchoolCreateView.as_view(), name='create'), ] when I run the server and type in the url http://127.0.0.1:8000/basic_app/create/, it throws the following error: ValueError at /basic_app/create/ Field 'id' expected a number but got 'create'. Request Method: GET Request URL: http://127.0.0.1:8000/basic_app/create/ Django Version: 3.2.4 Exception Type: ValueError Exception Value: Field 'id' expected a number but got 'create'. Interestingly when I interchanged the order of the 2nd and 3rd url patterns as follows: from django.urls import path, re_path from basic_app import views app_name = 'basic_app' urlpatterns = [ path('', views.SchoolListView.as_view(), name='list'), path('create/', views.SchoolCreateView.as_view(), name='create'), re_path(r'^(?P<pk>[-\w]+)/$', views.SchoolDetailView.as_view(), name='detail'), ] I got a different error: ImproperlyConfigured at /basic_app/create/ Using ModelFormMixin (base class of SchoolCreateView) without the 'fields' attribute is prohibited. Request Method: GET Request URL: http://127.0.0.1:8000/basic_app/create/ Django Version: 3.2.4 Exception Type: ImproperlyConfigured Exception Value: Using ModelFormMixin (base class of SchoolCreateView) without the 'fields' attribute is prohibited. I … -
Accessing submitted form data in separate Django view
I have looked around on SO for a solution to what seems to be a very simple question, but I've not been able to find anything matching. I'm making a simple recipe app in Django. I have made 3 models, one for recipe information like title etc, one foreignkey model for ingredients, and one foreignkey model for methods. From these I have made a model form for the recipe information and two formsets for the ingredients and methods. Everything is working fine on the form page and data is submitting and viewable in Django admin. Please see below my Django view. def make_recipe(request): if request.method == "GET": form = RecipeForm() iformset = IngredientFormSet() mformset = MethodFormSet() return render(request, 'recipes/create_recipe.html', { 'form':form, 'iformset':iformset, 'mformset':mformset,}) elif request.method == "POST": form = RecipeForm(request.POST) if form.is_valid(): recipe_card = form.save() iformset = IngredientFormSet(request.POST, instance = recipe_card) if iformset.is_valid(): ingredients = iformset.save() mformset = MethodFormSet(request.POST, instance = recipe_card) if mformset.is_valid(): methods = mformset.save() if form.is_valid() and iformset.is_valid() and mformset.is_valid(): return redirect('recipe_submitted') And my template: {% extends 'recipes/base.html' %} {% block content %} <form action="." method="post"> {% csrf_token %} <h1>Recipe Information</h1> {% if error_message %} <p><strong>{{ error_message }}</strong></p> {% endif %} {{ form.as_p }} <hr> <h2>Ingredients</h2> {{ … -
Django expects wrong format when validating modelform datefield
I have a page where the user inputs some dates in the dd/mm/yyyy format. In my settings file I have this: DATE_INPUT_FORMATS = ('%d/%m/%Y','%Y/%m/%d', '%Y-%m-%d',) I use the django bootstrap4 datetime picker plus The field renders as such: (i apologize about the screenshot, i couldnt copy the html without it being escaped and it looked extra-messy) The problem The problem is that when i input dates in dd/mm/yyyy format, it uses the american format (mm/dd/yyyy) to validate them. So if i enter 27/12/2021 it will try to save [day 12, month 27, year 2021] and fail the validation. Preventing the formset from being saved. What i don't understand is where in hell does django get the idea that it should use the american format to validate dates when I have set three separate DATE_INPUT_FORMATS and none of them are in the american format? Here an image showing that on the page the date is collected in the right format And the response : [{'start_date': ['Enter a valid date.'], 'end_date': ['Enter a valid date.']}] Forms this is where i am now: class EducationForm(forms.ModelForm): # def clean_start_date(self): # print(self.cleaned_data['start_date']) # return datetime.strptime((self.cleaned_data['start_date']), '%Y-%m-%d') # def clean_end_date(self): # return datetime.strptime((self.cleaned_data['end_date']), '%Y-%m-%d') class Meta: … -
How to send emails every day to subscribed users of a website with python and django?
I want to create some backend code that will send a different email to each subscribed user of my website every day. I am currently using django and want to understand the basic idea of how I can go about making such a backend. Thanks in advance -
How can save encrypted data in db using django
I am trying to save encrypted data in db but it show the error raise DjangoCryptoFieldsKeyPathDoesNotExist( django_crypto_fields.key_path.DjangoCryptoFieldsKeyPathDoesNotExist: Key path does not exist. Got '/KEY_PREFIX.bin' I am using crypto.cipher for encryption. My data is encrypted in salsa20 but it is not saved in db in encrypted form now i use EncyptedTextField, now it show the error Setting.py INSTALLED APPS =[ 'django_crypto_fields.apps.AppConfig', ] KEY_PREFIX.bin Model.py From django_crypto_fields.fields import EncryptedTextField class StoreOrder(models.Model): items = EncryptedTextField(max_length=100) quantity = models.BigIntegerField() dateTime = models.DateTimeField(auto_now_add=True) completion = models.BooleanField(default=False) manager = models.ForeignKey(Store_Employee, on_delete=models.CASCADE) store = models.ForeignKey(Store, on_delete=models.CASCADE) Store.py class Store_Order(LoginRequiredMixin, TemplateView): template_name = 'store/storeOrder.html' def get(self, request, *args, **kwargs): return render(request, self.template_name) def post(self, request): data = self.request.POST.get userId = self.request.user.id managerId = Store_Employee.objects.get(user_id=userId) storeId = Store.objects.get(manager_id=managerId) try: secret = get_random_bytes(32) cipher = Salsa20.new(key=secret) storeOrder = StoreOrder( manager_id=managerId.id, store_id=storeId.pk, items=data('items'), quantity=data('quantity'), ) dat: str = storeOrder.items orderData = dat.encode("latin-1") cipherData = cipher.nonce + cipher.encrypt(orderData) print(cipherData) file = open('KEY_PREFIX', "wb") file.write(cipher) file.close() storeOrder.save() -
How can I return a dict object from within to_representation method of RelatedField in Django rest framework? [closed]
I have a custom field like this: class TagField(serializers.RelatedField): def to_representation(self, value): resp = { 'name': value.name, 'categoryid': value.categoryid.pk } return resp I'm getting an error which says 'dict' object is not hashable. Why does this happen? How can I get it to work?