Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to rendering to html in the viewsets in Django Rest Framework
models.py class MyVideo(models.Model): title = models.CharField(max_length=100, null=True, default='') seotitle = models.CharField(max_length=100, null=True, default='') keywords = models.CharField(max_length=150, null=True, default='') status = models.IntegerField(default=1) serializers.py class MyVideoSerializer(serializers.ModelSerializer): class Meta: model = MyVideo fields = '__all__' views.py class My(viewsets.ModelViewSet): queryset = MyVideo.objects.all() serializer_class = MyVideoSerializer renderer_classes = (JSONRenderer, TemplateHTMLRenderer,) template_name = "my.html" def get(self, request, *args, **kwargs): # ?????? def get_query(self): # ?????? urls.py urlpatterns = [ path('my/', views.my), # ???????? anything wrong here? ] my.html <html><body> <h1>My video</h1> <ul> {% for d in data %} <li>{{ d.title }}</li> # ?????? anything wrong here? <li>{{ d.seotitle }}</li> <li>{{ d.keywords }}</li> {% endfor %} </ul> </body></html> I have a MyVideo model which store several videos record in the database. What I wanna implement is that to display the information of those videos through the my.html. e.g. http://127.0.0.1:8000/my/103 can access the video which id=103, and on this page display its fields (title, seotitle, keywords, etc.). Any nice implementation or suggestion? Thanks! -
Django get ranking from best results
I have a MySQL table called ViResults that keeps track of the time results for every competitor who has competed in a game. Say, each entry contains the fields competitorId, competitionId, and bestTime. One competitor can have multiple records in the database if they have participated in more than one competition. I am trying to get the ranking based on each competitor's personal record, and send it to front end with all the columns. This is my code: results = Result.objects.filter( bestTime__gt=0 ).values_list( 'competitorid', 'competitionid' ).annotate( Min('best') ).order_by('best') and this is the query executed (output of results.query) SELECT `ViResults`.`personId`, `ViResults`.`competitionId`, MIN(`ViResults`.`best`) AS `best__min` FROM `ViResults` WHERE (`ViResults`.`best` > 0 AND `ViResults`.`eventId` = 333) GROUP BY `ViResults`.`personId`, `ViResults`.`competitionId`, `ViResults`.`best` ORDER BY `ViResults`.`best` ASC I didn't get my desired result, since having competitionId in GROUP BY makes each record different, thus a competitor can have many records in the ranking table. How can I exclude competitionId from GROUP BY but still get all the fields I want in my result? Thank you. -
Can I change the default `ogin_required value for all pages in Django-CMS?
I've been tasked with creating a Django-CMS web application that should only be available to logged-in users. After some struggling I've settled to just check "Login Required" on Permissions for all pages, but it is bothersome to do this by hand (and potentially dangerous to forget to set it to true. So I was wondering: is there a way to change the default value of the login_required BooleanField on django-cms' pagemodel.py? Or maybe I can somehow override the API's create_page method to put the default value there? I don't know if there may be a situation in the future where we will want there to be some publicly-available pages, but if there's another way to do this rather than to set this flag to true on each Page, please let me know. I'm using Python 2.7.x, Django 1.11.x and Django-CMS 3.4.6. -
Reasonable stock price information for commerical site (not alpha vantage or quandl)?
The previous threads about stock price information seems to be very old on SO and the answers there mainly seems to be alpha vantage which i cant use for my situation (I have tried it and communicated with them but they dont provide the data the way i need it, more on this below). The other answers also seemed to be mostly about only forex data, or at least that is what the vendors in the answers seem to work with now. Is there any reasonable (below 500 USD a year) service that provides stock price information (it does not have to be real time) in addition to historic stock price information and forex to be used in python for NASDAQ, NYSE and Oslo stock exchange ? It is going to be used in a web application (django). I used alpha vantage, but the data they return is in a series so you have to download and parse quite a bit of data when you only need one intraday value for one stock and the performance overhead for this is too much, the parsing however could be done, but it also polutes the code. Quandl was also a product I … -
Django multi db test fails at teardown
My multi-db test problem is the following: # (django 2.0.7, python 3.6) # settings.py: DATABASES = { 'default':{}, 'one': { # connection1 settings here } 'two': { # connection2 settings here } } DATABASE_ROUTERS = [] # test.py class MyTestCase(TestCase): def test_my_function(self): pass # this IS literally the code I run python manage.py test -v 2 and see that the test runner builds up the two mock databases and runs the test that is green test_my_function (mymodule.test.MyTestCase) ... ok Then ERROR then ERROR: test_get_pronunciation (languages.test_hr.HRTestCase) with the following explanation: File "/Users/Barnabas/PycharmProjects/rhymedict-multisite/venv/lib/python3.6/site-packages/django/db/backends/dummy/base.py", line 20, in complain raise 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. This should mean that the program tries to access the 'default' database. (The same thing happens if I add multi_db = True to my MyTestCase) Yet strangely if I write class MyTestCase(TestCase): pass The db's are built up, torn down just fine. What do I do wrong? -
Opening sub directories in django website
I am working on a project that creates a website using django frameworks. Currently I'm working on a page that shows all the files and directories in the sample server. It works well and all, but I cannot figure out how to open the directories and show all the files and subdirectories in them, too. Can anyone tell me how to do this? -
Get webhook in django from recurly
I want to get webhook notification from recurly to my django project. I am following https://dev.recurly.com/page/python my class as follows class PushNotificationHandlerView(SimpleHTTPServer.SimpleHTTPRequestHandler, APIView): queryset = None def post(self,*args,**kwargs): bytes = int(self.headers["content-length"]) data = self.rfile.read(bytes) notification = recurly.objects_for_push_notification(data) print notification #each webhook is defined by a type if notification['type'] == "successful_payment_notification": print "Payment Received" elif notification['type'] == "failed_payment_notification": print "The payment did not work" self.send_response(200) self.wfile.write("OK") self.wfile.flush() When event occur in recurly it raise following error. Internal Server Error: /api/notifications/ Traceback (most recent call last): File "site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view return view_func(*args, **kwargs) File "site-packages/django/views/generic/base.py", line 62, in view self = cls(**initkwargs) TypeError: __init__() takes exactly 4 arguments (1 given) -
Get count and limit size of query django
I had this code: words = Word.objects.filter(...) return words right now I need to add pagination, So I need to get count of total words, and limit size of words finding query.(get only first 100 words, or words from 100 to 200 and so on..) How can I do this effectively? -
Django Admin "Add" fails for non-default database
I have scoured the internet, and my problem feels like it may be a bug in the django admin tool, but it is probably not. I am trying to add records to a non-default database using the django admin tool. I have setup my admin.py to use the MultiDBModel admin as described in the documentation. class MultiDBModelAdmin(admin.ModelAdmin): # A handy constant for the name of the alternate database. using = 'brite_obs' def save_model(self, request, obj, form, change): # Tell Django to save objects to the 'other' database. obj.save(using=self.using) def delete_model(self, request, obj): # Tell Django to delete objects from the 'other' database obj.delete(using=self.using) def get_queryset(self, request): # Tell Django to look for objects on the 'other' database. return super().get_queryset(request).using(self.using) def formfield_for_foreignkey(self, db_field, request, **kwargs): # Tell Django to populate ForeignKey widgets using a query # on the 'other' database. return super().formfield_for_foreignkey(db_field, request, using=self.using, **kwargs) def formfield_for_manytomany(self, db_field, request, **kwargs): # Tell Django to populate ManyToMany widgets using a query # on the 'other' database. return super().formfield_for_manytomany(db_field, request, using=self.using, **kwargs) admin.site.register(ObsField, MultiDBModelAdmin) The database works. It is connected I can view records i can change records, but when I try to add a record. I get the following error. Exception Type: … -
Which is best practice to add security headers for django application?
Now which is better for adding security headers configuration at the application level or the nginx level like add_header X-Frame-Options "SAMEORIGIN"; add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always; add_header X-Content-Type-Options nosniff; add_header X-XSS-Protection "1; mode=block"; add_header 'Referrer-Policy' 'origin'; Or at django settings SECURE_BROWSER_XSS_FILTER=True SECURE_CONTENT_TYPE_NOSNIFF=True SECURE_HSTS_INCLUDE_SUBDOMAINS=True SECURE_HSTS_SECONDS=36000 SECURE_SSL_REDIRECT=True And what if I added them on the two levels, will it make any conflict or any problems on the future? Sure what about any framework that provide its security middleware, not django specifically -
Django Crispy Form Layout
I've been reading for a few days and can't figure out how to do a layout for a form. I am new to Django and crispy forms and this is my first time going beyond the simple form layouts. I have a model with a boolean field (YES / NO). # FOR YES / NO RADIO BOXES BOOL_CHOICES = ((True, 'Yes'), (False, 'No')) class SomeModel(models.Model): field1 = models.BooleanField(choices=BOOL_CHOICES, blank=True) field1_answer = models.TextArea(blank=True) class SomeForm(ModelForm): class Meta: model = SomeModel fields = ('field1', 'field1_answer') widgets = { 'field1': RadioSelect } def __init__(self, *args, **kwargs): # CALL SELF super(SomeForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_tag = False self.helper.label_class = 'col-lg-2' self.helper.field_class = 'col-lg-8' self.helper.layout = Layout( Row('field1'), Row( Div( Row('field1_question') ), css_class='hidden', id='div_field1' ) ) What I am looking for is the ability to do the below layout for many questions like the above. The o's are radio select buttons. The layout above is far from that. I just provided something to let people know where I am stuck at. table layout ================================================= | yes | no | question | ================================================= | o | o | FIELD 1 QUESTION | ================================================= | HIDDEN DIV IF ANSWER IS YES SHOW | | FIELD1_QUESTION … -
How to add staff user permissions for my custom user model?
I followed the Django documentation to create a custom user model as shown below. However, I noticed that a staff user behaves exactly the same as a superuser but that is not what i wanted. I want to allow staff users to login to the admin to view information and have NO add, change, delete permissions. I have spent hours trying to figure out the documentation but i still do not have a solution. Please help! Also, i have to mention that the project is already on a live server hence i do not want to change the models fields too much for the fear of screwing up on the database. admin.py class UserAdmin(BaseUserAdmin): # The forms to add and change user instances form = UserAdminChangeForm add_form = UserAdminCreationForm # The fields to be used in displaying the User model. # These override the definitions on the base UserAdmin # that reference specific fields on auth.User. list_display = ('email', 'admin', 'is_active') list_filter = ('admin', 'is_active') fieldsets = ( (None, {'fields': ('email', 'password', 'is_active', 'ratings', 'rank')}), ('Personal info', {'fields': ()}), ('Permissions', {'fields': ('admin', 'staff', 'allow_more')}), ) # add_fieldsets is not a standard ModelAdmin attribute. UserAdmin # overrides get_fieldsets to use this … -
Cannot import ASGI_APPLICATION module while runserver using channels 2
I have followed the channels tutorial but while running these error throw Version of the packages is channels==2.1.2 Django==2.0.4 what is missed updates in settings.py INSTALLED_APPS = [ "channels" .... ] ROOT_URLCONF = 'byebyee.urls' ASGI_APPLICATION = "byebyee.routing.application" added file byebyee/routing.py from channels.routing import ProtocolTypeRouter application = ProtocolTypeRouter({ # Empty for now (http->django views is added by default) }) this is the error log System check identified no issues (0 silenced). August 01, 2018 - 13:11:42 Django version 2.0.4, using settings 'byebyee.local_settings' Starting ASGI/Channels version 2.1.2 development server at http://127.0.0.1:8080/ Quit the server with CONTROL-C. Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7f71ecfb6400> Traceback (most recent call last): File "/home/vkchlt0192/byebyee/lib/python3.5/site-packages/channels/routing.py", line 33, in get_default_application module = importlib.import_module(path) File "/home/vkchlt0192/byebyee/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 956, in _find_and_load_unlocked ImportError: No module named 'byebyee.routing' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/vkchlt0192/byebyee/lib/python3.5/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/home/vkchlt0192/byebyee/lib/python3.5/site-packages/channels/management/commands/runserver.py", line 80, in inner_run application=self.get_application(options), File "/home/vkchlt0192/byebyee/lib/python3.5/site-packages/channels/management/commands/runserver.py", line 105, in get_application return StaticFilesWrapper(get_default_application()) File "/home/vkchlt0192/byebyee/lib/python3.5/site-packages/channels/routing.py", line 35, in get_default_application raise ImproperlyConfigured("Cannot import … -
Connecting to a legacy informix database with django
I'm trying to connect to an existing Informix database with Django, I'm using django-pyodbc-azure to handle the connection via odbc, the connection work fine when trying in the python interpreter: >>>import pyodbc >>>conn = pyodbc.connect('DSN=test_ifx;UID=test;PWD=test') >>>curs = conn.cursor() >>>curs.execute("select * from someTable") <pyodbc.Cursor object at 0x0052E520> So this work just fine but in django I create the database connection parameters like that : DATABASES = { 'default' : { 'ENGINE' : 'sql_server.pyodbc', 'NAME' : 'test', 'USERNAME' : 'test', 'PASSWORD' : 'test', 'PORT' : '1260', 'OPTIONS':{ 'dsn' : 'test_ifx' } } } So when I launch the server I get the following error: Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x0353DED0> Traceback (most recent call last): File "C:\Users\PatrickStewball\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\backends\base\base.py", line 216, in ensure_connection self.connect() File "C:\Users\PatrickStewball\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\backends\base\base.py", line 194, in connect self.connection = self.get_new_connection(conn_params) File "C:\Users\PatrickStewball\AppData\Local\Programs\Python\Python37-32\lib\site-packages\sql_server\pyodbc\base.py", line 321, in get_new_connection conn.timeout = query_timeout pyodbc.Error: ('HYC00', '[HYC00] [Informix][Informix ODBC Driver]Driver not capable. (-11092) (SQLSetConnectAttr)') The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\PatrickStewball\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\PatrickStewball\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\commands\runserver.py", line 123, in inner_run self.check_migrations() File "C:\Users\PatrickStewball\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\base.py", line 427, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "C:\Users\PatrickStewball\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\migrations\executor.py", line 18, in __init__ self.loader = … -
oTree - modify the 'Configure Session' segment dynamically
I recently started using oTree to build an extensive-form game, and I want to be able to determine the role of each participant in each round when creating a session. Is it possible to change the SESSION_CONFIGS dictionary dynamically (depends on the number of participants and the number of rounds) so I'll be able to configure the roles of the participants online, or should I configure that using Treatments? Thanks. -
django cms PicturePlugin1
Dear all hope you are fine after install bootstrap-4 .. i got error 'PicturePlugin' Request Method: GET Request URL: http://127.0.0.1:8002/en/ Django Version: 1.11.14 Exception Type: KeyError Exception Value: 'PicturePlugin' Exception Location: /home/hazem/env/lib/python3.5/site-packages/cms/plugin_pool.py in get_plugin, line 194 Python Executable: /home/hazem/env/bin/python Python Version: 3.5.2 Python Path: ['/home/hazem/first-project', '/home/hazem/env/lib/python35.zip', '/home/hazem/env/lib/python3.5', '/home/hazem/env/lib/python3.5/plat-x86_64-linux-gnu', '/home/hazem/env/lib/python3.5/lib-dynload', '/usr/lib/python3.5', '/usr/lib/python3.5/plat-x86_64-linux-gnu', '/home/hazem/env/lib/python3.5/site-packages'] Server time: Wed, 1 Aug 2018 16:53:09 +0400 Error during template rendering In template /home/hazem/first-project/mysite/templates/base.html, error at line 6 6- <title>{% block title %} This is my new project homepage {% endblock title %}</title> -
Domain name has ssl certificate but IP does not - Django
I am trying to host a site on digital ocean and i have generated ssl certificate for my domain using 'Lets Encrypt' . But As the certificate authority allows certificates only for domain name. And Even if i pointed my IP to domain name either ssl certificates is disabled for both IP and domain . And in Django(2.0.7) manage.py runserver allows only on IPs (example: python3 manage.py runserver 0.0.0.0:8000). So how do retain my ssl(https) certificate and redirect my ip to domain with secure connection. -
Django page not found error
Hello I am trying to solve the error which keeps on occurring; my current code on mysite/urls.py is from django.contrib import admin from django.urls import path from django.conf.urls import url from polls import views admin.autodiscover() urlpatterns = [ url(r'^polls/$', views.index, name='index'), url(r'^polls/(?P<question_id>\d+)/$', views.detail, name='detail'), url(r'^polls/(?P<question_id>\d+)/vote/$', views.vote, name='vote'), url(r'^polls/(?P<question_id>\d+)/results/$', views.results, name='results'), url('admin/', admin.site.urls), ] and I am getting error when I try to access :8001/polls Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8001/ Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: ^polls/$ [name='index'] ^polls/(?P<question_id>\d+)/$ [name='detail'] ^polls/(?P<question_id>\d+)/vote/$ [name='vote'] ^polls/(?P<question_id>\d+)/results/$ [name='results'] admin/ The empty path didn't match any of these. Please help me to solve this error which makes me cannot access to the website. -
Static resources that get served over http don't get served over https
I wrote an application with Django that serves files built with Webpack. The application runs fine over http, but gives an error over https that I can't seem to find how to solve. With debug set to True I get (for example) GET https://localhost:8000/dist/bundles/css/main.f57231b6.css net::ERR_ABORTED 404 (Not Found) with debug set to false I get GET https://localhost:8000/dist/bundles/css/main.f57231b6.css net::ERR_ABORTED 500 (Internal Server Error) for css and javaScript. The traceback on the server looks like this: File "/Applications/anaconda3/lib/python3.6/wsgiref/handlers.py", line 137, in run self.result = application(self.environ, self.start_response) File "/Users/home/docs/Projects/Apprentice_Project/aws_env/lib/python3.6/site-packages/django/contrib/staticfiles/handlers.py", line 67, in __call__ return super().__call__(environ, start_response) File "/Users/home/docs/Projects/Apprentice_Project/aws_env/lib/python3.6/site-packages/django/core/handlers/wsgi.py", line 146, in __call__ response = self.get_response(request) File "/Users/home/docs/Projects/Apprentice_Project/aws_env/lib/python3.6/site-packages/django/contrib/staticfiles/handlers.py", line 62, in get_response return super().get_response(request) File "/Users/home/docs/Projects/Apprentice_Project/aws_env/lib/python3.6/site-packages/django/core/handlers/base.py", line 81, in get_response response = self._middleware_chain(request) TypeError: 'NoneType' object is not callable [01/Aug/2018 05:48:59] "GET /dist/bundles/css/main.f57231b6.css HTTP/1.1" 500 59 settings.py: """ Django settings for prentice project. Generated by 'django-admin startproject' using Django 2.0.5. 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 import environ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # defining which variables django-environ should look for env = environ.Env( SECRET_KEY=str, DB_HOST=(str, '127.0.0.1'), DB_NAME=str, DB_USER=str, DB_PASSWORD=str, … -
Python: Download Images from Google
I am using google's books API to fetch information about books based on ISBN number. I am getting thumbnails in response along with other information. The response looks like this: "imageLinks": { "smallThumbnail": "http://books.google.com/books/content?id=tEDhAAAAMAAJ&printsec=frontcover&img=1&zoom=5&source=gbs_api", "thumbnail": "http://books.google.com/books/content?id=tEDhAAAAMAAJ&printsec=frontcover&img=1&zoom=1&source=gbs_api" }, I want to download thumbnails on the links above and store them on local file system. How can it be done python? -
Django Admin Form Limit Dropdown Options
So in the Django admin I have an object change form like so: class SurveyChoiceField(forms.ModelChoiceField): def label_from_instance(self, obj): return u'{0} - {1}'.format(obj.id, obj.name) class BlahAdminForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(BlahAdminForm, self).__init__(*args, **kwargs) surveys = Survey.objects.filter(deleted=False).order_by('-id') self.fields['survey'] = SurveyChoiceField(queryset=surveys) class BlahAdmin(admin.ModelAdmin): form = BlahAdminForm and I would like to limit the dropdown to surveys of a certain type based on the blah. Something like blah_id = self.blah.id blah_survey_type = Blah.objects.filter(id=blah_id).get('survey_type') surveys = Survey.objects.filter(deleted=False, type=blah_survey_type).order_by('-id') but I'm not sure how to get the id of the Blah in the BlahAdminForm class. -
Django template : Need 2 values to unpack in for loop; got 8
Through my view I collected some data that I want to bundle together in a list of values that look like this : list = [(1,2,3,4,5,6,7,8),(1,2,3,4,5,6,7,8),(1,2,3,4,5,6,7,8)] Then I'll be rendering that to my template to unpack the data to my page : return render(request, 'accounts/page.html', list) Template goes like this : {% for a,b,c,d,e,f,g,h in list %} <h3>{{a}}</h3> <h3>{{b}}</h3> #and so on #.. <h3>{{h}}</h3> {% endfor %} So the error i get is : Need 2 values to unpack in for loop; got 8. Can anyone figure out the source of this error or maybe have a better way of rendering data in bundles ? Thanks ! -
add user friendly json editor to django admin
I have a django app, using also rest_framework, and a model Product with field of type JSONField. so data is stored as JSON in Postgres, Now I want to provide the admin with a nice user friendly way on how he can change the json field (names/keys and values). is there an extension for that or is there a faster way on how to do that. here is the column definition in the database. my_column = JSONField(default={"editorial1": "text 1", "editorial_2": "text2", "editorial_3": "text"}) BOTH KEYS AND VALUES SHOULD BE EDITABLE BY THE ADMIN The admin should not know anything about JSON, and should not enter/edit any json format field -
Django : migration error
I have a Django project. Everything worked , until suddenly I got some strange errors like "unknown argument 'pk'". Now I can't run admin, I am getting this error get() got an unexpected keyword argument 'session_key' I can't migrate , python can't understand my models.py changes and when I run the makemigrations command I am getting this error : Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions Running migrations: No migrations to apply. Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "C:\Users\kostas\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\__init__.py", line 364, in execute_from_command_line utility.execute() File "C:\Users\kostas\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\kostas\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\kostas\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\base.py", line 330, in execute output = self.handle(*args, **options) File "C:\Users\kostas\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\commands\migrate.py", line 227, in handle self.verbosity, self.interactive, connection.alias, apps=post_migrate_apps, plan=plan, File "C:\Users\kostas\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\sql.py", line 53, in emit_post_migrate_signal **kwargs File "C:\Users\kostas\AppData\Local\Programs\Python\Python36\lib\site-packages\django\dispatch\dispatcher.py", line 193, in send for receiver in self._live_receivers(sender) File "C:\Users\kostas\AppData\Local\Programs\Python\Python36\lib\site-packages\django\dispatch\dispatcher.py", line 193, in <listcomp> for receiver in self._live_receivers(sender) File "C:\Users\kostas\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\auth\management\__init__.py", line 63, in create_permissions ctype = ContentType.objects.db_manager(using).get_for_model(klass) File "C:\Users\kostas\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\contenttypes\models.py", line 54, in get_for_model ct = self.get(app_label=opts.app_label, model=opts.model_name) File "C:\Users\kostas\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) TypeError: get() got an unexpected keyword argument 'app_label' What did happen suddenly? Can someone … -
Django; Image that is uploded on S3 directly cannot be shown up
I'm creating Django project hosted on AWS. I'm creating blog and I didn't set user's default picture so I went to my AWS console and created folder and uploaded a default picture. But the image cannot be shown up even though the path is correct. models.py is like this class CustomUser(AbstractUser): objects = CustomUserManager() picture = models.ImageField( upload_to='blog/profile', max_length=255, default='blog/default/default-pic.png', ) settings.py is like this MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'blog/media') I inspected the element and it looks correct. <img src="https://blog-assets.s3.amazonaws.com/media/blog/default/default-picture.png"> Other images can be shown up (they are uploaded through the website I am creating .) element is like this <img height="300" id="entry-photo" src="https://blog-assets.s3.amazonaws.com/media/blog/entry/apple.jpg"> So I guess uploading file on S3 directly is the cause?How should I fix this? Also, for the users I already registered before I set the default, The 'picture' attribute has no file associated with it. I want to know how to fix this error as well.