Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
im trying to send authentication request for apple using python and django 1.9, but always giving me unsupported_grant_type
im trying to send authentication request for apple using python and django 1.9, but always giving me unsupported_grant_type def login_with_apple(self, code): apple_url = "https://appleid.apple.com/auth/token" client_secret = generate_apple_client_secret() adapter = AppleOAuth2Adapter(self.request) headers = {'content-type': 'application/x-www-form-urlencoded'} data = {'client_id': settings.CLIENT_ID, 'client_secret': client_secret, 'code': code, 'grand_type': 'authorization_code'} resp = requests.post(url=apple_url, data=data, headers=headers) access_token = None if resp.status_code in [200, 201]: try: access_token = resp.json() except ValueError: access_token = dict(parse_qsl(resp.text)) if not access_token or 'acces_token' not in access_token: raise OAuth2Error( 'Error retrieving access token: %s' % resp.content ) return access_token ** how i generates my client_secret** def generate_apple_client_secret(): now = datetime.utcnow() claims = { 'iss': settings.SOCIAL_AUTH_APPLE_TEAM_ID, 'aud': 'https://appleid.apple.com', 'iat': now, 'exp': now + timedelta(days=180), 'sub': settings.CLIENT_ID, } headers = {'kid': settings.SOCIAL_AUTH_APPLE_KEY_ID, 'alg': 'HS256'} client_secret = jwt.encode( payload=claims, key=settings.SOCIAL_AUTH_APPLE_PRIVATE_KEY, algorithm='HS256', **strong text** headers=headers).decode('utf-8') return client_secret ** im sending a request to apple but always giving me this error** user = self.login_with_apple(ser.instance.token) File "/home/omar/PycharmProjects/Aswaq/oscarapi/views/login.py", line 488, in login_with_apple Error retrieving access token: %s' % resp.content OAuth2Error: Error retrieving access token: {"error":"unsupported_grant_type"} -
Django how can I query only the records which exactly fullfill the filter condition in a Many-to-one condition
I have the following models: class McMbData(models.Model): lastname = models.CharField(max_length=50,blank=True) class Visits(models.Model): mcmbdata_id = models.ForeignKey(McMbData, on_delete=models.CASCADE) name = models.CharField(max_length=50,blank=True) signe_in = models.BooleanField(default=False) I only want to get the records of Visits where signe_in =True Here is what I have tried: McMbData.objects.filter(visits__signe_in = False) So I get all McMbData entries where the condition is fulfilled at least once: Lastname: Mutermann Visits: Bears,True - Renegade,False - Hollywood,False I only want to get the entries of visits which are true. Like this: Lastname: Mutermann Visits: Bears,True -
Response from Google Cloud Platform to Django app
I created a simple Django app and tested in the local server and it was working fine. The app is expected to work like, whenever a post request is received to the corresponding view, the response should be an audio file . In the local server it is working as expected and the response header is showing "'Content-Type': 'audio/mpeg'" but from the Google cloud I am not getting the audio file and the response header is showing the content type as "text/html". Django view if request.method == 'POST': data = request.FILES['file'] tmp = os.path.join(settings.MEDIA_ROOT, "Image", data.name) path = default_storage.save(tmp, ContentFile(data.read())) tmp_file = os.path.join(settings.MEDIA_ROOT, path) # ================ DATA PROCESSING ======================= # Image can be acced in :: tmp_file # ================ DATA PROCESSING - END ======================= fhandle = open("piZero/from_file.mp3", 'rb') # audio output file name tmp = os.path.join(settings.MEDIA_ROOT, "Audio", "output.mp3") path = default_storage.save(tmp, ContentFile(fhandle.read())) audioFile = os.path.join(settings.MEDIA_ROOT, path) # Response build response = HttpResponse() file_handle = open(audioFile, "rb") file = file_handle.read() file_handle.close() response['Content-Disposition'] = 'attachment; filename=filename.mp3' return HttpResponse(file, content_type="audio/mpeg") else: return HttpResponse("GET") app.yaml : since I don't have any static files I haven't run the collect static. In the actual program this audio file will be created from the program. So I … -
Reverse for 'add_review' with arguments '('',)' not found. 1 pattern(s) tried: ['addreview/(?P<id>[0-9]+)/$']
I am getting an error after i have added Review model in django... on admin page model is created but on my site it is not working.I don't know where i am going wrong ...please guide me Getting an error on line 28 of base.html Its also showing an error on views.py line 21 views.py from django.shortcuts import render, redirect from django.http import HttpResponse from .models import * from .forms import * # Create your views here. def home(request): allbooks= book.objects.all() context= { "books": allbooks, } return render(request,'main/index.html',context) #error line def detail (request,id): bk=book.objects.filter(id=id) reviews=Review.objects.filter(book=id) context ={ "book":bk, "reviews":reviews } return render (request,'main/details.html',context) def addBooks(request): if request.user.is_authenticated: if request.user.is_superuser: if request.method== "POST": form=BookForm (request.POST or None) if form.is_valid(): data=form.save(commit=False) data.save() return redirect("main:home") else: form=BookForm() return render (request, 'main/addbooks.html',{"form":form,"controller":"Add Books"}) else: return redirect("main:home") else: return redirect("accounts:login") def editBooks(request,id): if request.user.is_authenticated: if request.user.is_superuser: bk=book.objects.get(id=id) if request.method== "POST": form=BookForm (request.POST or None,instance=bk) if form.is_valid(): data=form.save(commit=False) data.save() return redirect("main:detail",id) else: form=BookForm(instance=bk) return render (request, 'main/addbooks.html',{"form":form,"controller":"Edit Books"}) else: return redirect("main:home") else: return redirect("accounts:login") def deleteBooks(request,id): if request.user.is_authenticated: if request.user.is_superuser: bk=book.objects.get(id=id) bk.delete() return redirect("main:home") else: return redirect("main:home") else: return redirect("accounts:login") def add_review(request,id): if request.user.is_authenticated: bk=book.objects.get(id=id) if request.method == "POST": form= ReviewForm(request.POST or None) if form.is_valid(): data=form.save(commit=False) … -
Django admin template css is not loaded when deploy it in Heroku?
this is the admin page deployed in heroku, enter image description here here is my settings.py STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' deploy_settings.init.py DEBUG = False STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] I tried to run python manage.py collectstatic locally, and run it in heroku bash also, but it didn't work. Do we actually need to run this command? or staticfiles are collected when pushing to heroku master? I tried to add DEBUG_COLLECTSTATIC=1 in heroku config variables, but it doesn't work. one last note, I tried to install whitenoise and add it to the settings.py middlewars, and add STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' in deply_settings.init.py but I recieved this error, enter image description here when -
How to create self defined token in Django Token Auth
Can we create a self-defined token in the Token Auth in Django? Currently, we are creating a super-user and generating a token for that super-user. But there are several environments and we want to keep the token same for all environments. Hence, a self-defined token is needed. -
I Have 2 python files in a same directory i want to import one .py file from another .py file
self.txtok=Button(Login_Frame,text='SIGN-IN',font=('arial',15,'bold'),command=self.Login, height=2,width=10,bd=4,padx=2,pady=2,fg='yellow',bg='brown',) self.txtok.grid(row=4,column=0) def Login(self): if (self.uname.get()=="" or self.upass.get()==""): messagebox.showerror("Error","All the feild are requried") elif(self.uname.get()=="1" and self.upass.get()=="1"): self.root.destroy() import WarehouseInventory #messagebox.showerror("SuccessFull",f"welcome{self.uname.get()}") import WarehouseInventory elif(self.uname.get()=="s" and self.upass.get()=="1"): self.root.destroy() import CRUD [Directrories I cannot execute Import WarehouseInventory in 2nd elif ]1 -
Django-allauth Not sending html email on Signup but works perfectly on other times / for other process
I'm using Django-allauth to authenticate user and I'm successfully send HTML email. But problem is when user SIGNUP then verification email is txt file and when Verification email resend it goes of HTML email. Other times like password Reset, login HTML email works perfectly. Only problem is for new user at time of signup only..... Please help me out.. -
How to use django html template tags in react jsx?
I want to use react as a template engine in django. But i don't know how to use django template tags in react jsx Syntex. I searched the web but i got a very common answer the use django as a backend and make an api with django rest framework and use it in react as an api. But in this i have to run two servers, one for django and another one for react but i want to use both in a single server. For this i have to pass data from django backend to template, and for reflect the data on template i have to use django template tags. But in react i don't know how to do this. Any help plz.... -
Provide a specific folder in the media folder for the user to download
Consider that there are three models that are related: class User(AbstractUser): # Its fields class Event(models.Model) user = models.ForeignKey('User', on_delete=models.CASCADE) # other fields class Event_file(models.Model): event = models.ForeignKey('Event', on_delete=models.CASCADE) file = models.ImageField(upload_to='{1}/{2}'.format(self.event.user, self.event) So we will have this structure in the media folder: media User 1 event 1 (where there are several photos) event 2 (where there are several photos) event 3 (where there are several photos) User 2 event 1 (where there are several photos) child 2 (where there are several photos) How can I provide a button in the web page for each user to download their own folder (ie user folder)? Although the user folder may need to be zipped for download. Note: Folder contents are not fixed and may change over time. Thank you in advance -
how to login multiple user in same browser using django
I am create a application where admin and customer login same browser. I read many blog not able not fix my problem. As Django use session based login. I am facing issue while logout my admin then my customer automatic logout. maybe session based functionally My admin LoginView and Logoutview: class AdminLoginView(SuccessMessageMixin,LoginView): authentication_form = LoginForm template_name = 'login.html' redirect_field_name = reverse_lazy('admin_panel:dashboard') redirect_authenticated_user = False success_message = '%(username)s login Successfully !' def dispatch(self, *args, **kwargs): if self.request.user.is_authenticated: # messages.info(self.request, f"{self.request.user.firstname} is already Logged In") return redirect('/admin/dashboard/') return super().dispatch(*args, **kwargs) def get_success_url(self): url = self.get_redirect_url() LOGIN_REDIRECT_URL = reverse_lazy('admin_panel:dashboard') return url or resolve_url(LOGIN_REDIRECT_URL) class LogoutView(LogoutView): """ Log out the user and display the 'You are logged out' message. """ next_page = "/admin/login" def dispatch(self, request, *args, **kwargs): response = super().dispatch(request, *args, **kwargs) messages.add_message(request, messages.INFO,'Successfully logged out.') return response I have implemented customer based login & logout def LoginView(request): form = LoginForm(request.POST or None) if form.is_valid(): username = form.cleaned_data["username"] password = form.cleaned_data["password"] remember_me = form.cleaned_data["remember_me"] user = User.objects.get(email=username) if user and user.check_password(password): if user.is_active: if remember_me == False: request.session.set_expiry(0) request.session['user_id'] = user.id request.session['username'] = user.email return HttpResponseRedirect('/') else: context = {'auth_error': "You're account is disabled"} return render(request, 'forntend-signin.html', context ) else: context = { … -
Ways to add new row or update existing in a CSV without using mysql using Django / PHP
I have to add a new row or update existing row of a csv file from a webpage (In the form of AJAX table with crud operation ) without using MySQL or any other DB Table . once i add or update the row it should be updated in that CSV file . Is this possible to do in Django / PHP if yes , can anyone provide me the link so that i can refer Thanks -
Django Filter show default last 30 days
Right now I have a filter that allows me to show objects from a specific date range. It's gotten to the point though where it does not make sense to show the full date range. One always ends up filtering for at least the month or last month. How can this month be set up by default? If you manually pick the dates for, let's say, this month the loaded URL looks as such: http://127.0.0.1:8000/stats/?type=&asset=&symbol=&broker=&date_range_min=2020-10-01&date_range_max= Ideally in the end there could be a quick-select button for [this month | last month | this year] filters.py class StatsFilter(django_filters.FilterSet): associated_portfolios = django_filters.ModelMultipleChoiceFilter(queryset=associated_portfolios) date_range = django_filters.DateFromToRangeFilter(label='Date Range', field_name='last_entry', widget=RangeWidget(attrs={'type': 'date'})) class Meta: model = Trade fields = ['type', 'asset', 'symbol', 'broker', 'patterns', 'associated_portfolios'] def get_filterset_kwargs(self, filterset_class): kwargs = super(StatsFilter, self).get_filterset_kwargs(filterset_class) if kwargs['data'] is None: # I've tried just setting a default to a simpler field but have yet to get any results # kwargs['queryset'] = kwargs['queryset'].filter(type='Long') # Is this where I could fitler for the date_range? # kwargs['queryset'] = kwargs['queryset'].filter(date_range= ???) return kwargs -
How to choose a csv file from a number of csv files available in django
I am pretty new to django and python. I have a number of different csv files with same format in my app in django project. I want to choose a particular file using the hyperlink of the project(website). How can I do that? Are there some other methods? -
what is the mean to getting invalid parameter to prefetch_related()
I am getting below error AttributeError: Cannot find 'detail_set' on Article object, 'detail_set' is an invalid parameter to prefetch_related() I want to know that from where this problem is comming. for exapmle:- Is the issue in serializers or in view file? -
Check if row exist in postgresql if not create and insert it
i would like to know if there is a way to check if a row exists in the db, I'm working with an api and I'll be adding a script who will run every 24 hours to collect data from a page wich has data from many companies but if I run the script today and tomorrow for example there's a chance of gather almost the same data with new ones so i need to get rid of those, is a good idea to use COUNT or should i use if statements? I'm adding this json data to my db: { OrgName: name, Direction: Street 123 City: cityname Lat: 13.123123 Lon: 12.123123 Code: XC23-123D } As mentioned before, the data can be repeated in all the keys but not in the code, will code=unique solve the problem? -
ValueError: source code string cannot contain null bytes in django while running python manage.py migrate after inspectdb
I connected my Django with mysql database and ran a sql script to make a database and ran migrations on my django project and I had no errors but to to use the database I had to use python manage.py inspectdb >appname/models.py , after doing this I cleaned my models as it was mentioned in the steps but when I ran python manage.py migrate it gave me this error: MYSQL script create database if not exists payroll_db; use payroll_db; create table m_state(state_code varchar(2) primary key, state_name varchar(30)); create table m_address(address_id integer primary key,building_details varchar(30) NOT NULL, road varchar(20) NOT NULL,landmark varchar(30) NOT NULL, city varchar(30) NOT NULL,state varchar(2) NOT NULL references m_state(state_code),country varchar(30) default 'India'); create table m_company(company_id integer primary key, company_name varchar(50) NOT NULL, building_details varchar(30) NOT NULL, Area Varchar(30), Landmark Varchar(30), City varchar(30), state varchar(2) NOT NULL references m_state(state_code),country varchar(30) default 'India'); create table m_department(company_id integer NOT NULL references m_company(company_id),department_id integer primary key,department_name varchar(30) NOT NULL); create table m_grade(grade_id integer primary key, grade_name varchar(20) NOT NULL); create table m_employee(employee_id integer primary key,employee_name varchar(30) NOT NULL,department_id integer references m_department(department_id),company_id integer NOT NULL references m_company(company_id), building_details varchar(30) NOT NULL, Area Varchar(30), Landmark Varchar(30), City varchar(30), state varchar(2) NOT NULL references … -
python manage.py makemigrations
Hey guys new to coding here. Just started a django python tutorial and when i type into the command: python manage.py makemigrations, it says ModuleNotFoundError: No module named 'products'. I created a model in the models.py 'products' and saved it in the settings.py under the INSTALLED_APPS array. Can anyone help? Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Users/Seung/Documents/DEV/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/Users/Seung/Documents/DEV/lib/python3.8/site-packages/django/core/management/__init__.py", line 377, in execute django.setup() File "/Users/Seung/Documents/DEV/lib/python3.8/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/Seung/Documents/DEV/lib/python3.8/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/Users/Seung/Documents/DEV/lib/python3.8/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'poducts' -
Django - Will adding or removing an index from a table every create an issue with the database and migrations?
I want to understand if adding or removing indexes from models creates issues with migrations Please indicate if any step(s) cause issues with migrations A) On Day One I create the following model class Person(models.Model): person_name = models.CharField(max_length=50) create_date = models.DateTimeField() country = models.ForeignKey(Country, on_delete=models.CASCADE) run migrate and makemigrations commands B) 20,000 records of data are added for the Person model C) I add an index to the person_name field class Person(models.Model): person_name = models.CharField(max_length=50, db_index=True) create_date = models.DateTimeField() country = models.ForeignKey(Country, on_delete=models.CASCADE) run migrate and makemigrations commands D) I remove the index from the person_name field class Person(models.Model): person_name = models.CharField(max_length=50) create_date = models.DateTimeField() country = models.ForeignKey(Country, on_delete=models.CASCADE) run migrate and makemigrations commands -
How can I put JSON from my Javascript code to my Django server?
I want to put JSON from my Javascript code to my Django server. I made test folder and it has test.js and test.html. I wrote test.js var info = [ { "name": "key", "pass": "123", }, ]; console.log(info); const csrftoken = Cookies.get("csrftoken"); var xhr = new XMLHttpRequest(); var userjson = JSON.stringify(info); xhr.open("POST", "http://127.0.0.1:8000/app/index/"); xhr.setRequestHeader("Content-Type", "application/json"); xhr.setRequestHeader("X-CSRFToken", csrftoken); xhr.send(userjson); and I wrote test.html <!DOCTYPE html> <html lang="ja"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <script src="https://cdn.jsdelivr.net/npm/js-cookie@2/src/js.cookie.min.js"></script> <script type="text/javascript" src="test.js"></script> </head> <body> <p>TEST</p> </body> </html> I wrote views.py of app like @csrf_exempt def index(request, data, status=None): json_str = json.dumps(data, ensure_ascii=False, indent=2) print(json_str) return render(request, 'app/top.html') I wrote urls.py of app like urlpatterns = [ path('index/', views.index, name='index'), ] My settings.py is INSTALLED_APPS = [ ・・・ 'corsheaders', ] CORS_ORIGIN_WHITELIST = ( 'http://localhost:8000', 'http://127.0.0.1:8000', ) I run this Django server and accessed http://127.0.0.1:8000/app/index/.I checked index method was called.However when I load test.html, console.log(info) was read but "Access to XMLHttpRequest Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, chrome-untrusted, https. " error happened. Also "POST file://Users/test/127.0.0.1:8000/app/index/ net::ERR_FAILED" error happened.Furthermore in Django server,TypeError: index() missing 1 required positional argument: 'data' error happened. I already installed CORS Unblock(https://chrome.google.com/webstore/detail/cors-unblock/lfhmikememgdcahcdlaciloancbhjino) in Google … -
Auth0 LOGIN URL 404 Not found
Reposting from https://community.auth0.com/t/login-url-404-not-found/52181 Ive setup an auth0 app. I am trying to setup an auth webapp flow and code authorization flow as well; I am following this article: https://auth0.com/docs/quickstart/webapp/django to implement Auth0 web app flow. To implement backend code authorization flow im following: https://auth0.com/docs/quickstart/backend/django Implementations are in this file: apps/auth_zero/auth0backend.py to write both the standard web app flow and the code authorization flow. which subroutes /login/auth0 as auth0/login/auth0; check the main app urls. But I get 404 not found when i Press Login: Ive setup an auth0 app. I am trying to setup an auth webapp flow and code authorization flow as well; I am following this article: https://auth0.com/docs/quickstart/webapp/django to implement Auth0 web app flow. To implement backend code authorization flow im following: https://auth0.com/docs/quickstart/backend/django Implementations are in this file: apps/auth_zero/auth0backend.py to write both the standard web app flow and the code authorization flow. which subroutes /login/auth0 as auth0/login/auth0; check the main app urls. But I get 404 not found when i Press Login: I suspect something must be wrong in my settings; The repo for ref is: https://github.com/Xcov19/covidX/tree/1777fe574c640c31db587e361c32758bc0c175d2/covidX this is my middleware: MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", # Map username from the Access Token payload to # … -
How do i solve this error : django.db.utils.IntegrityError: NOT NULL constraint failed
I'm writing unit tests for my wishlist button/view and I'm trying to check if my book ISBN and the userID is added to the wishlist after I press the button. I've tried it but it keeps giving me the error stated in the title. Here's my code: #tests.py class wishlist_view_test(TestCase): @classmethod def setUpTestData(cls): books.objects.create(ISBN = "976354890", bookName = "testingbook1", bookVersion = "1",bookAuthor = "Carlie Presley", bookPublisher = "TeamBananaMonkey1") retailer.objects.create(retailer= "Amazon", sellerID = 1) retailer_book.objects.create(condition = "new", reviews = "4.5", ID= 1, bookType = "hardcover", ISBN_id= "976354890", sellerID_id = 1, price = 177.98) def test_wishlist_button(self): user = User.objects.create_user(username='user1', password='djangolife') self.client.login(username='user1', password='djangolife') response1 = self.client.post(reverse('TextSearch:wishlist',args=("976354890",))) self.assertEqual(str(wishlist.objects.filter(userid_id= user.id),'<QuerySet [..........]>') #html code <form action="{% url 'TextSearch:wishlist' book.pk %}" method="post"> {% csrf_token %} <input type="hidden" value="{{book.pk}}" name="isbn"> <input type="submit" value="Add to wishlist★"> #views.py class wishlistView(TemplateView): template_name = 'TextSearch/wishlist.html' model = wishlist def post(self, request, pk): isbn = self.request.POST.get('isbn') current_user = request.user book = wishlist(userid_id = current_user.id, ISBN_id = isbn) book.save() return render(request, 'TextSearch/wishlist.html') #models.py class wishlist (models.Model): userid = models.ForeignKey(User, on_delete= models.CASCADE) ISBN = models.ForeignKey(books, on_delete = models.CASCADE) I'm using Django's built-in user model. -
Streamfields wagtail streamform can I add WagtailFormBlock to a different block?
I wanted to include a form in another block class HomeBannerBlock(blocks.StructBlock): background_image = CorrectImageBlock( label = 'Background Image' ) header = HeaderBlock( label="Banner Header", max_length=120, ) text = blocks.CharBlock( label = 'Banner Text', max_length=240, ) form = WagtailFormBlock() class Meta: #noqa template = 'streamfields/home_banner.html' icon = 'square' I was hoping it would pass a {{ form }} that I could loop through in the home_banner.html template. {{ form }} = nothing {{ value.form }} = StructValue([('form', <Form: Provider Sign Up Form>), ('form_action', ''), ('form_reference', '65fa1d39-c603-4537-8c16-245055b3516e')]) {{ value.form.form }} = <Form: Provider Sign Up Form> these will not print a form. If I loop through {{ value.form.form.fields }} it will output the label and value of the field label and help text it a definition table but it will not print the input. Is it possible to use Streamforms like this? -
I am trying to store my media files in google drive. The application is not showing any error other than images are not showing on my web page
This is my setting.py: INSTALLED_APPS = [ ... 'django.contrib.staticfiles', 'jobs', 'gdstorage', ] STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR,'static') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR,'static') GOOGLE_DRIVE_STORAGE_JSON_KEY_FILE = os.path.join(BASE_DIR,'Api_key.json') GOOGLE_DRIVE_STORAGE_MEDIA_ROOT = '/media/' GOOGLE_DRIVE_STORAGE_SERVICE_EMAIL = 'myaccount.iam.gserviceaccount.com' GOOGLE_DRIVE_STORAGE_KEY = '555e8bc_My_Storage_Key_aa4375f' This is my models.py: from gdstorage.storage import GoogleDriveStorage # Define Google Drive Storage gd_storage = GoogleDriveStorage() ... image = models.ImageField(upload_to='images', storage=gd_storage) I am trying to show my media files on my home page but the images are not loading. Thanks in advance. -
charfield and foreignkey without null=True in Django
I have a django project with multiple apps. There are some models in two apps. What I would like to know is how can I makemigrations and migrate without having to pass null=True and default=some_value for some models only in my local environment. This is required because in production these fields should not be null and some value will be passed based on the client requirements. So whenever I create a new model in the said apps I am getting errors while makemigrations for these fields to provide some default value. I am using postgresql. So if I provide some default values in my local database in postgresql will django ignore these errors or is there some way to do this so that I do not have to pass the null value everytime I migrate in my local environment? At present I am passing null values before I migrate in my local environement and delete them before pushing the code to github.