Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
Access to stye.css denied - Django Static files - Nginx - I can't make my project read staticfiles (style.css)
I don't know what it could be anymore, I've already given permissions to the files, directories, reviewed the nginx config, the files in sites-available/enabled , I've already cleared the cache through django-shell , I've restarted the instance. I simply don't know. Here is the output of nginx: sudo tail -f /var/log/nginx/error.log 2024/03/28 02:27:01 [error] 2952#2952: *12 open() "/home/ubuntu/learning-app/learning-log/learningLog/staticfiles/learningLogApp/css/estilo.css" failed (13: Permission denied), client: 179.214.112.55, server: django.xxx.dev, request: "GET /static/learningLogApp/css/estilo.css HTTP/1.1", host: "django.xxx.dev", referrer: "https://django.xxx.dev/assuntos/" nginx.config: user www-data; worker_processes auto; pid /run/nginx.pid; include /etc/nginx/modules-enabled/*.conf; events { worker_connections 768; # multi_accept on; } http { sendfile on; tcp_nopush on; types_hash_max_size 2048; include /etc/nginx/mime.types; default_type application/octet-stream; ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3; # Dropping SSLv3, ref: POODLE ssl_prefer_server_ciphers on; access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; gzip on; include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*; } sites-available server { listen 80; listen 443 ssl; server_name django.xxx.dev; ssl_certificate /etc/letsencrypt/live/django.xxx.dev/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/django.xxx.dev/privkey.pem; location / { proxy_pass http://localhost:8000; include /etc/nginx/proxy_params; } location /static/ { alias /home/ubuntu/learning-app/learning-log/learningLog/staticfiles; } # Redirecionamento de HTTP para HTTPS if ($scheme = http) { return 301 https://$server_name$request_uri; } } settings.py DEBUG = False ... STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') what have I tried sudo chmod -R a+r /home/ubuntu/learning-app/learning-log/learningLog/staticfiles sudo find /home/ubuntu/learning-app/learning-log/learningLog/staticfiles -type d -exec chmod a+x {} … -
Writing a Django signal to log user activities in a model
These are my models in the models.py file. class User(AbstractUser): date_of_birth = models.DateField(blank=True, null=True) bio = models.TextField(blank=True, null=True) job = models.CharField(max_length=250, blank=True, null=True) photo = models.ImageField(upload_to='account_images/',blank=True, null=True) phone = models.CharField(max_length=11, blank=True, null=True) followings = models.ManyToManyField('self', through='Contact', related_name='followers', symmetrical=False) def get_absolute_url(self): return reverse('social:user_detail', args=[self.username]) class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user_posts') description = models.TextField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) tags = TaggableManager(blank=True) likes = models.ManyToManyField(User, related_name='liked_post', blank=True) saved_by = models.ManyToManyField(User, related_name='saved_post', blank=True) total_likes = models.PositiveIntegerField(default=0) class Meta: ordering = ['-created'] indexes = [ models.Index(fields=['-created']) ] def __str__(self): return self.author.username def get_absolute_url(self): return reverse('social:post_detail', args=[self.id]) class UserActivity(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user_activity') post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='post_activity', blank=True, null=True) action = models.CharField(max_length=50) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return f"{self.user} {self.action} {self.post.author}' post" I want to write a signal in which when a user likes a post, an object of the UserActivity model is created, and the value of the user field is set to the user who liked it. The post field should be set to the post that the user liked. And the action field should be set to 'likes'. @receiver(post_save, sender=Post.likes.through) def create_like_activity(sender, instance, **kwargs): if instance.likes.exists(): UserActivity.objects.create( user=instance.likes.last(), post=instance.author, action='likes' ) I tried to achieve this through this … -
Django urls works locally, but deployed to heroku all but one work
I am creating a React/Django website for my final project. I have apps, such as posts, profiles, etc., that work perfectly both locally and when deployed to Heroku. However, one of the apps, "base," works without issue locally but breaks when pushed to Heroku. I suspect it's a serializers/views issue, but I'm not entirely sure. How can I fix this issue? "base" app that won't work on Heroku Views: Screenshot URLs: Screenshot Serializers: Screenshot Any help is appreciated. I'm still learning, and this could very well be a simple typo for all I know, but I cannot seem to solve it. I've tried changing the URLs in every way I could think of, to no avail. I've also attempted changing the serializers and views, but I can't seem to solve it. -
Error creating auth token for newly registered user in Django Rest Framework
I'm working on a Django project where I'm trying to create an auth token for a newly registered user using Django Rest Framework. However, when running the register function, I run into the following error: ValueError: Cannot assign "<User: Test>": "Token.user" must be a "User" instance. Here is the register function where the error occurs: @api_view(['POST']) def register(request): serializer = UserSerializer(data=request.data) if serializer.is_valid(): serializer.save() user = User.objects.get(username=request.data['username']) user.hash_password(request.data['password']) user.save() token = Token.objects.create(user=user) # This is where the error occurs return Response({ 'token': token.key, 'User': serializer.data }, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) How can I fix this error and successfully create the authentication token for the newly registered user? I have tried to register a new user using the register function in my Django Rest Framework view. I was expecting the user to register successfully (register in the database) and for an auth token to be generated associated with that user. -
Django site working for all pages except for a few
I'm using a combo of python and django in order to load a site. A HTML home file is also present in the templates folder. I coded all parts of my site the way I normally do, which has worked for every single instance except for this one. The only app in my site is called "news". Here's the error I recieved after in my terminal after clicking the link python manage.py runserver gave me. Internal Server Error: / Traceback (most recent call last): File "C:\Users\Mahsa\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Mahsa\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "K:\Desktop 2.0\Python 6\irna_project\news\views.py", line 6, in home return render(request, "news/home.html", {"news", all_news}) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Mahsa\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\shortcuts.py", line 24, in render content = loader.render_to_string(template_name, context, request, using=using) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Mahsa\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\template\loader.py", line 62, in render_to_string return template.render(context, request) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Mahsa\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\template\backends\django.py", line 57, in render context = make_context( ^^^^^^^^^^^^^ File "C:\Users\Mahsa\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\template\context.py", line 286, in make_context raise TypeError( TypeError: context must be a dict rather than set. [28/Mar/2024 02:45:00] "GET / HTTP/1.1" 500 78799 Not Found: /favicon.ico [28/Mar/2024 02:45:00] "GET /favicon.ico HTTP/1.1" 404 2334 For more info, here are the main files: settings.py: """ Django settings for …