Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to send extra parameter to unittest's side_effect in Python?
I'm using side_effect for dynamic mocking in unittest. This is the code. // main functionn from api import get_users_from_api def get_users(user_ids): for user_id in user_ids: res = get_users_from_api(user_id) // test script def get_dynamic_users_mock(user_id): mock_by_user_id = { 1: { "id": 1, "first_name": "John", "last_name": "Doe", ... }, 2: { "id": 2, "first_name": "Jane", "last_name": "Smith", ... }, ... } return mock_by_user_id[user_id] @patch("api.get_users_from_api") def test_get_users(self, mock_get_users) user_ids = [1, 2, 3] mock_get_users.side_effect = get_dynamic_users_mock # mock get_users_from_api get_users(user_ids) # call main function I want to send extra parameter from test_get_users to this get_dynamic_users_mock function. How to do this? -
How to change the background color of an input field of a Django form if it contains errors
I'm trying to code a form with fields that, if a user inputs data that doesn't pass the validation of the form, change their background colors from the default white to lightcoral. Here is a fragment of the HTML file that contains the form itself: <div id="div_formbox"> <form method="post" id="form_appointments"> {% csrf_token %} {{ form.non_field_errors }} <div class="input_group"> <div class="input_field {% if form.name.errors %}error{% endif %}"> {{ form.name}} </div> <div class="input_field {% if form.last_name.errors %}error{% endif %}"> {{ form.last_name }} </div> <div class="input_field {% if form.email.errors %}error{% endif %}"> {{ form.email }} </div> </div> <button type="submit">Send</button> </form> </div> And here is the part of the CSS file where I try to apply the color change to the input fields with errors: .error { background-color: lightcoral; } As you can see, I'm using Django tags to change the class of the form fields with errors from "input_field" to "error". Next, in the CSS file, I reference the "error" class to apply the styling I want. But it doesn't work. I've tried a bunch of variations but none have worked. I'm out of ideas. -
Celery server not terminating immediately when using prefork and without pool line command
I'm working on a django project with celery and redis installed. When I run the Celery server as 'celery -A main_proj -l debug -P solo' or 'celery -A main_proj -l debug -P threads', I can terminate them just fine by just pressing CTRL-C once or twice for warm/cold shutdown. However, when I run Celery as 'celery -A main_proj -l debug' and 'celery -A main_proj -l debug -P prefork', whenever I try to terminate them, it just get stuck at Worker: Stopping Pool. No matter how long I wait, it stays like that until I decide to terminate it with taskkill. I'm fine with the first two alternatives but I want to know why the latter options don't finish quickly. This is the code I have for my celery app: from __future__ import absolute_import, unicode_literals import os from celery.schedules import crontab from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'main_proj.settings') app = Celery('main_proj') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() Additionally, withing the settings.py file I set the CELERY_BROKER_URL with a redis URL that I get from Railway and I have the following code within the init file for the main_proj folder: from .celery import app as celery_app __all__ = ('celery_app',) This is what always happens whenever I … -
subdomain routing in django application
I have a django project that's hosted on a custom domain (e.g. mydomain.com). I have "app" app. For example, in development, requests looked like mydomain.com/app/dashboard. However, I wanted to use a subdomain instead so that my entire app is hosted on the subdomain app.mydomain.com and requests to mydomain.com/app/dashboard would route to app.mydomain.com/dashboard. I am using Nginx to handle this but I'm running into a few problems. Main part of nginx config: server { listen 443 ssl; server_name mydomain.co www.mydomain.co; location ~ ^/app(/?)(.*)$ { return 301 https://app.mydomain.co/$2; } location ~ ^/help(/?)(.*)$ { return 301 https://help.mydomain.co/$2; } location / { proxy_pass http://127.0.0.1:8000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; # WebSocket specific headers proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection $connection_upgrade; } } server { listen 443 ssl http2; server_name app.mydomain.co; location / { # Proxy to your Django application server proxy_pass http://127.0.0.1:8000; # Adjust the port to match your setup proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } } # same for help When my url pattern is like this: path('app', include('app.urls')), and I try to access the dashboard it redirects to app.mydomain.com/dashboard which is not valid since /dashboard is a url exclusively … -
upload images in Django save onlyto folder but not saving to mysql database
I need help my code below save image to folder but not saving to mysql database. pls i dont knw where am getting it wrong. VIEW.PY def indeximg(request): if request.method == "POST": form=ImageForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('uploadok') else: form = ImageForm() return render(request, 'indeximg.html', {'form': form}) def uploadok(request): return HttpResponse(' upload successful') IN MODEL.PY class Image(models.Model): caption=models.CharField(max_length=100) image=models.ImageField(upload_to='images/') -
Best method to model django database using through table to access associations by date
Looking for advice on a tidy solution for accessing The end result I am looking for is the following report: cast, start_date, wire, winch I currently run a script when a cast object is submitted via form to get the active wire associated with the cast, and save it in the 'wire' foreign key field. The active wire is accessed in the script through property tags. Technically this information is retained in the database through a series of models associating a cast with a wire (Cast-DrumLocation-WireDrum), and the date fields that store when the events occurred. These events update the association between cast and wire. Is the way I modelled this a proper solution?, or is there another solutions where the wire foreign key does not need to be stored as a field in the cast model. class Cast(models.Model): id = models.AutoField(db_column='Id', primary_key=True) startdate = models.DateTimeField(db_column='StartDate') enddate = models.DateTimeField(db_column='EndDate') wire = models.ForeignKey('Wire', models.DO_NOTHING, db_column='WireId') winch = models.ForeignKey('Winch', models.DO_NOTHING, db_column='WinchId') class Drum(models.Model): id = models.AutoField(db_column='Id', primary_key=True\) location = models.ManyToManyField(Location, through='DrumLocation', related_name='active_location') material = models.TextField(db_column='Material') wiretype = models.TextField(db_column='WireType') class Winch(models.Model): id = models.AutoField(db_column='Id', primary_key=True) name = models.TextField(db_column='Name') drums = models.ManyToManyField(Drum, through='Drumlocation', related_name='active_drum') class Wire(models.Model): id = models.AutoField(db_column='Id', primary_key=True) nsfid = models.TextField(db_column='NsfId') drums … -
Django ImportError: No module named 'idna' – How to Resolve?
I have a problem with the request module in Django. In development mode i can make API calls okay, but for some reason in production I run into an error that says "No module found 'idna'", I am using IIS webserver in my project. Please help! I tried to use Django rest framework but it seems the request module is still needed, to consume the API. -
Django can't read docker enviroment variable
I'm building a docker compose environment and Django can't read the environment variables i try to give it. Inside my settings.py i have this bit of code ... import os SECRET_KEY = os.environ["DJANGO_SECRET_KEY"] DEBUG = os.environ["DEBUG"] ... and this should be able to read the variables i give to the container, which i tried to give in many different ways. This is the content of my envfile: DJANGO_SECRET_KEY="k64dpx9s1h!ijwafy-lif!(*)sabwk*w+rg#6=nu@ty2jkw%gc" DEBUG="False" All of the following result in django not being able to read the variables during docker build. First attempt: env_file inside compose.yaml This is my compose.yaml services: django: env_file: - ./django/.env Error given: Keyerror Second attempt: changing env_file path This is my compose.yaml services: django: env_file: - /some/other/random/path Error given: no such file or directory (don't mess around with files that don't exist, the file location is correct) Third attempt: hardconding variables This is my compose.yaml services: django: environment: DJANGO_SECRET_KEY: "k64dpx9s1h!ijwafy-lif!(*)sabwk*w+rg#6=nu@ty2jkw%gc" DEBUG: "False" env_file: - ./django/.env Error given: Keyerror Fourth attempt: running standalone container I tried running a docker standalone container and giving the variables by cmd docker run -dp 127.0.0.1:8000:8000 \ -e DJANGO_SECRET_KEY='k64dpx9s1h!ijwafy-lif!(*)sabwk*w+rg#6=nu@ty2jkw%gc' \ -e DEBUG="False" django:v0 Error given: Keyerror Thanks for reading this far. I hope no one will … -
Cookies not accessible in react, but shown chrome developer tools. Django RF backend
Using Django rest framework, I have # views.py @method_decorator(ensure_csrf_cookie, name="dispatch") class SetCsrfTokenAPIView(APIView): permission_classes = (permissions.AllowAny,) def get(self, request, format=None): response = Response({"success": "CSRF cookie set"}) response.set_cookie( "my_cookie", "cookie_value", max_age=3600, secure=True, samesite="None" ) return response # settings.py CORS_ALLOW_ALL_ORIGINS = True CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True CSRF_COOKIE_SECURE = True CSRF_COOKIE_SAMESITE = "None" # CSRF_COOKIE_SAMESITE = "Lax" CSRF_COOKIE_HTTPONLY = False CORS_EXPOSE_HEADERS = ["Content-Type", "X-CSRFToken"] SESSION_COOKIE_SAMESITE = None CORS_ALLOWED_ORIGINS = [ "http://localhost:3000", # "*", ] INSTALLED_APPS = [ ... "rest_framework", "corsheaders", ] MIDDLEWARE = [ "corsheaders.middleware.CorsMiddleware", ... ] Using react frontend, i make a fetch request with to the endpoint that hits SetCsrfTokenAPIView. const data = await fetch( `${process.env.REACT_APP_API_URL}/auth/csrf/`, { method: "GET", credentials: "include", // This is equivalent to Axios's `withCredentials: true` headers: { "Content-Type": "application/json", }, } ); Call is successful and I can see the token values in chrome developer tools token in Applications header in Network However, when i use js-cookie, react-cookie or document.cookie to get the cookie contents, it cannot find any cookie set from django. How can I access cookies in react frontend? My goal is to extract the value and submit the value using the X-CSRFToken header. What I did so far I have scavenged relevant django … -
Stuck on Django 4.2.11
I try to learn Django but I came across a wall. I need to use Django 5 for my project but when I update Django to 5.0.3 my terminal update it than say that I am still in 4.2.11. So I tried to uninstall it then reinstall it but after a successfull uninstallation the command : "python -m django --version" still return the 4.2.11 version. So what can I do ? Thanks -
Best way for grouping models by two week periods and tie them to a data entry?
I am working on a project that is based on a two week time period. I have a model with a start_date and end_date as seen below: class CreateNewTimesheet(models.Model): employee = models.ForeignKey(Employee, on_delete=models.CASCADE) start_date = models.DateField(_("Start Date")) end_date = models.DateField(_("End Date")) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) I want to be able to add another line or something that groups the start_date and end_date. Dates: 03/06/2024 - 03/16/2024 And group or tie that to "week 1". The purpose behind this is to create a timesheet based on a two week time period. I need to be able to group the timesheets by a two week period and tie them to that specific group. All of the Timesheets need to be stored. After start_date and end_date are entered I need them to be tied to week one. I was thinking about adding another line to the CreateNew model and then tie that to week one. And then each start_date and end_date are entered, a new "week" is entered for each new start_date and end_date is created. Should that be based off of created_at entry? Should each week be grouped by a new url? I am honestly stuck at this point about … -
what is different between wsgi.py and asgi.py file, and why we not use manage.py file in deployment
what is different between wsgi.py and asgi.py file, and why we not use manage.py file in deployment I expected, a reason, why we not used manage.py file in devlopyment,if we deploy a web-application through manage.py then what is sceurity threat -
checkbox getlist return max two values from request GET in django
I have a problem with the getlist function in Django. Specifically, I have several checkboxes listed using a for loop. The form is written in HTML without Django Forms. The problem is that the getlist function returns a maximum of two values even if I check more than two checkboxes. Where could the error be? if 'category' in request.GET: print('Category in request GET.') if len(request.GET.getlist('category')) == 1: print(request.GET.getlist('category')) filters['category_id'] = Category.objects.get( slug='-'.join(request.GET.get('category').lower().split())).id if len(Property.objects.filter(**filters)) == 0: queryset.clear() messages.info(request=request, message='No Results.') return redirect(to='properties') else: request.session['sorted_type'] = 'Newest Properties' request.session['filters'] = filters context.update(sidebar_context(**filters)) queryset.clear() queryset.extend(Property.objects.filter(**filters)) else: print('More than one Category.') filters['category__pk__in'] = [Category.objects.get(slug='-'.join(obj.lower().split())).id for obj in request.GET.getlist('category')] if len(Property.objects.filter(**filters)) == 0: queryset.clear() messages.info(request=request, message='No Results.') return redirect(to='properties') else: print(request.GET.getlist('category')) request.session['sorted_type'] = 'Newest Properties' request.session['filters'] = filters context.update(sidebar_context(**filters)) queryset.clear() queryset.extend(Property.objects.filter(**filters)) <form data-properties-filters-form class="properties__filters__filters-form theme-form" method="get" action="{% url 'properties' %}"> <div style="opacity: 0; position: absolute; top: 0; left: 0; height: 0; width: 0; z-index: -1;"> <label>leave this field blank to prove your humanity <input type="text" class="url" autocomplete="off" tabindex="-1"> </label> </div> {% if categories %} <div class="properties__filters__title h4">Category</div> <div class="form__row"> <div class="form__field"> <div data-change-category class="form__input-wrap form__checkbox-wrapper"> {% for category in categories %} <label> <input data-checkbox data-input type="checkbox" name="category" value="{{ category|lower }}"{% if category|lower in request.GET.category … -
Can't connect Django with Mysql
I tried to connect Django with Mysql server But the error show up when I ran python manage.py migrate I already created the database in Mysql and modify the settings.py in Django. I also check if the Mysql server is running which it's currently running. Library installed mysqlclient pymysql Here is my settings.py Here is the error django.db.utils.OperationalError: (2003, "Can't connect to MySQL server on '127.0.0.1:3306' (111)") I tried restart the service of Mysql8services0 but still does not work for me -
400 Bad Request in Apollo Client querying Django Backend
I'm getting the following error when I attempt to make a GraphQL query using Apollo Client in my React frontend from my Django/Django Rest/Graphene Backend. I have also gotten some CORS errors so I have disabled cors on the client with: fetchOptions: { mode: "no-cors", }, and on the backend with csrf_exempt. I am able to make the query work just fine in Postman and GraphiQL but not in React. Here is my query: export const STOCKS_BY_ADJ_CLOSE_RANGE_AND_DATE_QUERY = gql` query StocksByAdjCloseRangeAndDate { stocksByAdjCloseRangeAndDate( low: 100 high: 105 start: "2024-03-01T00:00:00Z" end: "2024-03-10T00:00:00Z" ) { ticker datetime open high low close adjClose volume } } `; Here is my client: const errorLink = onError(({ graphQLErrors, networkError }) => { if (graphQLErrors) { console.log("graphQLErrors", graphQLErrors); } if (networkError) { console.log("networkError", networkError); } }); const client = new ApolloClient({ cache: new InMemoryCache(), headers: { "Content-Type": "application/json", "Access-Control-Allow-Origin": "*", }, connectToDevTools: true, link: from([ errorLink, new HttpLink({ uri: "http://127.0.0.1:8000/graphql", fetchOptions: { mode: "no-cors", }, headers: { "Content-Type": "application/json", "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Credentials": "true", }, }), ]), }); Here are my Django routes: urlpatterns = [ # path("", router.urls), # path("", include(router.urls)), path( "api-auth/", include("rest_framework.urls", namespace="rest_framework") ), path("admin/", admin.site.urls), # path("", TemplateView.as_view(template_name="frontend/build/index.html")), path("api/", include(router.urls)), path("", home), path( … -
Problem with "{% load static %}" in Django
I'm just starting with django, and when I put {% load static %} in the html it doesn't complete it, that is, it doesn't take it as code, I need helpenter image description here I tried importing it through a link, adding a general folder but I don't know what happens -
Could not deserialize class 'Functional'
I did transfer learning to VGG16 model in order to classify images to cat or dog and here is portion of the code snippet : prediction_layer = tf.keras.layers.Dense(1) prediction_batch = prediction_layer(feature_batch_average) def manual_preprocess_input(x, data_format=None): if data_format is None: data_format = tf.keras.backend.image_data_format() if data_format == 'channels_first': # If channels are first, move them to the last dimension x = tf.transpose(x, perm=[0, 2, 3, 1]) # Mean subtraction (ImageNet means in BGR order) mean = [103.939, 116.779, 123.68] x = x - tf.constant(mean, dtype=x.dtype) # Zero-centering by subtracting 127.5 x = x / 127.5 return x inputs = tf.keras.Input(shape=(224, 224, 3)) x = data_augmentation(inputs) x = manual_preprocess_input( x ) x = base_model(x, training=False) x = global_average_layer(x) x = tf.keras.layers.Dropout(0.2)(x) outputs = prediction_layer(x) model = tf.keras.Model(inputs, outputs) and here is the view code where I loaded my model : then I saved it using model.save('my_model.keras'), then I loaded in a django view but the problem is whenever I load it and make post request to the view, in the line where I load the model I encounter this error : def testSkinCancer(request): model = tf.keras.models.load_model( os.getcwd()+r'\media\my_model.keras', safe_mode=False) print(">>> model loaded") if not request.FILES: return HttpResponseBadRequest(json.dumps({'error': 'No image uploaded'})) # Access the uploaded image … -
How to get the foreign key value into href attribute of a hyperlink element as a url parameter in Django template
I have data table showing list of vehicles from the Vehicle model with Driver column. When user clicking on the Driver column value, I want to redirect the user to driver detail page url driver-detail/license_number. I tried to pass the license_number to href attribute of hyperlink element like href="{% url 'driver-detail' vehicle.driver.license_number %}". This does not help me, it's always empty. If I omit the license_number in the href value it will pass the __str__(self) return value of the Driver model, which is combination of license_number and fullname. If I change the return value of __str__(self) in the Driver model it will work. But I don't want to change the return value of __str__(self). Any help is much appreciated! Model.py class Driver(models.Model): license_number = models.CharField(primary_key=True, max_length=50) fullname = models.CharField(max_length=25) license_issue_date = models.DateField("Issued Date") def __str__(self): return self.license_number + " " + self.fullname class **Vehicle**(models.Model): license_plate = models.CharField(max_length=25, primary_key=True) model = models.CharField(max_length=100, verbose_name="Vehicle model") driver = models.ForeignKey(Driver,on_delete=models.SET_NULL,null=True, blank=True) template.html <a href="{% url 'driver-detail' vehicle.driver.license_number %}" > {{vehicle.driver.license_number}}{{vehicle.driver.fullname}} </a> urls.py urlpatterns = [ path('driver-detail/<str:pk>/', views.driverDetail, name='driver-detail'), ] -
Celery and Celery beat wit django after running in docker container running some job
I am trying to run django celery and celery beat after i start celery and celery beat this process is running every second is this normal celery-1 | [2024-03-10 16:08:11,479: INFO/MainProcess] Running job "EventPublisher.send_events (trigger: interval[0:00:01], next run at: 2024-03-10 16:08:12 IST)" (scheduled at 2024-03-10 16:08:11.478374+05:30) celery-1 | [2024-03-10 16:08:11,479: INFO/MainProcess] Job "EventPublisher.send_events (trigger: interval[0:00:01], next run at: 2024-03-10 16:08:12 IST)" executed successfully celery-beat-1 | [2024-03-10 16:08:11,767: INFO/MainProcess] Running job "EventPublisher.send_events (trigger: interval[0:00:01], next run at: 2024-03-10 16:08:12 IST)" (scheduled at 2024-03-10 16:08:11.766830+05:30) celery-beat-1 | [2024-03-10 16:08:11,767: INFO/MainProcess] Job "EventPublisher.send_events (trigger: interval[0:00:01], next run at: 2024-03-10 16:08:12 IST)" executed successfully I tried clearing redis db also tried uninstalling and installing redis,celery -
Django PasswordResetView not working properly with app_name causing DisallowedRedirect
I'm encountering an issue with Django's built-in password reset functionality within my project. Specifically, I have an app named 'user' and I've defined the app_name variable in my urls.py as app_name = 'user'. However, this seems to be causing problems with Django's password reset views. Initially, I encountered the "Reverse for 'url name' not found" error when using auth_views.PasswordResetView. To address this, I tried setting the success_url parameter to 'user:password_reset_done' and providing a custom email_template_name. However, now I'm facing a new issue where the debugger is raising a DisallowedRedirect exception with the message "Unsafe redirect to URL with protocol 'user'" when attempting to access the password reset functionality. This occurs during the execution of django.contrib.auth.views.PasswordResetView. the error is: Unsafe redirect to URL with protocol 'user' Request Method: POST Request URL: http://127.0.0.1:8000/accounts/reset_password/ Django Version: 5.0.2 Exception Type: DisallowedRedirect Exception Value: Unsafe redirect to URL with protocol 'user' Raised during: django.contrib.auth.views.PasswordResetView Here's a summary of my setup: urls.py (within the 'user' app): from django.urls import path from django.contrib.auth import views as auth_views app_name = 'user' urlpatterns = [ path('reset_password/', auth_views.PasswordResetView.as_view(template_name='registration/reset_password.html', success_url='user:password_reset_done', email_template_name='registration/password_reset_email.html'), name="reset_password"), path('reset_password_sent/', auth_views.PasswordResetDoneView.as_view(template_name='registration/password_reset_done.html'), name='password_reset_done'), path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(), name='password_reset_confirm'), path('reset_password_complete/', auth_views.PasswordResetCompleteView.as_view(), name='password_reset_complete') ] registration/reset_password.html: {% block content %} <h1>Password reset</h1> <p>Forgotten your … -
creating migrations in Django [closed]
I was following a YouTube video guide on django, and I ran into a problem when after filling out the file models.py I went to cmd and wrote python manage.py makemigrations, but instead of the created file in the migrations directory, I was met with a long error. This is my first experience with django and no migrations have been created before. The code models.py - ` from django.db import models class Articles (models.Model): title = models.CharField('Name', max_length=50) anons = models.CharField('Announcement', max_length=250) full_text = models.TextField('Article') date = models.DateTimeField('Publication date') def __str__(self): return self.title` ` error - `C:\Users\глеб\Desktop\pip\books> python manage.py makemigrations System check identified some issues: WARNINGS: ?: (staticfiles.W004) The directory 'C:\Users\глеб\Desktop\pip\books\static' in the STATICFILES_DIRS setting does not exist. Traceback (most recent call last): File "C:\Users\глеб\AppData\Local\Programs\Python\Python38-32\lib\site-package s\django\utils\module_loading.py", line 30, in import_string return cached_import(module_path, class_name) File "C:\Users\глеб\AppData\Local\Programs\Python\Python38-32\lib\site-package s\django\utils\module_loading.py", line 16, in cached_import return getattr(module, class_name) AttributeError: module 'django.db.models' has no attribute 'Bi gAutoField' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\глеб\AppData\Local\Programs\Python\Python38-32\lib\site-package s\django\db\models\options.py", line 275, in _get_default_pk_class pk_class = import_string(pk_class_path) File "C:\Users\глеб\AppData\Local\Programs\Python\Python38-32\lib\site-package s\django\utils\module_loading.py", line 32, in import_string raise ImportError( ImportError: Module "django.db.models" does not define a "Bi gAutoField" attribu te/class The above exception … -
Creating a model through the admin panel inside the test
I'm new to Python. I'm trying to create a test that will create an item inside the admin panel, but when I run the test I get: AssertionError: False is not true. Help me please class ItemAdminTest(TestCase): serialized_rollback = True def setUp(self): self.client = Client() self.user = User.objects.create_superuser(email='admin@example.com', password='admin') def test_create_item_admin(self): self.client.login(email='admin@example.com', password='admin') response = self.client.post('/admin/product/item/add/', { 'title': 'Test Item', 'description': 'Test Description', 'price': 10.00, 'code': 123456, 'color': 'Red', 'weight': 1.5, 'height': 10.0, 'width': 5.5, 'types': ["КБТ", "МБТ"], 'amount': 5, }) self.assertTrue(Item.objects.filter(title='Test Item').exists()) At the same time, I am absolutely sure that a superuser is created and authorization is successful, but for some reason the item itself is not created. -
Invalid credentials even putting right credentails django
I have created a sign in form for my user and when I’m trying to log in it says invalid student_ID or password even though I put my credentials properly I’m using postgresql via Railway I’m a beginner (https://i.stack.imgur.com/iRQcJ.png) This is my forms.py from django import forms from django.forms import ModelForm from .models import StudentInfo class StudentInfoForm(forms.ModelForm): class Meta: model = StudentInfo fields = ['student_id', 'firstname', 'lastname', 'middlename', 'course','year', 'section', 'password', 'confirm_password',] widgets = { 'password': forms.PasswordInput(), 'confirm_password': forms.PasswordInput() } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['student_id'].required = True self.fields['firstname'].required = True self.fields['lastname'].required = True self.fields['course'].required = True self.fields['section'].required = True self.fields['password'].required = True self.fields['confirm_password'].required = True class SignInForm(forms.Form): student_id = forms.CharField(label='Student ID', max_length=10) password = forms.CharField(label='Password', widget=forms.PasswordInput) This is my models.py from django.db import models from django.contrib.auth.hashers import make_password # Create your models here. class StudentInfo(models.Model): student_id = models.CharField(max_length=10, unique=True, primary_key=True) firstname = models.CharField(max_length=100) lastname = models.CharField(max_length=100) middlename = models.CharField(max_length=100, blank=True, null=True) course = models.CharField(max_length=100) year = models.CharField(max_length=1) section = models.CharField(max_length=1) password = models.CharField(max_length=128, null=True) confirm_password = models.CharField(max_length=128, null=True) def __str__(self): return f"{self.firstname} {self.lastname}" def save(self, *args, **kwargs): self.password = make_password(self.password) super(StudentInfo, self).save(*args, **kwargs) This is my urls.py from django.urls import path from . import views urlpatterns = [ … -
how to make a django model with no id column and primary key?
i am working with big data and i can have an extra column like id. i cant put the primary key to any other single column, because of duplicate. and even more i cant have primary key on two column or more because my data is not unique. so the only way to get rid of the id column with a primary key left for me is to stop django making it! and i don't know how... i tried to edit the operation part of the migration file before doing the migrate command but it didn't work. even if i delete the id column in the migration file it still make it /:(. -
Query using reverse relationship or objects manager?
from .models import Comment user = request.user comments_1 = user.comment_set.all().count() comments_2 = Comment.objects.filter(user=user).count() Between comments_1 and comments_2, which one is faster? Can someone explain to me? Any help will be greatly appreciated. Thank you very much. I looked in Django Documentation Making queries, but does not really say about the difference in performance.