Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Function-Based Middleware vs Class-Based Middleware in Django
I read the doc, then I could understand that we can define a function-based middleware and a class-based middleware in Django as shown below but I could not understand the difference between them. *I'm learning Middleware: Function-Based Middleware: def simple_middleware(get_response): # One-time configuration and initialization. def middleware(request): # Code to be executed for each request before # the view (and later middleware) are called. response = get_response(request) # Code to be executed for each request/response after # the view is called. return response return middleware Class-Based Middleware: class SimpleMiddleware: def __init__(self, get_response): self.get_response = get_response # One-time configuration and initialization. def __call__(self, request): # Code to be executed for each request before # the view (and later middleware) are called. response = self.get_response(request) # Code to be executed for each request/response after # the view is called. return response My questions: What is the difference between a function-based middleware and a class-based middleware in Django? Which should I use basically? -
docker nginx django ALLOWED_HOSTS not allowing requests through
I am deploying an api that doesn't require database or gunicorn to be used. With following configurations I am setting up the api: nginx.conf upstream django { server web:8000; } server { listen 80; server_name localhost; location / { proxy_pass http://django; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } } nginx Dockerfile # Base image for building the Django application FROM nginx:1.19.0-alpine RUN rm /etc/nginx/conf.d/default.conf COPY nginx.conf /etc/nginx/conf.d ALLOWED_HOSTS django settings.py ALLOWED_HOSTS = ['localhost', '127.0.0.1'] Dockerfile # Base image for building the Django application FROM python:3.8 ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 WORKDIR /code COPY requirements.txt /code/ RUN pip install --no-cache-dir -r requirements.txt COPY . /code/ EXPOSE 8000 EXPOSE 80 CMD python manage.py runserver 0.0.0.0:8000 --noreload docker-compose.yml version: '3' services: web: build: context: . dockerfile: Dockerfile volumes: - .:/code nginx: build: ./nginx ports: - 80:80 depends_on: - web The purpose is to create an api which will only be called by other client like a Python based client. I am testing this from my local machine but not working. Adding * wildcard works but is too risky. So, what changes should I make for following two cases: 1. To be able to call from my local python client. 2. To be … -
Django - The serializer field might be named incorrectly and not match any attribute or key on the `QuerySet` instance
I have run into a problem that I cannot figure out. First, my code: models.py from django.db import models import random def pass_gen(): password = '' def rand_uni(): return random.randint(33, 126) def rand(): return random.randint(8, 20) code = rand() for num in range(code): r_int = chr(rand_uni()) password += r_int return password # Create your models here. class User(models.Model): username = models.CharField(max_length=200) class Password(models.Model): url = models.CharField(max_length=800) password = models.CharField(default=pass_gen(), max_length=100) user = models.ForeignKey(User, on_delete=models.CASCADE) class Meta: constraints = [ models.UniqueConstraint(fields=['url', 'user'], name='unique_url_and_user_id') ] Serializers.py: from rest_framework import serializers from vault.models import User, Password class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = '__all__' class PasswordSerializer(serializers.ModelSerializer): url = serializers.CharField(max_length=800) class Meta: model = Password fields = ('url', 'password', "user") views.py: from django.shortcuts import render from django.http import HttpResponse, JsonResponse from rest_framework.parsers import JSONParser from vault.models import User, Password from django.views.decorators.csrf import csrf_exempt from vault.serializers import UserSerializer, PasswordSerializer # Create your views here. # GET list of all users @csrf_exempt def user_all(request): if request.method == 'GET': user = User.objects.all() serializer = UserSerializer(user, many=True) return JsonResponse(serializer.data, safe=False) elif request.method=='POST': data = JSONParser().parse(request) serializer = UserSerializer(data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status=400) #GET and DELETE unique users @csrf_exempt def user_detail(request, id): … -
Ansible URI module throws SSL error in spite of validate_certs set to false
I am trying to do a readiness check on a docker image deployed using Ansible. I am using Ansible module URI. In spite of validate_certs being set to false, I am receiving an SSL error when I try to get an html deployed on it. Verbose log: <my.ip.v4.address> (1, b'\r\n{"redirected": false, "url": "https://127.0.0.1/xxxx_xxxx/xxxx.html", "status": -1, "elapsed": 0, "changed": false, "failed": true, "msg": "Status code was -1 and not [200]: Request failed: <urlopen error EOF occurred in violation of protocol (_ssl.c:1131)>", "invocation": {"module_args": {"url": "https://127.0.0.1/xxxx_xxxx/xxxx.html", "validate_certs": false, "status_code": [200], "force": false, "http_agent": "ansible-httpget", "use_proxy": true, "force_basic_auth": false, "use_gssapi": false, "body_format": "raw", "method": "GET", "return_content": false, "follow_redirects": "safe", "timeout": 30, "headers": {}, "remote_src": false, "unredirected_headers": [], "unsafe_writes": false, "url_username": null, "url_password": null, "client_cert": null, "client_key": null, "dest": null, "body": null, "src": null, "creates": null, "removes": null, "unix_socket": null, "ca_path": null, "mode": null, "owner": null, "group": null, "seuser": null, "serole": null, "selevel": null, "setype": null, "attributes": null}}}\r\n', b'Shared connection to my.ip.v4.address closed.\r\n') <my.ip.v4.address> Failed to connect to the host via ssh: Shared connection to my.ip.v4.address closed. <my.ip.v4.address> ESTABLISH SSH CONNECTION FOR USER: ubuntu <my.ip.v4.address> SSH: EXEC ssh -C -o ControlMaster=auto -o ControlPersist=60s -o StrictHostKeyChecking=no -o 'IdentityFile="/home/jenkins/agent/workspace/XXXXXX/install/foo.pem"' -o KbdInteractiveAuthentication=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o … -
Django user.is_superuser not returning true in template if statement
I'm trying to have information about an object show up if the user is a super user. Normally the information is hidden unless the object's public attribute is true. The object.public part works and {{user.is_superuser}} works as expected but {% if user.is_superuser %} does not. <h1>Player Techniques</h1> <h2>{{user.is_superuser}}</h2> {% for object in techniques %} {% if user.is_superuser or object.public%} {% include "unlimited/technique.html" %} {% endif %} {% endfor %} here are my settings TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [], "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", ], }, }, ] I have also tried request.user.is_superuser with the same results, correctly displaying True for superuser and False otherwise in the h2, but not passing the if. -
Running django app + psql in vscode debugger causing FATAL: sorry, too many clients already
I have django app with psql database that I run with docker on port 5432. When I run the app and celery worker using vscode debugger after a few requests I see this error psycopg2.OperationalError: connection to server at "localhost" (127.0.0.1), port 5432 failed: FATAL: sorry, too many clients already Can't reproduce same error when I run app in standard way by typing python3 main.py in CLI. I used sudo lsof -i:5432 and discovered that if I run app in standard way, processes are being constantly cleaned, but if I run it using VScode debugger, processes are getting stacked and list if getting bigger until I get FATAL. Since I can only reproduce this error using VSCode debuger I assume it is related to that. Are there any settings to make debuger kill processes on the fly? -
django Image field is not loading current value on edit form and user have to upload again the file
I have a django form that have 3 image fields that are required. What I found is that when I use an instance to create an update form, the image is not loaded un the html input field, so when I send the form to the view to save it into database, I get an invalid form error due to images are missing. I defined the imageField as FileField: class Meta: model = Edicion exclude = ['festival'] widgets = { 'logo': FileInput, 'banner': FileInput, 'poster': FileInput, 'fecha_apertura_inscripciones': DateInput(), 'fecha_cierre_inscripciones': DateInput(), 'fecha_inicio': DateInput(), 'fecha_final': DateInput(), 'fecha_notificacion': DateInput(), } If I define again these fields then it works fine, but i'm not being able to send this field from the view. Many thanks Edit: Form Code: Form.py class createNewEdicion(forms.ModelForm): required_css_class = 'required-field' class Meta: model = Edicion exclude = ['festival'] widgets = { 'logo': FileInput, 'banner': FileInput, 'poster': FileInput, 'fecha_apertura_inscripciones': DateInput(), 'fecha_cierre_inscripciones': DateInput(), 'fecha_inicio': DateInput(), 'fecha_final': DateInput(), 'fecha_notificacion': DateInput(), } help_texts = { 'Nombre': ('Some useful help text.'), } error_messages = { 'Nombre': { 'max_length': ("This writer's name is too long."), }, } View.py if request.method == 'POST': form_festival = createNewFestival(request.POST, request.FILES) form_edicion = createNewEdicion(request.POST, request.FILES) # check whether it's valid: if … -
Unable to use `CheckboxSelectMultiple` for choices in wagtails `FieldPanel`: Form field validation raises an error
In a wagtail settings model I have a CharField-based choice field and want that to behave as a multi select in Wagtails FieldPanel. The choices are rendered correctly as multiple checkboxes, but on submit the form validation will raise an error: Select a valid choice. ['OPT1'] is not one of the available choices. So how do I use text-based choices as a multi select in Wagtails FieldPanel? Do I have to override the form field type to a forms.fields.MultipleChoiceField somehow? Setting the widget attribute to Select - instead of CheckboxSelectMultiple - the correctly rendered and populated select dropdown widget works as expected. My current implementation looks (roughly) like this: # models.py @register_setting(icon='cog') class MySettings(BaseGenericSetting): class MyChoices(models.TextChoices): OPT_1 = "OPT1" OPT_2 = "OPT2" choicefield = models.CharField( max_length=4, blank=True, choices=MyChoices.choices, ) panels = [ FieldPanel( 'choicefield', widget=forms.CheckboxSelectMultiple, ), ] I did not find any hints in the Customising generated forms docs. -
How to use django-admin-sortable2 and django-import-export package together in admin panel?
I want to use django-admin-sortable2 django-import-export package together in admin panel. Here is the code: class University(models.Model): name = models.CharField(max_length=50, help_text="University or Institution Name") short_name = models.CharField(blank=True, max_length=10, help_text="University or Institution Short Name") order = models.PositiveIntegerField( default=0, blank=False, null=False, ) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return f'{self.id}-{self.name}' class Meta: ordering = ['order'] admin.py: from import_export import resources from import_export.admin import ImportExportModelAdmin from adminsortable2.admin import SortableAdminMixin # Register your models here. class UniversityResource(resources.ModelResource): class Meta: model = University exclude = ('created_at', 'updated_at',) class UniveresityAdmin(ImportExportModelAdmin, SortableAdminMixin, admin.ModelAdmin): resource_classes = [UniversityResource] admin.site.register(University, UniveresityAdmin) But this is not working, If I remove ImportExportModelAdmin then sortable works and if I remove SortableAdminMixin, import-export works. But I want to use both package together. Is there workaround to solve this issue? Thanks in advance. -
My Django project is not displaying some components, I've tried everything but it's not working [closed]
So I have this resume builder web app project, and it has an experiences section. In the experiences, I have main experience and additional experiences. Whereby in a form, a person enters their experience, and if they have additional experiences, they click the "additional experiences" button and add more experiences. However when I visit preview page, the additional experiences are not displaying, only the main experiences are displaying. models.py: class experience(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, default=1) position = models.CharField(max_length=200) company = models.CharField(max_length=200) startdate = models.DateField() enddate = models.DateField() roles = models.TextField(max_length=500) is_main_experience = models.BooleanField(default=False) views.py: # Create experiences @login_required def experience_v(request): if request.method == 'POST': position = request.POST['position'] company = request.POST['company'] startdate = request.POST['startdate'] enddate = request.POST['enddate'] roles = request.POST['roles'] main_experience = experience(user=request.user, company=company, position=position, startdate=startdate, enddate=enddate, roles=roles) main_experience.is_main_experience = True main_experience.save() return redirect('education') else: form = ExperienceForm() return render(request, 'experience.html', {'form': form}) # Create additional experiences def addexperience_v(request): if request.method == 'POST': additional_experience_positions = request.POST.get('additional_experience_position') for i in range(len(additional_experience_positions)): additional_experience_position = request.POST.get('additional_experience_position[' + str(i) + ']') additional_experience_company = request.POST.get('additional_experience_company[' + str(i) + ']') additional_experience_startdate = request.POST.get('additional_experience_startdate[' + str(i) + ']') additional_experience_enddate = request.POST.get('additional_experience_enddate[' + str(i) + ']') additional_experience_roles = request.POST.get('additional_experience_roles[' + str(i) + ']') additional_experience = experience.objects.create( user=request.user, position=additional_experience_position, … -
HTTPConnectionPool Max retries exceeded with url" Error in Python Selenium
I have a web application where users can perform searches on specific retailers and view the results in tables. When two users start searching on t:he same retailer at the same time, after a while, I receive an error message saying HTTPConnectionPool(host='localhost', port=57640): Max retries exceeded with url: /session/9b99c06c009ea88cba5295bd6fb3725a/url (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x0000021B3ED66310>: Failed to establish a new connection: [WinError 10061])) (Sometimes I also receive InvaliedSessionIdException at /search/) If the retailers being searched are not the same, the program works fine. It also works fine if the searches don't start or end at almost the same time. Python Selenium Code: def standart_analysis(self, product_keys:list[str], category:str,search_method:int=0, img_method:int=0, goal:int=50, sleep_time:float=1): """ It searches for the given product codes in the given retails and analyzes the information it finds. * product_keys: The products from which information will be obtained in the search and analysis should be given as a list of strings. * category: Category type of products to be searched. ----------- * search_method '0': Google search with Request library * search_method '1': Google search with Google library * search_method '2': Google search with Selenium Webdriver * search_method '3': Search in Retail ----------- * img_method '0': Take screenshot * img_method '1': Download … -
django-ses: Connect timeout when using django.core.mail
I am using django-ses==3.4.1 to send email via django.core.mail and both send_mail() and EmailMessage() get the connection timeout after one minute: botocore.exceptions.ConnectTimeoutError: Connect timeout on endpoint URL: "https://email-smtp.eu-central-1.amazonaws.com/ Using this configuration in settings.py according to the instructions on https://pypi.org/project/django-ses/ EMAIL_BACKEND = 'django_ses.SESBackend' AWS_SES_USER = 'my-verified@email' AWS_SES_ACCESS_KEY_ID = '-my-access-key-' AWS_SES_SECRET_ACCESS_KEY = '-my-secret-access-key-' AWS_SES_REGION_NAME = 'eu-central-1' AWS_SES_REGION_ENDPOINT = 'email-smtp.eu-central-1.amazonaws.com' Where I use the variable AWS_SES_USER as from_email while calling email = EmailMessage(subject, message, from_email, recipient_list) email.content_subtype = 'html' email.send() I have also tested if the SES works without Django, i.e. simply using smtplib and it does. The working example derived from https://realpython.com/python-send-email/#option-2-using-starttls smtp_server = "email-smtp.eu-central-1.amazonaws.com" port = 587 # Create a secure SSL context context = ssl.create_default_context() # Try to log in to server and send email try: server = smtplib.SMTP(smtp_server,port) server.ehlo() # Can be omitted server.starttls(context=context) # Secure the connection server.ehlo() # Can be omitted server.login(AWS_SES_ACCESS_KEY_ID, AWS_SES_SECRET_ACCESS_KEY) message = """\ Subject: Test SES This message is sent from Python.""" receiver_email = 'my-recipient@email' server.sendmail(AWS_SES_USER, receiver_email, message) I have tried changing the parameters in settings.py in many ways, but without success. -
Is there any workaround to get celery task result if celery result backend is disabled?
I need to get a result of celery task but there is no CELERY_RESULT_BACKEND in the project I'm working on. | -------------- celery@e465919cc343 v5.2.3 (dawn-chorus) | --- ***** ----- | -- ******* ---- Linux-5.19.0-43-generic-x86_64-with-glibc2.31 2023-06-13 18:45:02 | - *** --- * --- | - ** ---------- [config] | - ** ---------- .> app: cms:0x7feb41db9490 | - ** ---------- .> transport: redis://redis-xxxxx:6379/0 | - ** ---------- .> results: disabled:// | - *** --- * --- .> concurrency: 8 (prefork) | -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) | --- ***** ----- It means an expression like task = my_task.delay(keyword=domain).get() won't ever work. What can I do? Is there any workaround? Everything I tried failed to work. It seems that it's impossible according to Celery documentation. -
How to write/mock testcases for uidb64 and tokens in DRF
I'm trying to verify user once user signup is done. I'm not sure how i can mock the uidb64 and token fields here. Can I get help with some mock test case here ? I have views.py class VerifyUserEmailAPIView(generics.GenericAPIView): serializer_class = EmailVerificationSerializer def patch(self, request): serializer = self.serializer_class(data = request.data) if serializer.is_valid(): user = serializer.validated_data user.is_verified = True user.save() return Response(status = status.HTTP_200_OK) return Response(serializer.errors, status = status.HTTP_400_BAD_REQUEST) serializers.py class EmailVerificationSerializer(serializers.Serializer): uidb64 = serializers.CharField(min_length = 1, max_length = 20) token = serializers.CharField(min_length = 10, max_length = 100) class Meta: fields = ['uidb64', 'token'] def validate(self, attrs): attrs = super().validate(attrs) uidb64 = attrs.get('uidb64', '') token = attrs.get('token', '') pk = urlsafe_base64_decode(uidb64).decode() if not pk.isnumeric(): raise ValidationError("Invalid type received for user id") if not User.objects.filter(pk = pk).exists(): raise ValidationError("Unable to find user") user = User.objects.get(pk = pk) isTokenValid = account_activation_token.check_token(user, token) if not isTokenValid: raise ValidationError("Invalid or expired token") return user -
Understanding PromQL in grafana dashboard
I am trying out django dashboards for grafana. I imported a django dashbord from grafana.com. It has following panel: (I have greyed out my app view names) The PromQL query is as follows: topk(20, (1 - (sum(max_over_time(django_http_requests_latency_seconds_by_view_method_bucket{app=~"^$application$",le="$threshold"}[$__range]) / ignoring(le) max_over_time(django_http_requests_latency_seconds_by_view_method_count{app=~"^$application$"}[$__range])) by (method, view) / count(present_over_time(django_http_requests_latency_seconds_by_view_method_count{app=~"^$application$"}[$__range])) by (method, view))) > 0.0099) Also, the bar gauge does not change as long as I select "Last X", i.e. from "Last day" to "Last Year". Q1. Is it because all data is generated in last day it is convered in "Last Year" and the query takes Max over whole range? Q2. Can someone help me understand this PromQL? Is it returning slowest view in given time range? Q3. Also what is ">1s" in its title bar? -
Vue.JS + Django issue, it wouldn't let me update my userprofile from the dashboard(I get no errors, yet my database doesn't update)
So I am working on this time tracking app for myself, to learn Django and Vue.js, I found a tutorial from Code with Stein. I got stuck at editing the profile part from the tutorial. I get no errors, yet there are no changes made to my username or email(the changes don't even apply to my admin dashboard or database). The thing is that I get no error, which leaves me completely in the dust. I used Python, Django, Vue.JS, and soon SaaS if I find a resolution for this issue. So here is my code in project/apps/userprofile/templates/userprofile/signup.html {% extends 'core/base.html' %} <!-- Extends the base template 'base.html' --> {% block title %}Sign Up | {% endblock %} <!-- Sets the page title to "Sign Up" --> {% block content %} <!-- Begins the content block --> <section class="hero is-medium is-light is-bold"> <!-- Creates a hero banner --> <div class="hero-body"> <div class="container"> <h1 class="title">Sign Up</h1> <h2 class="subtitle">To get started you need an account.</h2> </div> </div> </section> <div class="columns" id="signup-app"> <!-- Creates a container with two columns --> <div class="column is-6 is-offset-3"> <form method="post" action="." class="mt-6" v-on:submit="validateForm" novalidate> <!-- Sign-up form --> {% csrf_token %} <!-- Generates a CSRF token input … -
Django websocket - path not found
I looked everywhere in Stackoverflow discussions. I can't resolve my issue with django websocket. I'm working with React client side and Django server side. Following my code: asgi.py import os from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter, URLRouter from django.urls import path from flow import consumers os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject_project.settings') import flow.routing application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": URLRouter(flow.routing.websocket_urlpatterns) }) setting.py ASGI_APPLICATION = 'agonet_project.asgi.application' CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels.layers.InMemoryChannelLayer', }, } INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', 'django_celery_results', 'django_dump_die', 'django_extensions', 'channels', 'flow', 'authentification', 'rest_framework', 'rest_framework_simplejwt.token_blacklist' ] flow/consumers.py from channels.generic.websocket import AsyncWebsocketConsumer import json class MyConsumer(AsyncWebsocketConsumer): async def connect(self): await self.accept() async def disconnect(self, close_code): pass async def receive(self, text_data=None, bytes_data=None, **kwargs): text_data_json = json.loads(text_data) message = text_data_json['message'] await self.send(text_data=json.dumps({'message': message})) flow/routing.py from channels.routing import ProtocolTypeRouter, URLRouter from django.urls import path from django.core.asgi import get_asgi_application from . import consumers websocket_urlpatterns = [ path('ws/flow/', consumers.MyConsumer.as_asgi()), ] WebSocket.js const ws = new WebSocket('ws://127.0.0.1:8000/ws/flow/'); ws.onopen = () => { console.log('WebSocket connection opened.'); ws.setRequestHeader('Host', window.location.host); // Send the message once the connection is open ws.send(JSON.stringify({ message: 'Hello, server!' })); }; ws.onmessage = (event) => { const message = JSON.parse(event.data); console.log('Received message:', message); }; ws.onclose = () => { console.log('WebSocket connection … -
DJANGO non nullable field migration issue
Im a DJANGO/python novice. I have added two fields so that changes in enterprise and DJANGO admin are logged as who updated them and what date it was updated. the constraint is that these fields cannot be null. my changes are as follows: class Enterprise(models.Model): last_updated = models.DateTimeField( null=False, auto_now=True, verbose_name='Last Updated Date', help_text="Points to time this was last modified", ) last_updated_by = models.CharField( null=False, max_length=100, default='N/A', ) AND class EnterpriseAdmin(admin.ModelAdmin): model = Enterprise readonly_fields = ( "last_updated", "last_updated_by",) fieldsets = ('last_updated','last_updated_by',), however when I run pytest, I'm receiving an error: null value in column "last_updated" violates not-null constraint. when I ran makemigrations, Django prompted me to add a default for last_updated: You are trying to add a non-nullable field 'last_updated' to enterprise without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: 1) Provide a one-off default now (will be set on all existing rows) so I chose option '1' and default=datetime.datetime(1970, 1, 1, 0, 0),preserve_default=False, is added to last_updated in my migration file. migrations.AddField( model_name='enterprise', name='last_updated', field=models.DateTimeField(auto_now=True, default=datetime.datetime(1970, 1, 1, 0, 0), help_text='Points to time this was last modified', verbose_name='Last Updated Date'), preserve_default=False, ), I was under the impression … -
Tastypie queries for all fields, is it possible to only SELECT specific fields
With tastypie you create a resource for your Django model and point the queryset at your model.objects.all(). I was expecting "fields" to allow me to declare which fields i want to return: https://django-tastypie.readthedocs.io/en/latest/resources.html?highlight=exclude#fields This does work, but the sql query generated doesnt care it selects all fields. For me this seems a bit bit pointless if im querying a large table and only want to return 2 columns, and not the other 8. Hopefully I've missed something obvious in the TP documentation. If anyone has any pointers/ideas that would be great -
creating tags during post creation works, but using existing ones don't - possible problem with serializer or something else
I am trying to write a code that will make it able to create tags during creating post and use tags created by urself, other users earlier. I think thats a common approach. This test works without a problem, because it creates a tag during post creation: class TagTests(TestCase): """Tests for tags.""" def setUp(self): self.client = APIClient() self.user = User.objects.create_user(email='mail@example.com', password='password123') self.client.force_authenticate(self.user) self.admin = User.objects.create_superuser(email='admin@example.com', password='password123') self.post = Post.objects.create(user=self.user, text='Test post') self.tag1 = Tag.objects.create(user=self.user, name='Existing Tag 1') self.tag2 = Tag.objects.create(user=self.user, name='Existing Tag 2') self.url_post = reverse('posts-list') def test_create_tags_during_post_creation(self): """Test creating tags during post creation.""" payload = {'text': 'Test', 'tags': [{'name': 'tag1'}, {'name': 'tag2'}]} res = self.client.post(self.url_post, payload, format='json') post_id = res.data['id'] post = Post.objects.get(id=post_id) tags = post.tags.all() tag_names = set(tag.name for tag in tags) self.assertEqual(res.status_code, status.HTTP_201_CREATED) self.assertIn('tag1', tag_names) self.assertIn('tag2', tag_names) However I cannot get my next test to work, because it returns error 400 and response is {'tags': [{'name': [ErrorDetail(string='tag with this name already exists.', code='unique')]}, {'name': [ErrorDetail(string='tag with this name already exists.', code='unique')]}]} def test_create_post_with_existing_tags(self): """Test creating post with existing tags.""" payload = {'text': 'Test post creating with existing tags', 'tags': [{'name': 'Existing Tag 1'}, {'name': 'Existing Tag 2'}]} res = self.client.post(self.url_post, payload, format='json') print(res.data) self.assertEqual(res.status_code, status.HTTP_201_CREATED) post_id = … -
Django: Attach passed id to instance?
I am trying to attach the id I pass through my query string to an instance of a form field user_id. I have tried many different ways and can't seem to get it to work. The id IS being passed successfully. urls for how I passed it (tried int: still didn't work) path('customer_note/<id>', views.customer_note, name='customer-note'), views def customer_note(request, id): obj_instance = Customer.objects.get(user_id= id) obj_instance.user_id = id obj_instance.save(update_fields=['user_id',]) #this is the start of the form save. I couldn't figure out how to do it here either. if request.method =="POST": customer_form = CustomerForm(request.POST) if customer_form.is_valid(): . . . Thank you I have tried using request.user.customer.id and attaching it. I have tried update() in various ways. -
getting exception in working process in gunicorn with django (on digitalocean)
having trouble deploying django project with gunicorn and ningix on digital ocean. I have already created the droplet and am following the steps as mentioned in their official step by step guide but am stuck with these errors This is the error im getting when i run this gunicorn --bind 0.0.0.0:8000 wsgi:app [2023-06-13 11:58:41 +0000] [68713] [INFO] Starting gunicorn 20.1.0 [2023-06-13 11:58:41 +0000] [68713] [INFO] Listening at: http://0.0.0.0:8000 (68713) [2023-06-13 11:58:41 +0000] [68713] [INFO] Using worker: sync [2023-06-13 11:58:41 +0000] [68714] [INFO] Booting worker with pid: 68714 [2023-06-13 11:58:41 +0000] [68714] [ERROR] Exception in worker process Traceback (most recent call last): File "/usr/local/lib/python3.10/dist-packages/gunicorn/arbiter.py", line 589, in spawn_worker worker.init_process() File "/usr/local/lib/python3.10/dist-packages/gunicorn/workers/base.py", line 134, in init_process self.load_wsgi() File "/usr/local/lib/python3.10/dist-packages/gunicorn/workers/base.py", line 146, in load_wsgi self.wsgi = self.app.wsgi() File "/usr/local/lib/python3.10/dist-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/usr/local/lib/python3.10/dist-packages/gunicorn/app/wsgiapp.py", line 58, in load return self.load_wsgiapp() File "/usr/local/lib/python3.10/dist-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp return util.import_app(self.app_uri) File "/usr/local/lib/python3.10/dist-packages/gunicorn/util.py", line 359, in import_app mod = importlib.import_module(module) File "/usr/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1004, in _find_and_load_unlocked ModuleNotFoundError: No module named 'wsgi' [2023-06-13 11:58:41 +0000] [68714] [INFO] Worker … -
How can I solve the problem please suggest me?
Even I am also getting same error. After adding UUID in cart model, It is showing the (django.db.utils.ProgrammingError: cannot cast type bigint to uuid LINE 1: …LE “store_cart” ALTER COLUMN “id” TYPE uuid USING “id”::uuid) error. I deleted migration file and again migrate it but still I am facing this issue. I am using sqlite3 database so should I use postgresql database, please give me hint for it. Thank you!! What is solution please answer for it? -
django error when trying to migrate, I tried deleting the app but still not working
raise_error raise NodeNotFoundError(self.error_message, self.key, origin=self.origin) django.db.migrations.exceptions.NodeNotFoundError: Migration lead.0004_lead_team dependencies reference nonexistent parent node ('team', '0001_initial') py manage.py migrate team zero raise_error raise NodeNotFoundError(self.error_message, self.key, origin=self.origin) django.db.migrations.exceptions.NodeNotFoundError: Migration lead.0004_lead_team dependencies reference nonexistent parent node ('team', '0001_initial') manage.py migrate team [62024:0613/154507.114:ERROR:cache_util_win.cc(20)] Unable to move the cache: Access is denied. (0x5) [62024:0613/154507.114:ERROR:disk_cache.cc(205)] Unable to create cache -
Django login function not working when server run on host 0.0.0.0
def UserLogin(request): if request.method == 'POST': try: username = request.POST["username"] cif = request.POST["cif"] password = request.POST["password"] user = Users.objects.get(username=username) if user : if user.role == '001': login(request, user) return redirect('webapp:bank-details') elif user.role == '002': login(request, user) json = { "service": "CORE_BANKING_LOGIN", "request": { "username": f"{username}", "cif": f"{cif}", "password": f"{password}", "channelType": "CORPORATE" } } this is the code ive been using to log users in when using the localhost to run the server but ive discovered that when i run it using the host 0.0.0.0 i couldnt log in anymore, can someone help or explain why i tried specifying the authentication backend in my settings but that didnt help