Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error with Django application deployment on Heroku
Please, help me fix this issue with Heroku. I wanted to host my Django & python application on Heroku but having this error coming up. This is the error getting from my browser: this is the error getting in my prompt after doing heroku logs --tail: 2021-01-29T19:05:21.512000+00:00 heroku[run.6267]: Starting process with command `python manage.py migrate` 2021-01-29T19:05:29.245349+00:00 heroku[run.6267]: Process exited with status 0 2021-01-29T19:05:29.281276+00:00 heroku[run.6267]: State changed from up to complete 2021-01-29T19:12:55.201869+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=grouppublishingindia.herokuapp.com request_id=1cd6be75-9711-4890-ac37-542c02731f37 fwd="103.252.25.76" dyno= connect= service= status=503 bytes= protocol=https 2021-01-29T19:13:01.315149+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=grouppublishingindia.herokuapp.com request_id=9cb635ac-f755-437c-9706-b956967f9f32 fwd="103.252.25.76" dyno= connect= service= status=503 bytes= protocol=https 2021-01-29T19:14:17.641461+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=grouppublishingindia.herokuapp.com request_id=d8ed6b4d-3fe4-4c3a-95d7-fc1a4bc7cd52 fwd="103.252.25.76" dyno= connect= service= status=503 bytes= protocol=https 2021-01-29T19:14:20.774568+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=grouppublishingindia.herokuapp.com request_id=61570fe1-d1d3-41d0-846d-8f482e9f8bfe fwd="103.252.25.76" dyno= connect= service= status=503 bytes= protocol=https 2021-01-29T19:16:09.470063+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=grouppublishingindia.herokuapp.com request_id=19bd2fb7-9739-4a80-b881-759f36c0e5b6 fwd="103.252.25.76" dyno= connect= service= status=503 bytes= protocol=https 2021-01-29T19:16:13.909655+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=grouppublishingindia.herokuapp.com request_id=321e5a3a-798a-42ce-a9ab-39786097717f fwd="103.252.25.76" dyno= connect= service= status=503 bytes= protocol=https 2021-01-29T19:25:36.896690+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=grouppublishingindia.herokuapp.com request_id=13206d28-14c4-4fc1-b57a-2d6b82ab05c9 fwd="103.252.25.76" dyno= connect= service= … -
How do I rank blog posts by sentiment in their comments in django?
I'm using TextBlob and I'm trying to add the polarity part of the result into the Comment model and then adding the average of the comments' polarities into the Post model so it can be sorted. I'm new to this stuff, that is why I'm stuck. Help will be appreciated. -
Django app on Windows Server 2012 - HTTP Error 500.0 - The FastCGI process exited unexpectedly
I setup a django "hello world" app IIS (Windows Server 2012). The application is run successfully using the Django web server. However, when I tried to install in on IIS (following the instructions provided here) I get an HTTP 500 error with the message "python.exe - The FastCGI process exited unexpectedly". I have seen numerous related posts on stackoverflow, but nothing seems to work for me. Based on the guidance I have checked file permissions on both the app and virtual environment folder but they in my opinion this should not be the issue as the users IUSR and IIS_IUSRS can Read & execute, Read and List folder contents. I have tried also to run wfastcgi-enable based on the instructions provided by this post but I get the error "ensure your user has sufficient privileges and try again". Please note that I tried running it both from an "elevated" command line and also power shell with no results. I have reinstalled python to make sure it is installed for "all users" (as suggested by this post) but I get an error "0x80070659 - This installation is forbidden by system policy". I looked in the Event viewer but I could not … -
Django urls.py + React router
I built a Django API and a react frontend to consume the API. I'm using react-router and can navigate just fine until I refresh the page. I then get a Not Found error form Django. I'm not sure how to set up these paths with Django so it knows what to serve. api/urls.py urlpatterns = [ path('', views.apiOverview, name='api-overview'), path('product-list', views.product_list, name='product-list'), path('product/<str:slug>', views.product_detail, name='product-detail'), path('images/<str:fk>', views.product_images, name='product_images'), ] urls.py urlpatterns = [ path('', TemplateView.as_view(template_name="index.html"), name='app'), path('admin/', admin.site.urls), path('api/', include('api.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) app.js function App() { return ( <Router> <Nav /> <div className="App"> <Switch> <Route path="/products/:slug" exact component={ ProductDetail } /> <Route path="/products"> <Projects /> </Route> <Route path="/"> <div className='container'> <Header /> <hr /> <h2 className="section-title">Featured Products</h2> <ProductsListHome /> </div> </Route> </Switch> </div> <Footer /> </Router> ); } -
Is there a package in Atom IDE to help development/debugging Django projects as it is possible in VSCode/PyCharm?
Is there a package in Atom to help development/debugging Django projects as it is possible in VSCode/PyCharm? I went through many packages docs but I could not find any setting the packages autoimport and proper debugging tools (breakpoint, vars inspection, etc). Any suggestion? -
create_user() takes from 2 to 4 positional arguments but 5 were given django
I try to create user use User.objects.create_user. But it show error. create_user() takes from 2 to 4 positional arguments but 5 were given myuser = User.objects.create_user(username , email, password, friendid) -
Django Views redirect('homepage')
I'm stuck and don't understand why here my problem: I would like to return context if objects exists else redirect to homepage and raise error Objects.DoesNotExist. Here My Code : Views class PageDetail(TemplateView): """ Page View """ template_name = 'page_detail.html' def get_context_data(self, **kwargs): context = super(PageDetail, self).get_context_data(**kwargs) try: context['news'] = News.objects.filter(is_active=True).order_by('-date_created')[:4] except: pass try: context['page'] = Pages.objects.get(slug=kwargs.get('slug'), is_active=True) except Pages.DoesNotExist: return redirect('homepage') return context But I got this error : raise TypeError('context must be a dict rather than %s.' % context.__class__.__name__) TypeError: context must be a dict rather than HttpResponseRedirect. Tell me if you need more infos Thanks -
Get http://localhost:8000/Stack/script.js net:: Err_Aborted 404 / Django project
So I am attempting to build a simple to-do app, but when trying to work with some javascript to make the home page, I get the error detailed above (Get http://localhost:8000/Stack/script.js net:: Err_Aborted 404 ). I don't understand what I am doing wrong because this is my first time trying to work with javascript in my Django projects. Below is my code settings.py INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "Stack.apps.StackConfig", "crispy_forms", ] STATIC_URL = "/static/" STATICFILES_DIRS = (os.path.join(BASE_DIR, "static"),) STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles") CRISPY_TEMPLATE_PACK = "bootstrap4" base.py <!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous"> <link rel="stylesheet" type="text/css" href="{% static 'Stack/styles.css' %}"> <title>Stack | Home </title> </head> <body> {%block content%} {%endblock content%} <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/js/bootstrap.bundle.min.js" integrity="sha384-ygbV9kiqUc6oa4msXn9868pTtWMgiQaeYH7/t7LECLbyPA2x65Kgf80OJFdroafW" crossorigin="anonymous"></script> <script src="Stack/script.js" ></script> If I need to upload any more code to help solve this problem, please let me know. Thank you all. -
django app for loop: views.py or frontend?
I am building a django app which has a list of words. The app now tells the user the first word of the list via a speech function. Then the user can record an audio of a word he sais. This word gets turned into a string in the frontend. Now I want to compare the the word from the user with the first string of a second list that has the same amount of characters as the first list. And this whole process should be repeated with all characters of the first list. Can I do this kind of loop in my views.py or do I have to do it in the frontend? -
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