Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to make a ajax call with csrf and body?
I have build a login api with django. I used postman to check its function. The request body is {"user":{"email":"surendersingh1995nov@gmail.com", "password":"Singo*1995"}} The request url is POST 127.0.0.1:8000/api/users/login/ The header is content-type application/json The response is { "user": { "email": "surendersingh1995nov@gmail.com", "username": "ArjunSingh", "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6MSwiZXhwIjoxNjAwMjM3MjcxfQ.OBF3tg2YmXC4hl4D7eTfx38rrXX9RKGwIQBqKorwqOw" } } This is the way I would like to get the response in ajax call.The API works good in Postman. But if I try to make the same request through AJAX I get 400 Bad request error. The AJAX call I made $.ajax({ url: "/api/users/login/?", method: "POST", contentType: "application/json", data:{"user":{"email":"surendersingh1995nov@gmail.com", "password":"Singo*1995"}}, success: function (data) { console.log(data) }, error: function (data) { console.log("error") console.log(data.statusText) console.log(data.status) } }) -
ReplyError: ERR unknown command 'EVAL'
n [1]: import channels.layers In [2]: channel_layer = channels.layers.get_channel_layer() In [3]: from asgiref.sync import async_to_sync In [4]: async_to_sync(channel_layer.send)('test_channel', {'type': 'hello'}) In [5]: async_to_sync(channel_layer.receive)('test_channel') ReplyError Traceback (most recent call last) in ----> 1 async_to_sync(channel_layer.receive)('test_channel') ~\anaconda3\lib\site-packages\asgiref\sync.py in call(self, *args, **kwargs) 137 138 # Wait for results from the future. --> 139 return call_result.result() 140 141 def _run_event_loop(self, loop, coro): ~\anaconda3\lib\concurrent\futures_base.py in result(self, timeout) 426 raise CancelledError() 427 elif self._state == FINISHED: --> 428 return self.__get_result() 429 430 self._condition.wait(timeout) ~\anaconda3\lib\concurrent\futures_base.py in __get_result(self) 382 def __get_result(self): 383 if self._exception: --> 384 raise self._exception 385 else: 386 return self._result ~\anaconda3\lib\site-packages\asgiref\sync.py in main_wrap(self, args, kwargs, call_result, source_thread, exc_info, context) 202 result = await self.awaitable(*args, **kwargs) 203 else: --> 204 result = await self.awaitable(*args, **kwargs) 205 except Exception as e: 206 call_result.set_exception(e) ~\anaconda3\lib\site-packages\channels_redis\core.py in receive(self, channel) 483 else: 484 # Do a plain direct receive --> 485 return (await self.receive_single(channel))[1] 486 487 async def receive_single(self, channel): ~\anaconda3\lib\site-packages\channels_redis\core.py in receive_single(self, channel) 506 # be in the backup queue. 507 content = await self._brpop_with_clean( --> 508 index, channel_key, timeout=self.brpop_timeout 509 ) 510 ~\anaconda3\lib\site-packages\channels_redis\core.py in _brpop_with_clean(self, index, channel, timeout) 341 # Cancellation here doesn't matter, we're not doing anything destructive 342 # and the script executes atomically... --> 343 await … -
Django deployment on heroku throws django.db.utils.OperationalError: no such table: auth_user
I'm deploying on a free Heroku dyno. This is my Procfile: release: python manage.py migrate web: gunicorn app.wsgi --log-file - I've already made migrations locally and I'm deploying through Github. I figured out that the line release: python manage.py migrate indeed runs the command on the dyno but doesn't create tables(I've confirmed this by getting into the command line of my Dyno using heroku run bash and then check if there are any tables in the db.sqlite3 file. There were none. I rerun the migrate command using the Heroku bash and then the tables were populated in the db.sqlite3 file. I exited the console, reload my app and tried to login again but it threw the same error, yet again: django.db.utils.OperationalError: no such table: auth_user. I logged into Heroku bash again and saw that the tables that I've created in the db.sqlite3 file are not there anymore. -
Why am I getting integer when is use `post.Category` in shell?
here is my models.py from django.db import models class Post(models.Model): Category = ( ("", ("-----CHOOSE-----")), ("Space", ("Space")), ("Calculus", ("Calculus")), ("Technology", ("Technology")), ("Cosmology", ("Cosmology")) ) Title = models.CharField(max_length=64) Description = models.TextField() Author = models.CharField(max_length=30) Date = models.DateTimeField() Category = models.TextField(choices = Category, default="") def __str__(self): return self.Title This what I am doing in shell post = Post.objects.all(id = 1) print(post.Category) Please help me where I am getting wrong. -
Django filter with inner query?
Based on the following models: class OpportunityDetail(models.Model): ContactDetail = models.ForeignKey(ContactDetail, on_delete=models.CASCADE, related_name='OpportunityContactDetails') Stage = models.CharField(max_length=20, unique = False, choices=stages) class ProductDetail(models.Model): Name = models.CharField(max_length=30, unique = False) Amount = models.DecimalField(max_digits=12, decimal_places=2, unique = False) class ProductItemDetail(models.Model): ProductDetail = models.ForeignKey(ProductDetail, on_delete=models.CASCADE, related_name='ProductDetails') OpportunityDetail = models.ForeignKey(OpportunityDetail, on_delete=models.CASCADE, related_name='OpportunityDetails') ChildrenDetail = models.ForeignKey(ChildrenDetail, on_delete=models.CASCADE, related_name='ChildrenProduct') When I query the opportunity I would normally do something like this: oppLST = OpportunityDetail.objects.filter(ContactDetail = myCon.id) However, I am wondering how can I get an inner query of the product items? in sql i would do something like: SELECT Id, Stage, (SELECT Id, ProductDetail, ProductDetail.Name FROM ProductItemDetail) FROM OpportunityDetail WHERE ContactDetail = myCon.id I am wondering if it is possible to do something like this in django -
Url mapping to views in django 1.11
I am writing a code to map a url '/products/new' to its view function 'new'. Instead of getting an HttpResponse from 'new' I get HttpResponse of 'index' function which is also inside views.py My views.py code inside products.py is -- from __future__ import unicode_literals from django.shortcuts import render from django.http import HttpResponse def index(request): return HttpResponse('This is home page') def new(request): return HttpResponse('New Products') My urls.py code inside products.py is -- from django.conf.urls import url from . import views urlpatterns=[ url(r'^', views.index), url(r'^new', views.new) ] My urls.py file inside the project file is -- from django.conf.urls import url,include from django.contrib import admin urlpatterns=[ url(r'^admin/', admin.site.urls), url(r'^products/', include('products.urls')) ] Now when i access 127.0.0.1:8000/products I get desired result that is "This is the home page" But when i access 127.0.0.1:8000/products/new or even 127.0.0.1:8000/products/new/xxx/xxx any random text after /products i get the same result that is "this is home page" I don't know what is happening. Please help. -
nested objects in Django rest framework
I want to design solution for ordering items. I have endpoint that create orders BUT I need to to have items object in the order. let me show you the code class ItemModel(models.Model): name = models.CharField(max_length=50) price = models.FloatField() discretion = models.CharField(max_length=500) available = models.BooleanField(default=True) class OrderModel(models.Model): phone = models.CharField(max_length=20) delevary_time = models.DateTimeField() class CartModel(models.Model): order = models.ForeignKey(OrderModel, on_delete=models.CASCADE, related_name='order_m') item = models.ForeignKey(ItemModel, on_delete=models.CASCADE, related_name='item_m') I need endpoint that create order to me. her what I did class CartSerializer(serializers.ModelSerializer): class Meta: model = CartModel exclude = ['order',] depth = 2 class OrderSerializer(serializers.ModelSerializer): cart = serializers.SerializerMethodField() class Meta: model = OrderModel fields = ['phone', 'state', 'delevary_time', 'cart'] def get_cart(self, obj): cart = CartModel.objects.filter(order__id=obj.id) serializer = CartSerializer(cart, many=True) return serializer.data this is the endpoint router.register('order', OrderViewSet, 'api-order') { "phone": 124997988698, "delevary_time": "2020-07-17T19:34:00", "cart": [ { "item": 1 }, { "item": 2 } ] } when I post the json it don't save the cart it only save the oder phone and delevary_time. How I can save the cart at the same time -
Is there any way to change the default path which Django will use to locate files in generic class based views?
So I am making a Blog website. I am using Class Bases Views to give the users an ability to add posts, view posts, update and delete them. So in my views.py, I have this: from django.shortcuts import render, HttpResponse from .models import Post from django.views.generic import ListView, DetailView # Create your views here. def home(request): context = { 'posts': Post.objects.all() } return render(request, 'index.html', context) class PostListView(ListView): model = Post template_name = 'index.html' context_object_name = 'posts' ordering = ['-date_posted'] class PostDetailView(DetailView): model = Post My urls.py: from django.urls import path from . import views from .views import PostListView, PostDetailView urlpatterns = [ path('', PostListView.as_view(), name="home"), path('post/<int:pk>/', PostDetailView.as_view(), name="post-detail"), ] The problem is in the PostDetailView. When I create a file called post_detail.html in my templates folder, so that when user goes to a specific post in the website, we redirect them to the post_detail.html. But the site says that post_detail.html template cannot be found. I have learnt that the the generic class based views will be looking for a template with this naming convention, <app>/<module>_<viewtype>.html. So it's going to be looking in the directory of the app name, which, in my case, is going to be "blog_app" then a … -
How to use a mutable variable who's value is retained over each request in view.py in django?
I need a variable which can be changed and its value is retained even after request is completed I have tried using Global variable, session variable is there something else which im missing I ma not using any models so im not storing it in DB Eg value=False def ans(request): if(value==False): value=True perform_task1() else: perform_task2() but everytime the value is false and only task1 is executed TIA -
How to return additional information outside a list , in a list serializer
I have the following serializer : class SalesProjectListSerializer(serializers.ModelSerializer): permissions = serializers.SerializerMethodField('get_custompermissions',read_only=True) class Meta: model = SalesProject fields = ['sales_project_id', 'sales_project_name', 'sales_project_est_rev', 'project_status','permissions'] depth = 2 def get_custompermissions(self, obj): permission_list = ['add_salesproject'] user_perms = User.get_user_permissions(self.context['request'].user) return { permission: True if permission in user_perms else False for permission in permission_list } This serializer is used to serialize the data thats used to render the project listing page. The serialized data would give me something like : projects = [{sales_project_id : 1 , sales_project_name = 'test , ... ,permissions: [...]}] However instead what i wish to return is somthing like this : projects = {projects:[{sales_project_id : 1 , sales_project_name = 'test , ... }] ,permissions: [...]} -
What is the recommended way of passing parameters in Django request when its required in each request?
I have to pass two parameters in every Django Request to use them in a decorator which is being called on every view of my Django application. Currently, I am using the following way to pass parameters. class RoleTaskForm(forms.Form): task_id = forms.CharField(max_length=256, required=False) action = forms.CharField(max_length=10, required=False) Using followig form in html documents <form name="role_task_form" method="get"> <input type="hidden" name="task_id"> <input type="hidden" name="operation"> </form> Following JS function to manipulate the form values i.e. to change the action of form accordingly and set parameter values. function editProfile() { let form = document.role_task_form; form.task_id.value = "ProfileManagement"; form.operation.value = 'edit'; form.action = '/myschoolspace/edit-profile'; form.submit(); } And call above JS function to the anchor tags of HTML pages from where we have to navigate to the views. I am using this method to pass parameters to every request, but I feel this is not a best practice when Its necessary to pass parameters in each request. Kindly recommend me the best way of doing it. -
Django - Python getting a list from dictionary return a number and not the list
I have a form, which one of the fields is a multiselect, I am trying to retrieve all the values that where selected, but form some reason I only get the last item selected: print(type(self.get_form().data)) # <class 'django.http.request.QueryDict'> print(self.get_form().data) # <QueryDict: {'csrfmiddlewaretoken': ['K0GeMv5u8pnT3fnS1lnXjgYakuu2mkXg61GKMVuJc2bBnDH1YMTPUHr6iY3rsZ0A'], 'contactID': ['20'], 'locationID': ['2'], 'items': ['1', '3']}> In this point items is equal to: 'items': ['1', '3'], however when i try to get items: print(self.get_form().data.get('items')) that prints 3 What I am doing wrong? -
How do i use use javascript on form upload button django
My requirement is to first display the image on the template/html page then upload it in the database, for displaying the image on page i am using java script and for uploading image i am using Django forms inbuilt button of {{form.image}} by clicking one button i should be able to display and upload the image so .How do i use {{form.image}} in javascript button? form.py from django import forms from .models import Boneage class BoneageForm(forms.ModelForm): class Meta: model = Boneage fields = ('gender', 'age','images') javascript <script> const wrapper = document.querySelector(".wrapper"); const fileName = document.querySelector(".file-name"); const defaultBtn = document.querySelector("#default-btn"); const customBtn = document.querySelector("#custom-btn"); const cancelBtn = document.querySelector("#cancel-btn i"); const img = document.querySelector("img"); let regExp = /[0-9a-zA-Z\^\&\'\@\{\}\[\]\,\$\=\!\-\#\(\)\.\%\+\~\_ ]+$/; function defaultBtnActive(){ defaultBtn.click(); } defaultBtn.addEventListener("change", function(){ const file = this.files[0]; if(file){ const reader = new FileReader(); reader.onload = function(){ const result = reader.result; img.src = result; wrapper.classList.add("active"); } cancelBtn.addEventListener("click", function(){ img.src = ""; wrapper.classList.remove("active"); }) reader.readAsDataURL(file); } if(this.value){ let valueStore = this.value.match(regExp); fileName.textContent = valueStore; } }); </script> how do i use this java script code in the Django form button {{form.images}} -
Key error in serializers while using .values() in django rest
I want to filter and count the tasks based on their status. Additionally, I also want to add a count of tasks that are due in this week. I tried using .annotate() and .values(), but I am facing key error. Here is my code, as well as the error. Key Error Here is my code: models.py: class TaskStatus(models.Model): status = models.CharField(max_length=200) def __str__(self): return(self.status) class Task_category(models.Model): job = models.ForeignKey(Job,related_name='Job',on_delete=models.CASCADE, null=True) assigner = models.ForeignKey(User,related_name='assigner', on_delete=models.PROTECT, null=True) assignee = models.ForeignKey(User,related_name='assignee', on_delete=models.PROTECT, null=True) unit = models.ForeignKey(Unit,related_name='UnitName',on_delete=models.CASCADE, null=True) equipment = models.ForeignKey(Equipment,related_name='EquipmentName',on_delete=models.CASCADE, null=True) name = models.CharField(max_length=200) category = models.CharField(max_length=200, null=True,blank=True) start_date = models.DateField() end_date = models.DateField() created_at = models.DateTimeField(auto_now_add=True,blank=True, null=True) updated_at = models.DateTimeField(auto_now=True,blank=True, null=True) status = models.ForeignKey(TaskStatus, related_name='Status',on_delete=models.CASCADE) def __str__(self): return(self.name) serializers.py: class TaskcategorySerializer(serializers.ModelSerializer): class Meta: model = Task_category fields = ['id','job','name','category','start_date','end_date','created_at','updated_at','status','assignee', 'unit', 'equipment', 'assigner'] def to_representation(self, instance): rep = super(TaskcategorySerializer, self).to_representation(instance) rep['job'] = instance.job.name rep['unit'] = instance.unit.name rep['equipment'] = instance.equipment.name rep['status'] = instance.status.status return rep views.py: class ChartView(viewsets.ModelViewSet): http_method_names = ["get"] queryset = Task_category.objects.all() serializer_class = TaskcategorySerializer def get_queryset(self): return Task_category.objects.annotate(value=Count('status')).values('status__status') Please help. Any sort of help will be appreciated!! -
Skip django migrate default table
I use django-admin startproject to create a new project, then use python manage.py migrate. I find there are some tables will create by default. I want migrate my tables only when I run python manage.py migrate. Is it possible to skip the default? -
Why my django project is not visible from domain but working fine when accessed from server ip address?
I'm deploying a django project with nginx on digitalocean. When i accessed my project from server ip address, it is working fine but when i visited through domain connected with it, default welcome page of nginx is shown. After reading previous questions on stackoverflow, i figured it out that it usually happense when your domain is not in allowed host setting of django.But this is not the case this time. Here is my sllowed hosts in django settings:- ALLOWED_HOSTS=['server-ip-address','www.saporasocial.me','.saporasocial.me','saporasocial.me'] You can visit SaporaSocial How can i solve this behaviour? -
django.db.utils.OperationalError?? 1170?
Hi I'm doing my own server using python-virtualenv, django, nginx, uwsgi. django database is mysql. when i migrate django project on virtualenv, always django.db.utils.OperationalError: (1170, "BLOB/TEXT column 'credential_id_data' used in key specification without a key length") this error came out. i don't know this this error happend. when i google, someone said in model.py, TextField is not good, use Charfield. but my code is charfield... i don't know why this error happend. Here is the model.py from django.contrib.auth.models import(BaseUserManager, AbstractBaseUser, PermissionsMixin) from django.db import models from django.contrib.auth.models import AbstractBaseUser from django.utils.translation import ugettext_lazy as _ class UserManager(BaseUserManager): use_in_migrations = True def create_user(self, username, userid, company, companycode, password=None): if not username: raise ValueError(_('Users must have an name!')) user = self.model( username=username, userid = userid, company= company, companycode = companycode, ) user.set_password(companycode) #usrid를 암호화 user.save() return user def create_superuser(self, username, userid, company, companycode, password): user = self.create_user( username=username, userid = userid, company = company, companycode = companycode, password=password, ) user.set_password(password) user.is_superuser = True user.is_active = True user.save() return user class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=50, unique=True, verbose_name="이름") userid = models.CharField(max_length=40, unique=True, verbose_name="아이디") company = models.CharField(max_length=100, verbose_name="회사") companycode = models.CharField(max_length=100, verbose_name="회사코드") created_date = models.DateTimeField(auto_now_add=True, verbose_name="생성날짜") is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) class Meta: … -
How can I import a local postgres file into my Heroku postgres database?
My django application is working perfectly fetching and inserting data into local postgres database. Now i have data in my local postgres database. When i deployed my app on heroku and run migrate command in heroku then it create the tables. But the tables are empty. I just want to know that Did i have to insert all my data again in heroku postgres database or there is any way to migrate/export the local postgres database with data to heroku postgres database? -
how to solve django-query
class Userdata(models.Model): Username=models.CharField(max_length=20) Email=models.EmailField(unique=True,primary_key=True) Password1=models.CharField(max_length=20) Password2=models.CharField(max_length=20) City=models.CharField(max_length=50) def __str__(self): return self.Email class publish(models.Model): Userid=models.ForeignKey(Userdata,on_delete=models.CASCADE) tittle=models.CharField(max_length=20) contend=models.TextField(max_length=20000) def __str__(self): return self.tittle how to find Top 3 publishers who published more numbers of contend along with they email(query) -
i want to share my django post to facebook, using django social share
my settings.py i have installed and followed all the steps in the documentation: django-social-share, but am unable to post a particular post to my facebook what comes up is just a link INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # third party application 'crispy_forms', 'tinymce', 'django_social_share', my home.html {% load social_share %} {% post_to_facebook object_or_url "Post to Facebook!" %} is there any easy way i can share my blog post to facebook -
Bootstrap nav bar function is not working in django can anyone support?
I have just trying to create a simple code and in terms of designing it I used bootstrap CDN link and navigation bar is not showing its result. Could you help me with that? Code is below: <html> <head> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous"> </head> <body> <nav class="navbar navbar-inverse"> </nav> {% block body %} {% endblock %} </body> </html> Here it should show me a bar but it is not working. -
como cambiar el mensaje en git commit -m "add files via upload"
trabajando en github subí la base de datos por powershell pero no la reconoce y supongo que el problema puede ser que al lugar que esta diseccionada, como puedo cambiar el mensaje de git commit -m "add files via upload" para que sea correcto? -
Delete objects in django and api
I want delete an objects from my model in django and api! can anyone help me? The code that i wrote: @csrf_exempt def delete(request,news_id): if request.method == 'DELETE': News.objects.filter(id=news_id).delete() return JsonResponse({'message':'***'},safe=False) else: return JsonResponse({'message':'***'},safe=False) -
django-rest-framework aggregated sum fields
serializers.py class BuildPlanNewSerializer(serializers.ModelSerializer): StatusName = serializers.CharField(source='BuildPlanStatusID.StatusName', read_only=True) # build_plan_list_new = serializers.StringRelatedField(many=True, read_only=True) total_build_plan_list = serializers.SerializerMethodField() def get_total_build_plan_list(self, language): return language.build_plan_list_new.count() class Meta: model = BuildPlanNew fields = ('StatusName', 'total_build_plan_list') class BuildPlanListNewSerializer(serializers.ModelSerializer): sku = serializers.CharField(source='ProductID.sku', read_only=True) class Meta: model = BuildPlanListNew fields = "__all__" models.py class BuildPlanNew(models.Model): emp_id = models.ForeignKey(Employee, on_delete=models.CASCADE, null=True, blank=True) StartDate = models.DateTimeField() EndDate = models.DateTimeField() BuildPlanStatusID = models.ForeignKey(GlobalStatus, on_delete=models.CASCADE) class BuildPlanListNew(models.Model): BuildPlanID = models.ForeignKey(BuildPlanNew, on_delete=models.CASCADE, null=True, blank=True, related_name="build_plan_list_new") ProductID = models.ForeignKey(Product, on_delete=models.CASCADE) TotalPlanQty = models.IntegerField() TotalBuiltQty = models.IntegerField()) QtyPreset = models.IntegerField(default=None, max_length=256) Objective = models.IntegerField(default=None, max_length=256) QtyAssigned = models.IntegerField(default=None, max_length=256) view.py class BuildPlanNewView(viewsets.ModelViewSet): queryset = BuildPlanNew.objects.all() serializer_class = BuildPlanNewSerializer class BuildPlanListNewView(viewsets.ModelViewSet): queryset = BuildPlanListNew.objects.all() serializer_class = BuildPlanListNewSerializer Result i am getting: [{ "StatusName": "1234", "total_build_plan_list": 0 }] Result i am expecting: [{ "StatusName": "1234", "total_build_plan_list": 0, "QtyPreset_count":20, "Objective_count":30 }] Here i wants to fetch aggregated sum and average from foreign key table. Need QtyPreset_count sum as QtyPreset_count Need Objective_count sum as as Objective_count I have shared my models views and serializers Please have a look -
Django + S3 + Heroku strange behaviour
I have a contact form. And when I select photo and save. The server is heroku and the static image files are saved on S3. Everything goes well but for some contacts (NOT ALL) The image doesn't render but if I click the path it saves to AWS and shows the file in a separate browser tab. The strange thing is that behavior is not consistent. Another contact with the same form and the same process it works fine. Please note when I tried to change the image for the contact that had problem rendering ( I tried 3 different images. They all doesn't work except one. The images are all jpg format. I searched the internet for 2 days now and couldn't file a solution.