Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django UpdateVIew is not working with form_class
I need to edit an existing form and make changes to the database. So to do this I use UpdateView based class. When I use 'fields' everything works correctly, but there are no styles applied to the form, so I'm trying to use 'form_class' instead and when I click submit button changes are not saved. Please help me with this issue. (urls) from django.urls import path from . import views urlpatterns = [ path('', views.home, name='home'), path('register/', views.register_page, name='register'), path('login/', views.login_page, name='login'), path('logout/', views.logout_user, name='logout'), path('new_todo/', views.new_todo, name='new_todo'), path('update_todo/<int:pk>', views.UpdateTodo.as_view(), name='update_todo'), path('delete_todo/<int:pk>', views.delete_todo, name='delete_todo'), ] (views) class UpdateTodo(UpdateView): model = Todos template_name = 'todoapp/new_todo.html' # fields = ['title', 'notes', 'date', 'deadline'] form_class = TodosForm success_url = "/" (models) from django.db import models class Todos(models.Model): title = models.CharField('Title', max_length=50) notes = models.TextField('Note') date = models.DateField('Date') deadline = models.DateField('Deadline') def __str__(self): return f"Todo: {self.title}" def get_absolute_url(self): return f'/{self.id}' (forms) class TodosForm(ModelForm): class Meta: model = Todos fields = ['title', 'notes', 'date', 'deadline'] widgets = { 'title': TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Title' }), 'notes': Textarea(attrs={ 'class': 'form-control', 'placeholder': 'Notes' }), 'date': DateTimeInput(attrs={ 'class': 'form-control', 'placeholder': 'Date' }), 'deadline': DateTimeInput(attrs={ 'class': 'form-control', 'placeholder': 'Deadline' }) } (HTML template) {% extends 'base.html' %} {% block … -
How to choose clothing size on django?
sorry for my english... i wanna make choosing clothes size. I have been trying for 4 days, but i cant make views the task is: there are sizes such as S,M,L,Xl and customer chooses their and go in the cart i have models.py class Product(models.Model): ... category = models.ForeignKey('Category', related_name='products', on_delete=models.CASCADE) sizes = models.ManyToManyField('ClothingSize', through='ProductVariant') class ClothingSize(models.Model): size_choices = ( ('S', 'S'), ('M', 'M'), ('L', 'L'), ('XL', 'XL'), ) size_name = models.CharField(max_length=2, choices=size_choices, blank=True, null=True) class ProductVariant(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) product_size = models.ForeignKey(ClothingSize, on_delete=models.CASCADE) product_quantity = models.IntegerField(default=0) and then i tried to make views for choosing size and this is my fail: views.py def detail_product(request, product_slug): products = get_object_or_404(Product, slug=product_slug) get_all_photos = ProductPhotos.objects.filter(post=products) get_sizes = ProductVariant.objects.filter(product=products) if request.method == "POST": size_id = request.POST.get('size_variation') try: filter_sizes = ProductVariant.objects.filter(product_size=size_id) except: return HttpResponse('Ошибка сервера(') else: filter_sizes = None dict ={ "products": products, 'get_sizes':get_sizes, 'filter_sizes':filter_sizes, 'get_all_photos': get_all_photos } return render(request, 'shop/details.html', dict) template <form action="." method="post"> {%csrf_token%} {% for size in products.sizes.all %} <p><input name='size_variation' type="radio">{{size.size_name}}</p> {%endfor%} <input type="submit" value="Обновить"> </form> -
if statement is not working in Django HTML template
{% for feature in features %} {{feature.name}} {{feature.details}} **{% if feature.is_true == True %} Yes this is True {% endif %}** {% endfor %} I am just trying to use the if statement here. feature is the object of a class which has an attribute is_true which contains boolean values. I am trying to check if it is true then display the following paragraph else not. Eveything else seems to work fine. On runing the server Eveyrthing is dispalyed on the page except for the part in the if condition. Please help me get this right, I am new to Django. Thanks! -
(staticfiles.W004) The directory '/var/www/static/' in the STATICFILES_DIRS setting does not exist
I`ve been learning Django by yourube videos and I reached the moment when I had to create migrations I did exactly how it is in video but I got this Warning message: WARNINGS: ?: (staticfiles.W004) The directory '/var/www/static/' in the STATICFILES_DIRS setting does not exist. No changes detected and no migrations were created, I tried to google the problem but that was useless At the very start I had 2 problems: WARNINGS: ?: (staticfiles.W004) The directory '/var/www/static/' in the STATICFILES_DIRS setting does not exist. ?: (staticfiles.W004) The directory 'D:\PythonProjects\Projects\start\static' in the STATICFILES_DIRS setting does not exist. second problem I solved by creating a folder named 'static' in the project`s main folder but the second is still unsolved( -
Splitting Django application in many applications
I have a django project divided in 3 sprint. The first sprint is about importing data (20 imports about) in database A The second is about (merging) making request on database A and production of reporting in ``database B The three ... in database C The project have three differents databases. I have one app with three separate database. Do you think, I should split the app in three differents (inside the same project) and define a database router that routes to these databases. Like this: app_import with database A app_merging with database B -
Django DEBUG=False does not serve media files, thumbnails or thumbnails
I'm working on an application that when set to production mode (DEBUG=False) does not load image thumbnails, when DEBUG=True loads and displays normally, static files are also loaded normally in production when the command "python3 manage. py collectstatic" `Settings.py STATIC_URL = '/static/' MEDIA_URL = '/media/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') MEDIA_ROOT = os.path.join(BASE_DIR, 'media') urls.py ... urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) ...` -
Accessing Calls to Mocked Class functions
I have written a custom class to mock a general API client in a codebase so that I can centrally and easily mock all of the class methods for unit testing. This is working great so far, however I am looking for a way to track individual calls to each class method. Right now that only trackable call via Mock is the initial class instantiation. Here is the mock class: from faker import Factory faker = Factory.create() class MockAPIClass def get_some_data(self, data): return f"{data} - {faker.pyint()}" Then in my util file: def func_to_test_that_calls_client(arg): client = regular_api_client() return client.get_some_data(arg) Then in my unit tests: from unittest import mock from django.test import TransactionTestCase from .file import MockAPIClass from .util import func_to_test_that_calls_client class TestUils(TransactionTestCase): def setUp(self): self.api_call_patcher = mock.patch('path.to.mocked.class.instantiation') self.patch_api = self.api_call_patcher.start() self.mock_api = MockAPIClass() # this done so that the mocked class can be referenced below self.patch_api.return_value = self.mock_api def tearDown(self): mock.patch.stopall() def test_util_func(self): res = func_to_test_that_calls_client("test") self.assertTrue(res) self.patch_api.assert_called_once() The above functions exactly as expected and intended. However, inside of the funciton func_to_test_that_calls_client, the original client is instantiated then the class method get_some_data() is called. With this implementation, I have no visibility into the call stack of the class methods like that … -
Python (Django) createsuperuser not working with docker-compose environment
I'm currently running a project using django in docker. I have a docker-compose file that starts and runs an nginx server, an app server running alpine and a db-server running postgresql. All of these start up like they're supposed to and I can access the blank site on my localhost IP 127.0.0.1:8000. At the moment there's no models or views or anything, I just want to create the admin user for now. Dockerfile FROM python:3.10-alpine ENV PYTHONUNBUFFERED=1 ENV PYTHONDONTWRITEBYTECODE=1 RUN apk add python3-dev postgresql-client postgresql-dev musl-dev build-base COPY . /app WORKDIR /app RUN pip install -r requirements.txt ENTRYPOINT ["sh", "entrypoint.sh"] docker-compose.yml version: '3.9' services: web: image: nginx:latest ports: - 8000:8000 volumes: - ./nginx/:/etc/nginx/conf.d/ networks: - webnet depends_on: - app app: image: bankimage:latest networks: - dbnet - webnet env_file: - env depends_on: - db db: image: postgres:15.2-alpine volumes: - data:/var/lib/postgresql/data/ - ./dbscripts/:/dbscripts/ networks: - dbnet env_file: - env volumes: data: networks: dbnet: webnet: I can access the database with python manage.py exec db and I can see all the tables created for django, so I know there's a connection. Database setup: env POSTGRES_USER=pguser POSTGRES_PASSWORD=pgpassword POSTGRES_DB=bankdb TZ=Europe/Copenhagen PGTZ=Europe/Copenhagen settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.environ['POSTGRES_DB'], 'USER': os.environ['POSTGRES_USER'], 'PASSWORD': os.environ['POSTGRES_PASSWORD'], … -
Changing students level when session changes
I have a school management system website, i want to enable the functionality whereby the student's level will change when the school session year changes. I actually don't have an idea tackling this issue. This is my student model class Student(models.Model): student = models.OneToOneField(User, on_delete=models.CASCADE) level = models.CharField(max_length=25, choices=LEVEL, null=True) department = models.ForeignKey(Program, on_delete=models.CASCADE, null=True) def __str__(self): return self.student.get_full_name -
django.db.utils.OperationalError: connection to server at "127.0.0.1", port 5432 failed: Connection refused
psycopg2.OperationalError: connection to server at "127.0.0.1", port 5432 failed: Connection refused adh_dealmicroservice-copy-web-1 | Is the server running on that host and accepting TCP/IP connections? conn = _connect(dsn, connection_factory=connection_factory, **kwasync) adh_dealmicroservice-copy-web-1 | django.db.utils.OperationalError: connection to server at "127.0.0.1", port 5432 failed: Connection refused adh_dealmicroservice-copy-web-1 | Is the server running on that host and accepting TCP/IP connections? -
Django Web Application Mutual authentification on development server
I am working on an application that needs mutual authentication; there are needs to test it on the development server I have so far got all the keys, server and client, the server can be authenticated, what i don't know is how to request the client(browser) for the keys. Ideally this should be done once at the first request, since there is also password authentication. Anyone to show me how to go about. Note: I have searched the web for some good hours with no answer so far -
How to set the Navigation bar in the top of the html page?
I developed an index.html page in django project. The below is the template code I developed. Right now, the navigation bar is coming at the bottom index.html <!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Contact Book Template</title> <link type="text/css" rel="stylesheet" href="{%static 'css/style.css' %}" /> <!-- Google Font --> <link href="https://fonts.googleapis.com/css?family=PT+Sans:400" rel="stylesheet"> </head> <body> <img class="contact_book" src="{% static 'img/contact_book.jpg' %}" alt="first" /> <div id="booking" class="section"> <div> <ul id="horizantal-style"> <li><a href="#">Home</a></li> <li><a href="#">News</a></li> <li><a href="#">Contact</a></li> <li style="float:right"><a href="#">Login</a></li> <li style="float:right"><a class="active" href="#about">Sign up</a></li> </ul> </div> </div> </body> </html> I developed the style.css file as shown below ul { list-style-type: none; margin: 0; padding: 0; overflow: hidden; background-color: #dddddd } li { display: inline-block; } li a { display: block; color: #000; text-align: center; padding: 20px 24px; text-decoration: none; } li a:hover { background-color: #555; color: white; } .active { background-color: #337ab7; } I am expecting it to set the navigation bar at the top, could anyone please help? -
Unable to display multiple locations using GraphHopper in Leaflet map
Description: I am trying to display a route on a Leaflet map that connects multiple locations using GraphHopper. I have defined an array of latitude and longitude points and passed it to the ghRouting.route() function along with the vehicle type and API key. However, I am getting an error "ghRouting.route is not a function" in the console. Code: <!-- Leaflet JavaScript --> <script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"></script> <!-- GraphHopper Client Web JavaScript --> <script src="https://graphhopper.com/api/1/client.js?key=<your_api_key>"></script> <script> // Create a new Leaflet map centered on Kathmandu, Nepal var map = L.map('map').setView([27.7172, 85.324], 12); // Add a tile layer to the map L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { attribution: 'Map data &copy; <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors', maxZoom: 18, tileSize: 512, zoomOffset: -1 }).addTo(map); // Define an array of points (latitude and longitude) for the route var points = [ [27.7172, 85.324], // Kathmandu [27.6679, 85.3188], // Lalitpur [27.6729, 85.4286], // Bhaktapur [27.6256, 85.5154] // Banepa ]; // Define a GraphHopper routing object with the API key and profile var ghRouting = new GraphHopper.Routing({ key: '<your_api_key>', vehicle: 'car' }); // Calculate the route using the GraphHopper API ghRouting.route({ points: points, instructions: true, vehicle: 'car', elevation: false }, function (err, res) { if (err) { console.error(err); return; } // Create a new … -
How can I use the FloatingField function with an email input in Django crispy forms with Bootstrap 5?
I have a Django project where I'm using crispy forms with the Bootstrap 5 version. https://github.com/django-crispy-forms/crispy-bootstrap5 I have two floating fields for the username and password input, but I also need to add an email input. FloatingField('username', css_class='shadow-none'), FloatingField('password', css_class='shadow-none'), I tried to search for a solution in the GitHub repository, but I couldn't find anything. I was expecting to find some documentation or an example of how to add an email input to the floating field layout. I concluded that it would be best to ask here before submitting any issue to the github repository, so how can I add an email input to the floating field layout in Django crispy forms with Bootstrap 5? -
Testing Django API route with internal async call
I have a Django Rest Framework based API with some routes calling async methods (using Celery). Like so : class MyList(ListCreateAPIView, DestroyModelMixin): def post(self, request, format=None): # Asynchronous call using Celery shared task async_call = my_async_method.delay(request.data) return Response( { "status": async_call.status, "task_id": async_call.task_id }, status=status.HTTP_202_ACCEPTED ) my_async_method is doing some processing and finally serializes data to the database model. I already test (with pytest) that the API actually returns HTTP 202 response, and other basic use cases. Now I want to test that the object is actually created and check some assumptions about it. Yet, the call is asynchronous so the object is not created when I check the assert statements. @pytest.mark.django_db def test_post_myapi_success(api_client): my_object = {} client = api_client() url = reverse("api-v1-app:list") response = client.post(url, my_object) assert response.status_code == status.HTTP_202_accepted #True assert MyObject.objects.count() == 1 # False First question: does it make sense to test all at once (API response and object creation) or should I split the tests ? Second question: If I try to test the async function with @pytest.mark.asyncio and await asyncio.sleep(5) after making the API request, I get the following error : django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context. I guess this is … -
How to solve Django TemplateDoesNotExist at accounts/login.html error?
I made a blog app in Django and deployed it with Heroku. When I opened the app, get 'TemplateDoesNotExist at /accounts/login/' error. It should load the login.html and it did not load it. If anyone could help me, I would be thankful. I tried 'DIRS': [os.path.join(BASE_DIR, 'Templates')], but did not work. Or maybe I did something wrong. Here is my file structure: BLOG ├─.idea ├─accounts | ├─__pycache__ | ├─migrations | ├─Templates | | └─accounts | | ├─login.html | | └─signup.html | ├─__init__.py | ├─admin.py | ├─apps.py | ├─models.py | ├─tests.py | ├─urls.py | └─views.py ├─articles | ├─__pycache__ | ├─migrations | ├─Templates | | └─articles | | ├─article_create.html | | ├─article_details.html | | ├─article_form.html | | ├─article_list.html | | └─pagination.html | ├─__init__.py | ├─admin.py | ├─apps.py | ├─forms.py | ├─models.py | ├─tests.py | ├─urls.py | └─views.py ├─blog | ├─__pycache__ | ├─Templates | | └─default.html | ├─__init__.py | ├─asgi.py | ├─settings.py | ├─urls.py | ├─views.py | └─wsgi.py ├─media ├─static | ├─favicon.ico | ├─logo.png | ├─slugify.js | ├─styles.css | └─background.jpg ├─db.sqlite3 └─manage.py Here is some part of my settings.py: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['Templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] -
Factory Boy Base64 Encoded String Faker
Is it possible to fake a base64 encoded string within factory-boy? For example, in a given factory, I'm able to fake (generate) a random name by doing name = factory.Faker("name"). In addition, I can fake an email by doing email = factory.Faker("email"). However, I'm not sure how to fake a base64 encoded string. In my model, I have a field which is a simple CharField as such: encoded_string = models.CharField(max_length=512, blank=True, null=True). How can I go by faking this within my factory? I have tried several options, but they all result in errors. base64.b64encode("sample_string".encode("ascii")) results in: UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb5 in position 3: invalid start byte Doing base64.b64encode(bytes("[{\"key\":\"Key Example:\",\"value\":\"Value Example\\\"\"}]", 'utf-8')) results in: UnicodeDecodeError: 'utf-8' codec can't decode byte 0x95 in position 5: invalid start byte Doing base64.b64encode(b'data to be encoded') results in: binascii.Error: Invalid base64-encoded string: number of data characters (25) cannot be 1 more than a multiple of 4 -
How to disable WSGI debugging (Web application could not be started)?
If there is an error in my code, the debugging happens in the browser and the user sees it. How do I disable the debugging? I wanted the debugging not to work in the browser enter image description here -
Django update table from MYSQL query without refreshing the whole page
Developing my first Django app and i'm using an input and a button to query MYSQL database and render the result in a table . It works fine but I would like to achieve the same thing without the page to reload (so I wont loose the input content). I read many tutorials but still can't figure out how to use AJAX as it seems to be the only way to do this. home.html <form id="post-form" action='{% url "filter" %}' method="POST"> {% csrf_token %} <input id='search' name='search' type='text'> <button name="button" type="submit" >Send</button> </form> <table id='myTable' class="table table-striped table-hover table-bordered fixed_header sortable"> <thead class="table-dark"> <tr id='tableHeader'> <th scope="col">Name</th> <th scope="col">Email</th> <th scope="col">Phone</th> <th scope="col">Address</th> <th scope="col">City</th> <th scope="col">State</th> <th scope="col">Zipcode</th> <th scope="col">Created At</th> <th scope="col">ID</th> </tr> </thead> <tbody> {% if records %} {% for record in records %} <tr> <td>{{ record.first_name }} {{ record.last_name }}</td> <td>{{ record.email }}</td> <td>{{ record.phone }}</td> <td>{{ record.address }}</td> <td>{{ record.city }}</td> <td>{{ record.state }}</td> <td>{{ record.zipcode }}</td> <td>{{ record.created_at }}</td> <td><a href="{% url 'record' record.id %}">{{ record.id }}</a></td> </tr> {% endfor %} {% endif %} </tbody> </table> views.py def filter(request): data = request.POST.get('search') print(data) if not data == "": records = Record.objects.raw("SELECT * FROM website_record … -
My web site on AWS with Django does not read CSS files on Amazon S3
My web site that is made by Django and deployed on AWS does not apply CSS files after I uploaded CSS files on Amazon S3 using collectstatic. $ python manage.py collectstatic I checked one of CSS files on Amazon S3, but I am not sure which one is the url target I should set in settings.py. Which part of settings.py I write below should I change? Thank you. settings.py import os BASE_DIR = Path(__file__).resolve().parent.parent ################################################################# ##### Static Files (CSS, JavaScript, Images) ################################################################# STATIC_URL = "/static/" STATIC_ROOT = os.path.join(BASE_DIR, 'static') ################################################################# ##### Amazon S3 ################################################################# DEFAULT_FILE_STORAGE = "storages.backends.s3boto3.S3Boto3Storage" STATICFILES_STORAGE = "storages.backends.s3boto3.S3StaticStorage" AWS_LOCATION = "static" AWS_STORAGE_BUCKET_NAME = "mydomain-bucket" AWS_S3_REGION_NAME = "ap-northeast-1" AWS_S3_CUSTOM_DOMAIN = "%s.s3.amazonaws.com" % AWS_STORAGE_BUCKET_NAME # AWS_S3_CUSTOM_DOMAIN = "{}.s3.{}.amazonaws.com".format(AWS_STORAGE_BUCKET_NAME, AWS_S3_REGION_NAME) # AWS_DEFAULT_ACL = None STATIC_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) Python 3.9 Django 4.1 Apache 2 -
Django - Specify in which database a model (table) must be created
I have many django models in my models.py. I have two data bases (db1 and db2). How can I specify each model to be created in the corresponding database. For example: class ModelDB1(models.Model): # This class table must be created in db1 class ModelDB2(models.Model): # This class table must be creared in db2 -
How to store data that has been initialized by code in BaseInlineFormSet
I need help. I have a specific form which has the option to create a month and a specific value for that month. Here is the model: class MonthAllocat(BaseModel): variable = models.ForeignKey(Variable, related_name="month_allocat", on_delete=models.CASCADE) month = models.PositiveSmallIntegerField(choices=MONTH_CHOICES) weight = models.DecimalField(max_digits=5, decimal_places=2, validators=PERCENTAGE_VALIDATOR) class Meta: db_table = "month_allocation" unique_together = ["month", "forecast"] ordering = ("month",) variable - this is the main form on which the work takes place At the time of creating a new form, I set certain values for each month: Here is what I have in admin.py -> class MonthAllocationInline(admin.TabularInline): model = MonthAllocation formset = VariableMonthAllocationInlineFormSet fields = ("month", "weight") classes = ("collapse",) ordering = ("month",) max_num = len(MONTH_CHOICES) form = MonthAllocationForm class Media: css = {"all": ("css/hide_admin_object_name.css",)} def get_extra(self, request, obj=None, **kwargs): # pragma: no cover if obj: return 0 else: return len(MONTH_CHOICES) -> class MonthAllocationForm(ModelForm): def __init__(self, *args, **kwargs): # pragma: no cover super(MonthAllocationForm, self).__init__(*args, **kwargs) if kwargs.get("prefix").split("-")[1].isdigit() and not self.initial: # type: ignore self.fields["month"].initial = MONTH_CHOICES[int(kwargs.get("prefix").split("-")[1])][ # type: ignore 0 ] self.fields["weight"].initial = round(Decimal(100 / len(MONTH_CHOICES)), 2) class Meta: model = MonthAllocation fields = ("month", "weight") Previously, I checked that the sum is equal to 100 class VariableMonthAllocationInlineFormSet(FieldTargetSumFormSetMixin): SUM_BY_FIELD = "weight" TARGET_SUM = 100 class … -
OperationalError while connecting django and mysql other
I have problems when I try to connect the mysql database with my application in django. 'default': (1045, "Access denied for user 'PEPE'@'localhost' (using password: NO)") that user does not exist in the database and my settings.py file does not define it either DATABASES = { 'default': {'ENGINE': 'django.db.backends.mysql', 'NAME': 'db_python', 'DATABASE_USER': 'root', 'DATABASE_PASSWORD': 'abc', 'DATABASE_HOST': '127.0.0.1', 'DATABASE_PORT': '3306', } } I don't understand why django uses a different user when trying to establish the connection inside the python shell I print the value of the settings_dict['DATABASE_USER'] variable and it shows the correct user 'root' but it doesn't use it to establish the connection -
DRF: AttributeError when trying to creating a instance with SlugRelatedField and double underscore in slug_field
I get this error as the instance is successfully created and saved in the database with POST request and DRF: AttributeError: 'UserProfile' object has no attribute 'user__username' Here is my UserProfile and **UserImpression" models: class UserProfile(models.Model): user = models.OneToOneField(User, related_name='profile', on_delete=models.CASCADE, primary_key=True) avatar = models.ImageField(upload_to=user_directory_path, null=True, blank=True) imp_laptop = models.ManyToManyField(Laptop, related_name="laptop_impression", through="UserImpression", through_fields=('profile', 'laptop')) objects = models.Manager() custom_manager = UserProfileCustomManager() def __str__(self): return self.user.username + ' profile' class UserImpression(models.Model): profile = models.ForeignKey(UserProfile, on_delete=models.CASCADE) laptop = models.ForeignKey(Laptop, on_delete=models.CASCADE) liked = models.BooleanField(default=True) class Meta: constraints = [ models.UniqueConstraint(fields=['profile', 'laptop'], name='unique_profile_laptop_impression'), ] My serializer class UserImpressionSerializer: class UserImpressionSerializer(serializers.ModelSerializer): profile = serializers.SlugRelatedField(queryset=UserProfile.objects.all(), slug_field="user__username") laptop = serializers.SlugRelatedField(queryset=Laptop.objects.all(), slug_field="slug") class Meta: model = UserImpression fields = ['profile', 'laptop', 'liked'] validators = [ UniqueTogetherValidator( queryset=UserImpression.objects.all(), fields=['profile', 'laptop'] ) ] def create(self, validated_data): profile = validated_data.get("profile", None) laptop = validated_data.get("laptop", None) if profile is None: raise serializers.ValidationError( {"profile": "Cannot retrieve the profile instance with the username"} ) if laptop is None: raise serializers.ValidationError( {"laptop": "Cannot retrieve the laptop instance with the laptop slug"} ) liked = validated_data.get("liked", True) return UserImpression.objects.create(profile=profile, laptop=laptop, liked=liked) My goal for the profile field is to get the UserProfile instance through the username field in the User model which has a 1-1 relationship with … -
Django channels websocket gives 404
I have created a django channels project on windows following the tutorial, and when I run it using dev server python manage.py runserver it seems websocket requests are handled as HTTP and I get Not Found: /ws/socket-server/. What could be the reason? I have tried with Python 3.7 with Django 3.2.18; or Python 3.11, Django 4.1.7