Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Curl syntax error suspected, JSON parse error, django app
I am trying to use Django Rest Framework to allow different systems to post data to my app. I need a verification on whether or not my curl request is correct so I can investigate further. I do not have many experience with curl so I'm not sure about my syntax. curl -v -H "Content-Type:application/json" -u Admin:Admin http://192.168.2.54:8082/api/zam/ -d '{"my_id":"96/Admin/2021","data_z":"2021-04-15","data_r":"2021-04-29","status":"0","kom":"","uwg":"","products":[{"ean":"200000011111","model":"AAA","kolor_f":"KOLOR","kolor_k":"KOLOR","kolor_b":"KOLOR","symbol":"SYMBOL OF PRODUCT","qty":"15","zam_id":"138"}]}' Error I get: * Trying 192.168.2.54... * TCP_NODELAY set * Connected to 192.168.2.54 (192.168.2.54) port 8082 (#0) * Server auth using Basic with user 'Admin' > POST /api/zam/ HTTP/1.1 > Host: 192.168.2.54:8082 > Authorization: Basic QWRtaW46OWlqbm1rbzA= > User-Agent: curl/7.55.1 > Accept: */* > Content-Type:application/json > Content-Length: 258 > * upload completely sent off: 258 out of 258 bytes < HTTP/1.1 400 Bad Request < Date: Tue, 21 Dec 2021 11:34:53 GMT < Server: WSGIServer/0.2 CPython/3.10.0 < Content-Type: application/json < Vary: Accept, Cookie, Accept-Language < Allow: GET, POST, HEAD, OPTIONS < X-Frame-Options: DENY < Content-Length: 73 < X-Content-Type-Options: nosniff < Referrer-Policy: same-origin < Content-Language: pl < {"detail":"JSON parse error - Expecting value: line 1 column 1 (char 0)"}* Connection #0 to host 192.168.2.54 left intact -
Add extra value from ImportForm to model instance before imported or saved
I have the following model that I want to import: class Token(models.Model): key = models.CharField(db_index=True,unique=True,primary_key=True, ) pool = models.ForeignKey(Pool, on_delete=models.CASCADE) state = models.PositiveSmallIntegerField(default=State.VALID, choices=State.choices) then a resource model: class TokenResource(resources.ModelResource): class Meta: model = Token import_id_fields = ("key",) and a ImportForm for querying the pool: class AccessTokenImportForm(ImportForm): pool = forms.ModelChoiceField(queryset=Pool.objects.all(), required=True) This value shouls be set for all the imported token objects. The problem is, that I did not find a way to acomplish this yet. How do I get the value from the form to the instance? The before_save_instance and or similar methods I cannot access these values anymore. I have to pass this alot earlier I guess. Does someone ever done something similar? Thanks and regards Matt -
Django Integrity error from Abstractbaseuser
IntegrityError at / UNIQUE constraint failed: pages_profile.username Request Method: POST Request URL: http://127.0.0.1:8000/ Django Version: 3.2.9 Exception Type: IntegrityError Exception Value: UNIQUE constraint failed: pages_profile.username How would you update an Abstractuser's custom avatar field? Specifically obj = Profile.objects.create(avatar = img) from django.shortcuts import redirect, render from .forms import UserProfileForm from .models import Profile def index(request): context = {} if request.method == "POST": form = UserProfileForm(request.POST, request.FILES) if form.is_valid(): img = form.cleaned_data.get("avatar") obj = Profile.objects.create( avatar = img ) obj.save(commit=False) print(obj) return redirect(request, "home.html", obj) else: form = UserProfileForm() context['form']= form return render(request, "home.html", context) models.py from django.db import models from django.contrib.auth.models import AbstractUser class Profile(AbstractUser): """ bio = models.TextField(max_length=500, blank=True) phone_number = models.CharField(max_length=12, blank=True) birth_date = models.DateField(null=True, blank=True) """ avatar = models.ImageField(default='default.png', upload_to='', null=True, blank=True) forms.py from django import forms from django.core.files.images import get_image_dimensions from pages.models import Profile class UserProfileForm(forms.ModelForm): class Meta: model = Profile fields = ('avatar',) def clean_avatar(self): avatar = self.cleaned_data['avatar'] try: w, h = get_image_dimensions(avatar) #validate dimensions max_width = max_height = 1000 if w > max_width or h > max_height: raise forms.ValidationError( u'Please use an image that is ' '%s x %s pixels or smaller.' % (max_width, max_height)) #validate content type main, sub = avatar.content_type.split('/') if not … -
How to get the value for the particular user from the anchor tag in django view?
urls.py urlpatterns = [ path('vendors/', views.loomerang_admin_vendors, name="loomerang_admin_vendors"), path('vendor_profile/<str:userid>', views.loomerang_admin_vendor_profile, name="loomerang_admin_vendor_profile"),] template {% for vendor in vendors %} <tr> <th scope="row">{{vendor.id}}</th> <td>{{vendor.date_joined|date:"d-m-Y"}}</td> <td name="vendor_id"><a href="{% url 'loomgerang_admin:loom_admin_vendor_profile' userid %}">{{vendor.userid}}</a></td> <td>{{vendor.first_name}}</td> <td>{{vendor.status}}</td> <td>20-12-2021</td> <td>Lokesh</td> </tr> {% endfor %} views.py def loomerang_admin_vendor_profile(request, userid): print(request.user.userid) vendor_name = request.POST.get("vendor_id") basic_details = CustomUser.objects.filter(id=request.user.id) store_details = basic_details[0].vendor_details.all() print(store_details) return render(request, 'loom_admin/vendor_profile.html', {'basic_details':basic_details, 'store_details': store_details}) I have shown all the details of the users as a table. If I click the Id in one row, It will redirect me to another page and get all the information the particular user has. Here I am don't know to do that. please, expecting an answer. -
{"errors":{"errors":[{"detail":"You do not have permission to perform this action.","code":"permission_denied"}]}}
When I visit http://127.0.0.1:8000/ after running python manage.py runserver inside my virtual env I got this error permission denied my Django is still in the default folder structure and no change yet I have tried to instll pip install django-cors-headers and add all the below into the setting.py file file from corsheaders.middleware import CorsMiddleware from corsheaders.middleware import CorsMiddleware CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True ALLOWED_HOSTS = ['*'] CORS_ORIGIN_ALL_ALL =True CORS_ALLOWED_ORIGINS = [ "https://example.com", "https://sub.example.com", "http://localhost:8080", "http://127.0.0.1:9000", ] CORS_ALLOWED_ORIGIN_REGEXES = [ r"^https://\w+\.example\.com$", ] CORS_URLS_REGEX = r"^/api/.*$" CORS_ALLOW_METHODS = [ "DELETE", "GET", "OPTIONS", "PATCH", "POST", "PUT", ] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware' 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', "django.middleware.common.CommonMiddleware" ] -
Losing microseconds when inserting date to database
I have this code snippet in a view: time_from = datetime.strptime(req.POST['time_from'], "%Y-%m-%d %H:%M:%S.%f") with connections["mssql_database"].cursor() as cursor: sql_statement = "EXEC SaveActivity @TimeFrom='%s'" % (time_from) print(sql_statement) cursor.execute(sql_statement) It prints this SQL statement: EXEC SaveActivity @TimeFrom='2021-12-01 08:34:54' Microseconds are missing. They are zeros, but I need them in a database. How can I correct this? -
Error in Postgresql Connection Port not connected
I have started my ssh on local and I am trying to run python3 manage.py runserver but it gives this error? Is the server running locally and accepting connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"? I also tried psql on terminal it gives me this error as well. psql: error: could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"? I also check connection but it seems to be not working like netstat -nltp | grep 5432 I tried to restart as well but still same error. systemctl restart postgresql.service I saw that after restarting the pg_lscluster gives me output as 12 main 5432 online postgres /var/lib/postgresql/12/main /var/log/postgresql/postgresql-12-main.log But as soon as after few minutes its give me output as 12 main 5432 down postgres /var/lib/postgresql/12/main /var/log/postgresql/postgresql-12-main.log -
Django - Get all posts that were created in a month in a certain timezone
So I have this Post model, which is like a wall post on Facebook or Reddit. I want to be able to retrieve all posts that were created in a month under a certain time zone. The reason for this is because I have a paginator on my app that let's the users see posts by month and I want to query for it rather than send them all the posts as it could be thousands and that'll take a long time. I also want it in their time zone, because Django stores datetime in UTC so what could be a post created at the end of November in UTC should actually be in December when converted to the requestors local device time. model.py class Post(models.Model): uuid = models.UUIDField(primary_key=True) created = models.DateTimeField('Created at', auto_now_add=True) updated_at = models.DateTimeField('Last updated at', auto_now=True, blank=True, null=True) creator = models.ForeignKey( User, on_delete=models.CASCADE, related_name="post_creator") body = models.CharField(max_length=POST_MAX_LEN) So for example if a user creates 10 posts in November, 2 in December PST. Then I have a view that takes month and time_zone then it should return the 10 posts from November when given '11' for month and 'PST' for time_zone. How do I return all posts … -
i run command django-admin startproject dr it shows zsh: command not found: django-admin?
i run command django-admin startproject dr it show zsh: command not found: django-admin How to solve this problem ? -
Django how to properly test User instance
A few days ago I found a really nice webpage with Patterns and Anti-Patterns in Django. One of the anti-patterns is connected with linking custom user model to other models. Basic on Django documentation and this webpage I would like to know: What are the limitations between calling get_user_model() and settings.AUTH_USER_MODEL? What kind of differences are between those two approaches? How to prepare mock user in tests? Should I create user instance from AUTH_USER_MODEL or get_user_model? from django.contrib.auth import get_user_model User = get_user_model() # or settings.AUTH_USER_MODEL self.custom_user = User.objects.create( username='test', password='password', first_name='test name', email='test@test.test', ) -
request.FILES.get is empty in a Django project
For a project I would like to use two files loaded by the user via two inputs, to apply an external script. My problem is that I get an error because Django doesn’t seem to be able to locate these inputs. So I have an empty object instead of the file. Here are my codes: home.html <!DOCTYPE html> <html lang="fr"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Home</title> </head> <body> <h1>Home</h1> <form action="/external/" method="post" enctype="multipart/form-data"> {% csrf_token %} Input xlsx file :<br><br> <input type="file" name="file1" accept=".xml" required><br> <input type="file" name="file2" accept=".xml" required><br> <input type="submit" value="Valider"><br> </form> </body> </html> views.py from django.shortcuts import render from .scripts.extScript import * def home(request): return render(request, 'home.html') def external(request): f1=request.FILES.get('file1') f2=request.FILES.get('file2') extScript(f1,f2) return render(request,'home.html') urls.py from django.contrib import admin from django.urls import include, path from .views import * urlpatterns=[ path('',home,name="home"), path('external/',external, name="external") ] architecture: DjangoProject | -views.py -urls.py -scripts | -extScript.py templates | -home.html and the error specifies that f1 type is < NoneType > I want to point out that I tried to put f1=request.FILES[‘file1’] and it sends me that ‘file1’ is not found : raise MultiValueDictKeyError(key). If anyone has an idea, I can’t solve this problem, I feel that everything is fine. Besides, … -
Celery Flower didn't responding anything on the command line
I'm trying to up flower on my local machine but flower not responding. I'm using docker. First I up to the Celery worker in to the container like celery -A tasks worker -l info after that I run to the beat different shell. celery -A tasks beat -l info Worker and beat successfully works so I can see received tasks on worker stage. And when I try to run flower, flower did not responding. I tried to following commands and everyone stucks. I cant see any result like "visit me:" on command line and also localhost:5555 not responding. celery flower -A tasks --loglevel=info --broker=redis://redis-dev:6379/0 celery flower -A tasks celery -A tasks flower --address=127.0.0.1 --port=5555 celery -A tasks flower --address=127.0.0.6 --port=5556 My docker-compose file looks like version: "3.8" services: app: build: context: . dockerfile: ./app/Dockerfile command: python -u manage.py runserver 0.0.0.0:8000 volumes: - ./app:/app ports: - "8000:8000" depends_on: - redis-dev environment: APP_REDIS_HOST: redis-dev APP_REDIS_PORT: 6379 APP_REDIS_DB: 0 redis-dev: image: redis:latest ports: - "6379:6379" volumes: - redisdata:/data versions: celery==3.1.19 flower==0.9.2 tornado==4.2 I did suspect to broker was not working but worker and beat works success so I think broker part works. Thanks in advance for any suggestion. -
Django on Nginx and Gunicorn, permission denied 502 bad gateway
I've been following all tutorials and digging into all similar questions but none resolve my problem. I've a django app running on a vps. The django app is located at /home/larapida/webapp directory structure: drwxr-x--- 11 larapida larapida 4096 Dec 21 09:21 . drwxr-xr-x 4 root root 4096 Dec 20 21:17 .. drwxrwxr-x 4 larapida larapida 4096 Dec 20 21:25 .venv srwxrwxrwx 1 larapida www-data 0 Dec 21 08:59 larapida.sock drwxrwxr-x 3 larapida larapida 4096 Dec 21 09:21 logs -rw-r--r-- 1 larapida larapida 27492 Dec 20 19:56 poetry.lock drwxrwxr-x 3 larapida larapida 4096 Dec 20 21:51 public -rw-r--r-- 1 larapida larapida 704 Dec 20 19:56 pyproject.toml drwxr-xr-x 5 larapida www-data 4096 Dec 20 21:48 webapp My django settings: ALLOWED_HOSTS = [ "larapidamolinetto.com", "145.239.197.231", ".localhost", "127.0.0.1", "[::1]", ] my gunicorn service is called larapida.service [Unit] Description=larapida daemon After=network.target [Service] User=larapida Group=www-group WorkingDirectory=/home/larapida/webapp ExecStart=/home/larapida/.venv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/home/larapida/larapida.sock webapp.wsgi:application [Install] WantedBy=multi-user.target and my nginx configuration is: upstream larapida { server unix:/home/larapida/larapida.sock; } server { listen 80 default_server; server_name 145.239.197.231; access_log /home/larapida/logs/nginx/access.log; error_log /home/larapida/logs/nginx/error.log; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/larapida/public/static; } location / { try_files $uri @proxy_to_app; } location @proxy_to_app { include proxy_params; proxy_pass … -
Getting data from sqlite database by calling it from Django by using HTML forms
I have a HTML form : <form action = "" method = "get"> <label for="movie_title">Filmo pavadinimas: </label> <input id="movie_title" type="text" name="movie_title"> <input type="submit" value="OK"> </form> I want to enter the movie title and get all of the actors that casted in that movie, but I don't know how to get to that result even after reading the documentation. DB data: Model for that table: class Filmlist(models.Model): film_id = models.AutoField(primary_key=True) title = models.CharField(max_length=250) description = models.TextField(blank=True, null=True) # This field type is a guess. category = models.CharField(max_length=250) price = models.DecimalField(max_digits=10, decimal_places=5) # max_digits and decimal_places have been guessed, as this database handles decimal fields as float length = models.SmallIntegerField(blank=True, null=True) rating = models.CharField(blank=True, null=True, max_length=250) name = models.CharField(max_length=250) class Meta: managed = False db_table = 'film_list' So to conclude, I have to enter movie title and get all of those actors show under actors row. Is it possible to do that with Django and HTML? -
Is there a way to redirect my the user from my django website to an external website using urlField?
so here is my model.py from django.db import models # Create your models here. class TestSeries(models.Model): name=models.CharField(max_length=120) url_field=models.URLField(max_length=200) def __str__(self): return self.name def save(self, *args, **kwargs): super().save(*args, **kwargs) class Meta: verbose_name_plural="TestSeries" and here is my views.py from django.shortcuts import render from .models import TestSeries from django.views.generic import ListView class TestListView(ListView): context_object_name='test' model=TestSeries template_name='testseries/test_list_view.html' def test_view(request,pk): test=TestSeries.objects.get(pk=pk) return redirect(test.image_url) and my html template {% extends 'home.html' %} {% block content %} {% for obj in object_list %} {{obj.name}}:-<a href="{'url_field'}">{{obj.url_field}}</a> {% endfor %} {% endblock %} Note:- I am able to display the name and the url_field of the object in my html file but as soon as I click on the link it shows an error404, page not found. -
how to post multiple images together in django?
I want to create a post request with multiple images in django. I tried creating a different model for images and connected it to my 'vehicle' model using OnetoOneField, but it only allows to post 1 image at a time.(this method is shown below) I also tried to get multiple images as a comma-separated string but when I post my images as a list of binary images it shows 'invalid type' error. I just need to create an API for posting multiple images in one go. Here is my model.py file - class VehicleImage(models.Model): image_id = models.AutoField(primary_key=True) image = models.ImageField(upload_to="media") def __str__(self): return self.vehicle.auction_title class Vehicle(models.Model): auction_title = models.TextField() vehicle_images = models.ManyToManyField(VehicleImage, blank=True) vehicle_images_list = models.TextField() def __str__(self): return self.auction_title Serializer.py files - class VehicleImageSerializer(serializers.ModelSerializer): class Meta: model = VehicleImage fields = "__all__" class VehicleSerializer(serializers.ModelSerializer): vehicle_images = VehicleImageSerializer(many=True, read_only=True) class Meta: model = Vehicle fields = "__all__" def create(self, validated_data): images_data = validated_data['vehicle_images_list'] vehicle = Vehicle.objects.create(**validated_data) if images_data!="": for data in images_data.split(','): image = VehicleImage.objects.get(image_id=data) vehicle.vehicle_images.add(image) return vehicle Views.py file class add_vehicle(ListCreateAPIView): queryset = Vehicle.objects.all().order_by('-vehicle_id') serializer_class = VehicleSerializer pagination_class = CustomPagination def post(self, request, format=None): # creating the Vehicle vehicle_serializer = VehicleSerializer(data=request.data) if vehicle_serializer.is_valid(): vehicle_serializer.save() return Response({ "response":{"vehicle_id":vehicle_serializer.data['vehicle_id']}, "status_code":200}, status … -
How to async sending API request process in Django?
I'm doing a project in which, on loading(render) a page through views, an API request is sent. I want to async the API request process, i.e in intervals of 10sec, API requests should be sent. -
Import model without id field as primary key with django import_export
just tried out django-import-export to import som things from a csv-file. Followed the doc but I always get an error when trying to import the following Model: class Token(models.Model): key = models.CharField(db_index=True,unique=True,primary_key=True, ) pool = models.ForeignKey(Pool, on_delete=models.CASCADE) state = models.PositiveSmallIntegerField(default=State.VALID, choices=State.choices) then the resource class: class TokenResource(resources.ModelResource): class Meta: model = Token skip_unchanged = True report_skipped = True fields = "key" Now when importing a csv-file i get the following errors: Error row number: 1 - 'id' Traceback (most recent call last): File "/backend/.venv/lib/python3.9/site-packages/import_export/resources.py", line 667, in import_row instance, new = self.get_or_init_instance(instance_loader, row) File "/backend/.venv/lib/python3.9/site-packages/import_export/resources.py", line 359, in get_or_init_instance instance = self.get_instance(instance_loader, row) File "/backend/.venv/lib/python3.9/site-packages/import_export/resources.py", line 346, in get_instance import_id_fields = [ File "/backend/.venv/lib/python3.9/site-packages/import_export/resources.py", line 347, in <listcomp> self.fields[f] for f in self.get_import_id_fields() KeyError: 'id' There is no field id within my model the primary key field is key so why it is not taken? Or could it be that a model must have an id field to get imported? I know that this ids are taken for comparision and so on but there is a primary key field within the model, so I do not understand why this is not taken. How could I change this without having to … -
Django Models - Column save based on primary key when post
This is my model.py class AppointmentMaster(models.Model): id = models.AutoField(primary_key=True) user_key = models.CharField(max_length=30,blank=True,unique=True) phone_number = models.CharField(max_length=20, blank=True, null=True) email = models.CharField(max_length=20, blank=True, null=True) and i'm using viewsets.ModelViewSet for post details.I want to save user_key automatically when create a new row from post api. I want output like { "id":1, "user_key":"USER-1", "phone_number":"90000000", "email":"abc@gmail.com" } -
DJango - Two Different Views from Different Apps into a single Template
Django beginner here. I am trying to make a an app for where users can make connections, post stuff, chat, etc. There are two user types - Parents and Child. For this I extended the AbstractBaseUser model and created two another models - Parent and Child with a OneToOne link to the User. #accounts/models.py class User(AbstractBaseUser, PermissionsMixin): REQUIRED_FIELDS = [] EMAIL_FIELD = "email" USERNAME_FIELD = 'email' objects = UserManager() email = models.EmailField(unique=True) first_name = models.CharField(max_length=DefaultModel.MAX_LENGTH, unique=False) last_name = models.CharField(max_length=DefaultModel.MAX_LENGTH, unique=False) profile_photo = models.ImageField(default='uploads/profile/default_profile.jpg', upload_to=content_image_name) cover_photo = models.ImageField(default='uploads/profile/default_cover.jpg', upload_to=content_image_name) username = AutoSlugField(populate_from='first_name', unique=True, sep='.') bio = models.CharField(max_length=255, blank=True, default="Nothing to see here !") is_child = models.BooleanField(default=False) is_parent = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) # storing timestamps for users. created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) CHOICES = (('M','Male'),('F','Female'),('O','Other')) gender = models.CharField(max_length=10, choices=CHOICES) def get_absolute_url(self): return "/users/{}".format(self.username) def __str__(self): return "{} {}".format(self.first_name, self.last_name) class Child(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) friends = models.ManyToManyField('self', blank=True, related_name='friends', db_column='friends',) def __str__(self): return "{} {}".format(self.user.first_name, self.user.last_name) class Parent(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) connections = models.ManyToManyField('self', blank=True, related_name='connections', db_column='connections',) def __str__(self): return "{} {}".format(self.user.first_name, self.user.last_name) As you can see a Child can only be a friend with another Child and a Parent … -
How do you save Textarea form data line by line using Django's CreateView?
I have a Model and would like to save data as a batch by using a textarea form in Django. The data shall be save line by line, which I am using splitlines(), each data is comma separated by split(","). I am operating the manipulation in the form_valid() function but I can't seem to get it right. Only the last line is saved successfully. forms.py class DataForm(forms.ModelForm): textarea_data = forms.CharField(widget=forms.Textarea) class Meta: model = Item exclude = ('part_number','length','height','weight') views.py class InsertData(generic.CreateView): model = Item form_class = DataForm def get_success_url(self): return reverse('item_list') def form_valid(self, form): self.object = form.save(commit=False) textarea_data = form.cleaned_data['textarea_data '] data_line_list = textarea_data.splitlines() for each_line in data_line_list: each_line_list = each_line.split(",") self.object.part_number = each_line_list[0] self.object.length = each_line_list[1] self.object.weight = each_line_list[2] self.object.height = each_line_list[3] self.object.save() May I know where did I go wrong. Should the manipulation be done some where else? -
Add a new table row with HTMX
I am trying to add a new table row with Htmx. By clicking the "Add A New Row" button, a new row should be added to the table. I can't get the row in the secondary_hx.html to be added to the table, instead it results as three forms next to each other without or . Any help would be appreciated. Thank you in advance. My code is like this: main.html: <table id="myTable"> <thead> <tr> <th>1</th> <th>2</th> <th>3</th> </tr> </thead> <tbody id="Tbody"> <tr> <td> <button class="add_button" type="submit" hx-post="/add_row/" hx-target="#Tbody" hx-swap="beforeend" > Add A New Row </button> </td> </tr> </tbody> </table> partials/secondary_hx.html: <tr hx-target="this" hx-swap="outerHTML"> <td>{{ form.a }}</td> <td>{{ form.b }}</td> <td>{{ form.c }}</td> </tr> -
Programming Error: No result found Previous SQL was not a query in Django
I'm sending post request to the SQL Stored Procedure where I couldn't able to pass in the SQL it showing as no result. Even I tried the same approach for another API and passing it to another Stored Procedure which worked well. Programming Error at /api/Data/StartShift/ No results. Previous SQL was not a query. views.py: Here "IP" is empty @api_view(['POST', 'GET']) def UserStartShift(request): if request.method == 'GET': users = tblUserShiftDetails.objects.all() serializer = UserShiftStartSerializers(users, many=True) return Response(serializer.data) elif request.method == 'POST': UserId = request.POST.get('UserId') Ip = request.POST.get('Ip') PortNumber = request.POST.get('PortNumber') print("UserId-->", UserId) print("Ip-->", Ip) print('Portnumber-->', PortNumber) cursor = connection.cursor() cursor.execute('EXEC [dbo].[Usp_StartShift] @UserId=%s, @IP=%s, @Port=%s', (UserId, Ip, PortNumber,)) result_set = cursor.fetchall() response_data=[] for row in result_set: response_data.append( { "UserId":row[0], "Ip":row[1], 'PortNumber':row[2] } ) return Response(response_data, status=status.HTTP_200_OK) Here, is the Stored Procedure which I tried to access from Django SP: GO SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO ALTER Procedure [dbo].[Usp_StartShift] @UserId varchar(100), @IP nvarchar(255), @Port nvarchar(255) as begin insert into tblUserShiftDetails(UserId, IPAddress, PortNumber) values(@userid,@ip,'CD_'+@port) end -
TypeError: setQty is not a function. Can someone fit it. i cant solve that problem. Thanks beforehand
`<Form.Select as="select" value={qty} onChange={(e) => setQty(e.target.value)}> {[...Array(product.countInStock).keys()].map((x) => ( {x + 1}))} ` Here is the code... -
how do i get email delivery report(IP addresses (if more devices received email) ,message opened time, received time) python django [duplicate]
I have sent email to a test email address using smtp.EmailBackend python Django, how do i get email delivery report(IP addresses (if more devices received email) ,message opened time, received time)