Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is Django supposed to get so slow with around 250 000 model's objects?
I am doing some small project but with around 250 000 model's objects. I have my car model and I am importing data from external json. I talked with some people and they told me that 250 000 objects in django is not a big amount and it won't have much impact on performance. Loading up to models this data from json is takin around 5 - 10 min and I don't mind that. But, right now If I make any changes to the website (locally) while running runserver I have to wait around 1 minute (on macbook pro 2020 (not M1)). And it is pretty annoying. I ran command python -v manage.py check and apparently django.db.models.sql.compiler takes this whole time. I am wondering, if my approach with models is wrong, or it is normal with SQL Light? Or maybe I could safely turn off this check? Or I got wrong informations and workflow with this many model's object is totally wrong? -
TemplateDoesNotExit error when deploying project on heroku
am trying to deploy my project on heroku but am stumbling on the above error everything works fine when i run the code locally, kindly help out below are my setting and views file template settings TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'Templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] views of my Home app def Home(request): return render(request,'Home/index.html') -
Django - how can i call a model as a string?
I'm building a DRF api endpoint that should render some json data from my database. In my view, the name of the model to query to render the data is not fixed, it depends on what query does the user perform. So i have this: collection = 'MY_MODEL' queryset = collection.objects.filter(**filters) But this will give the following error: 'str' object has no attribute 'objects' This will work instead: queryset = MY_MODEL.objects.filter(**filters) Is there any way to get around this? -
Attribute Error - Model object has no attribute 'COOKIES'
I was initially having issues getting data from my API and it gave a "Forbidden" error, and now that I have fixed that with cookies and csrf token it's not working anymore. The Error: cookie_token = request.COOKIES[settings.CSRF_COOKIE_NAME] AttributeError: 'networthChart' object has no attribute 'COOKIES' [30/Jan/2021] "GET /api/networthchart/data/ HTTP/1.1" 500 102936 I am trying to data from an endpoint and this error comes up. here is the code: JS: <script> function getCookie(name) { let cookieValue = null; if (document.cookie && document.cookie !== '') { const cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } const csrftoken = getCookie('csrftoken'); const request = new Request( "/api/networthchart/data/", {headers: {'X-CSRFToken': csrftoken}} ); $(document).ready(function(){ var endpoint = 'http://127.0.0.1:8000/api/networthchart/data/' var defaultData = [] var labels = [] $.ajax({ method:"GET", url: endpoint, success: function(data){ labels = data.labels defaultData = data.default var ctx = document.getElementById('myChart').getContext('2d'); var myChart = new Chart(ctx, { type: 'bar', data: { labels: labels, datasets: [{ label: '# of Votes', data: defaultData, ....... </script> The … -
how to get date value in django template in format 1-7 day (weeks)
Please tell me if there is a way to transfer the day of the week, Monday -1, ... Sunday -7 to the django template. I found nothing among the tags and filters. -
How to send date based notification/ sms in djnago
I want to send date based notification/sms/email to user. I've created a dateBasedNotification model that contain title / date / recipent / message. Now data entry person can create the notifications. I want to send the contain message when date.today == smsDate. -
How can I add Redoc documentation to the Django using local yml schema file?
Does anyone know how can I add Redoc documentation endpoint using local schema.yml file? In the Swagger I do something like shown below unfortunately I have a problem with Redoc. Any ideas? urls.py: path('', TemplateView.as_view( template_name='swagger-ui.html', extra_context={'schema_url': 'openapi-schema'} ), name='swagger-ui'), swagger-ui.html: {% load static %} <html> <head> <title>Documentation</title> <meta charset="utf-8"/> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" type="text/css" href="//unpkg.com/swagger-ui-dist@3/swagger-ui.css" /> </head> <body> <div id="swagger-ui"></div> <script src="//unpkg.com/swagger-ui-dist@3/swagger-ui-bundle.js"></script> <script> const ui = SwaggerUIBundle({ url: "{% static 'schema.yml' %}", dom_id: '#swagger-ui', presets: [ SwaggerUIBundle.presets.apis, SwaggerUIBundle.SwaggerUIStandalonePreset ], }) </script> </body> </html> -
How to make Django display compiled Angular index.html page
I have following structure of my Django and Angular app. Here in application I have complied angular project in dist folder. In dist - application I have index.html. What should I do to to make Django give me this index page then I request for example localhost:8000? I tried to manipulate with STATIC_ROOT but have a TemplateError. setting.py looks like this ANGULAR_DIR = os.path.join( os.path.dirname(os.path.dirname(os.path.abspath(__file__))).split('client')[0], 'application/' ) STATIC_ROOT = os.path.join(ANGULAR_DIR, 'dist', 'application') STATICFILES_DIRS = ( os.path.join(ANGULAR_DIR, 'dist', 'application'), ) and url.py looks like this from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from django.conf.urls import url from django.views.generic import TemplateView urlpatterns = [ path('admin/', admin.site.urls), path('auth/', include('authentication.urls')), path('api/', include('api.urls')), url(r'^$', TemplateView.as_view(template_name='index.html')) ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
How to workout a logic, so that a user can send me a gift(point based) if they really like my blog? - In Django
hello guys/girls I am trying to figure out a logic similar to how we see in some social apps where the user is able to send gift points to the creator by paying some money. I am thinking of having a similar setup in my blog website, where the user can send me gifts if they find the blog useful. What's the best way to implement this? I want to store these information when the user sends a gift- the sender info (Only logged in users can send), for which blog post, how much points (There will be gift options like 10, 20, 50 points) and at what time. I am having trouble thinking about the logic as I have never done anything like this before. Should I go with the content types considering the future, if I plan to have vlogs section along with the current blogs for easier integration? Will using content type affect the performance greatly? Thanks -
django_crontab not working on production docker
I'm trying to run a scheduled script using django_crontab twice a day. I have tested it locally on ubuntu 18 and it works. However, when I'm trying to run it on the server (python Docker image that runs Django project on remote Ubuntu server) here is my code: setting.py: INSTALLED_APPS = ( . . 'django_crontab', . . . ) RONJOBS = [ ('25 8,21 * * *', 'appname.folder.file.start') ] I executed cron by: $ python manage.py crontab add . and see the active job: $ python manage.py crontab show f95300a5599dc7687ac79ab51c8bb33c -> ('13 9,21 * * *', 'appname.folder.file.start') def start(): logger.info(" process begins!") do_something() Note The function 'start' was tested in the production server and it works. I also tried to map the chronjob logs by adding path to the CRONJOB at setting.py: ('25 8,21 * * *', 'appname.folder.file.start','>> /Logs/crontab.log') but the file crontab.log wasn't created. Any suggestions? Thanks! -
Can I save 2 entries to my models that are referencing each other?
I have 2 models, "Listing" and "Bid" Bids: # bids and bidder class Bid(models.Model): bid = models.IntegerField(default=10) #default soll durch user gesetzt werden # Foreign Keys bidder = models.ForeignKey(User, on_delete=models.CASCADE, related_name="bids") listing = models.ForeignKey(Listing, on_delete=models.CASCADE, related_name="bids") Listing: # all information related to a listing class Listing(models.Model): creation_date = models.DateTimeField(auto_now_add=True, null=True) title = models.CharField(max_length=100, null=True) description = models.CharField(max_length=100) image = models.URLField(max_length=200, default="https://user-images.githubusercontent.com/24848110/33519396-7e56363c-d79d-11e7-969b-09782f5ccbab.png") bid = models.IntegerField(default=10) auction_open = models.BooleanField(default=True) # Foreign Keys author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="listings") place_bid(): def place_bid(request, listing_id): bidder = request.user bid = request.POST.get("bid") listing_entry = Listing.objects.get(pk=listing_id) bid_entry = Bid(listing=listing_entry, bid=bid, bidder=bidder) bid_entry.save() listing_entry.bid = bid_entry listing_entry.save() return; In a function "place_bid()" I want to create a new "Bid"-instance that references a already existing "Listing"-instance using a foreign key. The problem arrises because of what I want to do next: I want to change the same "Listing"-instance that was just referenced, I want to replace the "Bid" object of that Listing object to that "Bid"-object I just created. Can you please help me out there:) -
my author of the comment is showing null django
The author of the post is shown correctly but when I use the same for comment it is returning NULL instead of the author. models.py from django.conf import settings from django.contrib.auth.models import User from django.urls import reverse from django.template.defaultfilters import slugify from ckeditor.fields import RichTextField from ckeditor_uploader.fields import RichTextUploadingField class BlogPost(models.Model): title = models.CharField(max_length = 50 , null=False,blank=False) #body = models.TextField(max_length = 5000 , null=False,blank=False) body = RichTextUploadingField(blank=True,null= True) date_published = models.DateTimeField(auto_now_add=True) date_update = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(User,on_delete=models.CASCADE) #slug = models.SlugField(blank=True,unique=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('post:article-detail', args=(self.id,)) class comment(models.Model): BlogPost = models.ForeignKey(BlogPost,related_name="comments", on_delete=models.CASCADE) name = models.CharField(max_length = 250) body = models.TextField(max_length = 5000) date_added = models.DateTimeField(auto_now_add=True) #author = models.ForeignKey(User,on_delete=models.CASCADE) author = models.ForeignKey(User,null=True,on_delete=models.CASCADE) def __str__(self): return '%s %s' % (self.BlogPost.title, self.name) if "null=True" is not written in the author field then it it giving me this error "NOT NULL constraint failed: post_comment.author_id" -
I am facing a error about Django related to make migration ...how can I fix it? the version of installed Django is 3.1.5
File "C:\Users\Yogiraj Patil\PycharmProjects\myproject\venv\lib\site-packages\django\db\utils.py", line 122, in load_backend raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: 'django.db.backends.postgreysql' isn't an available database backend. Try using 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'postgresql', 'sqlite3' -
Get method in Django's detailview
This is my industry_employeelist detail view and it works perfectly. class industry_employeelist(DetailView): model = Industry template_name = 'app/industry_employeelist.html' def get_queryset(self): return Industry.objects.filter(user=self.request.user) def get_object(self): return get_object_or_404(Industry, user=self.request.user) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) this_industry = get_object_or_404(Industry.objects.filter(user=self.request.user)) context['employeeList'] = self.object.employee_set.all() return context def post(self, request, *args, **kwargs): this_industry = get_object_or_404(Industry.objects.filter(user=request.user)) this_name = request.POST['name'] this_rank = request.POST['rank'] this_email = request.POST['email'] this_phone = request.POST['phone'] this_nid = request.POST['nid'] this_address = request.POST['address'] employee_obj = Employee.objects.create( industry=this_industry, name=this_name, rank=this_rank, email=this_email, phone=this_phone, nid=this_nid, address=this_address ) employee_obj.save() return redirect('app:industry_employeelist') Now I want to make an auto-search suggestion for my project. Looking for a tutorial: youtubelink, and Doc. When I add the get method to the industry_employeelist detail-view it does not work anymore. def get(self, request, *args, **kwargs): this_industry = get_object_or_404(Industry.objects.filter(user=request.user)) if 'term' in request.GET: srckey = request.GET.get('term') suggession = this_industry.employee_set.all().filter(name__contains=srckey) sug_list = list() for i in suggession: sug_list.append(i.name) return JsonResponse(sug_list, safe=False) context = super().get_context_data(**kwargs) Please suggest how to fix it? my template(if you want to check): <!DOCTYPE html> {% extends 'app/base.html' %} {% load static %} {% block content %} <div class="content-fluid my-5"> <div class="row d-flex justify-content-center m-0 mb-3"> <div class="our-service-head"> <p class="our-service-title text-center">Your Employee List</p> <p class="our-service-subtitle text-center px-3"> Nulla ullamcorper bibendum orci, ac tempor nisl lacinia … -
Django form not submitting data
I'm making a simple to do list app. I have a form that is not submitting upon clicking submit. When I click submit the following url appears: http://127.0.0.1:8000/update_task/1/? csrfmiddlewaretoken=k8tpRlypuPUsckyGE4sekciegDUl0ghBqxelylScAUiZJeEs3AOnYWO1K6HATTgC&title=Go+shopping%28Updated%29&complete=on&Update+Task=Submit Here is my code: views.py from django.shortcuts import render, redirect from .models import Task from .forms import TaskForm def index(request): tasks = Task.objects.all() form = TaskForm() if request.method == "POST": form = TaskForm(request.POST) if form.is_valid(): form.save() return redirect('/') context = {'tasks':tasks, 'form':form} return render(request, 'task/list.html', context) def updateTask(request, pk): task = Task.objects.get(id=pk) form = TaskForm(instance=task) if request.method == "POST": form = TaskForm(request.POST, instance=task) if form.is_valid(): form.save() return redirect('/') context = {'form':form} return render(request, 'task/update_task.html', context) update_task.html <h5>Update Task</h5> <form class="POST" action=""> {% csrf_token %} {{form}} <input type="submit" name='Update Task'> </form> list.html <h2>To Do</h2> <div class="center-column"> <form method="POST" action="/"> {% csrf_token %} {{form.title}} <input type="submit" name="Create Task"> </form> <div class="todo-list"> {% for task in tasks %} <div class="item-row"> <a href="{% url 'update_task' task.id %}">Update</a> {% if task.complete == True %} <strike>{{task}}</strike> {% else %} <span>{{task}}</span> {% endif %} </div> {% endfor %} </div> </div> task/urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='list'), path('update_task/<str:pk>/', views.updateTask, name='update_task'), ] Thank you for the help. -
Django Objects looping in JavaScript
i want to loop over a object and manipulate it in JavaScript file but i am not able to get these object in JavaScript file although i can loop them if they are in html . But cannot do that in separate JavaScript file -
Django queryset NameError
Just started learning python and using sublime text. trying to run a queryset but getting a NameError. from the error, it seems the table which is in the models.py is not being picked up. the code in models.py shown in screenshot the error im getting is - name 'Stock' is not defined im trying to get the queryset to run such that i can get a list of items from the Stock table models code class Stock(models.Model): category = models.CharField(max_length=50, blank=True, null=True) item_name = models.CharField(max_length=50, blank=True, null=True) view code def list_item(request): title = 'List of list_item' queryset = Stock.objects.all() the error im getting is from the line with queryset -
ForeignKey Field replaced with text input, but not validating in form
I am working on a project that involves some foreign key fields but i converted them to text inputs in a form. I plan to use datalist to display some choices from the foreign keys but users can still input new data in the input field. The problem now is that the form is being submitted but the data isn't validating Here's the code models.py class Todo(models.Model): title = models.CharField(max_length=250) completed = models.BooleanField(default=False) due_date = models.DateTimeField(blank=True) created = models.DateTimeField(auto_now_add=True) tags = models.ManyToManyField(Tag, blank=True) goal = models.ForeignKey( Goal, on_delete=models.SET_DEFAULT, default='', blank=True) context = models.ForeignKey( Context, on_delete=models.SET_DEFAULT, default='', blank=True) project = models.ForeignKey( 'Project', blank=True, on_delete=models.CASCADE,default='') status = models.CharField(choices=status_types, max_length=250, blank=True) priority = models.CharField( choices=priority_types, max_length=250, blank=True, default='none') place = models.CharField(max_length=250, blank=True) def __str__(self): return self.title add_task.html <h5>Add Task</h5> <br><br> <form action="{% url 'todos:add_task' %}" method="POST" id="add-task-form"> {% csrf_token %} {% if form.error %} <p class="alert">{{form.error}}</p> {% endif %} {% for field in form %} {% if field == form.tags %} <div class="form-group row"> <div class="col"> {{field.label_tag}} </div> <div class="col"> {{field}} <datalist id="taglist"> {% for tag in tags %} <option value="{{tag}}"></option> {% endfor %} </datalist> </div> </div> {% elif field == form.context %} <div class="form-group row"> <div class="col"> {{field.label_tag}} </div> <div class="col"> {{field}} … -
DRF list endoint returns 404 while there are objects present in db
There's some problem when I'm trying to retrieve a list of objects. Here is my code (I've reduced it for simplicity) # Models.py class TournamentType(models.Model): name = models.CharField(max_length=255) # Serializers.py class TournamentTypeSerializer(serializers.ModelSerializer): class Meta: model = models.TournamentType fields = ('id', 'name') # Views.py class TournamentTypeViewSet(ReadOnlyModelViewSet): queryset = TournamentType.objects.all() serializer_class = serializers.TournamentTypeSerializer In Swagger I end up seeing 2 request types: http://localhost:8000/api/tournaments/time_control/{id} http://localhost:8000/api/tournaments/time_control/ First one (with ID) returns object as expected. But the second one, which is supposed to return a list, returns a 404 response. I've tried specifying a request type by adding this to the view: def list(self, request): queryset = TournamentType.objects.all() serializer = serializers.TournamentTypeSerializer(queryset, many=True) return Response(serializer.data) But result is still the same. What am I missing? I've checked all the docs, and everything seems to be in place. -
what __str__ is doing in the below code????The two code listed are different
We are creating a python django model.What is the use of __str__below? What str is actually returning and where? Sample code 1 from django.db import models from django.contrib.auth.models import User # Create your models here. class Profile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) image = models.FileField(upload_to='profile_pics', blank=True,default='default.jpg') def __str__(self): return self.user.username+ " Profile" Sample code 2 from django.db import models from django.contrib.auth.models import User # Create your models here. class Article(models.Model): title = models.CharField(max_length=100) body = models.TextField() date = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title -
ValueError at /newspaperapp/category/sports/ : Field 'id' expected a number but got 'sports'
I am creating categories for news. I am trying to filter the news category wise but getting a value error models.py class category(models.Model): title=models.CharField(max_length = 200) category_image = models.ImageField(upload_to="imgs") def __str__(self): return self.title class newsmodel_1(models.Model): category = models.ForeignKey(category,on_delete=models.CASCADE) title = models.CharField(max_length = 50 , null=False,blank=False) date_published = models.DateTimeField(auto_now_add=True) #details = models.TextField() details = RichTextUploadingField(blank=True,null= True) slug = models.SlugField(blank=True,unique=True) def slug(self): return slugify(self.date_published) this is views.py def index(request): cats=category.objects.all() return render(request,'newspaperapp/index.html',{'cats':cats}) class nowlist(ListView): model = newsmodel_1 template_name = 'newspaperapp/index.html' class newslist(DetailView): model = newsmodel_1 template_name = 'newspaperapp/home.html' context_object_name = 'newspaperapp' class SearchView(ListView): model = newsmodel_1 template_name = 'newspaperapp/search.html' context_object_name = 'all_search_results' def get_queryset(self): result = super(SearchView, self).get_queryset() query = self.request.GET.get('search') # query is of type 'str', convert to datetime start_day = datetime.fromisoformat(query) end_day = start_day + timedelta(days=1) if query: postresult = newsmodel_1.objects.filter( date_published__gte=start_day, date_published__lt=end_day ) result = postresult else: result = None return result def full_news(request): return render(request,'newspaperapp/full-news.html') def CategoryView(request,cats): category_posts = newsmodel_1.objects.filter(category = cats) return render(request,"newspaperapp/categories.html",{'cats':cats,'category_posts':category_posts}) this is urls.py urlpatterns = [ path('',views.index,name='index'), path('date/',nowlist.as_view(),name = "date"), path('<int:pk>',newslist.as_view(),name = "home"), path('results/', SearchView.as_view(), name='search'), path('full_news/',views.full_news,name = "full_news"), path('category/<str:cats>/',views.CategoryView,name='category'), ] categories.html <h1>{{cats}} category</h1> <ul> {%for post in category_posts%} <h3><a href="{%url 'newspaperapp:home' newspaperapp.pk %}">{{ newspaperapp.title}} {{newspaperapp.category}}</a></h3> {% endfor %} index.html {% for cat in … -
Change auto increment id to last without django ORM
i want refresh auto increment order_id from between rows to next of last row in database layer without Django ORM. my order_id field is integer and it's auto increment in MySQL for example i have 1, 2, 3, 4, 5 and i want update order_id from 3 to 6 id without get last order_id with Django ORM. is it possible? my model is like this: class Order(models.Model): order_id = models.BigIntegerField(unique=True) -
when I change urlconfig,images does not load in django
when I change urlconf my images are not load in the page. this code is when the images are loaded in the page,"urls.py" urlpatterns = [ path('admin/', admin.site.urls), path('<lang>/', home_page), path('', home_redirect), path('products/', include('products.urls')), path('', include('agents.urls')), path('', include('information.urls')), path('', include('media_app.urls')), ] in this code when the images are not loaded urlpatterns = [ path('admin/', admin.site.urls), path('<lang>/', home_page), path('', home_redirect), path('<lang>/products/', include('products.urls')), path('<lang>/', include('agents.urls')), path('<lang>/', include('information.urls')), path('<lang>/', include('media_app.urls')), ] I have no idea for solve it... -
Django:MEDIA_ROOT error : _getfullpathname: path should be string, bytes or os.PathLike, not tuple
I am new to Django Framework.I am trying to upload image to the customer table and this error occurs _getfullpathname: path should be string, bytes or os.PathLike,. I am using this code to upload MEDIA_ROOT = [BASE_DIR, 'static/images'].I change the code to MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images'), but,it says NameError: name 'os' not defined..what's the reason for the errors and how solve it? settings.py STATIC_URL = '/static/' MEDIA = '/images/' STATICFILES_DIRS = [BASE_DIR, 'static'] MEDIA_ROOT = [BASE_DIR, 'static/images'] models.py class Customer(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=200, null=True) phone = models.CharField(max_length=11, null=True) email = models.EmailField(max_length=200, null=True) profile_pic = models.ImageField(null=True, blank=True) date_created = models.DateTimeField(auto_now_add=True, null=True) -
WSGI apache Unsupported Media Type error in custom http request
I am using Django to receive request from an AVR. I uses an custom http POST request containing some byte. I receive data and store successfully to my database when I use manage.py runserver. But when I WSGI in apache (WSGIDaemonProcess) I get this error: [wsgi:error] [pid 5080] [remote 222.157.163.133:4773] Unsupported Media Type: /api/micro/data How can I fix it?