Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to check the registered celery task
My celery tasks do not start. How can I check the registered tasks. See my code here: Link to the code of my project -
Pythonanywhere not able to load static files during deploying django app
Pythonanywhere not able to load my static files during deploying but everything works fine on my local computer. Here is the directory structure of my app and settings of static file on my local pc: https://www.screencast.com/t/l0d6ehWWJ and the settings file contains STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "static"). the URL and DIRECTORY on pythonanywhere are as below URL-/static/ DIRECTORY-'/home//Myapp/static' what might be the reason for this? -
Django: Complex annotation, how to avoid for loop?
For an analytics app that utilizes Google Realtime Analytics API, I have my models.py definitions as follows: class Report(BaseModel): ios_report = JSONField() android_report = JSONField() class Article(BaseModel): internal_id = models.IntegerField(unique=True) title = models.CharField(max_length=500) short_title = models.CharField(max_length=500) picture_url = models.URLField() published_date = models.DateField() clip_link = models.URLField() reports = models.ManyToManyField( "Report", through="ArticleInReport", related_name="articles" ) class ArticleInReport(BaseModel): article = models.ForeignKey("core.Article", on_delete=models.CASCADE, related_name='articleinreports') report = models.ForeignKey("core.Report", on_delete=models.CASCADE, related_name='articleinreports') ios_views = models.IntegerField() android_views = models.IntegerField() @property def total_views(self): return self.ios_views + self.android_views Everything starts with a Report object that is created at set intervals. This report contains data about articles and their respective views. A Report will have a relationship with an Article through ArticleInReport, which holds the total number of users in Article at the time the report was imported. In my view, I need to display the following information: All articles that received views in the last 24 hours. With each article annotated with the following information: If present, the number of views the Article object had in the last Report. If not present, 0. I'm achieving this as follows in my views.py: reports_in_time_range = Report.objects.filter(created_date__range=[starting_range, right_now]) last_report = Report.objects.last() articles = Article.objects.filter(articleinreports__report__in=reports_in_time_range) \ .distinct().annotate( total_views=Case( When(articleinreports__report=last_report, then=(F("articleinreports__ios_views") + F("articleinreports__android_views"))) , default=0, output_field=IntegerField() … -
Need Help To solve Error in Django API
I write a code for integrate api for sms in django but the code throwing 101 | method error Code in view.py class RegisterView(CreateView): form_class = RegisterForm template_name = 'accounts/register.html' success_url = '/success-membership/' def form_valid(self, form): url = "http://enterprise.smsgupshup.com/GatewayAPI/rest" payload = "method=sendMessage&send_to=XXXXXXXXX&msg=new&msg_type=TEXT&userid=XXXXXX&auth_scheme=PLAIN&password=XXXXX&format=TEXT" response = requests.request("POST", url, data=payload) print(response.text) return HttpResponse(response) -
Django class based view related fields map url
I'm having trouble getting a Novel webpage to return a view with the appropriate chapters for a specific book. The model consists of 2 classes (Book and Chapter) that are linked by foreign key (in Book). The book index page lists each of the books in library and hyperlink to their chapter index page. The book index page works fine however I am can't seem to properly pass parameters to chapter view and display the chapter index page (simply list the chapter number, which I would also hyperlink later). The code is a bit frankensteinish, if anything is unnecessary or if there is an easier way to do it please tell. Any help is greatly appreciated models.py from django.db import models from django.template.defaultfilters import slugify class Book(models.Model): number = models.PositiveIntegerField(primary_key=True, unique=True, db_index=True) name = models.CharField(max_length=33, db_index=True) short = models.CharField(max_length=7) search = models.CharField(max_length=7) chaptercount = models.IntegerField() title = models.CharField(max_length=33) slug = models.SlugField(max_length=33, verbose_name=('Book Slug'), default=name) def save(self, *args, **kwargs): self.slug = slugify(self.name) super(Book, self).save(*args, **kwargs) def __str__(self): return self.name class Meta: ordering = ['number',] class Chapter(models.Model): book = models.ForeignKey(Book, related_name='chapters', on_delete=models.CASCADE) number = models.PositiveIntegerField(db_index=True) def __str__(self): return '%s %s' % (self.book.slug, self.number) def get_absolute_url(self): return ('chapter_detail', [self.book.slug, self.number]) class Meta: ordering … -
Uncaught SyntaxError: Unexpected token & in javascript django app
This is my function: function convert_strings() { var chart_labels = {{ chartlabels }}; var array_length = chart_labels.length; for (var i = 0; i < array_length; i++) { chart_labels[i] = chart_labels[i].replace(/&#039;/g, "'") } return chart_labels } This is my error: "Uncaught SyntaxError: Unexpected token &" function convert_strings() { var chart_labels = [&#39;CHENNAI LPG RO&#39;, &#39;KOCHI LPG RO&#39;, &#39;BANGALORE LPG RO&#39;, &#39;HUBLI LPG RO&#39;, &#39;MADURAI LPG RO&#39;, &#39;MANGLORE LPG RO&#39;]; var array_length = chart_labels.length; for (var i = 0; i < array_length; i++) { chart_labels[i] = chart_labels[i].replace(/&#039;/g, "'") } return chart_labels } Please advice what to do :) -
Multiple valued attribute within same object using one to many relationship in Django
I have to create a registration app using Django. There will be two models: Event, consisting of event name and fees; and Participant, consisting of participant details and the event in which they have participated. One participant may have participated in multiple events. While saving the objects I do not want multiple entries for different events of the same participant. I suppose this implies the use of a one to many relationship field, which I am unable to find in Django. The schema I tried was class Event(models.Model): name = models.CharField(max_limit=50) fees = models.IntegerField(default=100) class Participant (models.Model): name = models.CharField(max_limit=50) event = models.ForeignKey(Event) receiptno = models.IntegerField(primary_key=True) I tried using Foreign key field but it is able to store only one event the participant has participated in. I want to be able to store multiple events in one participant object (as only one receipt was issued manually per participant irrespective of the events participated in) How do I do the same? -
Ajax.abort(), django appears winerror 10053
I uploaded the file to the django server using ajax Post. Then during the data transfer, I used the 'ajax.abort()', and then the WinError 10053 appeared. -
Django - AJAX fails even if it correctly saves to DB
I made a working code for AJAX. I've wanted to submit data without refreshing a page through AJAX, and my code does what I want to achieve. And yet my jQuery AJAX returns error. $("input[type=\"submit\"]").on('click', function (e) { e.preventDefault(); var form = $(this).closest("form"); var data = form.serializeArray(); var formIdentifier = {"name": form.find('input[type="submit"]').attr("name")}; data.push(formIdentifier); console.log(data); $.ajax({ url: "", dataType:"json", type: "POST", data: data, success: function() { console.log('1234') }, error: function () { alert(data.status); } }); }); And I've correctly used csrf token in my html file, as my console.log(data) prints this: Here is my html code: <form id="demo-form" method="POST" \> <div class="row"> {% csrf_token %} {% for field in bha_overall_form %} <div class="col-lg-2 col-md-2 col-sm-4 col-xs-6" style="margin-bottom: 5px"> <label class="input-upper-title">{{ field.name }}</label> {{ field|add_class:"form-control input-field-height-vertical"}} </div> {% endfor %} <input type="submit" id="bha_overall_submit" class="hidden" name="bha_overall"> </div> Why is my AJAX function returning error, even if it achieved what I wanted to achieve? -
Django: Send Array from Template to View
script function submition(){ var result=finalaproduct; alert(result) $.ajax({ headers: { "X-CSRFToken": '{{csrf_token}}' }, type: "POST", url: "cart_in", data: result, success: function() { alert("SUCCESS") } }); } urls.py url(r'^cart_in/(?P<qid>\w+)/$', cart_in ,name='cart_in'), views.py def cart_in(request, qid): id = qid print(id) return redirect('/') array i want to pass [{"quantity":"36","customer_ID_id":1,"shop_ID_id":1,"product_ID_id":1},{"quantity":"3","customer_ID_id":1,"shop_ID_id":1,"product_ID_id":2}] I want to pass array mentioned above from 'template' to 'views.py', and i got stuck while doing this.I might be following the wrong way for this. Help me with this. -
Django Test with default database and without running any migrations
Is there any way I can use my default local database for testing in Django 1.9. I also don't want to run any migrations, and I want to test it locally. The reason I want to do it this way is that in my migrations, I have a data migration referring to some entry from a model and when tests run and create a test_database the migrations fail as there are no entries in the test model and this data migration use .get() I don't know how I should resolve this issue. The best way I could think of is my default database for testing. -
403 error when routing from empty index
I have django+angular6 web app and, probably, problems with routing. My 1st example of urls.py looks like: url(r'index/', views.GenericView.as_view()), url(r'api/checks/', views.GetChecksView.as_view()), url(r'api/editcheck/', views.ChecksEdit.as_view()), url(r'api/createcheck/', views.CreateCheckView.as_view()), and current version of app-routing-module.ts: const routes: Routes = [ { path: '', redirectTo: '/checks', pathMatch: 'full' }, { path: 'checks', component: ChecksComponent }, { path: 'editcheck/:id', component: CheckEditComponent }, { path: 'createcheck', component: AddCheckComponent} ]; @NgModule({ exports: [ RouterModule ], imports: [ RouterModule.forRoot(routes) ] }) export class AppRoutingModule { } While running on local, on '127.0.0.1:8000' I'm obviously getting page not found error. Solution could be simple, but when I change r'index/' at urls.py to r'' it runs into an error when I'm trying to post any data. Already tested a lot of options, such as posting through python script and changing angular component models, didnt work any good. I hope I could be sure that the problem in these parts of code, but if its not - will update post with other parts. As for python, it works only in first example, second one says 'CSRF verification failed. Request aborted.' Important note: I'm not using any auth on backend. Thanks in advance for extended answers -
Django - state variables in CBV & access self.request on global level.
I am trying to state a global variable inside a CBV. First I tried this: class Some_View(UpdateView): model = Some_Model def __init__(self): super().__init__() self.foo = do_something(self.request) But it obviously didn't work, as self.request is not available at __init__ level. I was looking for an way to state a global variable by accessing request, and came across this link. He basically says that I need to override dispatch() method and state self.foo here using request. So I wrote the following code: class Some_View(UpdateView): model = Some_Model def dispatch(self, request, *args, **kwargs): self.foo = do_something(request) return super(Some_View, self).dispatch(request, *args, **kwargs) And it gives me this error: 'QuerySet' object has no attribute '_meta' ...\views.py in dispatch return super(BHA_UpdateView, self).dispatch(request, *args, **kwargs) Why is this happening, and how can I fix this issue? My ultimate goal is to state a global variable inside CBV, which uses self.request. -
Failed to read PID from file /run/nginx.pid but the website works properly
When I check the status of Nginx sudo service nginx status Aug 01 12:35:07 iz2ze9wve43n2nyuvmsfx5z systemd[1]: Starting The nginx HTTP and reverse proxy server... .... Aug 01 12:35:07 iz2ze9wve43n2nyuvmsfx5z systemd[1]: Failed to read PID from file /run/nginx.pid: Invalid argument Aug 01 12:35:07 iz2ze9wve43n2nyuvmsfx5z systemd[1]: Started The nginx HTTP and reverse proxy server. It report that "Failed to read PID from file /run/nginx.pid: Invalid argument" However, my website runs properly, my custom_nginx.conf server { listen 80; server_name *.example.com 39.105.51.**; charset utf-8; location / { uwsgi_read_timeout 30; uwsgi_pass 127.0.0.1:8200; include uwsgi_params; } location /media/ { alias /usr/share/nginx/html/; autoindex on; } location /static/ { alias /root/forum/dst_static/; } } I could visit www.example.com and 39.105.51.** without error. Should I ignore it, what kind of error is waiting for me ahead? -
Django show opencv histogram into template
I'm using Python 3.6 and Django 1.11 with opencv. What I want to achieve is, user will upload a photo and then on a new function based action I'll show the uploaded image histogram on rendered template. I've done the following so far: import cv2 import numpy as np from matplotlib import pyplot as plt def show(request, id=None): instance = get_object_or_404(Album, id=id) img = cv2.imread(instance.photo.path) color = ('b', 'g', 'r') for i, col in enumerate(color): histr = cv2.calcHist([img], [i], None, [256], [0, 256]) plt.plot(histr, color=col) plt.xlim([0, 256]) # here plt.show() will open a new window with the histogram. # but I want to show that plt histogram to the below rendered # show.html template context = { 'title': 'Detail', 'instance': instance, 'histogram': # here i want to pass the histogram as image } return render(request, 'album/show.html', context) Can anyone have any clue how to achieve that? Thanks in advance! -
How do you add an attribute to a django app python module?
Given a django app called mattermost which has a model called Channel we can do something like this. import mattermost for channel in Channel.objects.all(): print(channel) I'd like to be able to do something like this import mattermost mattermost.channels.list I've tried adding channels.py with a def list(): function in the same folder as mattermost/init.py. I'm getting the following error. In [7]: reload(mattermost) Out[7]: <module 'mattermost' from '/home/csmu/mipgen-django/mattermost/__init__.py'> In [8]: mattermost.channels.list --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-8-d4715777f4f1> in <module>() ----> 1 mattermost.channels.list AttributeError: module 'mattermost' has no attribute 'channels' How do you add an attribute to a django app python module? -
jquery post a file form, but server get nothing?
i have a page need to click a button to post a file, but the server get nothing??? can anyone help me? <button class="btn btn-primary btn-sm" id="upload_item">上传</button> $('#upload_item').click(function(event) { event.preventDefault(); var form = $('<form action="." method="post" enctype="multipart/form-data" hidden> </form>').wrapInner( $('<input type="file" value="" name="uploadfile">').click()).appendTo('body').submit().remove(); }); -
TemplateDoesNotExist Django Error only on VPS - works fine locally
I know that there are many other questions like this one, but I believe my case is unique - I have spent hours, applying fixes from literally every website and youtube tutorial I have come across, and I still get this error. I am wondering why: Here is the error: TemplateDoesNotExist at /skills/ skills\skills.html Here is my settings.py """ Django settings for pranavblog project. Generated by 'django-admin startproject' using Django 2.0.7. For more information on this file, see https://docs.djangoproject.com/en/2.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.0/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SETTINGS_PATH = os.path.dirname(os.path.dirname(__file__)) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '...' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['178.128.79.59','pranaveranki.com','127.0.0.1'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'posts', 'sitepages', 'hackathons', 'projects', 'pagedown', 'skills.apps.SkillsConfig', 'django.forms' ] FORM_RENDERER = 'django.forms.renderers.TemplatesSetting' MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'pranavblog.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(os.path.dirname(__file__),'../templates'),], 'APP_DIRS': True, 'OPTIONS': … -
Django - How to modify template context from middleware
I am creating a Django middleware that manages a 'shopping cart' with sessions. I was able to successfully modify the session data like so: class ShoppingCartMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): # Ensure shopping cart exists if request.session.get('shopping_cart') is None: request.session['shopping_cart'] = {'items': []} return self.get_response(request) I now need to modify the template context so that my templates can have access to certain information about the shopping cart (number of items, etc). I looked at context processors, but context processors are not able to view the session or even the current context. I tried using the process_template_response hook like so: def process_template_response(self, request, response): response.context_data['cart_num_items'] = len(request.session['shopping_cart']['items']) return response but apparently when the hook is executed, response.context_data is None. Does anyone know how to edit the template context with middleware? Any help would be appreciated. -
time displayed is wrong in Django template
I am trying to create a face detection program that will detect a face and log the time it was detected in. I created a Django template and am trying to display the time on the template. But the time it is displaying is wrong. To double check, I tried printing the current time separately in a different python program. That displays the time correctly. This is code for displaying the time in the Django template (info.html) views.py import datetime def detect(request): global now now = datetime.datetime.now() def info(request): return render(request, 'info.html', {'entry_time':now}) this is code I used in the separate python file import datetime print(datetime.datetime.now()) both the code is the same. I checked online and found this links How to get the current time in Python I also tried setting the timezone to my timezone (Asia/Kolkata) according to this link Is there a list of Pytz Timezones? I feel that I am not declaring the 'now' variable in the right place. Please help me out. I am new to Django Thanks in advance -
How to get all the post in the same category in Django
I'm coding a news website.I have 'category' in News model. Now I want to get all the news in one of the categories named 'opinion'. But get: invalid literal for int() with base 10: 'opinion' here is part of my model: class News(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name="cate", blank=True, verbose_name='分类') here is part of my view: class NewsView(View): def get(self, request): opinion_news = News.objects.filter(category="opinion") return render(request, 'index.html', { 'opinion_news': opinion_news, }) here is part of my index.html {% for opinion in opinion_news %} <li class="media"> <h>{{opinion.title}}</h> </li> {% endfor %} Any friend can help?Thank you so much! -
How to fix the future >= 0.15.2 distribution not found
On fedora 27 when i put cookiecutterhttps://github.com/pydanny/cookiecutter-django on terminal i get File "/usr/bin/cookiecutter", line 6, in from pkg_resources import load_entry_point File "/usr/lib/python3.6/site-packages/pkg_resources/init.py", line 3038, in @_call_aside File "/usr/lib/python3.6/site-packages/pkg_resources/init.py", line 3022, in _call_aside f(*args, **kwargs) File "/usr/lib/python3.6/site-packages/pkg_resources/init.py", line 3051, in _initialize_master_working_set working_set = WorkingSet._build_master() File "/usr/lib/python3.6/site-packages/pkg_resources/init.py", line 657, in _build_master ws.require(requires) File "/usr/lib/python3.6/site-packages/pkg_resources/init.py", line 971, in require needed = self.resolve(parse_requirements(requirements)) File "/usr/lib/python3.6/site-packages/pkg_resources/init.py", line 857, in resolve raise DistributionNotFound(req, requirers) pkg_resources.DistributionNotFound: The 'future>=0.15.2' distribution was not found and is required by cookiecutter -
Django Selenium "live_server_url" convert to string
I'm trying to test that my links get me to the correct pages. I was using the 'assertRegex' which seemed to work until I wanted to get to my home page('/'). It passed(for obvious reasons) when it should have failed. I now want to use 'assertEqual'(I think), but I am running into a problem: I can't get a string out of live_server_url. So that leaves me searching for an answer to one of two questions: How can I get a string out of live_server_url to test that my links go to the correct url? Is there a different self.assert I should be using in my functional test to check correct url? function_test.py (what I currently have) class FunctionTest(FunctionalTest): # child of LiveServerTestCase def test_links(self): self.browser.get(self.live_server_url) # He clicks on the 'Products' link and it takes him to the # products page. Under the navbar to the left is a heading that # says 'Products'. products_link = self.browser.find_element_by_link_text( 'Products').click() products_url = self.browser.current_url # replace this with something more accurate self.assertRegex(products_url, '/products/') -
Using Djnago-Channels with django rest-Framework in the creation of mobile application
I already have a project writen in Djnago and I am able to use the django rest framework well with it. This project is actually based on django-oscar and I implemented some other features. I am now in the middle of working with the mobile version of this application and I am in need of realtime server updates like Sockets and I am aware of djnago channels. My question now is this, Is it possible to link django-rest framework with django-channels because if for example a user makes a purchase on the mobile app, the number of available products should decrease in real-time or if a user adds a product to cart the user should be a able to get an increased number of items immediately reflected witha notification badge and I feel this can be achieved by django channels. So how can I relate the rest API to django channels -
Django Modelform doesn't accept selection on POST
The dropdown list appears correctly in the html, However I am unable to figure out why I run into the same error time after time when I try to submit / . "Select a valid choice. That choice is not one of the available choices." the problem context I have two models defined in Django. One CourseModel database to hold all the offered courses and one registration database to link a course to a user. models.py from django.db import models # Create your models here. class CourseModel(models.Model): course = models.CharField(max_length=100) date = models.DateField(max_length=100) time = models.TimeField() location = models.CharField(max_length=100) datetime = models.DateTimeField() class RegistrationModel(models.Model): name = models.CharField(max_length=100) adress = models.CharField(max_length=100) city = models.CharField(max_length=100) email = models.EmailField(max_length=100) course = models.ForeignKey('self', on_delete=models.CASCADE) def __str__(self): return self.name I use modelForm to create a registration form, where the user can subscribe for a course from a dropdown list. forms.py from django.forms import ModelForm, RegexField from home.models import RegistrationModel, CourseModel from django import forms import datetime class RegistrationForm(ModelForm): def __init__(self, *args, **kwargs): super(RegistrationForm, self).__init__(*args, **kwargs) self.fields['course'].queryset = CourseModel.objects.exclude(date__lt=datetime.datetime.today()).values_list('datetime', flat=True) self.fields['course'].empty_label = None class Meta: model = RegistrationModel fields = '__all__' views.py from django.shortcuts import render, redirect from home.forms import RegistrationForm from .models import CourseModel import …