Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
The client noticed that the server is not a supported distribution of Elasticsearch?
I am using elasticsearch (version 7.10.2 ) with python (django version 3.0) but I am getting this error The client noticed that the server is not a supported distribution of Elasticsearch While searching on the internet I found that downgrading the version of elastic search from 7.14 is was working for a lot of people as version 7.14 was updating a few internal scripts. But in my case the version is already lower than 7.14. I used curl -X GET "HTTP://localhost:9200" to check its version. Also, other such issues included NODE, Angular and other frameworks which were not relevant to my case. How can I solve this issue? If I need to downgrade then which version am I supposed to downgrade? -
TypeError: Field 'id' expected a number but got (<Group: customer>, True) DJANGO ERROR
I am learning how to use Django through a small project ... I am trying to connect my project to a Postgreslq database and I get this type of error models.py from django.db import models from django.db.models.deletion import SET_NULL from django.contrib.auth.models import User class Customer(models.Model): user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=200, null=True) phone = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) profile_pic = models.ImageField(default='profile1.png',null=True, blank=True) date_created = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return self.name class Tag(models.Model): name = models.CharField(max_length=200, null=True) def __str__(self): return self.name class Product(models.Model): CATEGORY = ( ('Indoor', 'Indoor'), ('Out Door', 'Out Door'), ) name = models.CharField(max_length=200, null=True) prince = models.FloatField(null=True) category = models.CharField(max_length=200, null=True, choices=CATEGORY) description = models.CharField(max_length=200, null=True, blank=True) date_created = models.DateTimeField(auto_now_add=True, null=True) tags = models.ManyToManyField(Tag) def __str__(self): return self.name class Order(models.Model): STATUS = ( ('Pending', 'Pending'), ('Out for delivery', 'Out for delivery'), ('Delivered', 'Delivered'), ) customer = models.ForeignKey(Customer, null=True, on_delete=SET_NULL) product = models.ForeignKey(Product, null=True, on_delete=SET_NULL) status = models.CharField(max_length=200, null=True, choices=STATUS) date_created = models.DateTimeField(auto_now_add=True, null=True) note = models.CharField(max_length=1000, null=True) def __str__(self): return self.product.name signals.py from django.db.models.signals import post_save from django.contrib.auth.models import User, Group from .models import Customer def customer_profile(sender, instance, created, **kwagrs): if created: group = Group.objects.get_or_create(name='customer') instance.groups.add(group) Customer.objects.create( user = instance, name = instance.username … -
(Django) HTML: Table columns are displaying vertically
I'm currently trying to display a bunch of Information of a model inside the template. Therefore I've been creating a table to show all of the information horizontally for every "previous game" in the database: <table style="height: 100%"> {% for previous_game in previous_games %} <tr> <th> {{ previous_game.name }}</th> </tr> <tr> <td> <img id="Videogame_Picture" src="{{ previous_game.image.url }}"> </td> </tr> <tr> <td> {{ previous_game.date }} </td> </tr> <tr> <td> {% load static %} <img id= "Result_Icon" src="{% static previous_game.min_req %} "></td> </tr> <tr> <td> {% load static %} <img id= "Result_Icon" src="{% static previous_game.rec_req %} " ></td> </tr> <tr> <td> PC Rig {{ previous_game.config }}</td> </tr> {% endfor %} </table> But currently all the Table columns are displaying vertically underneath instead of horizontally next to each previous game and I can't figure out why. Can you help me out here? Thanks in Advance! -
How To Create UpdateView CBV with relationship
I'm tired to find the best way for UpdateView with CBV. Im test some tutorial but always got error. Maybe someone can help me. I have 2 models. Account and UserProfile. First. I Register Account User Like This, And Extending the user in UserProfile Model. Thats Success. UserProfile models My Question is, how to Update The data ini this field ? authentication/models.py class Account(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) full_name = models.CharField(max_length=150) create_account = models.DateTimeField(default=timezone.now) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_reviewer = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) objects = CustomAccountManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['full_name'] def __str__(self): return self.email dashboard/models.py class UserProfil(models.Model): JENIS_KELAMIN_CHOICE = ( ('Pria', 'Pria'), ('Wanita', 'Wanita' ), ) #Profil user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE,) gelar_depan = models.CharField(max_length=11, blank=True, default="") gelar_belakang = models.CharField(max_length=20, blank=True, default="") nik = models.CharField(max_length=11, blank=True, unique=True, default="") nidn = models.CharField(max_length=11, blank=True, unique=True, default="") email_alternatif = models.EmailField(_('email address'), blank=True, default="") jenis_kelamin = models.CharField(max_length=6, blank=True, default="", choices =JENIS_KELAMIN_CHOICE) tempat_lahir = models.CharField(max_length=30, blank=True, unique=True, default="") tanggal_lahir = models.DateField(null=True, blank=True) nomor_handphone = models.CharField(max_length=13, blank=True) alamat = models.CharField(max_length=255, blank=True, default="") dashboard/forms.py class UserProfil(models.Model): JENIS_KELAMIN_CHOICE = ( ('Pria', 'Pria'), ('Wanita', 'Wanita' ), ) #Profil user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE,) gelar_depan = models.CharField(max_length=11, blank=True, default="") gelar_belakang = models.CharField(max_length=20, blank=True, default="") nik … -
FileField in nested serializer is holding a path, when updated throws error "The submitted data was not a file. Check the encoding type on the form."
I have created a nested serialiser and custome create and update methods in it. While POST(Create) methos i am not getting any error, but while Updating i am getting error "The submitted data was not a file. Check the encoding type on the form.". Model: class SmsModelMaster(models.Model): SRNumber = models.CharField('Request Number', max_length=50, blank=True, unique=True) SRState = models.CharField(max_length=100, choices=STATUS_CHOICES, default='Requested', blank=False, null=True, unique=False) PreviousSRState = models.CharField(max_length=100, blank=True, null=False) SRCategory_SMS = models.ForeignKey(ServiceBucket, related_name='SRCategory_SMS', blank=True, on_delete=models.CASCADE) SRName_SMS = models.ForeignKey(ServiceBucket, related_name='SRName_SMS', blank=True, on_delete=models.CASCADE) RequestType = models.CharField(max_length=100, blank=True, null=False) RequesterName = models.CharField(max_length=100, blank=True, null=False) RequestedOnBehalfOf = models.CharField(max_length=100, null=True) SMETSVersion = models.CharField(max_length=100, blank=True, null=True) TPName = models.CharField(max_length=150, null=True) Expected_Completion_Time = models.DateTimeField(default=timezone.now, blank=True, null=True) Request_Time = models.DateTimeField(default=timezone.now, null=True, blank=True) CompletionDate = models.DateField(default=timezone.now, null=True, blank=True) MetersetUseEndDate = models.DateField(default=timezone.now, blank=True, null=True) ActivitySummary = models.CharField(max_length=3000, blank=True, null=True) DocumentUpload = models.FileField(upload_to='Support_Request/SMS_Model/', default=None, null=True, blank=True) Assigned_To = models.CharField(max_length=100,blank=True, null=True) def __str__(self): return self.SRNumber class Meta: verbose_name_plural = "SMS Administrator" Serializer: class sms_adminserializer(serializers.ModelSerializer): commentdata = sms_commentserializer(many=True, required=False) metersetdata = sms_metersetserializer(many=True, required=False) devicedata = sms_deviceserializer(many=True, required=False) Expected_Completion_Time = serializers.DateTimeField(required=False) class Meta: model = SmsModelMaster fields = ('SRNumber', 'SRState', 'PreviousSRState', 'SRCategory_SMS', 'SRName_SMS', 'RequestType', 'RequesterName', 'RequestedOnBehalfOf','SMETSVersion', 'TPName', 'Expected_Completion_Time, 'Request_Time','CompletionDate', 'MetersetUseEndDate', 'ActivitySummary', 'DocumentUpload', 'commentdata', 'metersetdata', 'devicedata','Assigned_To') read_only_fields = ('Request_Time', ) def create(self, validated_data): commentdata = validated_data.pop('commentdata') metersetdata … -
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 …