Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Azure Django App has SECRET_KEY Exception
I deployed my django web app on azure using GitHub, but the error I'm getting is: django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. My settings.py file is 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__))) SECRET_KEY = os.getenv('SECRET_KEY') DEBUG = False TEMPLATE_DEBUG = DEBUG ALLOWED_HOSTS = os.getenv('ALLOWED_HOSTS') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static/'), "C:/Users/ande/Documents/FC_Database/FC_Database/frontend/templates/frontend/index.html" ] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'SLAR', 'import_export', 'rest_framework', 'frontend' ] 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 = 'FC_Database.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, "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 = 'FC_Database.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': os.getenv('NAME'), 'USER': os.getenv('USER'), 'PASSWORD': os.getenv('PASSWORD'), 'PORT': 3306, 'HOST': os.getenv('HOST') } } # Password validation # https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.1/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.1/howto/static-files/ STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' … -
convert-engine issue with saving any thumbnail
So I have a model like this from django.db import models from sorl.thumbnail import get_thumbnail class Upload(BaseModel): @staticmethod def upload_path_handler(instance, filename): return f'boxes/{instance.box.id}/uploads/{filename}' @staticmethod def thumbnail_path_handler(instance, filename): return f'boxes/{instance.box.id}/thumbnails/{filename}' def save(self, *args, **kwargs): if self._state.adding: # we cache the file size and store # it into the database to improve performance # we cannot edit the object's file so we don't # bother to modify the file size on updates self.size = self.file.size super(Upload, self).save(*args, **kwargs) thumbnail = get_thumbnail(self.file, '1280x720', crop='center') # sorl is not saving the thumbnails for non-image files return self.thumbnail.save(thumbnail.name, ContentFile(thumbnail.read()), True) super(Upload, self).save(*args, **kwargs) objects = api_managers.UploadManager() size = models.PositiveBigIntegerField() name = models.CharField(max_length=100, default='untitled', validators=[MinLengthValidator(2)]) channel = models.ForeignKey('api_backend.Channel', on_delete=models.CASCADE, editable=False) box = models.ForeignKey('api_backend.Box', on_delete=models.CASCADE, editable=False) owner = models.ForeignKey('api_backend.User', on_delete=models.CASCADE, editable=False) thumbnail = models.ImageField(max_length=512, upload_to=thumbnail_path_handler.__func__, null=True, blank=True) file = models.FileField(max_length=512, upload_to=upload_path_handler.__func__) REQUIRED_FIELDS = [file, owner] the file field can be literally any file, and I want sorl-thumbnail to make a thumbnail for the same and save it into the thumbnail field. I am on windows and am using ImageMagick. [python version- 32 bits] this is the binary distribution I installed. https://imagemagick.org/script/download.php ImageMagick-7.0.10-61-Q16-x86-dll.exe Win32 dynamic at 16 bits-per-pixel component settings.py THUMBNAIL_ENGINE = 'sorl.thumbnail.engines.convert_engine.Engine' However, whenever an upload-model is … -
how to Insert or update if already exists use Django and SQLITE
I want to insert data in SQLite use Django, I want that if data is in Database exist, new record will only update my db, The next is if not exist will insert new. class User(models.Model): email= models.CharField(max_length=200, unique=True) name= models.CharField(max_length=200) salary = IntegerField(null=True) I tried to use try: # update codes except: # Insert codes but failed, all times it insert and fail and it give me error of that email is unique, without update existing record. What can I do? -
Django difficulty ORM annotate/aggregate query suggesion
I'm trying to come up with code for a fairly difficult query (for me at least). I'm not sure it's possible to do in the ORM. If not, dropping into SQL is fine, but I can't quite wrap my head around that either. Say I have these two models: class BlogArticle(models.Model): published_date = models.DateField() sentiment_score = models.DecimalField() Publication(models.Model): articles = models.ForeignKey() In the view, I want to accept Publication ids from query params. I then want to end up with a dictionary with a key for each publication, containing a value of a list of key-value pairs. The key will be a day (using TruncDay('publication_date')), and the value will be the average sentiment_score for that day. For example: { 'Some publication': [ '2021 01 31': 0.23, '2021 01 30': 0.31, ... ], 'Another publication': ... } The closest I've gotten is this: ids = request.GET.getlist('id', []) blog_articles = BlogArticle.objects.filter(publication__id__in=ids) blog_articles = self.perform_other_blog_filters(blog_articles) return blog_articles .annotate(day=TruncDay('publish_date')) .order_by('day').values('day').annotate(Avg('sentiment_score')) This doesn't work, because it will give the average per day for blog articles from all Publication ids passed in, whereas I need them separated by Publication. The kicker here is I need to start from a list of blog articles, not publications, because … -
Redis Django - how to rename all cache keys according to a specific pattern In python (django)
I have multiple keys in redis such as key_1, key_2, key_3 and so on. I wanted to append "s" after each keys prefix, (here key prefix is "key") so it will become keys_1, keys_2, keys_3 I am using django cache from django.core.cache import cache is there any functionality that can rename keys based on pattern or is there anything in redis-cli to solve this problem. Please help. -
why cron job is not showing the output in ubuntu?
I've setup corn job using django. the logs is showing that job is scheduled but it is not working. crontab -e: */1 * * * * /home/karanyogi/E-Mango/env/bin/python /home/karanyogi/E-Mango/Jan27New/eMango/manage.py crontab run 60a198cfdc0c719d07735a708d42bafb >> /path/to/log/file.log # django-cronjobs for iStudyMain Django setup: settings.py: INSTALLED_APPS = [ .. 'django_crontab', ] CRONJOBS = [ ('*/1 * * * *', 'allActivitiesApp.cron.sendNotification', '>> /path/to/log/file.log'), ] CRONTAB_COMMAND_SUFFIX = '2>&1' cron.py: from .models import * def sendNotification(): # notificationList = dateBasedNotificaton.objects.filter(scheduleDate = date.today()) obj = test(name="working") obj.save() obj.refresh_from_db() # print("sending notifications/messages") return "success" (env) karanyogi@karanyogi:~/E-Mango/Jan27New/eMango$ python manage.py crontab show Currently active jobs in crontab: 60a198cfdc0c719d07735a708d42bafb -> ('*/1 * * * *', 'allActivitiesApp.cron.sendNotification', '>> /path/to/log/file.log') also when I check the logs of ubuntu it is showing something is running: **** CRON[56232]: ***** CMD (/home/karanyogi/E-Mango/env/bin/python /home/karanyogi/E-Mango/Jan27New/eMango/manage.py crontab run 60a198cfdc0c719d07735a708d42bafb >> /path/to/> -
Istio 503 Service Unavailable (Django App)
I am trying to implement Istio on a Django project. The projects work fine until Istio sidecars are injected to the pods, and I am unable to access the app inside Istio. Deployments.yaml apiVersion: apps/v1 kind: Deployment metadata: name: api-manager labels: app: api-manager spec: replicas: 1 selector: matchLabels: app: api-manager template: metadata: labels: app: api-manager spec: containers: - name: api-manager image: api-manager:v1 command: ["python", "manage.py", "runserver", "0.0.0.0:8000"] imagePullPolicy: Always ports: - containerPort: 8000 Service.yaml apiVersion: v1 kind: Service metadata: name: api-manager-service spec: selector: app: api-manager type: LoadBalancer ports: - protocol: TCP name: http port: 8000 targetPort: 8000 Istio Gateway and Virtual Service apiVersion: networking.istio.io/v1alpha3 kind: Gateway metadata: name: api-manager-gateway spec: selector: istio: ingressgateway # use istio default controller servers: - port: number: 90 name: http protocol: HTTP hosts: - "*" --- apiVersion: networking.istio.io/v1alpha3 kind: VirtualService metadata: name: api-manager-vs spec: hosts: - "*" gateways: - api-manager-gateway http: - route: - destination: host: api-manager-service port: number: 8000 I use http://localhost:90/ to access the app inside that returns 503 Service Unavailable. The Application is accessible and works fine inside kubernetes with out Istio. I also tried disabling tls to see if that was causing the issue, but that did not work. -
django.db.utils.IntegrityError: duplicate key value violates unique constraint “my_model_id_pkey”
Stack: Django2.2.5/Postrgesql 10/Docker I try to run a test where I create User and related Customers models based on csv file 5 Users are creating with Django data migration as initial data When I run my test, I got an error but I do not understand why ... pk (user_id)=(6) already exist But this PK should not already exist I DROP and CREATE DATABASE but always the same issue def test_create_customers(self): with open('./import/randomuser.csv', newline='') as csvfile: has_header = csv.Sniffer().has_header(csvfile.read(1024)) csvfile.seek(0) spamreader = csv.reader(csvfile, delimiter=',', quotechar='|') if has_header: next(spamreader) for row in spamreader: user = User.objects.create( password = row[0], is_superuser = strtobool(row[2]), username = row[3], first_name = row[4], last_name = row[5], email = row[6], is_staff = strtobool(row[7]), is_active = strtobool(row[8]), ) Customers.objects.create( user = User.objects.get(username=row[3]), customer_type = 3, drink_preferences = 2, food_preferences = 1, ) -
Choose multiple choices in a MultipleChoiceField generated from a dynamic tuple list in Django 2.2
I have a MultipleChoiceField that is generated dynamically from a filtered tupled list and I want to be able to choose, or select multiple choices. The below form field only works for selecting one choice, how can I change it to select multiple choices? # in forms.py class Form1(forms.ModelForm): class Meta: model = ModelA fields = ('title',) def __init__(self, *args, **kwargs): self.dynamic_ls = kwargs.pop('dynamic_ls', None) super(Form1, self).__init__(*args, **kwargs) # It's only possible to select one choice with this widget and with this formulation when I want to select multiple choices self.fields['options'] = forms.MultipleChoiceField(widget=forms.SelectMultiple(attrs={'class': 'form-control'}),choices=[(o, str(o)) for o in self.dynamic_ls], required=False) def clean(self): cleaned_data = super(Form1, self).clean() return cleaned_data -
How Can I Host My Django Project On Hostinger Shared Hosting
Please Tell Me That How Can I Host My Django Project On Hostinger shared Hosting Otherwise My Rs.6200 Will Waste -
Django loaddata command error - cannot find fixutres
I can't figure this out.. I've tried what seems like every possible variation, loaddata can't find fixtures in any of my apps. It works in previous versions of Django but on 3.1.5 it does not work. CommandError: No fixture named 'products' found. python manage.py loaddata products python manage.py loaddata products.json python manage.py loaddata products --app product python manage.py loaddata product/fixtures/products python manage.py loaddata product/fixtures/products.json python manage.py loaddata */fixtures/*.json Here's my folder structure myproject ├─product ├─fixtures ├─products.json ├─models.py -
Use user_passes_test after login_required in function based view
I have written a passing condition for user which is as follows: def check_admin(user): isAdmin = False if user.role == "ADMIN": isAdmin=True return isAdmin This is working fine in class based view: class AgentUpdate(LoginRequiredMixin,UpdateView): model = User form_class = UserUpdateForm template_name_suffix = '_update_form' success_url='/agents' @method_decorator(user_passes_test(check_admin)) def dispatch(self, *args, **kwargs): return super(AgentUpdate, self).dispatch(*args, **kwargs) Bu when i use it in function based view it is giving me error 'AnonymousUser' object has no attribute 'role' @login_required @user_passes_test(check_admin) def upload_topic(request): ---- Rest of the view--- -
Ajax/Axios cookies not being set, but still being included in following requests
For some reason cookies set by server are not being saved, can't access them from within my js code, in devtools in Application tab in cookies section it's all empty, but somehow when I make a request to the server after the initial one, those cookies that apparently didn't save are being included in the header. I have set withCredentials to true in axios config, as well as CORS_ALLOW_CREDENTIALS to true on my backend. Here are the headers from the request that should save cookies: Response Header: access-control-allow-credentials: true access-control-allow-origin: <frontend url> content-length: 22 content-type: text/html; charset=utf-8 date: Mon, 01 Feb 2021 12:04:09 GMT server: nginx/1.19.2 set-cookie: csrftoken=<token>; expires=Mon, 31 Jan 2022 12:04:09 GMT; Max-Age=31449600; Path=/; SameSite=Lax set-cookie: sessionid=<sessionid>; expires=Mon, 01 Feb 2021 13:04:09 GMT; HttpOnly; Max-Age=3600; Path=/ strict-transport-security: max-age=31536000 vary: Cookie, Origin x-frame-options: SAMEORIGIN Request Headers: :authority: <backend url> :method: POST :path: /login/ :scheme: https accept: application/json, text/plain, */* accept-encoding: gzip, deflate, br accept-language: en-US,en;q=0.9 cache-control: no-cache content-length: 66 content-type: application/json;charset=UTF-8 dnt: 1 origin: <frontend url> pragma: no-cache referer: <current frontend url query> sec-fetch-dest: empty sec-fetch-mode: cors sec-fetch-site: same-site user-agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36 As you can see in the response I'm getting … -
Online store deployment error, with many models
As soon as I click on the link, a standard error is written to me. Tried to increase the request processing time but the error persists. I also updated the database completely and changed the host address. Before adding a new model, everything worked, but as soon as I made a couple of changes it stopped working. Here is my code https://github.com/Daryna00/My File location Preset >home >media >merchan >order >Preset >product >staticfiles >templates >' >db.sqlite3 >debug.log >manage.py >Procfile >requirements.txt >runtime.txt Procfile web: gunicorn Preset.wsgi After entering the command such errors. (venv) D:\PycharmProjects\My\Preset>heroku logs --tail 2021-02-01T11:48:20.661821+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1007, in _find_and_load 2021-02-01T11:48:20.661821+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked 2021-02-01T11:48:20.661822+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 680, in _load_unlocked 2021-02-01T11:48:20.661822+00:00 app[web.1]: File "<frozen importlib._bootstrap_external>", line 790, in exec_module 2021-02-01T11:48:20.661823+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed 2021-02-01T11:48:20.661823+00:00 app[web.1]: File "/app/home/urls.py", line 2, in <module> 2021-02-01T11:48:20.661835+00:00 app[web.1]: from .views import index, what_is_it, sign_in, register, logout_user, my_page, ajax_reg_login, contact, change_order_count, delete_from_card, add_to_card, get_pdf, questions_answer 2021-02-01T11:48:20.661835+00:00 app[web.1]: File "/app/home/views.py", line 19, in <module> 2021-02-01T11:48:20.661836+00:00 app[web.1]: from xhtml2pdf import pisa 2021-02-01T11:48:20.661836+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/xhtml2pdf/pisa.py", line 18, in <module> 2021-02-01T11:48:20.661836+00:00 app[web.1]: from xhtml2pdf.default import DEFAULT_CSS 2021-02-01T11:48:20.661837+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/xhtml2pdf/default.py", line 5, in … -
ImportError: No module named attr while starting any docker-compose file [closed]
Tried reinstalling docker but didn't help Traceback (most recent call last): File "/usr/bin/docker-compose", line 11, in <module> load_entry_point('docker-compose==1.17.1', 'console_scripts', 'docker-compose')() File "/usr/lib/python2.7/dist-packages/pkg_resources/__init__.py", line 480, in load_entry_point return get_distribution(dist).load_entry_point(group, name) File "/usr/lib/python2.7/dist-packages/pkg_resources/__init__.py", line 2693, in load_entry_point return ep.load() File "/usr/lib/python2.7/dist-packages/pkg_resources/__init__.py", line 2324, in load return self.resolve() File "/usr/lib/python2.7/dist-packages/pkg_resources/__init__.py", line 2330, in resolve module = __import__(self.module_name, fromlist=['__name__'], level=0) File "/usr/lib/python2.7/dist-packages/compose/cli/main.py", line 20, in <module> from ..bundle import get_image_digests File "/usr/lib/python2.7/dist-packages/compose/bundle.py", line 12, in <module> from .config.serialize import denormalize_config File "/usr/lib/python2.7/dist-packages/compose/config/__init__.py", line 6, in <module> from .config import ConfigurationError File "/usr/lib/python2.7/dist-packages/compose/config/config.py", line 44, in <module> from .validation import match_named_volumes File "/usr/lib/python2.7/dist-packages/compose/config/validation.py", line 12, in <module> from jsonschema import Draft4Validator File "/usr/local/lib/python2.7/dist-packages/jsonschema-3.2.0-py2.7.egg/jsonschema/__init__.py", line 11, in <module> from jsonschema.exceptions import ( File "/usr/local/lib/python2.7/dist-packages/jsonschema-3.2.0-py2.7.egg/jsonschema/exceptions.py", line 9, in <module> import attr ImportError: No module named attr -
python manage.py runserver giving nameError: Python not defined
I am using the following command: (env) C:\Users\Raktim_PC\PycharmProjects\pythonProject\mysite>python manage.py runserver This results in the following error: Traceback (most recent call last): File "manage.py", line 1, in <module> python#!/usr/bin/env python NameError: name 'python' is not defined I am getting started with Django framework and was following an online tutorial. I am in the outer mysite folder under which another mysite and mnagae.py resides when I am running the command leading to this error. Any ideas on what might be causing this and a possible solution? -
How to display list items in descending order in django?
I've created a website that streams cartoons. On the first page, the user gets to see the entire list of cartoons. When clicked, a page showing the details of the cartoon as well its corresponding seasons loads. When a specific season is clicked. It shows the list of episodes that season has. Now what happens is that it displays the episodes normally, however, it shows them in a jumbled format. I want to show it in descending order. How am I supposed to go about doing that? Here are my files. If you didn't understand this description of my problem(which you probably didn't) you can see the website for yourself http://cartoonpalace.herokuapp.com: Views.py from django.shortcuts import render from django.http import HttpResponse from django.views.generic import ListView, DetailView from .models import CartoonSeason, Cartoon, Episode # Create your views here class CartoonListView(ListView): model = Cartoon template_name = "index.html" class CartoonSeasonView(DetailView): model = Cartoon template_name = "season.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["seasons"] = CartoonSeason.objects.filter(cartoon=self.object) return context class SeasonDetailView(DetailView): model = CartoonSeason template_name = "episode_list.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["episodes"] = Episode.objects.filter(season=self.object) return context class EpisodeDetailView(DetailView): model = Episode template_name = "episode.html" Models.py # Create your models here. from django.db import models … -
Django rest framework queryset gives me .pk i want .name
my model class Vacatures(models.Model): title = models.CharField(max_length=50) employer = models.ForeignKey(Employer, on_delete=models.CASCADE) my .view class VacaturesOverzichtMobile(generics.ListAPIView): model = Vacatures serializer_class = VacaturesSerializer queryset = Vacatures.objects.all() def get_queryset(self): queryset = Vacatures.objects.all() return queryset So in the model there is Employer as Foreingkey. The api call in .view is working fine. The only thing is i get the employer as employer.pk , but i want the name of the Employer which is in the EmployersModel. Can i tune the queryset so that it returns employer.name for example instead of employer.pk -
Changing db_table on Django doesn't work after migrations, and adding a user (AbstractUser) foreign key breaks __str__()
This is a 2 problem post, which i suspect are somehow connected. My posts app on Django doesn't migrate properly (I think), and adding the 'author' (Users AbstractUser model) breaks my code with the error: str returned non-string (type tuple) whenever I try to add a row. I changed the name of the table using db_table (so it will change Postss to Posts on the admin page) and added an output to the __str__ function, I tried a few variations of output for the str function but non of them worked. I even tried to comment it out. and still. no changes in the table name or the error. I tried changing my str functions a few times and got the same result. when deleting the str function, I still get that same result. I have a few wild guesses about this situation: it might not work with an abstract users class for some reason, and do not know to to work around this and why this happens at all. (removeing the author=... row resolves this problem but doesn't change the table name, but I do need the user fk there). it might not be migrating properly due to my … -
Django: Include template with constructed name if available
I have a one template say: default_form.html which receives in its context a variable, say variant. I can of course render the contents of the variable with {{ variant }} And here: https://stackoverflow.com/a/28076380/4002633 I see a wonderful way to load a template if it exists. It works nicely if I have a template called variant as follows: {% try_include variant %} But I am hoping to go one step further. I would like to use a constructed template name, in the example above and include if it exists a template named default_form_variant.html. I imagine something like this: {% try_include "default_form_{{variant}}.html" %} but even more general rather than encoding the current template's name, getting that, if possible, from the context itself or in a custom tag from the parser. I am struggling to see how and where in the custom tag definition I'd have access to three things at once: The name of the current template: default_form.html in this case. The argument to the tag: variant in this case The ability to construct a template name from the first two (easy enough with os.path) and inject it into the do_include handler. -
choices are not showing in the selectbox in django
I am trying to add categories in my project. So that whenever user post a blog he will add category also but in the select box it is not showing I tried this : from django import forms from .models import Post,Category,Comment choices = Category.objects.all().values_list('name','name') choice_list = [] for item in choices: choice_list.append(item) class AddForm(forms.ModelForm): class Meta: model = Post fields = ('title','title_tag','author','category','body','snippet','header_image') widgets = { 'title' : forms.TextInput(attrs={'class':'form-control','placeholder':'Title of the Blog'}), 'title_tag' : forms.TextInput(attrs={'class':'form-control','placeholder':'Title tag of the Blog'}), 'author' : forms.TextInput(attrs={'class':'form-control','value':'','id':'elder','type':'hidden'}), 'category' : forms.Select(choices=choice_list, attrs={'class':'form-control','placeholder':"blog's category"}), 'body' : forms.Textarea(attrs={'class':'form-control','placeholder':'Body of the Blog'}), 'snippet' : forms.Textarea(attrs={'class':'form-control'}), } -
Is the server running on host host (192.46.237.35) and accepting TCP/IP connections on port 5432? Django&PostgreSQL
Basically i am trying to connect my postgresql database to my DjangoApp inside my Linode server,but i get this error. I have everything included here. Why do i get this error?Does somebody have the solution? -
CustomAuthBackend() missing 1 required positional argument: 'ModelBackend'
My models were fine, migrate successfully and I am able to create superuser. I am not able to go to admin login page as the error shows up "CustomAuthBackend() missing 1 required positional argument: 'ModelBackend'" In Custom Backends: def CustomAuthBackend(ModelBackend): def authenticate(self, request, email=None, password=None, phone=None): my_user_model = get_user_model() user = None if email: try: user = my_user_model.objects.get(email=email) except: return None #Return None if no such user elif phone: try: user = my_user_model.objects.get(phone=phone) except: return None #Return None is no such user if user: if user.check_password(password): return user else: return None def get_user(self, user_id): my_user_model = get_user_model() try: return my_user_model.objects.get(pk=user_id) except my_user_model.DoesNotExist: return None In Settings: AUTH_USER_MODEL = 'authengine.User' AUTHENTICATION_BACKENDS = ['authengine.backends.CustomAuthBackend'] Screenshot -
Permission Denied with react-google-login
I am using a Django backend and using django-rest-framework-social-oauth2 to manage my social logins. I am using react for my frontend and I am using the react-google-login package. But the problem is whenever I try to authenticate, the permission denied warning is shown as you can see in the pictures. I have tried putting in localhost and the IP address but to no avail. Any help is appreciated. Permission Denied -
Django ValueError: Cannot assign must be an instance
when i try to insert data to my database through manage.py shell, i got this error ValueError: Cannot assign "'Ciawigebang'": "Desa.kecamatan" must be a "Kecamatan" instance. this is my models.py from django.db import models class Kecamatan(models.Model): kecamatan = models.CharField(max_length=30) def __str__(self): return self.kecamatan class Desa(models.Model): desa = models.CharField(max_length=30) kecamatan = models.ForeignKey(Kecamatan, null=True, blank=True, on_delete=models.CASCADE) def __str__(self): return self.desa here my json file snippet scrap.json [ { "Kecamatan": "Ciawigebang", "Desa": [ "Ciawigebang", "Ciawilor", "Cigarukgak", "Cihaur", "Cihirup", "Cijagamulya", "Cikubangmulya", "Ciomas", "Ciputat", "Dukuhdalem", "Geresik", "Kadurama", "Kapandayan", "Karangkamulya", "Kramatmulya", "Lebaksiuh", "Mekarjaya", "Padarama", "Pajawanlor", "Pamijahan", "Pangkalan", "Sidaraja", "Sukadana", "Sukaraja" ] },{ "Kecamatan": "Cibeureum", "Desa": [ "Cibeureum", "Cimara", "Kawungsari", "Randusari", "Sukadana", "Sukarapih", "Sumurwiru", "Tarikolot" ] },{ "Kecamatan": "Cibingbin", "Desa": [ "BANTAR PANJANG", "CIANGIR", "Cibingbin", "Cipondok", "CISAAT", "Citenjo", "DUKUHBADAG", "Sindang Jawa", "SUKA MAJU", "SUKAHARJA" ] }... ] this is the code i use to insert the data to database from python manage.py shell import json from apps.models import Desa, Kecamatan with open('scrap.json') as f: daerahs = json.load(f) for daerah in daerahs: for x in daerah['Desa']: y=Desa(desa=x, kecamatan=daerah['Kecamatan']) y.save() how to solve this? there's so many similar question but i can't figure it out how to solve this problem in my case. Thanks for your help...