Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Want to retrieve a Foreign Key value instead of the whole object with django-rest-framework serializers
I'm using the Django rest framework to create an API. I have the following models: (https://i.stack.imgur.com/oasDY.png)](https://i.stack.imgur.com/oasDY.png) models.py class Faculty(models.Model): name = models.CharField(max_length=25, unique=False, null=False, blank=False) email = models.EmailField(max_length=25, unique=True, null=False, blank=False) class Course(models.Model): name = models.CharField(max_length=25, unique=True, null=False, blank=False) faculty_name = models.ForeignKey(Faculty, on_delete=models.CASCADE, related_name='faculty_name') end_date = models.DateField() def __str__(self): return self.faculty_name # @property # def faculty_name(self): # return self.faculty.name To create a serializer serializers.py class FacultySerializer(serializers.ModelSerializer): class Meta: model = Faculty fields = '__all__' class CourseSerializer(serializers.ModelSerializer): # faculty_name = serializers.SlugRelatedField(slug_field='name', read_only=True) # faculty_name = serializers.ReadOnlyField(source='faculty.name') print(Faculty.objects.all().values('name')) class Meta: model = Course fields = ('name', 'faculty_name', 'end_date') To create rest services using the following views: views.py class Course(mixins.ListModelMixin, mixins.CreateModelMixin, generics.GenericAPIView): serializer_class = CourseSerializer queryset = Course.objects.all() def get(self, request, *args, **kwargs): return self.list(request, *args, **kwargs) def post(self, request, *args, **kwargs): return self.create(request, *args, **kwargs) class Faculty(mixins.ListModelMixin, mixins.CreateModelMixin, generics.GenericAPIView): serializer_class = FacultySerializer queryset = Faculty.objects.all() def get(self, request, *args, **kwargs): return self.list(request, *args, **kwargs) def post(self, request, *args, **kwargs): return self.create(request, *args, **kwargs) Getting the Faculty object while accessing the /course/ endpoint as shown in the image. want to get the faculty name instead of the Faculty object in the post method's form fields(dropdown) I have tried the below codes: 1)faculty_name = … -
multipart/form-data not setting in MultipartEncoder (python)
I am trying to upload a file to a server and it only accepts the file in multipart/form-data format so when i try to send it by encoding like: m = MultipartEncoder( fields={'document': json.dumps(metadata), 'files': (file_name, open(file_path,'rb'),'multipart/form-data')} ) headers = {'content-type': m.content_type} response = requests.post(url, headers=headers, data=m) It still shows the error: '{"success":false,"errorMsg":"Content type 'application/octet-stream' not supported"}' How do i resolve this when i have explicitly set the content-type to multipart/form-data? -
request.FILES in Django
I need the following code to work as written: testo = request.POST.get('testo') lang = request.POST.get('lang') audio = request.FILES['audio'] fs = FileSystemStorage() filename = fs.save(audio.name, audio) uploaded_file_url = fs.url(filename) The problem is that for request.FILES the form is required to be - enctype="multipart/form-data" - My form instead is like this: <form action="{% url 'app' %}" method="post"> {% csrf_token %} <textarea name="testo" id="" cols="30" rows="10"></textarea> <label for="lang">Scegli lingua:</label> <select name="lang" id=""> <option value="it">Italiano</option> <option value="en">Inglese</option> <option value="es">Spagnolo</option> </select> <input type="file" name="audio" id=""> <button type="submit">INVIA</button> </form> With my form I can get the text to work, but I can't get request.FILES to work!!! Any solution? Unfortunately I can't with my form. I need it as is, but I need something that allows me to make text and files work in Django -
Why does Django add 1 second to the lifetime of a cookie?
I'm trying to implement JWT authentication using django-graphql-jwt on the backend, and nuxt3 for the frontend. My token and refresh_token are stored in cookies, and I wrapped the GraphQLView in a jwt_cookie decorator that automatically checks for the existence of the jwt token in the cookie, as well as its validity. In general, everything works great. When I send an authorization request, the backend returns me the "Set-Cookie" headers for JWT and JWT_REFRESH_TOKEN with an expiration date that automatically deletes them as soon as they become invalid, which saves me a lot of code/logic on the frontend. However, there is one very unpleasant thing - Django adds 1 second to the cookie lifetime for some reason in the set_cookie function, and it ruins everything. Here is the Django code: def set_cookie( self, key, value="", max_age=None, expires=None, path="/", domain=None, secure=False, httponly=False, samesite=None, ): self.cookies[key] = value if expires is not None: if isinstance(expires, datetime.datetime): if timezone.is_naive(expires): expires = timezone.make_aware(expires, datetime.timezone.utc) delta = expires - datetime.datetime.now(tz=datetime.timezone.utc) # Add one second so the date matches exactly (a fraction of # time gets lost between converting to a timedelta and # then the date string). # Here's what I mean ↓↓↓ delta += datetime.timedelta(seconds=1) … -
Django using Subquery in annotate: How to fetch all rows that match the condition of filtering
I have two models with M2M field. Because there wont be any update or deletion (just need to read data from db) I'm looking to have single db hit to retrieve all the required data. I used prefetch_related with Prefetch to be able to filter data and also have filtered objects in a cached list using to_attr. I tried to achieve the same result using annotate along with Subquery. but here I can't understand why the annotated filed contains only one value instead of a list of values. let's review the code I have: some Routes may have more than one special point (Point instances with is_special=True). models.py class Route(models.Model): indicator = models.CharField() class Point(models.Model): indicator = models.CharField() route = models.ManyToManyField(to=Route, related_name="points") is_special=models.BooleanField(default=False) views.py routes = Route.objects.filter(...).prefetch_related( Prefetch( "points", queryset=Point.objects.filter(is_special=True), to_attr="special_points", ) ) this will work as expected but it will result in a separate database querying to fetch the points data. in the following code I tried to use Subquery instead to have a single database hit. routes = Route.objects.filter(...).annotate( special_points=Subquery( Point.objects.filter(route=OuterRef("pk"), is_special=True).values("indicator") ) the problem is in the second approach will have either one or none special-point indicator when printing route_instance.special_points even if when using prefetch the printed … -
Why does the ImageGalleryBlock in wagtail-crx/coderedcms return no images?
Wagtail-CRX installs with a pre-defined StreamField ImageGalleryBlock that allow a user to select a Collection of images that are then output to the page along with a modal pop-up structure. In models.py of my app I have created the image_gallery variable like this image_gallery = StreamField([ ('image_gallery', ImageGalleryBlock()), ], verbose_name="Choose images for the gallery", null=True, blank=True, default="", use_json_field=True ) FieldPanel("image_gallery"), This worls fine. The FieldPanel adds the Collection choice block to the page edit form. However, the images in the chosen Collection never appear on the page using any of the possible methods for calling the block into the page template e.g. {% for block in page.image_gallery %} <section>{% include_block block %}</section> {% endfor %} The include here calls in the block using the template image_gallery_block.html - the structure for the modal pop-up is rendered on the page but there no images appear to populate it with. Inside the image_gallery_block.html template the first line is {% get_pictures self.collection.id as pictures %} where get_pictures is a function that should pass the data from the Collection objects into the variable pictures and they should be iterated over in the subsequent template html thus {% if pictures %} {% for picture in pictures … -
Getting 404 error when trying to use slugs in Django
I'm new one in Django and trying to develop website. What I need is to use slugs in URLs in Django. When I use id's everything works well. I have done the following steps: I have a model Posts with . class Post(models.Model): title = models.CharField(max_length=100) slug = models.SlugField(max_length=100, unique=True, default='') content = models.TextField() category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True, blank=True) photo = models.ImageField(upload_to='post_photos/', blank=True) # ImageField для хранения изображений created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) is_published = models.BooleanField(default=False) def __str__(self): return self.title def save(self, *args, **kwargs): if not self.photo: # Если поле photo пустое, генерируем случайный путь к изображению random_image_path = get_random_image_path() self.photo = random_image_path # Привязываем случайное изображение к объекту Post super().save(*args, **kwargs) def get_absolute_url(self): return reverse('post', kwargs={'post_slug': self.slug}) I have written the following in my urls.py and views.py path('fitness/<slug:post_slug>/', views.show_post, name='post'), def show_post(request, post_slug): post = get_object_or_404(Post, slug=post_slug) return render(request, 'show_post.html', {'post': post}) and this works well. But then I try to make some amendmens to use slugs. The following ones: def get_absolute_url(self): return reverse('post', kwargs={'post_slug': self.slug}) def show_post(request, post_slug): post = get_object_or_404(Post, slug=post_slug, category__slug='fitness') return render(request, 'show_post.html', {'post': post}) And I get the following error Page not found (404) “/home/tkzeujpw/blog/fitness/fitness-post-1” does not exist Request Method: GET Request … -
How to supress naive datetime warning in django
In django whenever i use Datetime.datetime.now() a runtime warning : enter code here received a naive datetime (2024-03-28 16:18:54.096253) while time zone support is active is displayed , i want to supress this warning or basically tell django to ignore this warning, is there a change i can make in the settings file to tell django to ignore the naive datetime field warning eg: b = User.objects.create() b.start = datetime.datetime.now() b.save() runtime warning : received a naive datetime (2024-03-28 16:18:54.096253) while time zone support is active tried : setting USE_TZ = False in settings.py -
How to configure django 5.0.3 to be able to use private/public media files on AWS - s3
today I feel very frustrated , after 3 days trying to implement django using amazon s3 with media file in private mode. In the past my apps has been configured using the following link bellow and always work fine: https://unfoldadmin.com/blog/configuring-django-storages-s3/ From now for some reasson is not possible to reach the goald (some media files need to be private) I undestand that from django 4.2 exist new way to configure storages but still you are able to continue with old option, To be honest I do not sure if this will be the cause of the problem: https://docs.djangoproject.com/en/5.0/ref/settings/ { "default": { "BACKEND": "django.core.files.storage.FileSystemStorage", }, "staticfiles": { "BACKEND": "django.contrib.staticfiles.storage.StaticFilesStorage", }, } versions: Phyhon: 3.12.2 asgiref==3.8.1 boto3==1.34.72 botocore==1.34.72 Django==5.0.3 django-storages==1.14.2 jmespath==1.0.1 python-dateutil==2.9.0.post0 s3transfer==0.10.1 six==1.16.0 sqlparse==0.4.4 tzdata==2024.1 urllib3==2.2.1 Configuration on AWS: Object Ownsership:ACls enabled Block all public access: off Bucket policy: { "Version": "2012-10-17", "Id": "Policy_id", "Statement": [ { "Sid": "my_sid", "Effect": "Allow", "Principal": "*", "Action": "s3:GetObject", "Resource": "arn:aws:s3:::mybucket_name/*" } ] } Note: I have to say that appear the ACLs is working because after uploading a private file if you try to retrieve the URL of the content , the API will generate a long URL that expire after a few minutes, … -
How notification works [closed]
Need an notification when a registration is complete or a new user is created on user side.This notification is shown in admin side.This is a REACT project and the backend is provided through django REST Api. I created a seperate db for notifications ,it is not working automatically when a registration is completed. -
Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response, nginx, django, waitress
I'm using nginx server to serve static React js files and waitress server for django rest framework with 0.0.0.0:8000 as address to serve api's. I'm using nginx as a reverse proxy for django. Even though i have modified django setting to allow all origins and modified nginx conf file to include cross origin headers and pre-flight headers. I'm still getting an error saying "Access to XMLHttpRequest at 'http://15.295.156.60:8000/core/profile/profile/' from origin 'http://15.295.156.60' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response." I tried modifying the nginx conf file to include cross origin headers and pre-flight headers for the django reverse proxy. Modified the django settings to allow all origins. I want to handle this error "Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response." these are my django settings " CORS_ALLOW_ALL_ORIGINS = True CORS_ORIGIN_WHITELIST = [ 'http://192.168.56.1:80', 'http://localhost:3000', 'http://*', # Add any other origins that you want to allow here ]" , This is my frontend request " const axiosInstance = axios.create({ baseURL: baseURL, timeout: 5000, headers: { Authorization: localStorage.getItem('access_token') ? 'JWT ' + localStorage.getItem('access_token') : null, 'Content-Type': 'application/json', accept: 'application/json', }, });" , This is how i'm configuring … -
migrate error : ...No migrations to apply
I made some changes in the models from my apps and then entered makemigrations and migrate in the terminal. PS C:\Users\USER 1\frist project\website> python manage.py makemigrations home No changes detected in app 'home' PS C:\Users\USER 1\frist project\website> python manage.py migrate ?[36;1mOperations to perform:?[0m ?[1m Apply all migrations: ?[0maccounts, admin, auth, cart, contenttypes, home, order, sessions, taggit, thumbnail ?[36;1mRunning migrations:?[0m No migrations to apply. -
Edit Form in Modal Window Django
I am trying to do an Edit form in the modal window. The problem is that I cannot pass the form into the modal window and show the modal. I tried to do it with HTMX but it is not what I am looking for. forms.py class SettingsForm(forms.ModelForm): code = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'})) value = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'})) description = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'})) class Meta: model = KrnListValue fields = ['code', 'value', 'description'] views.py def edit_setting(request, pk): entry = get_object_or_404(KrnListValue, pk=pk) if request.method == 'POST': form = SettingsForm(request.POST, instance=entry) if form.is_valid(): form.save() else: form = SettingsForm(instance=entry) settings.html <button hx-get="{% url 'edit_setting' pk=setting.pk %}" hx-target="#dialog" class="btn btn-primary" style="margin-right:5px;"> save </button> <div id="modal" class="modal fade"> <div id="dialog" class="modal-dialog" hx-target="this"> # PASS IT HERE </div> </div> I was doing something like this. But still it didnt work. I suppose in edit_setting I can return HttpResponce. But didnt figure out how to do that. -
Reading IPTC information Django
I have published my django project on shared hosting, there are no problems at all. Everything seems to work as it should, but as soon as the system is to read IPTC information from images, it does not work. I get absolutely no errors, but it doesn't read the information. But in the local development server on my macbook it works without problems, then it reads the iptc information. Both use the same code, the same python version and the same Pillow. What should I do? I have tried to change the code a bit, but to no avail. -
Dropzone inside a Django form
I'm trying to make a django form in which I want to upload a photo (Dropzone) and enter its title. I can't send the title field and the photo to my view at the same time. Could you please help me ? Request.files seems empty. add.js // DropzoneJs let myDropzone = new Dropzone("#kt_dropzonejs_example_1", { url: "add", // Set the url for your upload script location paramName: "file", // The name that will be used to transfer the file autoProcessQueue: false, maxFiles: 1, maxFilesize: 1000, // MB acceptedFiles: 'image/*', addRemoveLinks: true, init: function () { this.on("success", function (file, response) { console.log(response); }); }, headers: { 'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value } }); the "url" parameter seems obligatory and gives me problems but necessary with keenthemes metronic add.htm <form class="form" novalidate="novalidate" id="kt_add_video_form" data-kt-redirect-url="/" action="#" method="POST" enctype="multipart/form-data"> {% csrf_token %} <!--begin::titre photo group--> <div class="row mb-6"> <!--begin::Label--> <label class="col-lg-3 col-form-label required fw-semibold fs-6" for="{{ form.caption.id_for_label }}">Titre de la photo</label> <!--end::Label--> <!--begin::input--> <div class="col-lg-9 fv-row"> {% render_field form.caption class="form-control form-control-lg form-control-solid mb-3 mb-lg-0" placeholder="Titre"%} </div> <!--end::input--> </div> <!--end::titre photo group--> <!--begin::Dropzone--> <div class="dropzone" id="kt_dropzonejs_example_1"> <!--begin::Message--> <div class="dz-message needsclick"> <i class="ki-duotone ki-file-up fs-3x"><span class="path1"></span><span class="path2"></span></i> <!--begin::Info--> <div class="ms-4"> <h5 class="fs-6 fw-bold text-gray-500 mb-1">Faites glisser votre photo ici ou … -
Django queryset remains empty initially but populates after creating an object without re-running the query. How is this possible?
I'm encountering a perplexing issue in my Django application. I have a queryset (qs) obtained from a database query at the beginning of a DRF api call. Strangely, this queryset appears empty upon inspection. However, as I continue through the code execution, I create an object for the same model without re-running the queryset, and to my surprise, the queryset suddenly populates with the newly created object. Here's a simplified version of what I'm experiencing: # Initial queryset initial_qs = MyModel.objects.filter(some_condition=True) # At this point, initial_qs appears empty when I print it or inspect its contents # Creating an object without re-running the queryset new_object = MyModel.objects.create(some_field='value') # Now, if I print initial_qs or inspect its contents again, it contains the newly created object # How is it possible that the queryset remains empty initially but populates later without re-running the query? Is there something I'm overlooking in Django's ORM caching mechanism or the way queryset evaluation works? -
Need help in optimizing the seriliazer
I have the following model ProductCategory. class ProductCategory(Model): name = CharField(max_length=200) parent_category = ForeignKey( "ProductCategory", related_name='child_categories', on_delete=CASCADE, blank=True, null=True, ) is_base_category = BooleanField(default=True) I have the following ProductCategorySerializer. class ProductCategorySerializer(serializers.ModelSerializer): children = serializers.SerializerMethodField(read_only=True) @staticmethod def setup_eager_loading(queryset): # Prefetch for subsets of relationships queryset = queryset.prefetch_related( 'parent_category', Prefetch( 'child_categories', queryset=ProductCategory.objects.prefetch_related( 'child_categories', ) ), ).filter( is_base_category=True ).order_by( 'name' ) return queryset def get_children(self, category): return [{ 'name': c.name, 'id': c.id, 'children': self.get_children(c), 'is_base_category': c.is_base_category, 'parent_category': category.id, 'grandparent_category': category.parent_category.id if category.parent_category else None, } for c in category.child_categories.order_by('name')] class Meta: model = ProductCategory fields = ( 'id', 'name', 'is_base_category', 'children', 'parent_category', ) Only for top parent category will be having is_base_category=True. The above serializer is taking 10 to 15 seconds to execute. Is there any way I can optimize the above serializer. Or is there any other suggestions? -
Cassandra: "Model keyspace not set" and "Connection name doesn't exist in the registry" Errors
I recently upgraded to Django 4.2 and am facing issues with Cassandra integration. Initially, I encountered the following error when attempting to generate queries: cassandra.cqlengine.CQLEngineException: Model keyspace is not set and no default is available. Set model keyspace or setup connection before attempting to generate a query. This error was thrown despite specifying the model keyspace in settings.py. As an attempted fix, I explicitly set the keyspace in my models like so: __keyspace__ = "my_keyspace" However, this led to a new set of errors related to connection names not existing in the registry: Connection name '<object object at 0x7f4fb00d67a0>' doesn't exist in the registry. This issue persists across multiple models and queries. Here are some relevant details about my setup: Python 3.10 django-cassandra-engine 1.7.0 Running inside Docker; connectivity to Cassandra from within Docker has been verified Here's a full error. sessions, disconnected = fetch_sessions_list(ux_vms) File "/code/wtools2/apps/analytics/views.py", line 1652, in fetch_sessions_list metrics_session.extend(list(sessions_db)) File "/usr/local/lib/python3.10/site-packages/cassandra/cqlengine/query.py", line 437, in __len__ self._execute_query() File "/usr/local/lib/python3.10/site-packages/cassandra/cqlengine/query.py", line 472, in _execute_query self._result_generator = (i for i in self._execute(self._select_query())) File "/usr/local/lib/python3.10/site-packages/cassandra/cqlengine/query.py", line 456, in _select_query self.column_family_name, File "/usr/local/lib/python3.10/site-packages/cassandra/cqlengine/query.py", line 397, in column_family_name return self.model.column_family_name() File "/usr/local/lib/python3.10/site-packages/cassandra/cqlengine/models.py", line 559, in column_family_name raise CQLEngineException("Model keyspace is not set and no … -
Django Deployment on AWS EC2 with Docker Compose: Seeking Advice on Security, Scalability, and Best Practices
I am currently working on deploying a Django application to an AWS EC2 instance using Docker Compose. The setup involves containerizing both the Django app and NGINX, with AWS RDS utilized for the database. Additionally, there's a Redis service planned for use with a Celery worker. While the deployment process is functional, I have several questions and areas I'd like to improve. Current Setup: Dockerfiles are used to create images for the Django app and NGINX, each requiring a 'TAG' variable. Docker Compose is configured to utilize environment variables and create three services: Django app, NGINX, and Redis (for future Celery worker). GitHub Actions workflow is implemented with two jobs: 'build' to build and push Docker images (tag: short version of the SHA-1 hash of the latest commit), and 'deploy' to copy Docker Compose to EC2 and execute the deployment. Questions and Areas for Improvement: HTTPS Implementation: Currently, the setup only supports HTTP. Resource Limitation: Is it advisable to limit resources in Docker Compose? Locally, I noticed high CPU usage initially. How can I control this on EC2 to prevent performance issues? Multiple Environments: I aim to establish separate staging and production environments. Should I utilize AWS RDS for staging, … -
Django: FieldError: Cannot resolve keyword 'name' into field. Choices are: Name, id
Just get started with Django. I was following this tutorial:Django Tutorial Part 3: Using models, and I encountered this issue at the linked step python3 manage.py makemigrations python3 manage.py migrate After executing the second command the error appears. Full Error message: PS E:\DjangoDrill\locallibrary> python manage.py migrate Operations to perform: Apply all migrations: admin, auth, catalog, contenttypes, sessions Running migrations: Applying catalog.0001_initial...Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\Narea\AppData\Roaming\Python\Python38\site-packages\django\core\management\__init__.py", line 442, in execute_from_command_line utility.execute() File "C:\Users\Narea\AppData\Roaming\Python\Python38\site-packages\django\core\management\__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Narea\AppData\Roaming\Python\Python38\site-packages\django\core\management\base.py", line 412, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Narea\AppData\Roaming\Python\Python38\site-packages\django\core\management\base.py", line 458, in execute output = self.handle(*args, **options) File "C:\Users\Narea\AppData\Roaming\Python\Python38\site-packages\django\core\management\base.py", line 106, in wrapper res = handle_func(*args, **kwargs) File "C:\Users\Narea\AppData\Roaming\Python\Python38\site-packages\django\core\management\commands\migrate.py", line 356, in handle post_migrate_state = executor.migrate( File "C:\Users\Narea\AppData\Roaming\Python\Python38\site-packages\django\db\migrations\executor.py", line 135, in migrate state = self._migrate_all_forwards( File "C:\Users\Narea\AppData\Roaming\Python\Python38\site-packages\django\db\migrations\executor.py", line 167, in _migrate_all_forwards state = self.apply_migration( File "C:\Users\Narea\AppData\Roaming\Python\Python38\site-packages\django\db\migrations\executor.py", line 252, in apply_migration state = migration.apply(state, schema_editor) File "C:\Users\Narea\AppData\Roaming\Python\Python38\site-packages\django\db\migrations\migration.py", line 132, in apply operation.database_forwards( File "C:\Users\Narea\AppData\Roaming\Python\Python38\site-packages\django\db\migrations\operations\models.py", line 1135, in database_forwards schema_editor.add_constraint(model, self.constraint) File "C:\Users\Narea\AppData\Roaming\Python\Python38\site-packages\django\db\backends\sqlite3\schema.py", line 562, in add_constraint super().add_constraint(model, constraint) File "C:\Users\Narea\AppData\Roaming\Python\Python38\site-packages\django\db\backends\base\schema.py", line 532, in add_constraint sql = constraint.create_sql(model, self) File "C:\Users\Narea\AppData\Roaming\Python\Python38\site-packages\django\db\models\constraints.py", line 239, in create_sql expressions = self._get_index_expressions(model, … -
I don't understand which databases are invalid
I'm getting the following data: {'name_work': 'рациональные числа', 'writing_date': datetime.datetime(2024, 3, 15, 16, 18, 37, tzinfo=datetime.timezone.utc), 'student_type': <TypeStudentWork: TypeStudentWork object (2)>, 'number_of_tasks': '10', 'student': <User: Dear Student>, 'example': <Example: ответы к 1 самостоятельной>, 'teacher': <SimpleLazyObject: <User: Diana Berkina>>, 'image_work': <InMemoryUploadedFile: только_ответы.jpg (image/jpeg)>} My views is a class that receives this data and sends it to the form: class CreateStudentWorkView(View): def post(self, request, type_work_id): try: type_work_obj = TypeStudentWork.objects.get(pk=type_work_id) students = User.objects.filter(student_class=type_work_obj.school_class) print(students) for student in students: image_file = request.FILES.get("image_work_" + str(student.id)) if image_file: initial_data = { 'name_work': type_work_obj.name_work, 'writing_date': type_work_obj.writing_date, 'student_type': type_work_obj, 'number_of_tasks': '10', 'student': student, 'example': type_work_obj.example, 'teacher': request.user, 'image_work': image_file } print("Initial data for student", student.username, ":", initial_data) form = StudentWorkForm(initial=initial_data) print(form.errors) if form.is_valid(): form.save() else: print("Errors for student", student.username, ":", form.errors) except Exception as e: print(e) return redirect('moderator') My model is the model of the work I'm trying to keep: class StudentWork(models.Model): name_work = models.CharField(max_length=55) writing_date = models.DateTimeField() student_type = models.ForeignKey( TypeStudentWork, related_name='type_works', on_delete=models.CASCADE, blank=True, null=True ) number_of_tasks = models.CharField(max_length=5, default="5") student = models.ForeignKey( User, related_name='student', on_delete=models.SET_NULL, null=True ) example = models.ForeignKey( Example, on_delete=models.SET_NULL, null=True ) image_work = models.ImageField(upload_to='image') text_work = models.TextField(null=True, blank=True) proven_work = models.TextField(null=True, blank=True) assessment = models.CharField(max_length=10, null=True, blank=True) teacher = models.ForeignKey( User, related_name='teacher', on_delete=models.SET_NULL, … -
Always incorrect password in Django
So, the problem is always incorrect password even though its correct. I make sure to type the password correctly in the register and yet in the login its incorrect password. I don't know how to fix it anymore, I'm lost. views.py from django.contrib.auth.hashers import make_password, check_password from django.core.exceptions import ObjectDoesNotExist from django.contrib.auth import authenticate, login from .forms import RegistrationForm, LoginForm from django.shortcuts import render, redirect from django.contrib import messages from django.shortcuts import HttpResponse from .models import * # Create your views here. def home(request): return render (request,"home.html") def register(request): if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): email = form.cleaned_data.get('email').strip() # Trim leading and trailing whitespace password = form.cleaned_data.get('password1').strip() # Trim leading and trailing whitespace if Customer.objects.filter(email=email).exists(): messages.error(request, "A customer with this email already exists.") return redirect('user_register') # Hash the password using make_password encrypted_password = make_password(password) customer = Customer.objects.create( username=form.cleaned_data['username'], firstname=form.cleaned_data['firstname'], lastname=form.cleaned_data['lastname'], email=email, address=form.cleaned_data['address'], phone=form.cleaned_data['phone'], birthdate=form.cleaned_data['birthdate'], password1=encrypted_password ) messages.success(request, "You registered successfully!") return redirect('login') else: form = RegistrationForm() return render(request, "register.html", {'form': form}) def user_login(request): if request.method == 'POST': email = request.POST.get('email').strip() # Trim leading and trailing whitespace password = request.POST.get('password').strip() # Trim leading and trailing whitespace try: user = Customer.objects.get(email=email) stored_password = user.password1.strip() # Trim leading and trailing … -
How to host a react and django application on ec2
I have a reactjs and django application using mysql for backend. I want to host this website on ec2. I have also purchased a domain. Right now I am running both the react server and django server on the ec2 instance and I am being able to access this website, with the elastic IP address assigned to the instance, something like public-address:3000. I now want to able to link the domain with the ec2 instance. I have configured my domain to be linked to my instance using DNS, but the problem is the react server is running on the local host of the ec2 instance, and when I access the domain, I cont view the website. Can someone help me out with this -
How do I store sensitive user specific data in my Django application?
Users in my Django application all have unique API keys from a third-party service. The feature in my application that I'm building requires the retrieval of the api key with respect to the current user. What are the best practises here and best options? -
Cant deploy django-tailwind development server
Ive followed django-tailwind installation docs and did everything until last step, however, when I try to run 'python manage.py tailwind start', I got the following error: `(venv) catatal@catatal-Predator-PH315-52:~/dev/portal_prosesmt$ python manage.py tailwind start > theme@3.8.0 start > npm run dev > theme@3.8.0 dev > cross-env NODE_ENV=development tailwindcss --postcss -i ./src/styles.css -o ../static/css/dist/styles.css -w /home/catatal/dev/portal_prosesmt/theme/static_src/node_modules/postcss-load-config/node_modules/lilconfig/src/index.js:161 } = getOptions(name, options ?? {}, false); ^ SyntaxError: Unexpected token '?' at wrapSafe (internal/modules/cjs/loader.js:915:16) at Module._compile (internal/modules/cjs/loader.js:963:27) at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10) at Module.load (internal/modules/cjs/loader.js:863:32) at Function.Module._load (internal/modules/cjs/loader.js:708:14) at Module.require (internal/modules/cjs/loader.js:887:19) at require (internal/modules/cjs/helpers.js:74:18) at Object.<anonymous> (/home/catatal/dev/portal_prosesmt/theme/static_src/node_modules/postcss-load-config/src/index.js:6:16) at Module._compile (internal/modules/cjs/loader.js:999:30) at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)` My node version is: 12.22.9; My npm version is: 8.5.1; Ubuntu is 20.0.4. Ive changed postcss.config.js file from: `module.exports = { plugins: { "postcss-import": {}, "postcss-simple-vars": {}, "postcss-nested": {} }, }` to: `export const plugins = { "postcss-import": {}, "postcss-simple-vars": {}, "postcss-nested": {} };` As suggested from VS Code, however it didnt solve the problem.