Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there a quick way to grab a the ending of current page url? Django
I have a page. www.example.com/chat/testuser I want to grab the username (testuser). I'm doing this within the template in order to pass along in an ajax call. Is there a simple way? Something like {{ request.path }} (this returns full path). -
Email cannot be sent in Python.[Errno 61] Connection refused error happens
Email cannot be sent in Python.I want to send an email by using Gmail. I wrote codes in views.py like def mail(mail_adress, docx): msg = MIMEMultipart() msg["Subject"] = "TEST" msg["From"] = settings.EMAIL_HOST_USER msg["To"] = email message = "TEST" body = MIMEText(message) msg.attach(body) mime = {'type': 'text', 'subtype': 'docx'} attach_file = {'name': 'test.docx', 'path': '/Users/test.docx'} attachment = MIMEBase(mime['type'], mime['subtype']) file = open(attach_file['path'], 'rb') attachment.set_payload(file.read()) file.close() encoders.encode_base64(attachment) msg.attach(attachment) attachment.add_header("Content-Disposition", "attachment", filename=attach_file['name']) return msg def send(from_addr, to_addrs, msg): smtp = smtplib.SMTP() smtp.connect() from_addr = 'xxxx@gmail.com' from_addr_name = "test" to_addr= "yyyyy@gmail.com" subject = u"test" message = "test" body = MIMEText(message) mime = {'type': 'text', 'subtype': 'docx'} attach_file = {'name': 'test.docx', 'path': '/Users/test.docx'} msg = mail(from_addr, from_addr_name, to_addr, subject, body, mime, attach_file) smtp.sendmail(from_addr, to_addrs, msg) smtp.close() send() in settings.py EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'xxxx@gmail.com' EMAIL_HOST_PASSWORD = 'xxxxxxxxx' EMAIL_USE_TLS = True When I run the codes, [Errno 61] Connection refused error happens.Traceback says Traceback (most recent call last): File "/Users/xxxx/anaconda3/envs/py36/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/Users/xxxx/anaconda3/envs/py36/lib/python3.6/site-packages/django/core/handlers/base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/xxxx/anaconda3/envs/py36/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/xxxx/Downloads/legal_doc_mail/common/views.py", line 400, in make_document send() File "/Users/xxxx/Downloads/legal_doc_mail/common/views.py", line 454, in send smtp.connect() … -
Two annotations in a single query
I am trying to build a query set to do a count, the query set involves three models. class Owner(models.Model): name = models.Charfield(max_length=10, null=false) class Location(modes.Model): name = models.Charfield(max_length=10, null=false) tenant = models.ForeignKey(Owner, on_delete=models.SET_NULL, null=True, blank=True) class Asset(models.Model): name = models.Charfield(max_length=10, null=false) tenant = models.ForeignKey(Tenant, on_delete=models.SET_NULL, null=True, blank=True) Location = models.ForeignKey(Owner, on_delete=models.SET_NULL, null=True, blank=True) I am trying to do a count for Locations for the owner and Assets for the owner, I can achieve this as two separate Querysets as follows: locations = Owner.objects.all().annotate(locations=Count('location')) assets = Owner.objects.all().annotate(assets=Count('asset')) This works fine, but what I'm trying to do is get a single row for both values and build a table similar to the one below. | Owner | Assets | Locations | |--------+--------+-----------| | owner1 | 10 | 3 | | owner2 | 100 | 20 | | owner3 | 70 | 50 | I've tried to put both annotations in a single query but I don't appear to get the right results, the count is either the same for both assets and location or I get very large numbers which I assume because both count operations are impacting each other. Query below gives me the same numbers for both asset and … -
django pytest splinter selenium.common.exceptions.WebDriverException: Message: unknown error: Chrome failed to start: exited abnormally
I'm trying to use pytest-bdd and pytest-splinter together. I use docker and docker-compose. It's my fixtures: @pytest.fixture(scope="session") def splinter_webdriver(): return "chrome" @pytest.fixture(scope="session") def splinter_headless(): return True And if I try to run the tests, I get the following error: E selenium.common.exceptions.WebDriverException: Message: unknown error: Chrome failed to start: exited abnormally E (unknown error: DevToolsActivePort file doesn't exist) E (The process started from chrome location /usr/lib/chromium/chrome is no longer running, so ChromeDriver is assuming that Chrome has crashed.) E (Driver info: chromedriver=2.38 (05121428cd0fc129e40a3694cf5405698236ad14),platform=Linux 4.9.122-1-MANJARO x86_64) I tried many different options, but I still could not solve the problem. Also, an obstacle in solving the problem was that I can not pass on all the options that I want. Most of the answers I find relate to the use of pure Selenium or Splinter. But I'm interested in using exactly the pytest-splinter. -
keep getting error when trying to run makemigrations locally with Django/Postgres/Heroku site
I need to be able to add models to my site and I was unable to migrate new models to heroku. I've read that the only way peope are able to do it is to run the migrations locally. Problem is I keep getting an error: ImproperlyConfigured("settings.DATABASES is improperly configured. " django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details. Would just using a different settings file, migrating, and then pushing back to heroku work? What is the best way to solve this? Here is my settings file: import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = '-////' DEBUG = True ALLOWED_HOSTS = ['djangoandreact.herokuapp.com', '127.0.0.1', 'localhost'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'corsheaders', 'rest_auth', 'rest_auth.registration', 'rest_framework', 'rest_framework.authtoken', 'articles' ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', '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 = 'djreact.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'build')], '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', ], }, }, ] WSGI_APPLICATION = 'djreact.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_ppsycopg2', 'NAME': os.path.join(BASE_DIR, 'thesite'), 'USER': 'tom', 'PASSWORD': '/////', 'HOST': 'https://djangoandreact.herokuapp.com' } } AUTH_PASSWORD_VALIDATORS = [ {'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator'}, {'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator'}, {'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator'}, {'NAME': … -
Ajax post not working for each request inside loop in django
I have a blog page. Blog's has 'comments' and comments has 'replies' as a related objects.Creating comment to blog and creating reply to comment working with ajax call. Creating comment to blog is working fine. But creating reply to comment working only first comment. I know that html should has unique id in ajax post so i used class in form instead if id. Posting reply for first comment is successfully. But posting reply for second comment ,it posted for first comment. How manage ajax call in loop request ? Here is my code: Html code: <div class="collapse" id="comment-own"> <div id="ajax"> {% for comment in comments %} <div class="comment-content"> { comment.content }} </div> <div class="comment-reply"> <div id="rep-ajax"> {% for child_comment in comment.children %} <div class="comment-content"> {{ child_comment.content }} </div> {% endfor %} </div> <form method="POST" class="new_reply"> {% csrf_token %} <input type="text" name="content" id="rep-id" class="form-control" placeholder='Write a reply...'/> <input type="hidden" name="content_type" value="post" id="id_content_type" /> <input type="hidden" name="object_id" value={{instance.id}} id="id_object_id" /> <input type="hidden" name="parent_id" value="{{comment.id}}" id="id_parent_id"> <input id="submittt" type="submit" value="Reply"/> </form> </div> {% endfor %} </div> <form method="POST" class="new_comment"> {% csrf_token %} <div id="write-comment"> <input type="text" name="content" id="id-content" class="form-control" placeholder='Write a comment...'/> <input type="hidden" name="content_type" value="post" id="id_content_type" /> <input type="hidden" name="object_id" value={{instance.id}} … -
Run Configuration Error: Please specify script name IN PyCharm
Run Configuration Error i added project interpreter but code cant run -
Django rest multiple file upload don't work
I'm trying to upload multiple files using django rest framework, i've try several time with some resources that i found in the internet, but still not working. can someone help me trying to explain to me why this is not working? PS: I just can upload one file, and this is not the purpose, I'm using postman to test the api and I'm setting the content-type as multipart too. This is my viewsets: from rest_framework.response import Response from rest_framework import viewsets from rest_framework.parsers import FormParser, MultiPartParser from rest_framework.decorators import api_view # Local app import from apps.samples.models import BucketFile from .serializers import BucketFileSerializer class BucketViewSet(viewsets.ModelViewSet): serializer_class = BucketFileSerializer parser_classes = (MultiPartParser, FormParser,) queryset = BucketFile.objects.all And this is my serializers: import os from rest_framework import serializers # Local app import from apps.samples.models import BucketFile class BucketFileSerializer(serializers.ModelSerializer): class Meta: model = BucketFile fields = ("name", "analyse") -
Unable to return serializer class in django reset framework
I am developing a Web API using the Django REST framework. I am new to Django and Python. The problem I am having now is that I cannot return the serializer class. Please, see my code below. This is my project structure I created quickstart/serializers.py with the following definition from django.contrib.auth.models import User, Group from rest_framework import serializers class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ('url', 'username', 'email', 'groups') class GroupSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Group fields = ('url', 'name') This is my quickstart/views.py definition from django.shortcuts import render # Create your views here. from django.contrib.auth.models import User, Group from rest_framework import viewsets from quickstart.serializers import UserSerializer, GroupSerializer class UserViewSet (viewsets.ModelViewSet): queryset = User.objects.all().order_by('-date_joined') serializer_class = UserSerializer class GroupViewSet(viewsets.ModelViewSet): queryset = Group.objects.all() serializer_class = GroupSerializer This is the definition of quickstart/urls.py from django.urls import path from quickstart import views urlpatterns = [ path('users/', views.UserViewSet) ] This is the urls.py inside the secondly red-lined folder from django.contrib import admin from django.urls import path from django.conf.urls import url, include from quickstart import views from rest_framework import routers urlpatterns = [ path('admin/', admin.site.urls), path('', include('quickstart.urls')) ] When I access to this url (http://127.0.0.1:9191/users/) in the browser, I get this error. TypeError … -
Django AJAX Request Only Getting Last Element (not getlist issue)
I'm trying to make a tagging system in Django. Basically I'm passing through a list of tags (checkboxes in a form) through AJAX to a Django view which will update the list of tags with a new selection of relevant tags in an httpresponse. The problem is that Django only seems to be receiving the last element of the list on its own even after getlist. In fact, if I print the entire request.GET, it shows just one element in each list. The javascript/jQuery code is here: $(document).on('change', '.form-check-input',function () { var all_tags = $("input:checkbox").map(function() { return this.id; }).get(); var selected_tags = $("input:checkbox:checked").map(function() { return this.id; }).get(); alert(all_tags); alert(selected_tags); $.ajax({ url: "{% url 'AJAX_tagFilter' %}", data: { 'all_tags': all_tags, 'selected_tags': selected_tags }, cache: false, type: 'GET', success: function (data) { alert(selected_tags); $('#test').html(data); console.log('success'); } }); }); And I did a couple of alerts so that I can see what is being passed is correct at each stage. I see all the tags I expect it to. 12,13,21,16,17,15,11,7,18 12,13 But when it gets to the Django view: def getTagFilterSidebar(request): if 'selected_tags[]' in request.GET: all_tags = request.GET.getlist("all_tags[]") selected_tags = request.GET.getlist("selected_tags[]") debug_text4 = str(request.GET) I don't see the list of tags. This is … -
Overriding get_context_data is blocking some context data going to the template
I am inheriting from CreateView to create a form for a model. class NewBlogView(CreateView): form_class = BlogForm template_name = 'blog_settings.html' def form_valid(self, form): blog_obj = form.save(commit=False) blog_obj.owner = self.request.user blog_obj.slug = slugify(blog_obj.title) blog_obj.save() return HttpResponseRedirect(reverse('home')) Here is my template code: {% extends 'base.html' %} {% block content %} <h1>Create New User</h1> <form action='' method='post'>{% csrf_token %} {{ form.as_p }} <input type='submit' value='Create Account' /> </form> {% endblock %} At this moment everything is working as expected, but when I am overriding get_context_data() my title field is disappearing. class NewBlogView(CreateView): form_class = BlogForm template_name = 'blog_settings.html' def form_valid(self, form): blog_obj = form.save(commit=False) blog_obj.owner = self.request.user blog_obj.slug = slugify(blog_obj.title) blog_obj.save() return HttpResponseRedirect(reverse('home')) def get_context_data(self, **kwargs): ctx = super(NewBlogView, self).get_context_data(**kwargs) print(ctx) I am thinking although I am running the original get_context_data() form the function that I am inheriting, there is something that is going wrong when it comes to taking the field name from the form_class. Can someone help with that confusion that I have? -
cur.execute("use scraping") eroor
I studied from python web scraping I grant all previleges to root, but the error occured Python : 3.7 and mysql server : 6.3 version... why??!!! cur.execute("USE scrapping") Traceback (most recent call last): File "", line 1, in cur.execute("USE scrapping") File "C:\Users\XXX\AppData\Local\Programs\Python\Python37\lib\site-packages\pymysql\cursors.py", line 170, in execute result = self._query(query) File "C:\Users\XXX\AppData\Local\Programs\Python\Python37\lib\site-packages\pymysql\cursors.py", line 328, in _query conn.query(q) File "C:\Users\XXX\AppData\Local\Programs\Python\Python37\lib\site-packages\pymysql\connections.py", line 516, in query self._affected_rows = self._read_query_result(unbuffered=unbuffered) File "C:\Users\XXX\AppData\Local\Programs\Python\Python37\lib\site-packages\pymysql\connections.py", line 727, in _read_query_result result.read() File "C:\Users\XXX\AppData\Local\Programs\Python\Python37\lib\site-packages\pymysql\connections.py", line 1066, in read first_packet = self.connection._read_packet() File "C:\Users\XXX\AppData\Local\Programs\Python\Python37\lib\site-packages\pymysql\connections.py", line 683, in _read_packet packet.check_error() File "C:\Users\XXX\AppData\Local\Programs\Python\Python37\lib\site-packages\pymysql\protocol.py", line 220, in check_error err.raise_mysql_exception(self._data) File "C:\Users\kkm\AppData\Local\Programs\Python\Python37\lib\site-packages\pymysql\err.py", line 109, in raise_mysql_exception raise errorclass(errno, errval) pymysql.err.OperationalError: (1044, "Access denied for user 'root@xxx.xxx.xxx.xxx' to database 'scrapping'") -
django model for view with multiple joins
I have a question about making a Django model for a Postgres View. My view is created in my database, and it uses joins on multiple tables. This is my view: select cp.trade_date, ins.symbol, mgr.username, pt.strategy, pt.substrategy, pos.quantity, cp.price from position pos join manager mgr on pos.manager_id = mgr.id join instrument ins on pos.instrument_id = ins.id join price cp on cp.instrument_id = ins.id and cp.trade_date = pos.trade_date join portfolio pt on pt.manager_id = mgr.id and pos.portfolio_id = pt.id Among other fields, I believe the trade_date and manager_id fields are the most confusing to me in terms of setting up the model. The field trade_date lives on the following two tables, position and price. Similarly, the manager_id field lives on the following three tables, manager, position, and portfolio. All of the tables are properly using foreign keys as described in the JOIN statements above, and I can share their Django models if desired (my models share a name with the database tables). This is how I picture the View's model (to get the trade_date field) being completed but ManyToManyField doesn't have a 'to_field' option. Both tables position and price have many records with the same trade_date. I have read about the … -
when running: from news.models import Article, Reporter getting Error: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet ---
I am new in Django and I'm practicing in this page: https://docs.djangoproject.com/en/2.1/intro/overview/ note: I'm using windows I did a virtual environment. Install django 2 Create the project call Django_Practice Did the app call experimento Install the app INSTALLED_APPS = [ 'news', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] 6.Did the model as it appear in the tutorial: from django.db import models class Reporter(models.Model): full_name = models.CharField(max_length=70) def __str__(self): return self.full_name class Article(models.Model): pub_date = models.DateField() headline = models.CharField(max_length=200) content = models.TextField() reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE) def __str__(self): return self.headline 7.then did migration --> py manage.py migrate When trying to import the news model with the Python API --> from news.models import Article, Reporter then appears this: Traceback (most recent call last): File "", line 1, in File "C:\Users\Junior\Desktop\projects\Django_Practica\experimento\news\models.py", line 3, in class Reporter(models.Model): File "C:\Users\Junior\Desktop\projects\Django_Practica\env\lib\site-packages\django\db\models\base.py", line 100, in new app_config = apps.get_containing_app_config(module) File "C:\Users\Junior\Desktop\projects\Django_Practica\env\lib\site-packages\django\apps\registry.py", line 244, in get_containing_app_config self.check_apps_ready() File "C:\Users\Junior\Desktop\projects\Django_Practica\env\lib\site-packages\django\apps\registry.py", line 127, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. this is my wsgi.py code: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "experimento.settings") application = get_wsgi_application() -
How to display datetime field with a certain format
I have a datetime field column where I use in my detail view template. I show this in my HTML page as: {{ post.created_at }} and the output is: July 15, 2018, 7:03 p.m Which is way verbose than I need it to be. I would like the following: If I posted a post 59 minutes ago, it should display as 59m If I posted a post 23 hours ago, it should display as 23h If I posted a post 6 days ago, it should display as 6d Now anything that exceeds a week's time, should be displayed as day, month, year. In the example we have above it should be: 15 Jul 18 with no time. Is there a way to accomplish this in the HTML page using Jinja? -
Not finding proper connections for Django to connect to Neo4j
I am trying to sync Neo4j database with django. But I am getting this error. I am following scholarly GIT page for Neo4django. -
Am I missing something very simple? NoReverseMatch at / for homepage/index only
I get the NoReverseMatch at / error below when I try to visit the homepage (ie localhost:8000) only. If I go to localhost/books/<slug>, there are no errors and the page displays as intended. NoReverseMatch at / Reverse for 'book_detail' not found. 'book_detail' is not a valid view function or pattern name. Request Method: GET Request URL: http://localhost:8000/ Django Version: 2.1.2 Exception Type: NoReverseMatch Exception Value: Reverse for 'book_detail' not found. 'book_detail' is not a valid view function or pattern name. Error during template rendering In template D:\Documents\django\myproject\library\templates\base.html, error at line 10 Reverse for 'book_detail' not found. 'book_detail' is not a valid view function or pattern name. Where line 10 of base.html is this: 10 <link rel="stylesheet" href="{% static 'css/style.css' %}" /> Here's the relevant code: urls.py from django.contrib import admin from django.urls import path from library import views urlpatterns = [ path('', views.index, name='home'), path('books/<slug>/', views.book_detail, name='book_detail'), path('admin/', admin.site.urls), ] views.py from django.shortcuts import render from library.models import Book def index(request): books = Book.objects.all() return render(request, 'index.html', { 'books': books, }) def book_detail(request, slug): book = Book.objects.get(slug=slug) return render(request, 'books/book_detail.html', { 'book': book, }) models.py from django.db import models class Book(models.Model): name = models.CharField(max_length=255) description = models.TextField() slug = models.SlugField(unique=True) … -
Custom method for unlimited *args with set() function usage?
I am working on some project, and we have lots of some code usage like this; # filtering fields are different from each other, please ignore the similarity below def function1(self, param): list_x = Model1.objects.filter(foo=bar, bla=bla).values_list('field', flat=True) list_y = Model2.objects.filter(foo=bar, bla=bla).values_list('field', flat=True) lists_to_delete = set(list_x) - set(list_y) # here is the code line with set() that needed to be method self._delete(lists_to_delete) def function2(self, param): list_z = Model3.objects.filter(foo=bar, bla=bla).values_list('field', flat=True) list_q = Model4.objects.filter(foo=bar, bla=bla).values_list('field', flat=True).distinct() list_w = Model5.objects.filter(foo=bar, bla=bla).values_list('field', flat=True) lists_to_delete = set(list_x) - set(list_y) - set(list_w) # here is the code line with set() that needed to be method self._delete(lists_to_delete) ... # other functions continues like above ... ... So, as you can see we have same usage with set() function. And I need to change this usage with custom method. I tried to write a method like this; def _get_deleted_lists(self, *args): value = set() for arg in args: value |= set(arg) return value and usage will be change like; lists_to_delete = self._get_deleted_lists(list_x, list_y, ...) instead of this; lists_to_delete = set(list_x) - set(list_y) But my custom method not return same value as before. How can I achieve this? -
Better Alternate instead of using chained union queries in Django ORM
I needed to achieve something like this in Django ORM : (SELECT * FROM `stats` WHERE MODE = 1 ORDER BY DATE DESC LIMIT 2) UNION (SELECT * FROM `stats` WHERE MODE = 2 ORDER BY DATE DESC LIMIT 2) UNION (SELECT * FROM `stats` WHERE MODE = 3 ORDER BY DATE DESC LIMIT 2) UNION (SELECT * FROM `stats` WHERE MODE = 6 ORDER BY DATE DESC LIMIT 2) UNION (SELECT * FROM `stats` WHERE MODE = 5 AND is_completed != 3 ORDER BY DATE DESC) # mode 5 can return more than 100 records so NO LIMIT here for which i wrote this : query_run_now_job_ids = Stats.objects.filter(mode=5).exclude(is_completed=3).order_by('-date') list_of_active_job_ids = Stats.objects.filter(mode=1).order_by('-date')[:2].union( Stats.objects.filter(mode=2).order_by('-date')[:2], Stats.objects.filter(mode=3).order_by('-date')[:2], Stats.objects.filter(mode=6).order_by('-date')[:2], query_run_now_job_ids) but somehow list_of_active_job_ids returned is unordered i.e list_of_active_job_ids.ordered returns False due to which when this query is passed to Paginator class it gives : UnorderedObjectListWarning: Pagination may yield inconsistent results with an unordered object_list I have already set ordering in class Meta in models.py class Meta: ordering = ['-date'] Without paginator query works fine and page loads but using paginator view never loads it keeps on loading . Is there any better alternate for achieving this without using chain of union . So I … -
Json is not serializable in django
def ajax_leave_type_data(request): pk = request.GET.get('id', None) is_taken= Leave_Types.objects.filter(user_id=pk) return HttpResponse(json.dumps(is_taken), content_type='application/json') Thats the error i am getting everytime please give some solution if anyone face this problem before i tried many ways but unable to solve this Thanks in advance Internal Server Error: /ajax/leave_ty Traceback (most recent call last): File "/mnt/e/Leave_Management/venv/lib/python3.5/site-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/mnt/e/Leave_Management/venv/lib/python3.5/site-packages/django/core/handlers/base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "/mnt/e/Leave_Management/venv/lib/python3.5/site-packages/django/core/handlers/base.py", line 126, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/mnt/e/L_Management/Leave_Management_App/views.py", line 209, in ajax_leave_type_data return HttpResponse(json.dumps(is_taken), content_type='application/json') File "/usr/lib/python3.5/json/__init__.py", line 230, in dumps return _default_encoder.encode(obj) File "/usr/lib/python3.5/json/encoder.py", line 198, in encode chunks = self.iterencode(o, _one_shot=True) File "/usr/lib/python3.5/json/encoder.py", line 256, in iterencode return _iterencode(o, 0) File "/usr/lib/python3.5/json/encoder.py", line 179, in default raise TypeError(repr(o) + " is not JSON serializable") TypeError: <QuerySet [<Leave_Types: Casual leaves>, <Leave_Types: Unpaid leaves>, <Leave_Types: Privilege leaves>, <Leave_Types: Sick leaves>]> is not JSON serializable [13/Oct/2018 17:07:20] "GET /ajax/leave_ty?id=52&csrfmiddlewaretoken=3Fxb3n2PBMRSYWOgPLgRSWZzvQANFiFLTDihrZJ0HklK02YPU39C7eSGY5su7QKX HTTP/1.1" 500 15445 -
Authenticating user problem with django-tenant-schema
I want to have admin module available to tenants (using django-tenant-schema). My apps section of settings.py: # Application definition SHARED_APPS = ( 'tenant_schemas', # mandatory, should always be before any django app 'customers', # you must list the app where your tenant model resides in # 'django.contrib.sites', # everything below here is optional ) TENANT_APPS = ( 'django.contrib.contenttypes', # your tenant-specific apps 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ) INSTALLED_APPS = ( 'tenant_schemas', # mandatory, should always be before any django app 'customers', # 'django.contrib.sites', #using this will cause error - see my stackoverflow question 'django.contrib.auth', 'django.contrib.admin', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ) I have set up 2 schemas (tenant1 and public). Crated superuser and can see that superuser is created within tenant1 schema. However when trying to log in by tenant1.domain.com/admin getting login screen but after entering credentials getting ProgrammingError at /admin/login/ relation "auth_user" does not exist Looks like it is not picking up my tenant1 schema? What I have to change in configuration? -
How do I read this line given to me by django debugger? (NoReverseMatch)
There are several posts on here already about NoReverseMatch, I've read the documentation and understand why I am receiving this error (what raised it) but I'm struggling to find out how to fix it. I was originally going to post hoping someone could tell me what I'm doing wrong so I could fix it. I figured that wouldn't help me much so I instead was wondering if someone could tell me how to read this line: Reverse for 'detail' with arguments '('', 2, 1)' not found. 1 pattern(s) tried: ['projects\\/categories\\/(?P<category_slug>[-a-zA-Z0-9_]+)\\,\\ (?P<category_id>[0-9]+)\\/(?P<project_id>[0-9]+)$'] Specifically: ['projects\\/categories\\/(?P<category_slug>[-a-zA-Z0-9_]+)\\,\\ (?P<category_id>[0-9]+)\\/(?P<project_id>[0-9]+)$'] Obviously, this is a common type of syntax used by Django (and I believe programming in general) so I'd rather be taught to understand this so I can then better debug these situations myself. Thanks! Relevant Code index.html {% block content %} <h1>Recent Projects</h1> {% for project in recent_projects %} <li><a href="{% url 'projects:detail' project.category.slug project.category.id project.id %}">{{ project.name }}</a></li> {% endfor %} {% endblock %} urls.py app_name = 'projects' urlpatterns = [ path('', views.index, name='index'), path('categories/', views.categories, name='categories'), path('categories/<slug:slug>, <int:category_id>/', views.category_detail, name='category_detail'), path('categories/<slug:category_slug>, <int:category_id>/<int:project_id>', views.detail, name='detail') ] The relevant view: def detail(request, project_id): project = get_object_or_404(Project, pk=project_id) return render(request, 'projects/detail.html', {'project': project}) -
DJANGO: Model Translation
Am trying to make my app support multiple languages so i ended up with this from django.utils.translation import gettext_lazy as _ def __str__(self): return _('%(name)s') % {'name':self.name} but django throws an error each time i try to create a new mode instance. TypeError at /en/admin/exchange/offer/ __str__ returned non-string (type __proxy__) -
Upload image using Django built in forms
I am trying to upload an image using the Django built in forms, and can't seem to get the image to actually be stored. The form functions as expected, where I can browse for a file, and submit the form (everything else from form is posted and saved), but the image does not get saved into the "media/images" folder What am I missing here? models.py from django.db import models from django.conf import settings from django.contrib.auth.models import AbstractUser from django.db.models.signals import post_save from django.db.models.signals import pre_save from django.core.files.storage import FileSystemStorage class CustomUser(AbstractUser): customerTag = models.CharField(max_length=50,) deviceSerial= models.CharField(max_length=50,) image = models.ImageField(upload_to='images/', blank = True) forms.py from django import forms from django.contrib.auth.forms import UserCreationForm, UserChangeForm from .models import CustomUser class addNewEquipmentForm(UserCreationForm): class Meta(UserCreationForm.Meta): model = CustomUser fields = ('username', 'email', 'customerTag', 'deviceSerial','image', ) urls.py from django.urls import path, include from . import views from django.conf.urls.static import static from django.conf import settings urlpatterns = [ #path('', views.home), path('login/', include('django.contrib.auth.urls')),#django powered login page path('newequipment/',views.addEquipment.as_view(), name='newEquipment'), ] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) settings.py STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static") ] STATIC_ROOT = os.path.join(BASE_DIR, "static_files") -
django rest framework api to make a connected API of various views.
I have a Django view which goes like this. def active_part_redirect(request): user = request.user if user.is_authenticated: student_state_ = CurrentActiveState.objects.filter(user= user) if student_state_.exists(): student_state = student_state_.first() if student_state.active_part == 1: return redirect('content:show-content') elif student_state.active_part == 2: return redirect('content:illustrations') elif student_state.active_part == 3: return redirect('content:questions') elif student_state.active_part ==4: return redirect('content:report') elif student_state.active_part ==6: return redirect('content:move') else: return redirect('content:report') It takes the URL and redirects it to the active part of student either content, illustration or other. I want to make the same thing in API. How can I do so? Problem is I have certain post requests within these also. For example, a student can view the content (GET) and can give answers to some questions via POST. student.active_state changes by 1 as the student move between on part to other, for example from content to illustrations. (It becomes 1 to 2).