Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
- 
        
Docker compose executable file not found in $PATH": unknown
but I'm having a problem. Dockerfile: FROM python:3 ENV PYTHONUNBUFFERED 0 RUN mkdir /code WORKDIR /code COPY requirements.txt /code/ RUN pip install -r requirements.txt COPY . /code/ compose.yml : version: '3' services: db: image: postgres volumes: - ./docker/data:/var/lib/postgresql/data environment: - POSTGRES_DB=sampledb - POSTGRES_USER=sampleuser - POSTGRES_PASSWORD=samplesecret - POSTGRES_INITDB_ARGS=--encoding=UTF-8 django: build: . environment: - DJANGO_DEBUG=True - DJANGO_DB_HOST=db - DJANGO_DB_PORT=5432 - DJANGO_DB_NAME=sampledb - DJANGO_DB_USERNAME=sampleuser - DJANGO_DB_PASSWORD=samplesecret - DJANGO_SECRET_KEY=dev_secret_key ports: - "8000:8000" command: - python3 manage.py runserver volumes: - .:/code error : ERROR: for django Cannot start service django: OCI runtime create failed: container_linux.go:346: starting container process caused "exec: \"python3 manage.py runserver\": executable file not found in $PATH": unknown At first, I thought Python Manage was wrong. But i tried command ls , To my surprise, I succeeded. Then I tried the ls -al command, but it failed. I think the addition of a command to write space is causing a problem. how can i fix it ? - 
        
Django - how to run background script in loop
I have install django 3.0 and I want to add on website bot which will listen for events in background, manage server and users. Bot is dedicated for teamspeak application, using https://github.com/benediktschmitt/py-ts3/tree/v2 simple code: import time import ts3 with ts3.query.TS3ServerConnection("telnet://localhost:25639") as ts3conn: ts3conn.exec_("auth", apikey="AAAA-....-EEEE") # Register for events ts3conn.exec_("clientnotifyregister", event="any", schandlerid=0) while True: event = ts3conn.wait_for_event() print(event.parsed) How can I run this in django background, I have try add code with asyncio to manage.py but teamspeak bot connect to server and website doesn't work Shoud I use Celery, django-background-task or just add it as app, how to manage events received by bot in django? - 
        
Django 1.11 error while trying to post data
I'm new to Django 1.11 LTS and I'm trying to solve this error from a very long time. Here is my code where the error is occurring: model.py: name = models.CharField(db_column="name", db_index=True, max_length=128) description = models.TextField(db_column="description", null=True, blank=True) created = models.DateTimeField(db_column="created", auto_now_add=True, blank=True) updated = models.DateTimeField(db_column="updated", auto_now=True, null=True) active = models.BooleanField(db_column="active", default=True) customer = models.ForeignKey(Customer, db_column="customer_id") class Meta(object): db_table="customer_build" unique_together = ("name", "customer") def __unicode__(self): return u"%s [%s]" % (self.name, self.customer) def get(self,row,customer): build_name = row['build'] return self._default_manager.filter(name = build_name, customer_id = customer.id).first() def add(self,row): pass Views.py block: for row in others: rack_name = row['rack'] build = Build().get(row,customer) try: rack = Rack().get(row,customer) except Exception as E: msg = {'exception': str(E), 'where':'Non-server device portmap creation', 'doing_what': 'Rack with name {} does not exist in build {}'.format(rack_name,build.name), 'current_row': row, 'status': 417} log_it('An error occurred: {}'.format(msg)) return JsonResponse(msg, status = 417) Error traceback: File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py", line 249, in _legacy_get_response response = self._get_response(request) File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "./customers/views.py", line 2513, in create_rack add_rack_status = add_rack(customer, csv_file) File "./customers/views.py", line 1803, in add_rack build = Build().get(row,customer) File "./customers/models.py", … - 
        
ModuleNotFoundError: No module named 'C:\\Python\\Scripts'
I'm self-learning the Django and following the 'writing your first Django app' tutorial. I can start new projects. but when I ran ...\> py manage.py runserver to check the project. ModeleNotFoundError occurs. It says ModuleNotFoundError: No module named 'C:\Python\Scripts' I have no idea why this is happening. It used to work well until this happened recently. I would greatly appreciate any help. Thanks! - 
        
How to create a form for feeding multiple object entries based on a query in django?
I am currently working on my college management application, where staff can enter internal marks of students and the student can view their marks. What i am stuck with is, i want a populate a list of forms to fill the internal marks of each student and submit it at once. I tried modelformset with the code below and it work exactly as below formset = modelformset_factory(Internal, fields=('student','marks1','marks2','marks3')) if request.method == "POST": form=formset(request.POST) form.save() form = formset() return render(request, 'console/academics/internals.html',{'form':form}) For the model class Internal(models.Model): student = models.ForeignKey(User, on_delete=models.CASCADE) subject = models.ForeignKey(Subject, on_delete=models.CASCADE) marks1 = models.IntegerField(default=0) marks2 = models.IntegerField(default=0) marks3 = models.IntegerField(default=0) marks = models.IntegerField(default=100) marksob = models.IntegerField(default=0) def save(self): self.marksob = (self.marks1 + self.marks2 + self.marks3)/15 return super(Internal, self).save() I want the form to be rendered in html using <input> and not passing {{form}} in html. And moreover I want the form to display only the entries of particular students based on a query. Can anyone help me on this? - 
        
django.db.migrations.exceptions.NodeNotFoundError: Migration analytics.0002_auto_20140827_1705
I have created new app catalogue and while doing migrations getting django.db.migrations.exceptions.NodeNotFoundError: Migration analytics.0002_auto_20140827_1705 dependencies reference nonexistent parent node ('catalogue', '0001_initial') my Catalogue.models.py is from oscar.apps.catalogue.abstract_models import AbstractProductImage class ProductImage(AbstractProductImage): name = models.CharField(max_length=64) from oscar.apps.catalogue.models import * init.py default_app_config = 'catalogue.apps.CatalogueConfig' apps.py class CatalogueConfig(apps.CatalogueConfig): name = 'catalogue' label = 'catalogue' verbose_name = 'Catalogue' - 
        
Django one field and multiple Formset
In Django, I want to create a form that involves 2 Models - a Library model and a Book model. The Library can contain multiple Books. class Library(models.Model): name = models.CharField(max_length=100) class Book(models.Model): for_library = models.ForeignKey(Library, null=False, on_delete=models.PROTECT) title = models.CharField(max_length=200) author = models.CharField(max_length=100) Now, I have created a Library with id=1 and now want to create a form to tag multiple books to the library. How can I create the form such that the fields look like (including pre-filling the library ID): Library: <id=1 Library> Book1 Title: _____ Book1 Author: _____ Book2 Title: _____ Book2 Author: _____ The furthest I have gone is: BookFormset = inlineformset_factory(Library, Book, fields=['title', 'author'], form=CreateBookForm, extra=2, min_num=1, max_num=20, can_delete=True) But cannot continue and am not sure of integrating this with views.py. Any help on this? - 
        
Similar Image api drf
I am trying to make api for similar image based on keyword with drf search filter: models.py: class Image(models.Model): title = models.CharField(max_length = 100) image = models.ImageField(upload_to = 'home/tboss/Desktop/image' , default = 'home/tboss/Desktop/image/logo.png') category = models.ForeignKey('Category', null=True, blank=True, on_delete=models.CASCADE) image_keyword = models.TextField(max_length=1000) def __str__(self): return self.title views.py: class DynamicSearchFilter(filters.SearchFilter): def get_search_fields(self,view,request): return request.GET.getlist('search_fields',[]) class SimilarImageView(generics.ListCreateAPIView): authentication_classes = [] permission_classes = [] search_fields = ['image_keyword','id'] filter_backends = (DynamicSearchFilter,) queryset = Image.objects.all() serializer_class = ImageSearchSerializer what i want to achieve is that if i add keyword 'lake nature ocean' it should show all the images which contain keyword lake or nature or ocean but search filter show only image which keyword contain lakenatureocean keyword - 
        
Getting empty file from response and not able to save the file in django models class
My task is to create .xlsx file of late employees and return it to download at the same time I should create an object for every day with fields day and list(.xlsx). My implementation code is: ... file = excel_file.save('my_data.xlsx') day = Day.objects.create(days_date=timezone.now(), days_file=File(file)) response = HttpResponse(file, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',) response['Content-Disposition'] = 'attachment; filename={date}-attendance.xlsx'.format(date=timezone.now().strftime('%Y-%m-%d'),) return response There are no error messages but the file from response is empty, for the class object doesn't exist my models.py: class Day(models.Model): days_date = models.DateField() days_file = models.FileField(upload_to='day/') def __str__(self): return '{date}'.format(date=timezone.now().strftime('%Y-%m-%d')) I am using django==2.2 and I am using Linux ubuntu OS - 
        
On looping through django allauth social login profile pictures
I've been trying to loop through the social login account photos of the users and myself on the app that I'm doing. Currently, I have a different model for the contributors on the app that is shown on the homepage and on a separate page. The models of my pages app is class Volunteers(models.Model): name = models.CharField(max_length=100) image = models.ImageField(upload_to="volunteers/") def __str__(self): return self.name class Meta: verbose_name = "volunteer" verbose_name_plural = "volunteers" The profile page has {% if object == request.user %} ... <img class="rounded-circle account-img center-align" src="{{ user.socialaccount_set.all.0.get_avatar_url }}"> ... {% endif %} Since cookiecutter-django has a default users model, I imported the views of the model to my pages app to try and see if it will show on the home page. The default cookiecutter-django model for the users is class User(AbstractUser): # First Name and Last Name do not cover name patterns # around the globe. name = CharField(_("Name of User"), blank=True, max_length=255) def get_absolute_url(self): return reverse("users:detail", kwargs={"username": self.username}) The view on the pages app is from pages.users.models import User def home(request): ... users = User.objects.all() ... context = {"user": user } return render(request, pages/home.html, context) The for loop on the template is {% for u in … - 
        
How to Append/Include
I have the following line of code in my index.html {% csrf_token %} <div class="form-group"> <input type="text" id="form_name" class="form-control" name="name" required="required" placeholder="Your Full Name" value='{% if submitbutton == "Submit" %} {{ name }} {% endif %}'> </div> <div class="form-group"> <input type="email" id="form_email" class="form-control" name="email" required="required" placeholder="abc@email.com" value='{% if submitbutton == "Submit" %} {{ email }} {% endif %}'> </div> <div class="form-group"> <textarea name="message" id="form_message" rows="5" class="form-control" required="required" placeholder="Add your message." value='{% if submitbutton == "Submit" %} {{ message }} {% endif %}'></textarea> </div> <input type="submit" class="btn btn-outline-light btn-sm" value="Send Message" name="Submit"> </form> and for views.py def index(request): if request.method == 'POST': name = request.POST['name'] email = request.POST['email'] message = request.POST['message'] try: send_mail( name, message, email, ['cmadiam@ruthlymtspmuandaesthetics.com'], fail_silently=False) except BadHeaderError: return HttpResponse('Invalid header found.') return HttpResponse('Success! Thank you for your message.') return render(request, "index.html", {}) Now, I want add New Inquiry from: before the name(subject) when the email is received. How can I do that. Is that possible? Thank you in advance! - 
        
Move div to next line
In my django templates some fields are created using multiple divs but all the columns are coming in a single row HTML <div class="row product-form-row"> <form method="post" id="Outwarddocketform" data-kit-url="{% url 'client:ajax_load_kit_c' %}" data-product-url="{% url 'client:ajax_load_product_c' %}" onkeyup="add()" class="col-md-10 proct-form" novalidate> {% csrf_token %} <div class="form-group col-md-3 mb-0"> {{ form.transaction_date|as_crispy_field }} </div> <div class="form-group col-md-3 mb-0"> {{ form.dispatch_date|as_crispy_field }} </div> <div class="form-group col-md-3 mb-0"> {{ form.sending_location|as_crispy_field }} </div> <div class="form-group col-md-3 mb-0"> {{ form.flow|as_crispy_field }} </div> <div class="form-group col-md-3 mb-0"> {{ form.kit|as_crispy_field }} </div> <div class="form-group col-md-3 mb-0"> {{ form.transporter_name|as_crispy_field }} </div> <div class="form-group col-md-3 mb-0"> {{ form.vehicle_details|as_crispy_field }} </div> <div class="form-group col-md-3 mb-0"> {{ form.invoice_number|as_crispy_field }} </div> <div class="form-group col-md-3 mb-0"> {{ form.remarks|as_crispy_field }} </div> <div class="form-group col-md-3 mb-0"> {{ form.created_for|as_crispy_field }} </div> <div class="form-group col-md-3 mb-0"> {{ form.product1|as_crispy_field }} </div> <div class="form-group col-md-3 mb-0"> {{ form.product1_quantity|as_crispy_field }} </div> <div id="products-table" class="col-md-12 col-sm-8 col-12 product-table-ajax"></div> <div class="form-group col-md-12 mb-0"> <button type="submit" class="btn btn-success">Save</button> <a href="{% url 'client:inward_table' %}" class="btn btn-outline-secondary" role="button">Nevermind</a> </div> </form> This creates a page like this: I want to move product1 or product1 quantity to the next line. How can I do that ? Basically what i want to do is shown below: - 
        
Cannot Install Pillow with Python 3.6
I downloaded the Pillow package for my offline computer and tried installing it locally with this command: pip install Pillow-6.2.1.tar.gz But it gives the following error: The headers or library files could not be found for zlib Then I tried installing it with Python 3.7, 3.8 and it gives the same error. - 
        
Can’t sort elements to categories
Im writing an online store, which is why I need the list of goods to be sorted in categories Eventually, the right path does generate, but there is no content on the page. Where might I made a mistake? models.py class Category(models.Model): class Meta(): db_table = 'category' ordering = ['name'] verbose_name_plural = 'Категории' name = models.CharField(max_length=150, unique=True, verbose_name='Категория') slug = models.SlugField(verbose_name='Транслит', null=True) def __str__(self): return self.name def __unicode__(self): return self.name class Merchandise(models.Model): title = models.CharField(max_length=50,verbose_name='Имя товара') image = models.ImageField(upload_to='user_images',default='default.jpg',verbose_name='Изображение') price = models.CharField(max_length=15,verbose_name='Цена') text = models.TextField(max_length=150,verbose_name='Описание') category = models.ForeignKey(Category,on_delete=models.CASCADE,verbose_name='Категория') views.py There was a pagination func primarily def category(reguest, slug): category = Category.objects.get(slug=slug) merch = Merchandise.objects.filter(category=category) return render(reguest, 'mainpage/category.html', { 'category': category, 'merch': merch}) def mainpage(request): data = { 'goods': Merchandise.objects.all(), 'slides': Slide.objects.all(), 'categories': Category.objects.all(), 'title': 'CyberGear' } return render(request,'mainpage/home.html',data) category.html {% extends 'mainpage/main.html' %} {% for mer in merch %} <div class="col-lg-4 col-md-6 mb-4"> <div class="card h-100"> <a href="#"><img class="card-img-top" src="{{ mer.image.url }}" alt=""></a> <div class="card-body"> <h4 class="card-title"> <a href="#">{{ mer.title }}</a> </h4> <h5>{{ mer.price }}</h5> <p class="card-text">{{ mer.text }}</p> </div> <div class="card-footer"> <small class="text-muted">&#9733; &#9733; &#9733; &#9733; &#9734;</small> </div> </div> </div> {% endfor %} and urls.py url(r'^category/(<slug>)/$',views.category,name'category'), - 
        
I don't know where i mess up with my code in my view
from django.http import HttpResponse from django.shortcuts import render,redirect, get_list_or_404, get_object_or_404 from .models import Users from .forms import UsersForm from django.contrib.auth import authenticate # Create your views here. def login(request): #Username = request.POST.get(‘username’) #password = request.POST.get(‘password’) form = UsersForm(request.POST or None) if form.is_valid(): form.save() form = UsersForm() return redirect('/product/itemlist') user = authenticate(username='username', password='password') if user is not None: # redirect to homepage return redirect('/product/itemlist') else: # display login again return render(request, 'users/login.html', {'form':form}) This is my view page when i runserver it takes me to login page then the problem start when i enter my credintials and try to log in Page not found (404) Request Method: POST Request URL: http://127.0.0.1:8000/users/login/index.html Using the URLconf defined in mazwefuneral.urls, Django tried these URL patterns, in this order: admin/ product/ users/ login/ [name='login'] main/ accounts/ The current path, users/login/index.html, didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. This is the error am getting - 
        
Django ElasticSearch DSL DRF aggregations
What is the correct approach to adding aggregations to Django ElasticSearch DSL DRF? The codebase contains some empty filter backends https://github.com/barseghyanartur/django-elasticsearch-dsl-drf/tree/a2be5842e36a102ad66988f5c74dec984c31c89b/src/django_elasticsearch_dsl_drf/filter_backends/aggregations Should I create a custom backend or is there a way to add them directly to my viewset? In particular, I want to calculate the sum of an IntegerField across all results in a particular facet. - 
        
Merge duplicate dictionaries in a list
I have this list of dictionary and I am trying to merge the duplicate dictionaries in the list below is the sample of the list of duplicate dictionary [ { "userName": "Kevin", "status": "Disabled", "notificationType": "Sms and Email", "escalationLevel": "High", "dateCreated": "2019-11-08T12:19:05.373Z" }, { "userName": "Kevin", "status": "Active", "notificationType": "Sms and Email", "escalationLevel": "Low", "dateCreated": "2019-11-08T12:19:05.554Z" }, { "userName": "Kevin", "status": "Active", "notificationType": "Sms", "escalationLevel": "Medium", "dateCreated": "2019-11-08T12:19:05.719Z" }, { "userName": "Ercy", "status": "Active", "notificationType": "Sms", "escalationLevel": "Low", "dateCreated": "2019-11-11T11:43:24.529Z" }, { "userName": "Ercy", "status": "Active", "notificationType": "Email", "escalationLevel": "Medium", "dateCreated": "2019-11-11T11:43:24.674Z" }, { "userName": "Samuel", "status": "Active", "notificationType": "Sms", "escalationLevel": "Low", "dateCreated": "2019-12-04T11:10:09.307Z" }, { "userName": "Samuel", "status": "Active", "notificationType": "Sms", "escalationLevel": "High", "dateCreated": "2019-12-05T09:12:16.778Z" } ] I want to merge the the duplicate dictionaries keeping the value of duplicate keys and have something like this [ { "userName": "Kevin", "status": ["Disabled","Active", "Active"] "notificationType": ["Sms and Email", "Sms and Email", "Sms"] "escalationLevel": ["High", "Low", "Medium"] "dateCreated": "2019-11-08T12:19:05.373Z" }, { "userName": "Kevin", "status": "Active", "notificationType": "Sms and Email", "escalationLevel": "Low", "dateCreated": "2019-11-08T12:19:05.554Z" }, { "userName": "Samuel", "status": ["Active", "Active"], "notificationType": ["Sms", "Sms"], "escalationLevel": ["Low", "High"], "dateCreated": "2019-12-04T11:10:09.307Z" }, ] anyone with a simpler way of achieving this please share your … - 
        
CrashLoopBackOff Error when deploying Django app on GKE (Kubernetes)
Folks, How do I resolve this CrashLoopBackOff? I looked at many docs and tried debugging but unsure what is causing this? The app runs perfectly in local mode, it even deploys smoothly into appengine standard, but GKE nope. Any pointers to debug this further most appreciated. $ kubectl get pods NAME READY STATUS RESTARTS AGE library-7699b84747-9skst 1/2 CrashLoopBackOff 28 121m $ kubectl describe pods library-7699b84747-9skst Name: library-7699b84747-9skst Namespace: default Priority: 0 PriorityClassName: <none> Node: gke-library-default-pool-35b5943a-ps5v/10.160.0.13 Start Time: Fri, 06 Dec 2019 09:34:11 +0530 Labels: app=library pod-template-hash=7699b84747 Annotations: kubernetes.io/limit-ranger: LimitRanger plugin set: cpu request for container library-app; cpu request for container cloudsql-proxy Status: Running IP: 10.16.0.10 Controlled By: ReplicaSet/library-7699b84747 Containers: library-app: Container ID: docker://e7d8aac3dff318de34f750c3f1856cd754aa96a7203772de748b3e397441a609 Image: gcr.io/library-259506/library Image ID: docker-pullable://gcr.io/library-259506/library@sha256:07f54e055621ab6ddcbb49666984501cf98c95133bcf7405ca076322fb0e4108 Port: 8080/TCP Host Port: 0/TCP State: Waiting Reason: CrashLoopBackOff Last State: Terminated Reason: Completed Exit Code: 0 Started: Fri, 06 Dec 2019 09:35:07 +0530 Finished: Fri, 06 Dec 2019 09:35:07 +0530 Ready: False Restart Count: 2 Requests: cpu: 100m Environment: DATABASE_USER: <set to the key 'username' in secret 'cloudsql'> Optional: false DATABASE_PASSWORD: <set to the key 'password' in secret 'cloudsql'> Optional: false Mounts: /var/run/secrets/kubernetes.io/serviceaccount from default-token-kj497 (ro) cloudsql-proxy: Container ID: docker://352284231e7f02011dd1ab6999bf9a283b334590435278442e9a04d4d0684405 Image: gcr.io/cloudsql-docker/gce-proxy:1.16 Image ID: docker-pullable://gcr.io/cloudsql-docker/gce-proxy@sha256:7d302c849bebee8a3fc90a2705c02409c44c91c813991d6e8072f092769645cf Port: <none> Host Port: <none> Command: … - 
        
How to perform split() function inside django template tag?
I need to perform split() function inside django template tag. I tried to do this, but its not working {% for m in us.member %} {% with mv=((m.split(','))[0].split('='))[1] %} <h3 class="media-title"> {{ mv }} </h3> {% endwith %} {% endfor %} Here value of m return a string value 'cn=RND3,ou=Production_test,dc=iss,dc=rndtest,dc=local' Expected output is RND3 - 
        
Forbidden (403) CSRF verification failed. Request aborted. login page not working
i was stuck while creating login page and getting error like "Forbidden (403) CSRF verification failed. Request aborted." please help me out of this Views.py from django.shortcuts import render, redirect from django.contrib.auth.forms import UserCreationForm from users.forms import UserRegisterForm # Create your views here. def register(request): if request.method=="POST": form=UserRegisterForm(request.POST) if form.is_valid(): form.save() username=form.cleaned_data.get('username') messages.success(request, f"Account created for {username}") return redirect('app1-home') else: form=UserRegisterForm() return render(request, "users/register.html",{"form":form}) Urls.py from django.contrib import admin from django.urls import include, path from users import views as user_views from django.contrib.auth import views as auth_views from app1 import views urlpatterns = [ path('admin/', admin.site.urls), path('', include('app1.urls')), path('register/', user_views.register, name='register'), path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'), name='logout'), Forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class UserRegisterForm(UserCreationForm): email=forms.EmailField() class Meta: model=User fields=["username", "email", "password1", "password2"] **login.html** {% extends "app1/base.html" %} {% load crispy_forms_tags %} {% load staticfiles %} {% block content %} <div class="content-section"> <form method="POST" > {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Login</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Login </button> </div> </form> <div class="border-top pt-3"> <small class="text-muted"> Sign Up Here? <a class="ml-2" href="{%url "register" %}">Sign Up</a> </small> </div> </div> {% endblock content %} In setings.py file, I used to write … - 
        
Saving a vector in Django Sqlite3
I am trying to store a vector using Django in Sqlite3 using the following Model Field vector = models.CharField(validators=[int_list_validator(sep=' ', allow_negative=True)], max_length=256) and the corresponding Serializer Field vector = serializers.CharField() Before saving the instance the vector has a shape of (1,128) and on retrieval from database it isn't of required shape. Is it the correct way of saving a vector or an alternate solution exists? - 
        
django-rest-auth "Unable to log in with provided credentials."
If I create a user in django admin and login with that user's correct credentials I fail to have access I do not know why that is. But one more thing, I create user in postman and login it works fine and in django admin it does not work. I think the problem with that, it may be hashing the password because if I type password as user12345 in admin it appear as user12345 but if I do this process in postman it hashes the password like pbkdf2_sha256$150000$W4T5vHbtbI3o$bV+CLOohqcmd0Gi70jcEyRTbOyp45LU5PhBwWHbdCnU= for hashing the password I have this class UserManager(BaseUserManager): use_in_migrations = True def _create_user(self, email, password, **extra_fields): user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(email, password, **extra_fields) set_password should hashes passwords and I think it may be problem for not logging in my opinion. Any idea please for this issue? Thanks - 
        
data i had posted below and i want to upload it to django model and want to convert the image_link to our local host link
{ "news_by": "Entertainment ", "news_title": "'Sarileru Neekevvaru' teaser: Mahesh Babu is visually pleasing, but Prakash Raj takes the cake again", "news_description": "Mahesh Babu is a pleasure to the eye, much like always, and 'Sarileru Neekevvaru' teaser is high on style quotient too, but Prakash Raj will win you over once again", "image_link":"https://cdn.dnaindia.com/sites/default/files/styles/third/public/2019/11/22/882305-sarileru-neekevvaru-teaser.jpg" } - 
        
Django Query first ForeignKey of an object in a query
Trying to run a query on ordered store instances by distance, and then query the first Foreignkey Coupon of each store Instance. I am trying to show a coupon from each nearby store. models.py ... class Store(models.Model): location = models.PointField(srid=4326, null=True, blank=True) class Coupon(models.Model): store = models.ForeignKey(Store, on_delete=models.CASCADE, null=True, related_name='store') views.py class homeView(View): def get(self, *args, **kwargs): store_nearby = Store.objects.annotate(distance = Distance("location", user_location)).order_by("distance") context = { 'store_list': store_nearby, # 'offer': offer, } return render(self.request, 'mysite/home_page.html', context) home_page.html {% for object in store_list %} {% for coupon in object.offer.first %} // This doesnt work {{ coupon.title }} {% endfor %} {% endfor %} - 
        
switch user in django
I have django server installed under ownership of user say 'X'. Now I want to switch to user 'Y' and execute some scripts. Currently for changing user I am using sudo su "Y" -c "commands to execute" . I have added user "X" in sudoers file so that now it does not ask for a password. Is there any way to do it without sudo.I have already tried it by editing /etc/pam.d/su file so that it does not ask for password when user X runs "su Y" without sudo. Is there any other way in which this can be achieved?