Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework - Using set_rollback in a custom exception handler
We would like to return JSON traces to our mobile clients during development, and have written a custom Django Rest Framework error handler to do exactly that. def drf_exception_handler(exc, context): """ This is the custom exception handler used for DRF view exceptions. It first gives DRF a chance to handle any exceptions it cares about - auth, etc, then, it returns a JSON response containing the traceback, so mobile clients can handle it. DRF's handler states that if it returns None, a 500 will be raised, so we choose that as the returned response's status """ # Call REST framework's default exception handler first, # to get the standard error response. response = exception_handler(exc, context) # Don't hijack exceptions that DRF has already handled # This includes 4xx, etc codes if response is not None: return response request = context.get('request', None) # we need a request object to see if it has an Accept header, # and that that header specifies JSON if request is None or getattr(request, 'accepted_media_type', None) != u'application/json': return response data = {"message": "Internal Server Error", "exception": traceback.format_exc()} # Should we call this? set_rollback() return Response(data=data, status=status.HTTP_500_INTERNAL_SERVER_ERROR) However, we are not sure about calling set_rollback() before … -
django filter() queryset issue
I want to show only specific cards, related with specific board: HTML: {% for i in card %} <p>{{ i.title_card}} </p> {% endfor %} models.py class Board(models.Model): title = models.CharField(max_length=15, unique=True) description = models.CharField(max_length=25) category = models.CharField(max_length=20) def get_absolute_url(self): return reverse('board:board_detail', args=[self.title]) def __str__(self): return self.title class Card(models.Model): board = models.ForeignKey(Board, related_name='cards') title_card = models.CharField(max_length=15) description_card = models.CharField(max_length=15) def __str__(self): return self.title_card views.py def board_detail(request, slug): board = get_object_or_404(Board, title=slug) #NOT WORKING card = Card.objects.filter(title_card=slug) template = 'board/board_detail.html' context = {'board': board, 'card': card} return render(request, template, context) For example: I have Board : title: stack Inside stack I have cards: -> overflow -> i'm not programmer, yet. And I want to show only Stack cards. -
heroku and static files, same 404 error
ive been looking at this for weeks and it has been driving me insane. it is the usual 404 error when deploying to heroku. Can someone advise me what is the purpose of this static file and this complication on heroku? And secondly, what should I do? I tried so many things already. settings.py DEBUG = False PROJECT_ROOT = BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_URL ='/static/' STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static') STATICFILES_DIRS = (os.path.join(os.path.realpath(PROJECT_ROOT), "/static"),) STATICFILES_FINDERS = ('django.contrib.staticfiles.finders.FileSystemFinder',) STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' wsgi.py import os from django.core.wsgi import get_wsgi_application from mezzanine.utils.conf import real_project_name from whitenoise.django import DjangoWhiteNoise os.environ.setdefault("DJANGO_SETTINGS_MODULE", "%s.settings" % real_project_name(appname)) application = get_wsgi_application() application = DjangoWhiteNoise(application) yes, I've done python manage.py collectstatic I've also tried adding that in Procfile -
Why does select_for_update never work for me in Django + Postgres?
I feel like I have some conceptual mis-understandings of 'select_for_update' in django. Lets start with a few simple lines of code Rank is a Django model. Report is a Django model, with a bunch of Rank's. Like so: class Rank(models.Model): search_term = models.CharField() rank = models.IntegerField() created_on = models.DateTimeField() class Report(models.Model): ranks = models.ManyToManyField('Rank') Simple enough. I have a worker, his job is to check the last unique iteration of a 'rank' object based on the search term. So if we have a search term 'foo', foo could have say 12 entries. If the last entry is older than 24 hours, than we want to make a new entry to see what the new ranking is. With me so far? Okay. So, here's where the problem happens. Obviously, there are more than 1 worker. So here is how I attempted to make sure to only write one record: with transaction.atomic(): # hidden code.. select the max (created_on) model of unique search_term # loop through the maxes for r in ranks: if q['max_date'] <= one_day_ago: ids_we_need_to_update.append(q['rank_id']) rows_to_update = Rank.objects.select_for_update(skip_locked=True).filter(pk__in=ids_we_need_to_update)[:16] for rtu in rows_to_update: #update row.... rtu.save() To my disappointment, I woke up this morning to see that a race condition had … -
Django OperationalError at /books/add_review_to_book
I'm stuck for 2 days on this error,I'm new to Django and I don't understand why do I get this error - OperationalError at /books/add_review_to_book/8 table books_review has no column named book_id. Everything looks okay for me heres the code: My models.py class Book(models.Model): user = models.ForeignKey(User, default=1) title = models.CharField(max_length=100, null=True) author = models.ForeignKey('Author', on_delete=models.CASCADE, null=True) def __str__(self): return self.title + ' - ' + self.author class Author(models.Model): first_name = models.CharField(max_length=50, null=True) last_name = models.CharField(max_length=50, null=True) class Review(models.Model): book = models.ForeignKey('Book', related_name='reviews') author = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) def __str__(self): return self.text My views.py: def add_review_to_book(request, id): book = get_object_or_404(Book, id=id) if request.method == "POST": form = ReviewsForm(request.POST) if form.is_valid(): review = form.save(commit=False) review.book = book review.save() return redirect('book_detail.html', id=book.id) else: form = ReviewsForm() return render(request, 'books/add_review_to_book.html', {'form': form}) My forms.py: class ReviewsForm(forms.ModelForm): class Meta: model = Review fields = ('author', 'text') My html that takes the form add_review_to_book: {% block content %} <hr> <a class="btn btn-default" href="{% url 'add_review_to_book' id=book.id %}">Add review</a> {% for review in book.reviews.all %} {% if user.is_authenticated %} <div class="review"> <div class="date"> {{ review.created_date }} </div> <strong>{{ review.author }}</strong> <p>{{ review.text|linebreaks }}</p> </div> {% endif %} {% empty %} <p>No comments</p> … -
How to access a variable in inherited class based views
I am wondering how to run a reality check to decide which template file to use. How do I access agency_count from AgencyFullView? What I currently have returns type object 'AgencyFullMixin' has no attribute 'agency_count' class AgencyFullMixin(ContextMixin): def get_context_data(self, pk, **kwargs): context_data = super(AgencyFullMixin, self).get_context_data(**kwargs) agency = Agencies.objects.filter(pk=pk) context_data["agency"] = agency agency_count_test = agency.count() context_data["agency_count"] = agency_count_test return context_data class AgencyFullView(TemplateView, AgencyFullMixin): if agency_count != 0: **<<<--- What to put here?** template_name = 'community_information_database/agency_full.html' else: template_name = 'community_information_database/not_valid.html' def get_context_data(self, **kwargs): context_data = super(AgencyFullView, self).get_context_data(**kwargs) return context_data -
Django: template url tag wrong target
I have in my main urls: urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'', include('scoring.urls', namespace='scoring')), ] and in my app urls: urlpatterns = [ url(r'scoring/(?P<query_id>[0-9]+)/$', views.get_table_data, name='table_api'), url(r'^scoring/$', views.index, name='index'), ] and in my template: <li><a href="{% url 'scoring:index' %}">Scoring</a></li> but what {% url 'scoring:index' %}generates is localhost/instead of localhost/scoring. Why? -
Invalid regular expression: invalid escape \ sequence, Postgres, Django
I'm trying to escape a string яблуко* for Postgres regex query: name = re.escape('яблуко*') Model.objects.filter(name__iregex='^%s' % name) This gives me: Invalid regular expression: invalid escape \ sequence What am I doing wrong? P.S. I know that I can do it with istartswith, just wondering why regex is not working. -
Django - Admin ListFilter on QuerySet extra - Cannot resolve keyword 'ad_hist_status_id' into field
More than one day trying to figure out on how to use the Django Admin list_filter on a QuerySet using .extra() In the AdAdmin I need to ad one new column 'ad_hist_status_id' from the model AdHist so I can use this portion of the code on SomeListFilter: def queryset(self, request, queryset): return queryset.filter(ad_hist_status_id=self.value()) It looks like impossible. Doing this with sql is easy: select a.*, ah.ad_hist_status_id from ad_ad a join ad_adhist ah on ah.ad_id = a.id where ah.datetime_end is null order by a.id DESC Until now I cannot make to work this SomeListFilter in the Django Admin, the error is: FieldError at /admin/ad/ad/ Cannot resolve keyword 'ad_hist_status_id' into field. Choices are: addetailscategories, address, adhist, adphotos, adprice, adscheduleinfo, age, comment, county, county_id, date_inserted, date_updated, description, district, district_id, email, id, lat, lng, name, parish, parish_id, schedule_type, schedule_type_id, telephone, title, user_inserted, user_inserted_id, user_updated, user_updated_id My question is, how do I effectively add a new column to a QuerySet and then how can I query this new QuerySet with the new column? Some portions of my code bellow The Models: class Ad(models.Model): title = models.CharField(max_length=250) name = models.CharField(max_length=100) description = models.TextField() age = models.IntegerField(blank=True, null=True) telephone = models.CharField(max_length=25) email = models.EmailField() district = models.ForeignKey(District) … -
Python Django flow and navigation
This is my Django-python webb app's project structure and below are the contents of views.py and url.py files . My understanding is that web the after running python manage.py runserver when the following link is loaded http://127.0.0.1:8000/ R6Scorextractor/R6Scorextractor/url.py is run and it redirects to R6scoreex.urls.py and from there it runs R6Scorextractor/R6scoreex/views.py and inside view it runs the function index. I am trying to do a simple file upload and later on a form submission.I was working on OCR app which extracts score data and then displays it as text .So I wanted to make web interface for testing it out for other people .And this is my first attempt at making Django python web app Please explain to me the things that are understanding wrong and how to do correct url mapping .Right now I am trying to call simple upload function but its not getting executed. R6Scorextractor R6Scoreex migrations templates R6Scoreex header.html home.html __Init__.py settings.py urls.py views.py models.py apps.py admin.py tests.py R6Scorextractor __Init__.py settings.py urls.py manage.py R6Scorextractor/R6scoreex/urls.py from django.conf.urls import url from . import views from django.conf.urls import include urlpatterns = [ url(r'^$', views.index, name='simple_upload'), url(r'^simple_upload$', views.index, name='simple_upload'), ] R6Scorextractor/R6scoreex/views.py # -*- coding: utf-8 -*- from __future__ import unicode_literals … -
Preserving disabled form vield value in Django
I'm running into an issue where my form is not preserving the form field value on a failed form submission. The catch is that I want it to be visible to the user that they can't select any other state (since it's a website specifically for a city within the state), so I have it disabled. If I remove this widget attribute, it preserves the field info, otherwise, it resets and I can't edit the field since I have it disabled. Request a remedy or a recommendation. Code follows. forms.py from django import forms from django.core.exceptions import ValidationError from django.forms import ModelForm from .models import Resource from localflavor.us.forms import USStateSelect from localflavor.us.forms import USZipCodeField import pickle zips = pickle.load(open('../zips.p', "rb")) def validate_zip(zip_code): """Ensure zip provided by user is in King County.""" if zip_code not in zips: raise ValidationError( '{} is not a valid King County zip code.'.format(zip_code), params={'zip_code': zip_code}, ) class ResourceForm(ModelForm): """Form for editing and creating resources.""" zip_code = forms.IntegerField(validators=[validate_zip]) class Meta: model = Resource fields = ['main_category', 'org_name', 'description', 'street', 'city', 'state', 'zip_code', 'website', 'phone_number', 'image', 'tags'] labels = { 'org_name': 'Name of Organization', 'main_category': 'Main Categories', } help_texts = { 'main_category': 'The core services your organization provides.', … -
django-forms: allow logged in user to submit only one comment per individual post
I have a model Post in which the User can leave a Comment along with a set of ratings. I would like to limit the user comments to only one per post. I'm having trouble setting that up in my view models class Comment(models.Model): post = models.ForeignKey(Post, related_name="comments") user = models.ForeignKey(User, related_name="usernamee") ... class UserProfile(models.Model): user = models.OneToOneField(User, related_name='profile') class Post(models.Model): ... views def add_comment(request, slug): post = get_object_or_404(Post, slug=slug) # I tried wrapping all of the below in an "if" statement, something like # if request.user.comment.exists(): to check if the user has already # left a comment on this specific post, but I'm not sure of the right way to perform such a check here. if request.method == 'POST': form = CommentForm(request.POST or None) if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.user = request.user comment.email = request.user.email comment.picture = request.user.profile.profile_image_url() comment.save() messages.success(request, "Thank you for leaving a review!") return redirect('blog:post_detail', slug=post.slug) else: messages.error(request, "Something went wrong! We weren't able to process your review :(") else: form = CommentForm() template = "blog/post/add_comment.html" context = { 'form': form, 'post': post, #'comment_count': comment_count } return render(request, template, context) I am under the impression that all I would need is to wrap … -
Best practice for Django search page with ordering, listing, and filtering
Sorry for an easy question. I have search in the Internet I know how to get an answer for small question, but I fail to complete the solution on my own. I know small answers on these: 1. I know how to get session from Django. It makes use of login form 1. I know how to get jwt token form Django REST. It uses /auth with POST JSON 1. I know how to use django-filter, serializer, pagination, ... etc Backgrond: My Django web has single page with 2 forms. First form is responsible for query parameters. Second form is table row. Suppose I want to use combination of session and jwt token. session to control the time for the user jwt token to let user filter over Django REST. The reason why I prefer this way because 1. Django REST has ready-made pagination and easy to do with django-filter 2. Django tag on template is somewhat difficult for me. I am new to template. My background is infra. Therefore company put me in the backend first and frontend later. 3. I do not want to let web browser refresh the whole page again. Question How do I store the … -
upload image django rest framework corrupted
I have the next view to upload a image but the generated image is corrupted. class FileUploadView(views.APIView): parser_classes = (parsers.FileUploadParser,) def uploadFile(self, up_file): if not os.path.exists(BUILDING_PHOTOS_FOLDER): os.mkdir(BUILDING_PHOTOS_FOLDER) file_name = '{}.jpeg'.format(uuid.uuid4()) destination = open( '{}/{}'.format(BUILDING_PHOTOS_FOLDER, file_name), 'wb+') for chunk in up_file.chunks(): destination.write(chunk) destination.close() def put(self, request, filename, format=None): file_obj = request.data['file'] self.uploadFile(file_obj) return HttpResponse(status=204) -
Command "python manage.py shell" pops out error message
Whenever I enter "python manage.py shell" in Windows PowerShell ISE, I get an error message: CategoryInfo: NotSpecified FullyQualifiedErrorId: NativeCommandError -
Django database model
I am confusing about the postgresql database table made by django. I got information about my user table from psql command. The first colmun, it is last_login field. But I don't set last_login field anywhere. table definition is the following. remoshin_devdb=# \d remosys_remoshin_user_tbl; Table "public.remosys_remoshin_user_tbl" Column | Type | Modifiers -----------------+--------------------------+----------- last_login | timestamp with time zone | userid | character varying(64) | not null username | character varying(128) | not null email | character varying(254) | not null password | character varying(128) | not null usertype | character varying(1) | not null is_active | character varying(1) | not null is_admin | character varying(1) | not null u_kana_name | character varying(128) | u_date_of_birth | date | u_gender | character varying(1) | not null u_postno | character varying(7) | u_address1 | character varying(128) | u_address2 | character varying(128) | u_telno | character varying(16) | u_photo | character varying(100) | d_photo | character varying(100) | create_date | timestamp with time zone | not null modify_date | timestamp with time zone | not null d_clinic_id_id | character varying(8) | Indexes: "remosys_remoshin_user_tbl_pkey" PRIMARY KEY, btree (userid) "remosys_remoshin_user_tbl_email_key" UNIQUE CONSTRAINT, btree (email) "remosys_remoshin_user_tbl_d_clinic_id_id_65dbde14" btree (d_clinic_id_id) "remosys_remoshin_user_tbl_d_clinic_id_id_65dbde14_like" btree (d_clinic_id_id varchar_pattern_ops) "remosys_remoshin_user_tbl_email_4dc9031b_like" btree (email varchar_pattern_ops) "remosys_remoshin_user_tbl_userid_e92979ce_like" btree … -
Django not migrating
I have a database full of tables, I tried migrating an object with several primary keys. It let me do the: python manage.py makemigrations However, when I try running the: python manage.py migrate I keep getting: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/var/www/env/lib/python3.5/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/var/www/env/lib/python3.5/site-packages/django/core/management/__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/var/www/env/lib/python3.5/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/var/www/env/lib/python3.5/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/var/www/env/lib/python3.5/site-packages/django/core/management/commands/migrate.py", line 204, in handle fake_initial=fake_initial, File "/var/www/env/lib/python3.5/site-packages/django/db/migrations/executor.py", line 115, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/var/www/env/lib/python3.5/site-packages/django/db/migrations/executor.py", line 145, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/var/www/env/lib/python3.5/site-packages/django/db/migrations/executor.py", line 244, in apply_migration state = migration.apply(state, schema_editor) File "/var/www/env/lib/python3.5/site-packages/django/db/migrations/migration.py", line 129, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/var/www/env/lib/python3.5/site-packages/django/db/migrations/operations/models.py", line 97, in database_forwards schema_editor.create_model(model) File "/var/www/env/lib/python3.5/site-packages/django/db/backends/base/schema.py", line 303, in create_model self.execute(sql, params or None) File "/var/www/env/lib/python3.5/site-packages/django/db/backends/base/schema.py", line 120, in execute cursor.execute(sql, params) File "/var/www/env/lib/python3.5/site-packages/django/db/backends/utils.py", line 80, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "/var/www/env/lib/python3.5/site-packages/django/db/backends/utils.py", line 65, in execute return self.cursor.execute(sql, params) File "/var/www/env/lib/python3.5/site-packages/django/db/utils.py", line 94, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/var/www/env/lib/python3.5/site-packages/django/utils/six.py", line 685, in reraise raise value.with_traceback(tb) File "/var/www/env/lib/python3.5/site-packages/django/db/backends/utils.py", line 63, in execute return … -
DJANGO: how to make a view that check process of something
Many web apps which have a page that take more than 0.5ms to load have a intermediate status page. Such pages might have a spinning wheel or more useful for the user, state the current part of the process the server is at e.g.: (page request) (message 1) loading user preferences (message 2) initializing user whatever (message 3) getting content (page loades) How could one do this in Django? e.g. say there is a form and after submitting it may take a few minutes for the server to finish processing. How can I show the user where the server is at? Views form page def form_page(request): # stuff context = {'useful_data': useful_data} render(request, 'my_app/form_page.html', context) handler page def handler(request): # what goes here? render(request, 'my_app/form_page.html', context) HTML form_page {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'my_app/css/index.css' %}" /> <form action="{% url 'my_app:handler' %}" method="post"> {% csrf_token %} <input type="submit" name="submit"> </form> handler // Status goes / is updated here ?????? -
convert query to list in django
hello i had this code in views.py def prod_aff(request): queryset =Produit.objects.all() ca = sortiestk.objects.all().select_related('ref').select_related('codecateg').values_list('ref__codecateg',flat=True).distinct() ca1 = list(ca) print ca1 for val in ca1: pp = sortiestk.objects.select_related('ref').select_related('codecateg').filter(ref__codecateg=val).aggregate(Sum('qtesrt')) print pp return render(request, 'produit/produit.html',{'nomc':getnomcat,'produit':queryset}) it display to me {'qtesrt__sum': 8} {'qtesrt__sum': 40} {'qtesrt__sum': 10} i want to put only then int value in list i try list(pp) it show only [qtesrt__sum , qtesrt__sum ,qtesrt__sum] -
Django Templating - background images Jinja
I can't display my background image on my website. I put the background image in my style.css and linked that in "< style> background: < /style>". I put the {% load staticfiles %} above the style but im pretty sure that is wrong. I've checked my settings and the STATIC_URL setting is STATIC_URL = '/static/' Here's my css style.css body { background:slategray url("/personal/static/personal/images/background.gif")no-repeat right bottom; } Here is my html code <!DOCTYPE html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title>Mr. Hart</title> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous"> <div class="row"> <div class="col-md-8"> <a href='/' style="display: inline-block; text-decoration-color: #1a8002;">Home</a> <a href='/blog/' style="display: inline-block; text-decoration-color: green;"> Blog </a> <a href='/Aboutme/' style="display: inline-block; text-decoration-color: green;"> About Me </a> <a href='/stocks/' style="display: inline-block; text-decoration-color: green;"> My stock Tips </a> <a href='/crypto/' style="display: inline-block; text-decoration-color: green;"> Crypto </a> </div> <div class="col-md-4">"This is where my contacts stack,github, stocktwits, twitter, all picture links "</div> </div> {% load staticfiles %} <style type="text/css"> html, body { background: url("{% static "/personal/style.css" %}") no-repeat center center fixed; -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; background-size: cover; } </style> </head> -
Jinja Invalid Filter, filter is built in
I have read through the Jinja documentation and am using the truncate filter. I have used it exactly as defined in the documentation. From the docs: truncate(s, length=255, killwords=False, end=’…’, leeway=None) Return a truncated copy of the string. The length is specified with the first parameter which defaults to 255. If the second parameter is true the filter will cut the text at length. Otherwise it will discard the last word. If the text was in fact truncated it will append an ellipsis sign ("..."). If you want a different ellipsis sign than "..." you can specify it using the third parameter. Strings that only exceed the length by the tolerance margin given in the fourth parameter will not be truncated. Here is my code: {% if post.replies.all %} <ul class="accordion" data-accordion data-multi-Expand="true" data-allow-all-closed="true"> {% for reply in post.replies.all %} <li class="accordion-item" data-accordion> <a href="#" class="accordion-title">{{reply.by}}: {{reply.content|truncate(14)}}</a> <div class="accordion-content" data-tab-content> <img src="{{ reply.by.profile.img_url }}" class="thumbnail" width="50" height="50"> <p>{{ reply.content }}</p> </div> </li> {% endfor %} </ul> {% endif %} -
SQL Server and Django
Hello I'm new to Django. Currently we are using Python 3.6.2 with Django 1.11.5. I can get Django up and running, but when I attempt to change my #Database in settings.py to the following: DATABASES = { 'default': { 'ENGINE': 'sqlserver_ado', 'HOST': 'NADCWPDBSRBA02' 'NAME': 'QlikView', 'USER': '', 'PASSWORD': '', 'TEST_CREATE': False, } } I'm greeted with the following error message: (venv) PS C:\Python\myproject\myproject> python manage.py inspectdb Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "C:\Python\myproject\venv\lib\site-packages\django\core\management\__init__.py", line 364, in execute_from_comman d_line utility.execute() File "C:\Python\myproject\venv\lib\site-packages\django\core\management\__init__.py", line 308, in execute settings.INSTALLED_APPS File "C:\Python\myproject\venv\lib\site-packages\django\conf\__init__.py", line 56, in __getattr__ self._setup(name) File "C:\Python\myproject\venv\lib\site-packages\django\conf\__init__.py", line 41, in _setup self._wrapped = Settings(settings_module) File "C:\Python\myproject\venv\lib\site-packages\django\conf\__init__.py", line 110, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Python\myproject\venv\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 978, in _gcd_import File "<frozen importlib._bootstrap>", line 961, in _find_and_load File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 655, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 674, in exec_module File "<frozen importlib._bootstrap_external>", line 781, in get_code File "<frozen importlib._bootstrap_external>", line 741, in source_to_code File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed File "C:\Python\myproject\myproject\myproject\settings.py", line 80 'NAME': 'QlikView', ^ SyntaxError: invalid syntax My database name is QlikView, i'm … -
AWS Cloud Watch unreadable symbols
I want to get all logs from docker (from stdout) on my EC2 instance. So after configuring policy and IAM roles, in my docker-compose.yml I add next configuration for logging: django: ... logging: driver: "awslogs" options: awslogs-region: "eu-central-1" awslogs-group: "my-group-auto" awslogs-stream: "my-stream" awslogs-create-group: "true" Django config: LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'root': { 'level': 'ERROR', 'handlers': ['console'], }, 'formatters': { 'message-only': { 'format': '%(message)s' } }, 'handlers': { 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'message-only' } }, 'loggers': { 'celery': { 'level': 'DEBUG', 'handlers': ['console'], 'propagate': False, } } } Then I run the python shell and try to send some logs: In [1]: import logging In [2]: logger = logging.getLogger('celery') In [3]: logger.info('info2') In [4]: logger.info('info22') But on AWS Cloud Watch I got logs with unreadable symbols before original log message: 16:34:27 [J[?7h[0m[?12l[?25h[?2004linfo2 16:35:23 [J[?7h[0m[?12l[?25h[?2004linfo22 Looks like some unreadable date before the messages. How can I remove it? -
Why is Django sites not embedded inside another HTML? - iframe?
I try to embedded django form in another html page but nothing works. I tried my other django sites. But non works. Also tested for some other sites. Do django block to be used in iframe? How to make it works? form needed to be embedded Programming competition form -
Migrate command error in Django
I am getting a migrate command error -- django.db.utils.OperationalError: (1170, "BLOB/TEXT column 'module_name' used in key specification without a key length") The model is class Coupling(models.Model): coupling_name = models.CharField(max_length=150, blank=False, default=True, unique=True) module_name = models.TextField(max_length=255) There is a key length though. Any help is highly appreciated. Thanks in advance.