Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
POST form data and wait the response or any other possible solution?
I made the research but couldn't found the answer I am looking for, most likely due to my failure to address the question properly. I hope I can do better here. So, I have a web form and I am sending this form's fields as JSON to the backend server via a POST request. The server should send back a JSON response to the client after a computation according to those fields. This computation could take up to 5 minutes or so on. My question is, does the server should send back the computed JSON as the response to this POST request? Or, is there any way to do something like set the job with a POST request, then GET the result somehow? Or, is there any other ways, like, what is the best practice? If the description is too vague, I can give more implementation detail. -
Create,Update in different view and get in different view in django class based view
My urls.py def generate_urls(): for service in SERVICES_MAPPING: service_name = service.split('_')[0] if 'list' in service: yield path( "v1/{}/".format(service_name), GenericListView.as_view(), name=service ) if 'detail' in service: yield path( "v1/{}/<int:pk>/".format(service_name), GenericDetailView.as_view(), name=service ) My view.py class GenericListView(APIView): def get(self, request, format=None): #for list view class GenericDetailView(APIView): def get(self, request, pk, format=None): #for detail view Urls.py is creating many urls and sending to same view for list and detail view.But for Create and Update i want to create seperate view with same url. In more detail: This are few urls created by urls.py.There are many. api/ v1/browser/ [name='browser_list'] api/ v1/browser/<int:pk>/ [name='browser_detail'] api/ v1/language/ [name='language_list'] api/ v1/language/<int:pk>/ [name='language_detail'] Now for 'v1/browser/' and 'v1/language/' calls GenericListView.'v1/browser/int:pk/' and 'v1/language/int:pk/' calls GenericDetailView.But when i create,update in 'v1/browser/' i need seperate view for this with same url. -
from_db_value error with cache in django3.0.10
I'm trying to update to Django3 and got an error in cache. Is it an existing bug because it's all an error in the Django package? It seems that this error occurs when the query is cached and the content of the query is empty. How can I handle this error? Traceback (most recent call last): File "project/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "project/lib/python3.8/site-packages/django/core/handlers/base.py", line 145, in _get_response response = self.process_exception_by_middleware(e, request) File "project/lib/python3.8/site-packages/django/core/handlers/base.py", line 143, in _get_response response = response.render() File "project/lib/python3.8/site-packages/django/template/response.py", line 105, in render self.content = self.rendered_content File "project/lib/python3.8/site-packages/django/template/response.py", line 83, in rendered_content return template.render(context, self._request) File "project/lib/python3.8/site-packages/django/template/backends/django.py", line 61, in render return self.template.render(context) File "project/lib/python3.8/site-packages/django/template/base.py", line 171, in render return self._render(context) File "project/lib/python3.8/site-packages/django/test/utils.py", line 95, in instrumented_test_render return self.nodelist.render(context) File "project/lib/python3.8/site-packages/django/template/base.py", line 936, in render bit = node.render_annotated(context) File "project/lib/python3.8/site-packages/django/template/base.py", line 903, in render_annotated return self.render(context) File "project/lib/python3.8/site-packages/django/template/loader_tags.py", line 150, in render return compiled_parent._render(context) File "project/lib/python3.8/site-packages/django/test/utils.py", line 95, in instrumented_test_render return self.nodelist.render(context) File "project/lib/python3.8/site-packages/django/template/base.py", line 936, in render bit = node.render_annotated(context) File "project/lib/python3.8/site-packages/django/template/base.py", line 903, in render_annotated return self.render(context) File "project/lib/python3.8/site-packages/django/template/defaulttags.py", line 398, in render return strip_spaces_between_tags(self.nodelist.render(context).strip()) File "project/lib/python3.8/site-packages/django/template/base.py", line 936, in render bit = node.render_annotated(context) File "project/lib/python3.8/site-packages/django/template/base.py", line 903, in render_annotated return … -
how to deploy django/react app to heroku with different directory structure
I have a django/react app I created using this tutorial here Although slightly different, I then tried to deploy my app to heroku using this tutorial here The directory structure following the tutorials are different though. My directory structure is as follows... django-todo-react/ backend/ backend/ todo/ manage.py ... frontend/ all my react stuff... in my django-todo-react folder (the project root directory) I have requirements.txt, Procfile, package.json, and '.gitignore` file. To my understanding the Procfile should contain something like web: gunicorn backend.wsgi but because my Procfile is in the root directory I do instead the following web: gunicorn backend/backend.wsgi that looks very weird but basically I go into my backend folder where I have my actual backend project I started with django-admin startproject backend and get wsgi. I added all the other stuff from the second tutorial I mentioned this one but still no such luck. I get a COLLECT_STATIC error and if I silence the error everything passes but I then get a application error when opening my heroku app. I have already tried deploying an app just using the 2nd tutorial and all worked fine but that had the directory structure of the second tutorial. I thought that changing … -
Clarification of Django and Celery workings
I implemented an installable app of Django which includes a Rate Limiter (a Python object), but I am afraid of going to production because I find no documentation or readings regarding how production server works compared to Django dev server. The Rate Limiter is a Python object, all the request should go through this limiter in order to be "safe" to make calls (to an API). So far in the Django dev server it is working as expected (everything shares the same rate limiter), but when I enable logs, I see that the app (and the limiter) was initialized twice, which wasn't clear of what is happening at all. While it does work on the dev server, I find no docs of production servers (the server I am using is Daphne or Apache depending if I add websockets support) if this still works as expected (they share the same object). Another question I have is regarding Celery, will Celery tasks also share the same app object (and rate limiter)? I have a task that runs periodically for a large amount of time. -
Django filter returns queryset with ID instead of username
Hi guys so I have a search function but when using the .objects.filter() method I get a queryset that shows an ID instead of the username. This is the view: def search_expense(request): if request.method == 'POST': search_str = json.loads(request.body).get('searchText') expenses = Expense.objects.filter( amount__istartswith=search_str) | Expense.objects.filter( date__icontains=search_str) | Expense.objects.filter( description__icontains=search_str) | Expense.objects.filter( category__icontains=search_str) data = expenses.values() return JsonResponse(list(data), safe=False) <QuerySet [{'id': 16, 'amount': 2.33, 'date': datetime.date(2020, 10, 2), 'description': 'Something', 'owner_id': 1, 'category': 'Food'}]> So instead of the 'owner_id': 1 I need it to be 'owner': username The model (the User model is Django's standard model): class Expense(models.Model): amount = models.FloatField() date = models.DateField(default=now) description = models.TextField() owner = models.ForeignKey(to=User, on_delete=models.CASCADE) category = models.CharField(max_length=255) def __str__(self): return self.category class Meta: ordering: ['-date'] -
Media Files not Loading on pythonanywhere.com (Django)
I deployed a personal portfolio project using pythonanywhere.com's server and my instructor sent me a video explaining why my media files weren't loading properly (https://d.pr/v/RARFcF) but I couldn't understand what he was telling me I should do about it. If you look at my urls.py file I believe my code is good. Can someone please examine this, thanks? Can someone please watch it and help me understand what he was trying to tell me to do!? Thanks. website: https://willpeoples1.pythonanywhere.com/ -
AttributeError: module 'django.db.models' has no attribute 'DataField'
i tried running my server then i got this updated_at=models.DataField(auto_now_add=True) AttributeError: module 'django.db.models' has no attribute 'DataField' Based on the line of the error, here is the code exactly where the error was detected. id=models.AutoField(primary_key=True) name=models.CharField(max_length=225) email=models.CharField(max_length=224) password=models.CharField(max_length=225) created_at=models.DateField(auto_now_add=True) updated_at=models.DataField(auto_now_add=True) objects=models.Manaager() Kindly help me as i am new to python -
Im not sure what im doing wrong here but im guessing i need to change the path
main urls.py: from django.contrib import admin from django.urls import path , include urlpatterns = [ path('admin/', admin.site.urls), path(r'' , include("learning_logs.urls", 'app_name')) ] second urls.py: from django.urls import path from . import views urlpatterns = [ #Home page path(r'^$', views.index, name='index'), ] app_name = 'learning_log' views.py: from django.shortcuts import render def index(request): return render(request , 'learning_logs/index.html') result: djangowebapp -
Django: Order object depending in two values
So I have this: class Thread(models.Model): first_thread_notification = models.IntegerField(default=0) second_thread_notification = models.IntegerField(default=0) I need to order the objects depending on the sum of the 2 objects: class Meta: ordering = ['-first_thread_notification' + '-second_thread_notification'] I know this is incorrect but how can I do it? -
Graphene-django - Mutating types with enums
So, I have the following model: class Semester(models.Model): course = models.ManyToManyField(Course, through='CourseSemester') class SemesterType(models.TextChoices): A = 'A', 'Winter' B = 'B', 'Spring' SUMMER = 'SU', 'Summer' name = models.CharField( max_length=200, choices=SemesterType.choices, default=SemesterType.A, ) year = models.IntegerField() I try to add a mutation to add a new semester. Graphene-django seems to automatically generate an Enum field for me, but how can I get it inside the arguments? According to the github issues, something like SemesterType._meta.fields['name'] should work, but I can't get it right, even with wrapping it inside graphene.Argument. It is possible to tell Graphene not to convert it to Enum, however I'd rather avoid that if possible. Any clue how to get that right? -
Error:405 Method Not Allowed (POST) when trying to save/upload media files to my cpanel server
I keep getting HTTP ERROR 405 when trying to save/upload an image or file to my media directory located in the app root directory on Cpanel. When I checked the error log I got: App 8077 output: [ pid=8077, time=2020-09-02 21:24:43,037 ]: Method Not Allowed (POST): /accounts/profile/ App 8077 output: [ pid=8077, time=2020-09-02 21:24:43,038 ]: Method Not Allowed: /accounts/profile/ Everything works locally, but I don't get why the error appears now I hosted the site on Cpanel shared hosting. in my settings.py I have # ALLOWED_HOST = ['mysubdomain'] DEBUG = False STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] STATIC_ROOT ='/path/to/subdomain/staticfiles' MEDIA_URL='/media/' MEDIA_ROOT='/path/to/subdomain/media' STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' in my urls.py urlpatterns = [ ................., ...................... ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) in my models.py class Profile(models.Model): # Columns for Profile Model user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(verbose_name="Image", upload_to=user_directory_path, default='default.jpg') def __str__(self): # Return the username on the database "e.g Anderson Dean Profile" return "{} {} Profile".format(self.user.first_name, self.user.last_name) # Saves a users profile def save(self, *args, **kwargs): super(Profile, self).save(*args, **kwargs) img = Image.open(self.image) if img.mode != 'RGB': img = img.convert('RGB') if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size, Image.ANTIALIAS) fh = storage.open(self.image.name, "w") … -
ModuleNotFoundError: No module named 'errors'
I have a problem when I try to run my project in django, I put the command of "python3 manage.py runserver [localhost:..]. I have python 3.6.7 and django 2.2.2 in a venv. import errors ModuleNotFoundError: No module named 'errors' -
Extract hours & seconds from Django Interval
I have the following Django PostgreSQL query that calculates an interval; querySet = dbname.objects.all().annotate(duration=Func(F('date_start'), F('date_end'), function='age')) which gives me a date interval, evaluated as a timedelta when .values() is called. Now I'd like to further annotate the query to extract the hours & seconds. Tried django.db.models.functions.Extract, django.db.models.functions.Cast, but can't seem to find a solution. querySet.annotate(hours=Extract('duration', 'hour')) ProgrammingError: function pg_catalog.timezone(unknown, interval) does not exist querySet.annotate(seconds=Cast('duration', DateTimeField())) ProgrammingError: cannot cast type interval to timestamp with time zone -
Phoenix (Elixir) Error running test suite
I have inherited a web project with a backend written in Elixir using the Phoenix framework. I am a Python (Django) developer by trade and new to Elixir. There is 0 test coverage on this project, so I thought that would be a good place to start and get familiar with Elixir and Phoenix. But I get an error message running mix test before I can even get started. 16:27:35.818 [info] Application tzdata started at :nonode@nohost ** (Mix) Could not start application cowboy: exited in: :application.cowboy({:description, 'Small, fast, modular HTTP server.'}, {:vsn, '1.1.2'}, {:id, 'git'}, {:modules, [:cow_uri, :cowboy, :cowboy_app, :cowboy_bstr, :cowboy_clock, :cowboy_handler, :cowboy_http, :cowboy_http_handler, :cowboy_loop_handler, :cowboy_middleware, :cowboy_protocol, :cowboy_req, :cowboy_rest, :cowboy_router, :cowboy_spdy, :cowboy_static, :cowboy_sub_protocol, :cowboy_sup, :cowboy_websocket, :cowboy_websocket_handler]}, {:registered, [:cowboy_clock, :cowboy_sup]}, {:applications, [:kernel, :stdlib, :ranch, :cowlib, :crypto]}, {:mod, {:cowboy_app, []}}, {:env, []}) ** (EXIT) :already_loaded And this is where, I am hoping, my ignorance of Elixir and Phoenix is hindering my debugging capability. Is this tzdata that is throwing this error and not letting the test suite load properly? Any direction or insight is appreciated. -
What happens after Django clean method but before commit?
I am using an awesome library called Django Auditlog. It tracks what changes occurred to an object. For model Book if I changed the Author name from 'John' to 'Mary' it records the before value (John), after value (Mary), when it occurred, and what user made the change. It's working except that it is detecting changes that aren't changes for some of my decimal fields. It thinks a change occurs anytime I save this model: it thinks that I started with .00 and changed it to .0. But .00 is the existing value and I didn't change anything. I just saved() the record. I checked the output of the form itself in the clean() method: services_sub_total 44.00 sum_payments 33.00 And then in the database: I just can't figure out where/why this is detecting only one zero in the decimal place - I'm not seeing that .0 anywhere. So I'm wondering what is happening between the clean() method and the commit that might be truncating the .00 to .0 where Auditlog might be incorrectly detecting a change? -
How to correct CORS errors when redirecting to client from server
I have a django server and react client. My app has been making calls, unabated, to the server for various data I have stored to redux state. Furthermore, I have an authorization flow with an external API achieved via a link (not fetch request) to my backend and then, after obtaining the token, redirects back to my front end. All no problem. The issue comes when I try to refresh my token via get request to my backend. That all works, but then when my backend tries to redirect to my front end I get a CORS error: Access to XMLHttpRequest at 'http://localhost:3000/users/1/.../' (redirected from 'http://localhost:8000/api/callback?refresh_token=....') from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. How do I deal with this? Again, note that the redirect works just fine when I initially authorize the user via the external API, it's almost the exact same flow. That's why I am confused about this error. -
DNS_PROBE_FINISHED_NXDOMAIN when trying to run a django webapp locally on 127.0.0.1:8000
So this weird issue came out after I pulled a project from pythonanywhere into github and then tried to run it locally. Every time I try to run ANY Django project I get this error and generally cannot use my localhost to open any Django projects This is what my settings.py looks like: import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = *REDACTED* # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['*'] PREPEND_WWW = True CORS_REPLACE_HTTPS_REFERER = False HOST_SCHEME = "http://" SECURE_PROXY_SSL_HEADER = None SECURE_SSL_REDIRECT = False # Application definition THUMBNAIL_PRESERVE_FORMAT = True INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'django.contrib.sitemaps', 'dynamic_raw_id', 'django.contrib.humanize', 'ckeditor', 'ckeditor_uploader', 'cachalot', 'sorl.thumbnail', 'cryptocracy' ] SITE_ID = 1 MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'website.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'cryptocracy/templates')], '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 = 'website.wsgi.application' # Database # https://docs.djangoproject.com/en/2.1/ref/settings/#databases DATABASES = { … -
ForeignKey child objects disappeared from table
So for some reason, when I refreshed my api view today the child objects in my model disappeared from the following JSON object: { "id": 1, "title": "test movie", "date": "2020-09-02", "start_date": "2020-09-23", "end_date": "2020-09-24", "location": "Manhattan", "overview": "Adrian", "studio": "Ghibli", "poster": "http://127.0.0.1:8000/media/", "genre": "Horror", "status": "Paid", "job_type": "Fulltime", "user": 1 }, Initially I had right after "id" an indented section "listing" with all the children objects. I've checked my models to make sure that I didn't accidentally delete anything, and I can't quite figure out what went wrong. user_applications is the many to one (Listings) class User_applications(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, default="1") listing = models.ForeignKey(Listings, on_delete=models.CASCADE, default="1", related_name="listing") ... class Listings(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, default="1") ... -
DRF with TokenAuthentication - Authentication credentials were not provided
I've deployed a project on Elastic Beanstalk and I can't figure out why Django Rest Framework returns this response: Authentication credentials were not provided. when I go to ../api/article I'm sending header - Authorization: Token curl -X GET http://environment.eba-etpcqsqk.us-west-1.elasticbeanstalk.com/api/article/ -H 'Authorization: Token MYTOKEN' {"detail":"Authentication credentials were not provided."} Views: class ArticleViewSet(ModelViewSet): queryset = Article.objects.all() serializer_class = ArticleSerializer pagination_class = StandardResultsSetPagination filterset_class = ArticleFilter # user must be either logged in or must provide AUTH TOKEN authentication_classes = [TokenAuthentication, SessionAuthentication] permission_classes = [IsAuthenticated] I've DEBUG=True and it works on the development server. Do you know where is the problem? Maybe EBS doesn't forward Headers? -
Deploying Django project on Heroku: ModuleNotFoundError
No where in my project do I import users. Every single aspect of the project runs locally. I am using visual studio for my project. In my Project Directory Settings.py INSTALLED_APPS = # Add your apps here to enable them 'users.apps.usersConfig', 'resume.apps.resumeConfig', 'MainApp.apps.MainAppConfig', 'crispy_forms', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', Procfile: web: gunicorn Project.Project.wsgi:application Here is the error 2020-08-16T06:35:31.691841+00:00 app[web.1]: Traceback (most recent call last): 2020-08-16T06:35:31.691846+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker 2020-08-16T06:35:31.691850+00:00 app[web.1]: worker.init_process() 2020-08-16T06:35:31.691851+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/workers/base.py", line 129, in init_process 2020-08-16T06:35:31.691852+00:00 app[web.1]: self.load_wsgi() 2020-08-16T06:35:31.691852+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/workers/base.py", line 138, in load_wsgi 2020-08-16T06:35:31.691852+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2020-08-16T06:35:31.691857+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/app/base.py", line 67, in wsgi 2020-08-16T06:35:31.691857+00:00 app[web.1]: self.callable = self.load() 2020-08-16T06:35:31.691858+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 52, in load 2020-08-16T06:35:31.691858+00:00 app[web.1]: return self.load_wsgiapp() 2020-08-16T06:35:31.691858+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 41, in load_wsgiapp 2020-08-16T06:35:31.691859+00:00 app[web.1]: return util.import_app(self.app_uri) 2020-08-16T06:35:31.691859+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/util.py", line 350, in import_app 2020-08-16T06:35:31.691859+00:00 app[web.1]: __import__(module) 2020-08-16T06:35:31.691861+00:00 app[web.1]: File "/app/Project/Project/wsgi.py", line 29, in <module> 2020-08-16T06:35:31.691861+00:00 app[web.1]: application = get_wsgi_application() 2020-08-16T06:35:31.691861+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application 2020-08-16T06:35:31.691862+00:00 app[web.1]: django.setup(set_prefix=False) 2020-08-16T06:35:31.691862+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/django/__init__.py", line 24, in setup 2020-08-16T06:35:31.691863+00:00 app[web.1]: apps.populate(settings.INSTALLED_APPS) 2020-08-16T06:35:31.691863+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/django/apps/registry.py", line 91, in populate 2020-08-16T06:35:31.691863+00:00 app[web.1]: app_config = AppConfig.create(entry) 2020-08-16T06:35:31.691864+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/django/apps/config.py", … -
AttributeError: 'str' object has no attribute 'state_forwards' with django migrations migrations.RunSQL(
I am trying to set the autogenerated id of my postgres tables to a start value of 10000 for different models. I used this article and did the following: python3 manage.py makemigrations core --empty Then in the migration I added: operations = [ migrations.RunSQL( "ALTER SEQUENCE CORE_ORG_id_seq RESTART WITH 10000", "ALTER SEQUENCE CORE_USER_id_seq RESTART WITH 10000", "ALTER SEQUENCE CORE_PARTLISTING_id_seq RESTART WITH 1000", "ALTER SEQUENCE CORE_BOMITEM_id_seq RESTART WITH 1000", "ALTER SEQUENCE CORE_MANUFACTURER_id_seq RESTART WITH 1000;" ), migrations.RunSQL( "ALTER SEQUENCE CORE_BOM_id_seq RESTART WITH 1000", "ALTER SEQUENCE CORE_SPECIFICPART_id_seq RESTART WITH 10000", "ALTER SEQUENCE CORE_GENERICPART_id_seq RESTART WITH 10000;" ), ] I put these in two separate lines because I was getting an error that __init.py__ could only take 6 commands btw. When I run migrate on this, I get: File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/Users/myname/.local/share/virtualenvs/mobiusAPI-NVQT3lgx/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/Users/myname/.local/share/virtualenvs/mobiusAPI-NVQT3lgx/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/myname/.local/share/virtualenvs/mobiusAPI-NVQT3lgx/lib/python3.8/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/Users/myname/.local/share/virtualenvs/mobiusAPI-NVQT3lgx/lib/python3.8/site-packages/django/core/management/base.py", line 371, in execute output = self.handle(*args, **options) File "/Users/myname/.local/share/virtualenvs/mobiusAPI-NVQT3lgx/lib/python3.8/site-packages/django/core/management/base.py", line 85, in wrapped res = handle_func(*args, **kwargs) File "/Users/myname/.local/share/virtualenvs/mobiusAPI-NVQT3lgx/lib/python3.8/site-packages/django/core/management/commands/migrate.py", line 243, in handle post_migrate_state = executor.migrate( File "/Users/myname/.local/share/virtualenvs/mobiusAPI-NVQT3lgx/lib/python3.8/site-packages/django/db/migrations/executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, … -
Django model manager isn't working as expected
I have a model "Name" in models.py file of a django app. from .managers.py import NameManager class Name(models.Model): ....................... objects = NameManager() I have created NameManager in managers.py file. class NameManager(models.Manager): def get_func(self, arg): .............. def check_func(self, arg1, arg2): .............. Now in my views.py file, when I write: from .models import Name if Name.check_func(arg1, arg2): ......................... I am getting an error: type object 'Name' has no attribute 'check_func' Where am I making mistake? -
Access request.GET or inject a variable in Django's auth login/registration form
I have a custom form using Django's auth library and I want some users to click on a link to login/register that will pre-populate the email field, without them having to enter their email (avoid entering it manually and make sure the user uses the email we have on file). A link like this: /account/login?email=name@domain.com However on the receiving page, I can't use this as Django doesn't permit in templates: <input type="text" name="username" placeholder="Email" class="form-control" required="" value="{{ request.GET.get('email', '') }}"> If there is a way to inject a variable in Django's auth template, I don't know how since the view is not accessible. Is there a way to access request.GET.get() in the templates, or is there a better way to do this? -
What do they mean when they are saying for you to put Authorization (eg. token) in header of each request?
I am using Django and doing calls for API. I have not used headers for Django before. Am I creating a header variable? E.G Let's say my API key is 'abcd', and ID is '123', from what I have in mind I do header = {'API':'abcd', 'ID':'123'} class CancelApt(APIVIEW): def post(request, id): pass Is this what they meant? Can someone give me an example? Thanks.