Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cross-domain issues between Vue and Django
I encountered a problem when using CROS to solve cross-domain issues between Vue and Django. In the Django part, I have completed the corresponding settings and can already request Django from the Vue interface at http://localhost:5173. But when I use http://127.0.0.1:5173 to access Vue, a CORS error occurs when requesting Django.As follows: The localhost domain name can be cross-domain normally A cross-domain error occurred in the 127.0.0.1 domain name My Django side has been configured with corsheaders and CORS_ORIGIN_WHITELIST Django settings -
Django: messages.error doesn't work with redirect('/')
I'm so confused in templates main page I have: {% for message in messages %} {% if message.level == DEFAULT_MESSAGE_LEVELS.ERROR %} <div class="alert alert-danger" role="alert">{{ message }}</div> {% endif %} {% endfor %} but the message is not printed. in views.py I have def my_form(request): if not str(request.POST['name']): messages.error(request,'error message.') return redirect('/') and in myapp urls.py path('', views.index, name='index'), re_path(r'^MyForm/$', views.my_form, name='my_form') and in the general urls.py re_path(r'^', include('myapp.urls'), name='home') what could be the issue, the log file shows nothing -
Hello, how do I correct this django error because I've already done everything?
Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/concesionario/lista_vehiculos/ Using the URLconf defined in concesionario_proyecto.urls, Django tried these URL patterns, in this order: Lista_vehiculos.html The current path, concesionario/lista_vehiculos/, didn’t match any of these. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. This error is from Django I tried all the methods and it doesn't work and I hope to create a project using the Django Framework, of an application for a dealer of new vehicles, the project must contain a use and/or configuration of: Django installation. Creation of the Django project. Creation of the application for the dealership. Creation of the required data models Create the required views. Create the base template to apply to two dependent HTML documents. Execution and correct functional demonstration of the created system -
Django usercreation form not creating user after authentication
I am currently learning Django and working on a project to help me learn, I created my custom usercreation form and everything seems to work except when i fill in the form it does not create a new user, when i open the sign up page it seems to see it as a request to create a new user and doesnt create one since the form hast been filled and it isnt valid and even when i do fill it still doesnt seem to think its valid and renders the sign up form again. i put two print statements in the sign up function in views.py one in the if statement and one outside just to know if a user was actually created from the console and every single time it says user not created meaning the form is never valid views.py: def signup(request): form = RegisterForm(request.POST) if request.method == 'POST': if form.is_valid(): print("User is valid") username = form.cleaned_data.get('username') password = form.cleaned_data.get('password1') form.save() new_user = authenticate(username=username, password=password) if new_user is not None: authlogin(request, new_user) redirect('home/') print("User created") form = RegisterForm() print("User not created") return render(request, 'registration/signup.html', {'form': form}) forms.py: class RegisterForm(UserCreationForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['username'].widget.attrs.update({ 'id':'RegisterUsername', 'type':"text", … -
Django and Polars strange slow response behavior
I am using Django rest framework with polars for creating reports. When having big response data, about 3,500 records, a response takes about a minute. At first, I thought the polar process was slow, but then I timestamped the beginning and end, and found out the whole process is about 1 sec. class TaskViewSet(SearchViewSet): """Task view set""" queryset = Task.objects.all() serializer_class = TaskSerializer search_vector = SearchVector("id", "name") permission_classes = [D7896DjangoModelPermissions] filter_backends = [ filters.DjangoFilterBackend, ] filter_class = TaskFilter pagination_class = None def list(self, request, *args, **kwargs): start_time = datetime.now() branch = request.GET.get("branch", None) orders = request.query_params.getlist("order", []) events = request.query_params.getlist("event", []) production_orders = request.query_params.getlist("production_order", []) start_date = request.GET.get("date__gte", None) start_date = ( datetime.strptime(start_date, "%Y-%m-%d").date() if start_date else start_date ) end_date = request.GET.get("date__lte", None) end_date = ( datetime.strptime(end_date, "%Y-%m-%d").date() if end_date else end_date ) # Validate branch is present if not branch: raise ValidationError("The 'branch' field is missing.") _, tasks = WorkOrderManager.get_work_orders( branch, start_date, end_date, orders, events, production_orders ) if not tasks.is_empty(): tasks = tasks.filter(pl.col("unused_components_task") == False).drop( ["unused_components_task"] ) tasks = tasks.with_columns( tasks['date'].dt.strftime('%Y-%m-%d'), tasks['supply_date'].dt.strftime('%Y-%m-%d') ) data = tasks.to_dicts() json_data = json.dumps(data) end_time = datetime.now() total_time = end_time - start_time print(total_time) return Response(json_data, content_type='application/json') Total Time printing in the terminal: printing in … -
How can I process Image in Django
In my Django Application, I am using imagekit to process images in my model but any time I try uploading image error says: module 'PIL.Image' has no attribute 'ANTIALIAS'. Initially, I never had issues with it but recently any time I try to save my form, I get that error. I have upgraded Pillow and used ImageFilter.MedianFilter() instead of ANTIALIAS but error persist. Someone should help with the best way of doing this. I am using Django Django==4.0. See my Model code: from django.db import models from PIL import Image from phonenumber_field.modelfields import PhoneNumberField from imagekit.processors import ResizeToFill, Transpose from imagekit.models import ProcessedImageField from django.core.exceptions import ValidationError from django.utils.deconstruct import deconstructible @deconstructible class FileExtensionValidator: def __init__(self, extensions): self.extensions = extensions def __call__(self, value): extension = value.name.split('.')[-1].lower() if extension not in self.extensions: valid_extensions = ', '.join(self.extensions) raise ValidationError(f"Invalid file extension. Only {valid_extensions} files are allowed.") Allowed Image extensions image_extensions = ['jpeg', 'jpg', 'gif', 'png'] class ResizeToFillWithoutAntialias(ResizeToFill): def process(self, img): img = super().process(img) return img.resize(self.size, Image.LANCZOS) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=30, blank=True, null=True) middle_name = models.CharField(max_length=30, blank=True, null=True) last_name = models.CharField(max_length=30, blank=True, null=True) date_birth = models.DateField(blank=False, null=True) phone_number = models.CharField(max_length=11, blank=True, null=True) gender = models.CharField(max_length=10, choices=GENDER_CHOICES) marital_status = … -
ModuleNotFoundError: No module named '<django_project_name>' Heroku deployment
I have seen tens of queries on same topic in past 2 days on web but unfortunately nothing has helped in my case. I am trying to deploy on Heroku from windows 10. Python manage.py runserver works the job fine on local PC and projects runs. Here is my project structure austbooks ├── accounting │ ├── admin.py │ ├── apps.py │ ├── forms.py │ ├── migrations │ ├── models.py │ ├── static │ │ └── accounting │ │ ├── css │ │ └── js │ ├── templates │ │ ├── account │ │ └── accounting │ ├── tests.py │ ├── views.py │ ├── __init__.py │ └── __pycache__ ├── austbooks │ ├── asgi.py │ ├── settings.py │ ├── urls.py │ ├── wsgi.py │ ├── __init__.py │ └── __pycache__ ├── manage.py ├── Procfile ├── requirements.txt ├── runtime.txt └── staticfiles ├── Accounting │ ├── css │ └── js ├── admin │ ├── css │ ├── img │ └── js ├── debug_toolbar │ ├── css │ └── js └── staticfiles.json I was getting the following error on deployment to heroku -----> $ python manage.py collectstatic --noinput Traceback (most recent call last): File "/app/.heroku/python/lib/python3.12/site-packages/django/core/management/__init__.py", line 255, in fetch_command app_name = commands[subcommand] ~~~~~~~~^^^^^^^^^^^^ KeyError: 'collectstatic' During … -
Django Added ForeignKey object in Custom User Model, when creating users im getting value error
Django Added ForeignKey object in Custom User Model, when creating users im getting value error this is user model(AppUser) having foreignkey in it, the error is as folllowed, ValueError: Cannot assign "1": "AppUser.branch" must be a "Branches" instance. tried with just instance also user = User.objects.create_user(email='admin@fmlk.com',branch=Branches.objects.get(name="Temp_Branch")) class AppUser(AbstractUser): username = None secId = models.CharField(max_length=255,default=sec.token_urlsafe(16)) email = models.EmailField(unique = True, null=False) password = models.CharField(max_length=255) branch = models.ForeignKey(Branches,on_delete=models.SET(tempBranch),null=False) is_verified = models.BooleanField(default = False) USERNAME_FIELD = "email" ` REQUIRED_FIELDS = ['branch'] objects = UserManager() class UserManager(BaseUserManager): def create_user(self, email, branch, password = None,**extra_fields): if not email: raise ValueError("Email is required") if not branch: raise ValueError("Need Branch") email = self.normalize_email(email.lower()) user = self.model(email = email, branch= branch, **extra_fields) user.set_password(password) user.save(using = self.db) return user def create_superuser(self, email,branch, password = None, **extra_fields): extra_fields.setdefault("is_staff",True) extra_fields.setdefault("is_superuser",True) extra_fields.setdefault("is_active",True) return self.create_user(email,branch,password, **extra_fields) >>> user = User.objects.create_user(email='admin@fmlk.com',branch=Branches.objects.get(name="Temp_Branch").id) Traceback (most recent call last): File "<console>", line 1, in <module> File "/Users/Varun/Spaces/spaces/core/manager.py", line 9, in create_user email = self.normalize_email(email.lower()) File "/Users/Varun/Spaces/env/lib/python3.10/site-packages/django/db/models/base.py", line 543, in __init__ _setattr(self, field.name, rel_obj) File "/Users/Varun/Spaces/env/lib/python3.10/site-packages/django/db/models/fields/related_descriptors.py", line 283, in __set__ raise ValueError( ValueError: Cannot assign "1": "AppUser.branch" must be a "Branches" instance. -
nginx unit + django + docker - wsgi.py cannot import module
Currently containerizing a legacy Django project, and running into an odd error. When pushing the config file to the running server, it fails to apply, and on inspecting the log, I get the following: 2023/12/06 21:36:02 [info] 39#39 discovery started 2023/12/06 21:36:02 [notice] 39#39 module: python 3.11.2 "/usr/lib/unit/modules/python3.11.unit.so" 2023/12/06 21:36:02 [info] 1#1 controller started 2023/12/06 21:36:02 [notice] 1#1 process 39 exited with code 0 2023/12/06 21:36:02 [info] 41#41 router started 2023/12/06 21:36:02 [info] 41#41 OpenSSL 3.0.11 19 Sep 2023, 300000b0 2023/12/06 21:40:22 [info] 49#49 "myapp" prototype started 2023/12/06 21:40:22 [info] 50#50 "myapp" application started 2023/12/06 21:40:22 [alert] 50#50 Python failed to import module "myapp.wsgi" Traceback (most recent call last): File "/app/myapp/wsgi.py", line 5, in <module> from django.core.wsgi import get_wsgi_application # noqa: E402 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ModuleNotFoundError: No module named 'django' 2023/12/06 21:40:22 [notice] 49#49 app process 50 exited with code 1 2023/12/06 21:40:22 [warn] 41#41 failed to start application "myapp" 2023/12/06 21:40:22 [alert] 41#41 failed to apply new conf 2023/12/06 21:40:22 [notice] 1#1 process 49 exited with code 0 My config file is as follows: { "applications": { "myapp": { "type": "python 3.11", "module": "myapp.wsgi", "processes": 150, "environment": { "DJANGO_SETTINGS_MODULE": "myapp.settings.production", } } }, "listeners": { "0.0.0.0:8000": { "pass": "applications/myapp" } } … -
Django php bridge
I have configured my app like this: client -> server(Apache -> php -> [django]) Some requests are handled by the php, and some are "forwarded" to django. I can successfully access the django app via this php proxy. But when I try to upload a file to the server (here django should handle that request), is there any way to directly forward the file content to the django app or I need to temporarily save it in the php server and make a request to the django app for the rest? -
Bootstrap Modal - Deleting a Review using Django
I'm using a simple Boostrap modal and it works fine. I have a delete URL which will delete the review based on the id. My issue is, I don't know how to pass the review.id from the button, through to the modal confirm delete button. If I don't use a modal and just do a simple delete button, it works fine using: How do I pass that review.id through to the final button? {% url 'delete_review' review.id %} HTML: {% if request.user.is_authenticated and user.username == review.name or user.is_superuser %} <div> <a class="btn btn-black rounded-0 text-uppercase mt-2" href="{% url 'edit_review' review.id %}" role="button">Edit</a> | <!-- Button trigger modal --> <a class="btn-delete btn rounded-0 text-uppercase btn-outline-danger mt-2" data-toggle="modal" data-target="#exampleModal" role="button">Delete</a> </div> {% endif %} <hr> </div> <!-- Modal --> <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Delete Review</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> Are you sure you want to <strong class="text-danger">DELETE</strong> your Review? </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="button" class="btn btn-danger" href="{% url 'delete_review' review.id %}">Delete Review</button> </div> </div> </div> </div> -
Django-pipeline collect my statics in dev
I use Django-pipeline on my project. Here are the configurations: STATIC_URL = '/static/' MEDIA_URL = '/media/' STATICFILES_DIRS = [ BASE_DIR / "static", ] STATIC_ROOT = os.path.join(BASE_DIR, 'zstatics') MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATICFILES_STORAGE = 'pipeline.storage.PipelineManifestStorage' STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'pipeline.finders.PipelineFinder', ) PIPELINE = { 'PIPELINE_COLLECTOR_ENABLED': False, 'PIPELINE_ENABLED': False, 'CSS_COMPRESSOR': None, 'JS_COMPRESSOR': None, 'JAVASCRIPT': { 'unauthenticated_main': { 'source_filenames': ( 'website/js/theme.bundle.min.js', 'js/htmx.min.js', 'website/vendors/js/prism.min.js', 'js/copyleft.min.js', 'js/unauthenticated_custom.min.js', 'js/oqb.min.js', ), 'output_filename': 'compressed/unauthmain.min.js', } } } It works quite well but in developpement mode with DEBUG=False it collects my files anyway, and minify them in doucble and I got new files in zstatics, the files declared in the dictionnary. for example I got a 'js/htmx.min.js' file and a 'js/htmx.min..min.js' file which is quite weird. Any idea where I failed in the configuration? -
Connecting to Amazon SQS key (SSE-SQS) Encrypted SQS Queue via Django Celery [sqs]
I am unable to get my Celery working running while connecting to an SQS Encrypted Queue This is my settings.py for my django project SQS_AWS_ACCESS_KEY_ID = 'xxxx' SQS_AWS_SECRET_ACCESS_KEY = 'xxxx' SQS_AWS_QUEUE_NAME = 'sqs.eu-west-2.amazonaws.com/xxxx/xxx-celery-broker' broker_url = f"sqs://{SQS_AWS_ACCESS_KEY_ID}:{SQS_AWS_SECRET_ACCESS_KEY}@{SQS_AWS_QUEUE_NAME}" CELERY_BROKER_URL = broker_url CELERY_RESULT_BACKEND = None CELERY_BROKER_CONNECTION_RETRY_ON_STARTUP = True When i run my worker i get this error, i assume as my Queue Name is not https:// botocore.exceptions.ClientError: An error occurred (InvalidSecurity) when calling the GetQueueAttributes operation: All requests to this queue must use HTTPS and SigV4. when i change it to SQS_AWS_QUEUE_NAME = 'https://sqs.eu-west-2.amazonaws.com/xxxx/xxx-celery-broker' I get this error Cannot connect to sqs://xxx:**@https//sqs.eu-west-2.amazonaws.com/xxx/xxx-celery-broker: Could not connect to the endpoint URL: "http://https/". The Config seems to add a random http onto the url which is why i assume its failing When i connect to a non encrypted queue it works fine as seen as This is my celery.py config os.environ.setdefault("DJANGO_SETTINGS_MODULE", "proj.settings") # Create a Celery instance and configure it to use SQS app = Celery("proj") # Load task modules from all registered Django app configs. app.config_from_object("django.conf:settings", namespace="CELERY") # Auto-discover tasks in all installed apps app.autodiscover_tasks(settings.INSTALLED_APPS) app.conf.task_default_queue = 'xxx-celery-broker' I'm at my wits end trying to fix this im assuming there is a small config change … -
Django get a certin value from a dict with a for key value inside of a template
Sorry if my title is a bit crypt, but this is the problem I have a list of dict data = [{"a": 1, "b": 2},{"a": 3, "b": 4} ] and a list with keys = ["a","b"] I want in a template do this: for dat in data: <tr> for k in keys: <th> dat[k]</th> </tr> to get this: <tr> <th>1</th> <th>2</th> </tr> <tr> <th>3</th> <th>4</th> </tr> -
Is there any way to open Google Earth Engine images in Django and render it to leaflet?
I want to open a Google Earth Engine image in Django and display it in a Leaflet. I have used the following codes for this: l8 = ee.ImageCollection("LANDSAT/LC08/C01/T1_SR").mean() geometry = ee.Geometry.Polygon([[[-80.92489760146748, 25.433457120928352], [-80.64474623427998, 25.488013471687964], [-80.57882826552998, 25.710940372707608], [-81.02377455459248, 25.770317250349557], [-80.95236342177998, 25.552457242621447]]]); image = image.filterBounds(geometry) and my template: var map = L.map('map', { zoomControl: false }) now i want to show'image' on leaflet ap. Is there a way to do this? -
Username input and username label are overlapping after refreshing the page, this is happening for both username and password
This is my html code: {% load static %} web Login User Name Password Remember Me Log in And this my css @import url('https://fonts.googleapis.com/css2?family=Poppins:wght@500&display=swap'); *{ margin: 0; padding: 0; font-family: 'poppins',sans-serif; } section{ display: flex; justify-content: center; align-items: center; min-height: 100vh; width: 100%; background: url('background6.jpg')no-repeat; background-position: center; background-size: cover; } .form-box{ position: relative; width: 400px; height: 450px; background: transparent; border: 2px solid rgba(255,255,255,0.5); border-radius: 20px; backdrop-filter: blur(15px); display: flex; justify-content: center; align-items: center; } h2{ font-size: 2em; color: #fff; text-align: center; } .inputbox{ position: relative; margin: 30px 0; width: 310px; border-bottom: 2px solid #fff; } .inputbox label{ position: absolute; top: 50%; left: 5px; transform: translateY(-50%); color: #fff; font-size: 1em; pointer-events: none; transition: .5s; } input:focus ~ label, input:valid ~ label{ top: -5px; } .inputbox input { width: 100%; height: 50px; background: transparent; border: none; outline: none; font-size: 1em; padding:0 35px 0 5px; color: #fff; } .inputbox ion-icon{ position: absolute; right: 8px; color: #fff; font-size: 1.2em; top: 20px; } .forget{ margin: -15px 0 15px ; font-size: .9em; color: #fff; display: flex; justify-content: space-between; } .forget label input{ margin-right: 3px; } .forget label a{ color: #fff; text-decoration: none; } .forget label a:hover{ text-decoration: underline; } button{ width: 100%; height: 40px; border-radius: 40px; … -
Can I create a single endpoint for authorization and registration?
I have an interesting problem that I can't cope with, I wrote an api to register a basic django user to which his profile is attached and which does not have anything special at all, now I need this api to perform 2 functions, that is, the user enters his username , mail and password, and the system should check if there is such a user? If there is no such user in the database, then register him otherwise, authorize and return tokens, here is my code: class UserSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True) email = serializers.CharField(write_only=True) is_active = serializers.BooleanField(default=False, read_only=True) refresh_token = serializers.SerializerMethodField() access_token = serializers.SerializerMethodField() class Meta: model = User fields = ('id', 'username', 'password', 'email', 'is_active', 'refresh_token', 'access_token') def create(self, validated_data): password = validated_data.pop('password') email = validated_data.pop('email') is_active = validated_data.pop('is_active', True) username = validated_data.get('username') user = User.objects.create_user(username=username, email=email, password=password, is_active=is_active) profile, created = UserProfile.objects.get_or_create(user=user) return user def get_refresh_token(self, user): refresh = RefreshToken.for_user(user) return str(refresh) def get_access_token(self, user): refresh = RefreshToken.for_user(user) return str(refresh.access_token) maybe someone knows how to add an authorization mechanism to it? -
Displaying static images with Django
Despite having gone through the 6 billion other questions asking the exact same thing, Django still seems to not want to display an image. HTML: <img src="{{ article.article_cover_image }}" alt="img"> Model: def upload_article_image_path(instance, filename): return f'./static/assets/article_media/{instance.id}/{filename}' article_cover_image = models.ImageField(upload_to=upload_article_image_path,help_text='Enter article cover image') settings.py: STATICFILES_DIRS = ( os.path.join(BASE_DIR,'catalog/static'), ) urls.py: urlpatterns = [ path('admin/', admin.site.urls), path('catalog/', include('catalog.urls')), ] urlpatterns += [ path('', RedirectView.as_view(url='catalog/static/', permanent=True)), ] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) And this is the file structure: -
Django Mixed Block
I have a problem on my website I get a mixed block, the server is written in django and the front is in react + connected ssl certificate + nginx, how can I fix this problemconfig nginx, I have no idea how to go to the Django https server and how to connect a certificate there, whether a certificate is needed separately for the server side and what can be done in general server { listen 3000; listen [::]:3000 ipv6only=on; server_name localhost; listen 443 ssl; ssl_certificate crt.crt; ssl_certificate_key key.key; ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3; ssl_ciphers HIGH:!aNULL:!MD5; access_log /var/log/nginx/httpstatus.access.log; error_log /var/log/nginx/httpstatus.error.log; location / { root /data/www; index index.html; try_files $uri $uri/ /; } } I will be very pleased if you tell me where else this problem could arise -
Cannot make ForeignKey optional...?
In my django application, I defined a model: class CourtOrder(models.Model): category = models.ForeignKey(CourtOrderCategory, blank=True, null=True,on_delete=models.PROTECT) institution = models.ForeignKey(Institution, blank=True, null=True, on_delete=models.PROTECT) The class contains a number of other entries, but I'm having trouble with these two. I already read this post: How to make the foreign key field optional in Django model? But did not have any success, the debugger still tells me that my form is invalid if these values are not set. I ran python manage.py makemigrations and python manage.py migrate several times and I also tried to change the on_deletevalue to SET_NULLto see if my mistake was there, but that did not change the outcome. What am I doing wrong? -
Load data to navbar without rendering the django template
Im creating a music streaming webapp and im stuck at a certain section, so as part of the search results a list of music data is displayed and when clicked on a particular item the data about the item should be passed to the navbar without rendering the template. (the navbar is part of the indexpage and the search results are at another page) i tried using ajax but wasn't successfull since im not familiar with it , -
Django query hangs on a model with a ManyToManyField to "self", when adding to prefetch_related
I have an Offer model with a self-referential ManyToManyField: class Offer(models.Model): title = models.CharField(max_length=255) priority = models.PositiveIntegerField(default=100, help_text="The highest priority offers are applied first.") cannot_combine_with = models.ManyToManyField( "self", blank=True, help_text="Never combine this offer with these offers (only the highest priority offer is applied).", ) This query works fine: >>> Offer.objects.all() This also works perfectly fine: >>> Offer.objects.prefetch_related("cannot_combine_with").all() But as soon as I add a model manager, then Offer.objects.all() no longer completes, it just hangs. class OfferManager(models.Manager): def get_queryset(self): return ( super() .get_queryset() .prefetch_related("cannot_combine_with") ) class Offer(models.Model): _base_manager = OfferManager objects = OfferManager() # ... original fields With this manager in place I can't fetch any Offer models anymore as the query just hangs. Why is it that adding prefetch_related to the OfferManager makes the query hang, while manually adding this condition (without using a custom manager) works fine? -
How to pre-populate Username field with Django
I have a ReviewsForm created in forms.py and I have a 'name' model in models.py in my reviews app. I want the name field in this reviewsform to be prepopulated by the full_name from my Profiles app if that's at all possible. I have achieved this in my course project for the Checkout process in a convuluted way. I tried recreating that method and cleaning it up but it's just not working as expected. Somethings to add - I have a Profile Model and this is the model where the saved name is actually pulled from. I have imported this model into my reviews model. My add_review function in views.py: @login_required def add_review(request): """ Add a review to the reviews page """ if not request.user: messages.error(request, 'Sorry, you must login to do that.') return redirect(reverse('reviews')) if request.method == 'POST': form = ReviewsForm(request.POST, request.FILES) if form.is_valid(): form.save() review = form.save() messages.success(request, 'Successfully posted a review, waiting for approval.') return redirect(reverse('reviews')) else: messages.error(request, 'Failed to add review. Please ensure the form is valid.') else: form = ReviewsForm() if request.user.is_authenticated: try: profile = UserProfile.objects.get(user=request.user) review_form = ReviewsForm(initial={ 'name': profile.default_full_name, }) except UserProfile.DoesNotExist: review_form = ReviewsForm() template = 'reviews/add_review.html' context = { 'form': form, … -
Get function in django rest framework does not work even though i explicitly say for permission to allow any
I want to send my product category data to the frontend. this is my view function: class CategoryView(APIView): def get(self,request,format=None): permission_classes=[AllowAny] category=Category.objects.all() serializer=CategorySerializer(category, many=True) return Response(serializer.data) In the frontend i have this: useEffect(()=>{ axios.get('http://localhost:8000/Category/') .then(res=>setCategory(res?.data)) .catch(err=>console.log(err)) .then(res=>console.log('category are'+res?.data)) },[category]) Even though i have stated for permission to allow any, it still says 401 unauthorized error. why is this happening and how do i fix it? -
ALLOWED_HOSTS and CORS_ALLOWED_ORIGINS don't work on VPS
I have project on VPS with front-end (Angular) and back-end (Django, DRF). VPS is running on Ubuntu 22.04 and has nginx. I used docker with compose to build images and run containers. Docker works fine on VPS and if I try to get to ip-address:8081 or <domain_name:8081> I see my Angular page and other links. But if try to get port 8082 (this is where back-end is listening, see the docker-compose below) I see error DisallowedHost at /, Invalid HTTP_HOST header: 'ip-address'. You may need to add 'ip-address' to ALLOWED_HOSTS. I added everything that I found from other topics. For now I have smth like that in settings.py: ALLOWED_HOSTS = ['localhost', 'ip:8082', '127.0.0.1', 'domain_name:8082', '*',] CORS_ALLOWED_ORIGINS = [ 'http://localhost:8081', # This is to allow requests from Angular app ] but it doesn't work even when I try to rebuild images, containers and volumes. I think that's the reason why Angular can't connect to django and daphne (websocket, channels). P.S. it works locally in docker and without. If the problem can be related to CORS_ALLOWED_ORIGINS, write about it too. I don't use nginx as proxy, request filter. docker-compose.yml: version: "3" services: # Back-end django: build: context: ./back-end dockerfile: ./Dockerfile image: django-image …