Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why I see no Django log in git-bash?
I am using Python 3's print to log from Django dev server. I should mention that I also tried to configure Django to use the Python logger but without much luck. I am using pipenv run but the same happens when I activate the virtual env using pipenv shell. I have a very simple view: from django.shortcuts import render def index(request): print('Printing to the console from myapp.views.index') return render(request, 'myapp/index.html', { 'message': 'Hello, World!' }) While everything works perfectly fine in cmd.exe, git-bash does not display any output from my custom logging. See image below. Why is that? Does it have to deal with the fact that one console is considered a terminal (tty) and the other is not? -
Django to create a website that performs various analytics using a document?
I am new to Django and I created a website which show the frequent word count in a given document(.pdf, .word) in views.py using chart.js as a bar chart. So, my question is I want to create multiple tabs which uses the same file and perform some analysis like text summarization, NER(I do have code for that) and return the result in another tabs. The problem I am facing here is when I return the value of a function in views.py and input that value in a html file it can take the data and I can create bar charts, so when I create another function(so that I can input this function's value in another tab as I previously mentioned) and add a new jquery block it says two jquery blocks are not allowed. What might be the issue and is there any process to create a django website to perform various analytics using a single document. Thanks in advance! -
Can I filter listview in DRF with different URL patterns?
I currently have /items/ point to the listview of all Item objects and a detailview also. I have done this using ViewSets. Is it possible for me to get /items/category/ to display list of items in that category? Is it possible for me to get /items/category/subcategory/ to display list of items in that subcategory? I want to do the above using ViewSets and Routers only. -
Urls config in django-registration in Django
I am newbie Django dev, I have a bit problem about urls config. I want to make url http://localhost:8000/user-auth/register/ In my project, there is user_auth app with below urls: from django.conf.urls import url from . import views urlpatterns = [ url(r'^register$', views.register), ] </pre> In register this url within urls in my site: from django.conf.urls import include, url from django.contrib import admin from django.urls import path urlpatterns = [ path('admin/', admin.site.urls), url(r'^polls/', include('polls.urls')), url(r'^user-auth/', include('user_auth.urls')), ] In my view user_auth/views.py: from django.shortcuts import render from django.http import HttpResponse from .forms import RegisterForm def register(request): if request.method == 'POST': response = HttpResponse() response.write("<h1>Thanks for registering</h1></br>") response.write("Your username:" + request.POST['username']) response.write("Your email" + request.POST['email']) return response registerForm = RegisterForm() return render(request, 'user_auth/register.html', {'form':registerForm}) In my user_auth/forms.py from django import forms class RegisterForm(forms.Form): username = forms.CharField(label='Username', max_length=100) password = forms.CharField(widget=forms.PasswordInput) email = forms.EmailField(label='Email') When I access to the link http://localhost:8000/user-auth/register/, the console announce "Not Found: /user-auth/register/". I dont know reason why and where. Could you please help me on this problem?. Tks -
Django Value Error attempted import beyond top level
I'm trying to run a suite of tests for a django project I've been brought into. Running the tests in my Power Shell environment using python manage.py test --settings=tRecorderApi.settings_test returns the following output: Creating test database for alias 'default'... DEBUG 2018-03-26 09:05:56,124 base 276900 275184 Configuring Raven for host: http://sentry:9000 EEEEEEEEEEEEEEEE ====================================================================== ERROR: file_transfer (unittest.loader._FailedTest) ---------------------------------------------------------------------- ImportError: Failed to import test module: file_transfer Traceback (most recent call last): File "C:\Program Files (x86)\Python36-32\lib\unittest\loader.py", line 462, in _find_test_path package = self._get_module_from_name(name) File "C:\Program Files (x86)\Python36-32\lib\unittest\loader.py", line 369, in _get_module_from_name __import__(name) File "C:\Users\dipinton\tE-backend\tRecorderApi\api\file_transfer\__init__.py", line 1, in <module> from .FileUtility import * File "C:\Users\dipinton\tE-backend\tRecorderApi\api\file_transfer\FileUtility.py", line 12, in <module> from ..models.language import Language ValueError: attempted relative import beyond top-level package ====================================================================== ERROR: models (unittest.loader._FailedTest) ---------------------------------------------------------------------- ImportError: Failed to import test module: models Traceback (most recent call last): File "C:\Program Files (x86)\Python36-32\lib\unittest\loader.py", line 462, in _find_test_path package = self._get_module_from_name(name) File "C:\Program Files (x86)\Python36-32\lib\unittest\loader.py", line 369, in _get_module_from_name __import__(name) File "C:\Users\dipinton\tE-backend\tRecorderApi\api\models\__init__.py", line 1, in <module> from .book import Book File "C:\Users\dipinton\tE-backend\tRecorderApi\api\models\book.py", line 4, in <module> class Book(models.Model): File "C:\Program Files (x86)\Python36-32\lib\site-packages\django\db\models\base.py", line 118, in __new__ "INSTALLED_APPS." % (module, name) RuntimeError: Model class models.book.Book doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. ---------------------------------------------------------------------- Ran … -
"django.db.utils.ProgrammingError: relation "auth_user" does not exist" Django V2.0
I've recently upgraded Django to V2.0 and I'm unable to make migrations due to the following error: django.db.utils.ProgrammingError: relation "auth_user" does not exist I know a similar bug existed in V1.8 which I fixed by migrating the model which others depend on, i.e. auth_user and then the rest: python manage.py migrate auth python manage.py migrate When I try to migrate 'auth' I encounter the same error. Has anybody encountered/found a solution to this? -
django rest ImportError
as you see in provided image i have app named academy in the academy folder i have middleware folder. in one of my mcustom middleware file i want work with a model (manager model you can see in image) in my custom middleware when i import model like this: from academy.api.v1.manager.models import UserViewControll i get this error : from academy.api.v1.manager.models import UserViewControll ImportError: No module named 'academy.api' The above exception was the direct cause of the following exception: ... why? -
Django "NULLS LAST" for creating Indexes
Django 1.11 and later allow using F-expressions for adding nulls last option to queries: queryset = Person.objects.all().order_by(F('wealth').desc(nulls_last=True)) However, we want to use this functionality for creating Indexes. A standard Django Index inside a model definition: indexes = [ models.Index(fields=['-wealth']), ] I tried something along the lines of: indexes = [ models.Index(fields=[models.F('wealth').desc(nulls_last=True)]), ] which returns AttributeError: 'OrderBy' object has no attribute 'startswith'. Is this possible to do using F-expressions in Django? -
Django: resend activation link view
I am trying to put a link on the login page for "Resend Activation Link" the template for resend activation link is as below: {% extends 'base.html' %} {% block title %}Forgot Your Password?{% endblock %} {% block content %} <h1>Resend Account Activation</h1> <p>Enter your email address below, and we'll email the activation link.</p> <form method="POST"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Send me instructions!"> </form> </div> {% endblock %} I have used the built in accounts/password_reset/ for password_reset. How to create the view for resend activation email. HOw can use the similar code for password_reset and use for resend_activation email i have the following code for sending activation link when first time some one signs up. def signup(request): if request.method == 'POST': print("inside post") form = MyUserCreationForm(request.POST) if form.is_valid(): print("form.is_valid()") user = form.save(commit=False) user.is_active = False user.save() current_site = get_current_site(request) subject = 'Activate Your MySite Account' message = render_to_string('account_activation_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)).decode(), 'token': account_activation_token.make_token(user), }) user.email_user(subject, message) return redirect('account_activation_sent') else: print("else") form = MyUserCreationForm() print("ending before render") return render(request, 'signup.html', {'form': form}) and class MyUserCreationForm(UserCreationForm): class Meta(UserCreationForm.Meta): model = User fields = ("email",) and path('signup/', views.signup, name='signup'), -
How to use Cython for Django?
I am new to Django development. I am trying to use cython for my django app. But I couldn't find any relevant pages or sites to do so. Can anyone help me in this? Thanks !!! -
Can't remove Actions field from admin panel
I am using django-inline-actions==1.3.0 and django==1.11.2 and I can't remove 'Actions' from admin panel. I removed 'Actions' column with inline_actions = None but I have still 'Actions' field, after click on detail. class ConcertAdmin(InlineActionsModelAdminMixin, ExportMixin, TranslationAdmin): model = models.Concert inline_actions = None change_form_template = 'admin/import_export/change_form.html' list_display = ('title', 'date', 'text', 'image', 'flag') I tried also with exclude = ('actions', ) and nothing. -
django different interfaces for different users
I have a model user2 with a one to one field with the user model, user2 has an additional field user_type where it could be "etud", "ensg" "chef" or "tech". what I would like to do is to serve each type of users a different version of the site, currently what I'm doing is that I have everything on one page, then I check the user type for some specific HTML tags, and I'm doing this for all the site pages. so, how would I do something like that ? and is the method i'm using the best way ? -
How to check a password in Django with LDAP?
I have a django page when users have to type again his password to confirm an action. The user is already on (logged), but to do this action he must "sign" confirming his password. Users are authenticating with LDAP (Active Directory). I tried to use something like that but it always return false, even when password is correct: def check_password(request): """This method will compare logged user password with typed password""" password = request.POST.get('password', None) user = request.user.username result = request.user.check_password(password) if result: return JsonResponse({'status': 'true'}) else: return JsonResponse({'status': 'false'}) Django Version: 2.0.2 Python: 3.6.x Someone can help me? Thank you in advance. -
In search form using haystack in django, results are not returned
Currently, I made search system in a blog by Django using Solr and haystack. However, if I inputted search word in the search form, it displays all "There are no results for your query", even if I search the word which has a possibility to hit in the result. ---version---- django 2.0.1 python 3.6 solr 7.2.1 haystack 2.8.0 base.html <form action="/search/" method="GET"> <input id="search" type="TEXT" name="query" value="{{ s_form }}"> <button type="SUBMIT" class="btn btn-primary">SEARCH</button> </form> view.py def post_search(request): s_form = SearchForm() cd = results = total_results = None if 'query' in request.GET: s_form = SearchForm(request.GET) if s_form.is_valid(): cd = s_form.cleaned_data results = SearchQuerySet().models(Post).filter(content=cd['query']).load_all() # count total results total_results = results.count() return render(request, 'post/search.html', {'form': s_form, 'cd': cd, 'results': results, 'total_results': total_results}) search.html(result) {% if "query" in request.GET %} <h1 class="mt-4">Posts containing "{{ cd.query }}"</h1> <h3 class="mt-4">Found {{ total_results }} result{{ total_results|pluralize }}</h3> {% for result in results %} {% with post=result.object %} <h4 class="mt-4"><a href="{{ post.get_absolute_url }}">{{ post.title }}</a></h4> {{ post.body|truncatewords:5 }} {% endwith %} {% empty %} <p>There are no results for your query.</p> {% endfor %} {% else %} {% endif %} I can get query by accessing http: // localhost: 8983 with solr. (I can get response corresponding … -
Raise validation error on parent form in Django
Let's say I have this form: from django import forms from django.core.exceptions import ValidationError class NameForm(forms.form): name = forms.CharField(max_length=200) class NameAgeForm(NameForm): age = forms.IntegerField() def clean(self): data = self.cleaned_data if data.get('age') == 24 and name == 'Nebu': raise ValidationError({'name': "You can't pick that name and age, they are mine!"}) The thing is, i have a sub-form where validation is happening. But i want my field error being shown at the parent form. Sidenote I can't access the parent form and therefor the solution must come from the child. Now, is this possible? -
How to modify get_queryset result value
I am trying to modify my get_queryset result Here is my my filter, view and serializer view.py class AccountDetailFilter(filters.FilterSet): product_key = filters.CharFilter(name='product__product_name') account_name = filters.AllValuesFilter(name='account__account_key') service_provider_name = filters.CharFilter(name='product__service_provider__service_provider_name', ) allocation_key = filters.CharFilter(name='account__account_allocation__allocation_key') class Meta: model = BillingLine fields = ('product_key', 'account_name', 'service_provider_name', 'allocation_key') class AccountDetailList(generics.ListAPIView): serializer_class = BillingSerializer filter_backends = (DjangoFilterBackend,) filter_class = AccountDetailFilter def get_queryset(self): now = datetime.datetime.now() start_date = self.kwargs.get('start_date_time', now) end_date = self.kwargs.get('end_date_time', now) serializer = BillingSerializer(data={'start_date': start_date, 'end_date': end_date}) serializer.is_valid(raise_exception=True) queryset = BillingLine.objects.select_related().filter(start_date__gte=start_date, end_date__lte=end_date) queryset = queryset.order_by('-id') print(queryset.count()) return queryset Serializers.py class BillingSerializer(serializers.Serializer): id = serializers.IntegerField(read_only=True) start_date = serializers.DateTimeField() end_date = serializers.DateTimeField() account_key = serializers.CharField(source='account_id',required=False) product_key = serializers.CharField(source='product_id',required=False) total_amount = serializers.FloatField(required=False) After retrieving the result(ie get_queryset), I need to modify/add the data in the result . Is there any way to do this . Also can we get the other field values to serializers from the result queryset. Because the queryset = BillingLine.objects.select_related().filter(start_date__gte=start_date, end_date__lte=end_date) is returning the almost all the data (sepecifally product name which is from products table) -
NoReverseMatch from url tag inside include tag
I am trying to render a link inside an include html template with the url tag. I have done this before and usually it works, but for some reason this time I can't make it. I get a NoReverseMatch Error and suspect its because Django tries to load the url tag first but my object isn't ready, so the pk is empty. I believe that because it takes a moment until the dynamic data loads, while the static is already loaded. The url works if I set pk to a fixed number, but I would like it to change dynamically. Error: Reverse for 'transaction' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['en/budget/account\\/(?P<pk>[0-9]+)\\/$'] Relevant urls: from django.urls import path from django.contrib import admin from django.contrib.auth import views as auth_views from . import views app_name='budgetapp' urlpatterns = [ path('', views.index, name='index'), path('account/<int:pk>/', views.transaction, name='transaction'), path('account/', views.account, name='account'), ] Relevant views: from django.shortcuts import get_object_or_404, render, redirect from django.contrib.auth.models import Group from django.contrib.auth.decorators import login_required, user_passes_test from .models import * from .forms import * def index(request): context = {} context['accounts'] = Account.objects.filter(author=request.user) return render(request, 'budgetapp/index.html', context) def account(request): context = {} context['account'] = get_object_or_404(Account, pk = request.POST['accountPk']) return render(request, 'budgetapp/account.html', … -
upgrading django webtest 1.7.8 to 1.9.2
Background: I am trying to upgrade django-webtest to 1.9.2 as my previous version 1.7.8 does not supports django 1.11. so i upgraded django webtest and my test cases started failing with 3 type of errors. the problem: self.app.get(self._URL, {'q': 'AppD', 'company': 'AppDynamics'}, user=user) failed with error "TypeError: get() takes exactly 2 argument" I tried with these self.app.get(self._URL, {'q': 'AppD', 'company': 'AppDynamics', 'user':user) and then as self.app.get(self._URL, {'q': 'AppD', 'company': 'AppDynamics'}, extra_environ=dict(REMOTE_USER=user)) but still they failed. similarly i tried for self.app.post(URL, dict) can any one point me to examples for django-webtest, i did not found the docs sufficient as doing exactly like same did not provided me with any results. -
Django email not working - smtplib.SMTPServerDisconnected: Connection unexpectedly closed
I'm using the standard Django/SendGrid setup for sending emails. Here's the relevant fields in my settings.py: EMAIL_HOST = 'smtp.sendgrid.net' EMAIL_HOST_USER = 'myusername' EMAIL_HOST_PASSWORD = 'mypassword' EMAIL_PORT = 465 EMAIL_USE_SSL = True DEFAULT_FROM_EMAIL = 'admin@mysite.com' I'm testing sending emails in my shell by executing: send_mail('test','test','email@email.com',['to@email.com']) however, it returns this error Traceback: Traceback (most recent call last): File "<console>", line 1, in <module> File "/Users/zorgan/Desktop/app/lib/python3.5/site-packages/django/core/mail/__init__.py", line 62, in send_mail return mail.send() File "/Users/zorgan/Desktop/app/lib/python3.5/site-packages/django/core/mail/message.py", line 348, in send return self.get_connection(fail_silently).send_messages([self]) File "/Users/zorgan/Desktop/app/lib/python3.5/site-packages/django/core/mail/backends/smtp.py", line 104, in send_messages new_conn_created = self.open() File "/Users/zorgan/Desktop/app/lib/python3.5/site-packages/django/core/mail/backends/smtp.py", line 71, in open self.connection.login(force_str(self.username), force_str(self.password)) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/smtplib.py", line 720, in login initial_response_ok=initial_response_ok) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/smtplib.py", line 630, in auth (code, resp) = self.docmd("AUTH", mechanism + " " + response) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/smtplib.py", line 420, in docmd return self.getreply() File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/smtplib.py", line 393, in getreply raise SMTPServerDisconnected("Connection unexpectedly closed") smtplib.SMTPServerDisconnected: Connection unexpectedly closed Any idea why I'm getting this error? -
CSS not loading wrong MIME type Django when DEBUG = False
I'm using Django 2.02 and when i use runserver with DEBUG = True, it worked well but when I config the settings.py DEBUG = True ALLOWED_HOSTS = ['127.0.0.1', 'localhost'] I get this error in browser: Resource interpreted as Stylesheet but transferred with MIME type text/html: "http://localhost:8000/static/css/main.95aaf39b.css". I tried this solution: CSS not loading wrong MIME type Django but this not worked. -
inspectdb command crashes when generate model classes from postgres db
when executing inspectdb > modelys.py , i'm getting the following error. I searched for solution but i cant find anything. More over i dont know what this error really mean. (gathiApiVirtualEnv) G:\GathiCatalog\dev\gathiApi\gathi_api>python manage.py inspectdb >models.py Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "G:\GathiCatalog\dev\gathiApi\gathiApiVirtualEnv\lib\site-packages\django\core\management\__init__.py", line 371, in execute_from_c ommand_line utility.execute() File "G:\GathiCatalog\dev\gathiApi\gathiApiVirtualEnv\lib\site-packages\django\core\management\__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "G:\GathiCatalog\dev\gathiApi\gathiApiVirtualEnv\lib\site-packages\django\core\management\base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "G:\GathiCatalog\dev\gathiApi\gathiApiVirtualEnv\lib\site-packages\django\core\management\base.py", line 335, in execute output = self.handle(*args, **options) File "G:\GathiCatalog\dev\gathiApi\gathiApiVirtualEnv\lib\site-packages\django\core\management\commands\inspectdb.py", line 28, in handl e for line in self.handle_inspection(options): File "G:\GathiCatalog\dev\gathiApi\gathiApiVirtualEnv\lib\site-packages\django\core\management\commands\inspectdb.py", line 163, in hand le_inspection for meta_line in self.get_meta(table_name, constraints, column_to_field_name): File "G:\GathiCatalog\dev\gathiApi\gathiApiVirtualEnv\lib\site-packages\django\core\management\commands\inspectdb.py", line 273, in get_ meta tup = '(' + ', '.join("'%s'" % column_to_field_name[c] for c in columns) + ')' File "G:\GathiCatalog\dev\gathiApi\gathiApiVirtualEnv\lib\site-packages\django\core\management\commands\inspectdb.py", line 273, in <gen expr> tup = '(' + ', '.join("'%s'" % column_to_field_name[c] for c in columns) + ')' KeyError: 'prj_id' -
Could not resolve URL for hyperlinked relationship using view name "restaurant-detail"
im getting error Could not resolve URL for hyperlinked relationship using view name "shop-detail" in file shop/api/urls.py router = routers.DefaultRouter() router.register('shops', ShopView, base_name='shop') urlpatterns = [ path('', include(router.urls)),] file shop/api/serializers.py class ShopSerializer(serializers.HyperlinkedModelSerializer): url = serializers.HyperlinkedIdentityField( view_name="shop-detail", lookup_field='id',) class Meta: model = Shop fields = [ 'id', 'url', 'name', ] what is wrong there? everything works if I dont add 'url' field. -
Django ModelForm.save() not working
I'm trying to add a comment to a database through a ModelForm but then the website just refreshes and nothing is actually saved in DB (confirmed it on the admin page). Also manually adding a comment through admin page works fine, so the problem probably lies in form mechanics. form class CommentForm(ModelForm): class Meta: model = Comment exclude = ['episode'] model class Comment(models.Model): autor = models.CharField(max_length=30) text= models.TextField(default='') data = models.DateField(auto_now_add=True) episode= models.ForeignKey(Episode, on_delete='Cascade', related_name='comments') view def episode(request, numer): episode = Episode.objects.get(numer=numer) comments = Comment.objects.all() if not request.method == 'POST': form = CommentForm() if request.method == 'POST': form = CommentForm(data=request.POST) if form.is_valid(): new_comment = form.save(commit=False) new_comment.episode= episode new_comment.save() I know there are some similar topics already, but none of them actually solves my issue. Also didnt find any mistakes according to the docummentation. -
Retrieve all static images in django
In my django app I have a javascript modal.In that modal I want to display all the available static images.I know if there is a single image we can display it as {% load static %} <img src="{% get_static_prefix %}images/abc.png"> But I want to display all the images(they are not fixed) dynamically.How can I write a loop for that. My desired output (the loop should generate this output) {% load static %} <img src="{% get_static_prefix %}images/abc.png"> <img src="{% get_static_prefix %}images/def.png"> <img src="{% get_static_prefix %}images/ghi.png"> . . . <img src="{% get_static_prefix %}images/xyz.png"> -
In django, how can I update a batch sessions without request?
I want to update a batch of django sessions and create fields for django session so that I can put a list in each session. 1、how can I visit these sessions by clue of fields(like user id\phoneNO etc) without request ? 2、how can I set format of sessions before request?