Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django-rest-framework custom user model login failed
I am using django custom usermodel with restframework , after registering successfully I am unable to login for normal users.I am able to login via the initial superuser but if I create new superuser ,they are registered successfully but gives error while logging in as when trying with a normal user. Error Please enter the correct email and password for a staff account. Note that both fields may be case-sensitive. For few profiles I also observed following error in admin panel. invalid password format or unknown hashing algorithm models.py from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin from django.db import models from django.utils import timezone class UserManager(BaseUserManager): def _create_user(self, email, password, is_staff, is_superuser, **extra_fields): if not email: raise ValueError('Users must have an email address') now = timezone.now() email = self.normalize_email(email) user = self.model( email=email, is_staff=is_staff, is_active=True, is_superuser=is_superuser, last_login=now, date_time_onboarded=now, **extra_fields ) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password, **extra_fields): return self._create_user(email, password, True, True, **extra_fields) def create_superuser(self, email, password, **extra_fields): user = self._create_user(email, password, True, True, **extra_fields) return user class AppOnboarding(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=254, unique=True) product_name = models.CharField(max_length=254, null=True, blank=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=True) is_active = models.BooleanField(default=True) last_login = models.DateTimeField(null=True, blank=True) date_time_onboarded = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = 'email' EMAIL_FIELD … -
"Reverse for 'about' with no arguments not found. 1 pattern(s) tried: ['$about$'] Request Method:"
blog_project\mysite\blog\templates\blog\base.html, error at line 26 Line number 26 is About In App's URL file: # url(r'^about', views.AboutView.as_view(), name='about'), path('about',views.AboutView.as_view(), name='about'), Tried both with and without $ sign. And in views.py file class AboutView(TemplateView): template_name = 'about.html' -
Axes Backend Request Parameter Required django
i'm using axes in my customised view in order to block my ecommers costumers after 3 fail logs. i'm getting an error "Axes Backend Request Parameter Required" each time i try to log with any user. The error disappear if delete 'axes.backends.AxesBackend' from AUTHENTICATION_BACKENDS. I'll apreciate any help or sugestion. Thanks Error: AxesBackendRequestParameterRequired at /account/signin/ AxesBackend requires a request as an argument to authenticate AUTHENTICATION_BACKENDS = [ # AxesBackend should be the first backend in the AUTHENTICATION_ 'axes.backends.AxesBackend', # Django ModelBackend is the default authentication backend. 'django.contrib.auth.backends.ModelBackend', INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'store', 'stripe', 'crispy_forms', 'axes', ] 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', #clickjacking protection # 'axes.middleware.FailedLoginMiddleware', 'axes.middleware.AxesMiddleware', Thanks -
Django: TypeError: Calling `.seed()` on instances is deprecated. Use the class method `Faker.seed()` instead
i tried to make virtual data using django_seed. when python version was 3.7, there was no error. however, after updating python to 3.8 version there are error. what this error means? -
AttributeError: 'tuple' object has no attribute '_committed'
Full traceback: Traceback (most recent call last): File "crawl_ebaumsworld.py", line 92, in <module> crawl(first_url) File "crawl_ebaumsworld.py", line 66, in crawl creator=mike File "/home/michael/projects/deepsteg/venvdeepsteg/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/michael/projects/deepsteg/venvdeepsteg/lib/python3.6/site-packages/django/db/models/query.py", line 422, in create obj.save(force_insert=True, using=self.db) File "/home/michael/projects/deepsteg/engine/models.py", line 62, in save return super(AttackImage, self).save(*args, **kwargs) File "/home/michael/projects/deepsteg/venvdeepsteg/lib/python3.6/site-packages/django/db/models/base.py", line 741, in save force_update=force_update, update_fields=update_fields) File "/home/michael/projects/deepsteg/venvdeepsteg/lib/python3.6/site-packages/django/db/models/base.py", line 779, in save_base force_update, using, update_fields, File "/home/michael/projects/deepsteg/venvdeepsteg/lib/python3.6/site-packages/django/db/models/base.py", line 870, in _save_table result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) File "/home/michael/projects/deepsteg/venvdeepsteg/lib/python3.6/site-packages/django/db/models/base.py", line 908, in _do_insert using=using, raw=raw) File "/home/michael/projects/deepsteg/venvdeepsteg/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/michael/projects/deepsteg/venvdeepsteg/lib/python3.6/site-packages/django/db/models/query.py", line 1186, in _insert return query.get_compiler(using=using).execute_sql(return_id) File "/home/michael/projects/deepsteg/venvdeepsteg/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1334, in execute_sql for sql, params in self.as_sql(): File "/home/michael/projects/deepsteg/venvdeepsteg/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1278, in as_sql for obj in self.query.objs File "/home/michael/projects/deepsteg/venvdeepsteg/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1278, in <listcomp> for obj in self.query.objs File "/home/michael/projects/deepsteg/venvdeepsteg/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1277, in <listcomp> [self.prepare_value(field, self.pre_save_val(field, obj)) for field in fields] File "/home/michael/projects/deepsteg/venvdeepsteg/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1228, in pre_save_val return field.pre_save(obj, add=True) File "/home/michael/projects/deepsteg/venvdeepsteg/lib/python3.6/site-packages/django/db/models/fields/files.py", line 286, in pre_save if file and not file._committed: AttributeError: 'tuple' object has no attribute '_committed' models.py class AttackImage(models.Model): title = models.CharField(max_length=255) image = models.ImageField(upload_to='attack_images', blank=True, null=True) source_url = models.URLField(blank=True,null=True) domain = models.ForeignKey(Domain, on_delete=models.CASCADE, blank=True, null=True) creator = models.ForeignKey(User, on_delete=models.CASCADE, … -
Django Defender Connection error at /admin/login
the las couple of days i have been trying to find the solution to my issue, i'm trying to use Defender to block access after some fail loggin access. I installed it, set the backends ,installed app, middleware, and views. i read and tried to find the solution but i didnt find anything. Any sugestion? SETTINGS CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379/1", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient" }, "KEY_PREFIX": "example" } } # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'store', 'stripe', 'crispy_forms', 'defender', ] 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', 'defender.middleware.FailedLoginMiddleware', ] AXES_LOCK_OUT_AT_FAILURE = True AXES_USE_USER_AGENT = False # AXES_COOLOFF_TIME = 1 AXES_LOGIN_FAILURE_LIMIT = 2 #defender customizing DEFENDER_LOGIN_FAILURE_LIMIT = 2 DEFENDER_DISABLE_IP_LOCKOUT = True DEFENDER_USE_USER_AGENT = True DEFENDER_COOLOFF_TIME = 1 Thansk you so much, i will apreciate any help -
New Project in Django. Can't access admin
I am a beginner and have been practicing creating django projects with vscode. I created a new project and set up a superuser. I then ran the server. The development server was http://127.0.0.1:8000 as usual and the django page come up. I went to admin and the login page came up. I logged in as superuser and got the following error: This site can’t be reached 127.0.0.1 refused to connect. When I went back to vscode, the server was shut down. I thought it might be a problem with a firewall, but I have completely uninstalled my anti-virus and changed the settings on windows defender to allow VScode access through the firewall, but nothing works. I exited the project, deleted it and set up a new project. The same thing happened and it did not matter what browser I used. I have set up a dozen projects before and never had this problem. -
Template tag into column name
I'm trying to add filter field from django-filter to replace column name in django-tables2. Is there any way to do that? I tried: tables.Column(verbose_name="{{ filter.form.as_p }}") but it just interprets it as a text. Is there a way to put that there with use of those libraries? I use django_filters.ChoiceFilter as filter type. -
I'm facing a problem with redirecting in class-based success_url
I'm working with Django 2.2 and I'm facing a problem with redirecting in class-based success URL. enter code here - view.py class LetterFormView(CreateView): template_name = 'post.html' model = Letter form_class = LetterForm def get_success_url(self): return reverse ('mainapp:user-profile') and the url.py enter code here- urls.py path('profile/<username>/', views.UserProfilePage.as_view(), name='user-profile'), Now I'm not sure how to pass the username argument in here. -
Passwords are not hashed in Django as well as some missing columns
I'm not sure why my passwords are not hashed when creating a new user using Django Rest Framework This is what I see in postgres. Not sure why my admin/staff/active columns aren't showing up either even after migrating models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class UserManager(BaseUserManager): def create_user(self, email, password=None, first_name=None, last_name=None, is_active=True, is_staff=False, is_admin=False): if not email or not first_name or not last_name: raise ValueError('Email is required') if not password: raise ValueError('Password is required') if not first_name: raise ValueError('First name is required') if not last_name: raise ValueError('Last name is required') user_object = self.model( email=self.normalize_email(email), first_name=first_name, last_name=last_name, active=is_active, staff=is_staff, admin=is_admin, ) user_object.set_password(password) # change password user_object.save(self._db) return user_object def create_staff_user(self, email, first_name, last_name, password=None): staff_user_object = self.create_user(email, first_name, last_name, password, is_staff=True) return staff_user_object def create_superuser(self, email, first_name, last_name, password=None): super_user_object = self.create_user(email, first_name, last_name, password, is_staff=True, is_admin=True) return super_user_object class User(AbstractBaseUser): email = models.EmailField(unique=True, max_length=255) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) date_joined = models.DateTimeField(auto_now_add=True) # joined timestamp is_active = models.BooleanField(default=True) # Can login? is_staff = models.BooleanField(default=False) # staff user, non super user is_admin = models.BooleanField(default=False) # super user? objects = UserManager() USERNAME_FIELD = 'email' EMAIL_FIELD = 'email' REQUIRED_FIELDS = [] # email and passwords are required … -
How to require authentication to all views using social-auth-app-django? (All views are showing to non authenticated users)
I'm using social-auth-app-django version 3.1.0, and the login using Google OAuth2 is apparently running fine (I can succeed to login and get redirected back, also the user data from login is saved correctly (username, email)) But all my routes/views are accessible without authentication, even with the SocialAuthExceptionMiddleware (It was suposed to block this kind of unauthorized access I guess). I just need all my current views (routes) to require authentication and redirect user to my login page. This is my settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_jinja', 'bootstrapform_jinja', 'django_celery_results', 'social_django', 'apps' ] MIDDLEWARE = [ 'social_django.middleware.SocialAuthExceptionMiddleware', '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', 'wharf.auth.LoginRequiredMiddleware' ] AUTHENTICATION_BACKENDS = [ 'social_core.backends.google.GoogleOAuth2', 'wharf.auth.SettingsBackend', 'django.contrib.auth.backends.ModelBackend' ] # Social Login Django SOCIAL_AUTH_POSTGRES_JSONFIELD = True SOCIAL_AUTH_URL_NAMESPACE = 'social' SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = os.environ.get('SOCIAL_AUTH_GOOGLE_OAUTH2_KEY', '') SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = os.environ.get('SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET', '') SOCIAL_AUTH_GOOGLE_OAUTH2_USE_UNIQUE_USER_ID = True SOCIAL_AUTH_STRATEGY = 'social_django.strategy.DjangoStrategy' SOCIAL_AUTH_STORAGE = 'social_django.models.DjangoStorage' LOGIN_REDIRECT_URL = "/" LOGIN_URL = "/" SESSION_COOKIE_SAMESITE = None LOGIN_EXEMPT_URLS = ["webhook", "favicon.ico", "status"] SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.auth_allowed', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.user.get_username', 'social_core.pipeline.user.create_user', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', ) ROOT_URLCONF = 'wharf.urls' TEMPLATES = [ { 'BACKEND': 'django_jinja.backend.Jinja2', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'social_django.context_processors.backends', 'social_django.context_processors.login_redirect', 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], "match_extension": None, "app_dirname": "templates", }, }, … -
Efficient way of running Django query over list of dates
I am working on an investment app in Django which requires calculating portfolio balances and values over time. The database is currently set up this way: class Ledger(models.Model): asset = models.ForeignKey('Asset', ....) amount = models.FloatField(...) ... class HistoricalPrices(models.Model): asset = models.ForeignKey('Asset', ....) price = models.FloatField(...) date = models.DateTimeField(...) Users enter transactions in the Ledger, and I update prices through APIs. To calculate the balance for a day (note multiple Ledger entries for the same asset can happen on the same day): def balance_date(date): return Ledger.objects.filter(date__date__lte=date).values('asset').annotate(total_amount=Sum('amount')) Trying to then get values for every day between the date of the first Ledger entry and today becomes more challenging. Currently I am doing it this way - assuming a start_date and end_date that are datetime.date() and tr_dates a list on unique dates on which transactions did occur (to avoid calculating balances on days where nothing happened) : import pandas as pd idx = pd.date_range(start_date, end_date) main_df = pd.DataFrame(index=tr_dates) main_df['date_send'] = main_df.index main_df['balances'] = main_df['date_send'].apply(lambda x: balance_date(x)) main_df = main_df.sort_index() main_df.index = pd.DatetimeIndex(main_df.index) main_df = main_df.reindex(idx, method='ffill') This works but my issue is performance. It takes at least 150-200ms to run this, and then I need to get the prices for each date (all … -
Django Add Recaptcha V3 To Allauth Login
I was able to follow this answer to be able to implement Google Recaptcha V3 to my allauth sign up page. Now I would like to do the same thing for the allauth login page. I tried using the same method as the sign up page but did not have success. Here is what I tried doing replicating the answer above: https://dpaste.org/UXcD How does one go about doing this? If possible, I would like to keep the the default allauth functionality the same and would not like to override it. I would like to figure out how to do this on all allauth pages not just the signup and login pages. If there is one universal way to do it for all the allauth pages, that would be great. Otherwise I will ask separate stackoverflow questions on each one. -
How do I make a childless node have an input box that will post a number so it can call a python function?
As the question states, I need a childless node to act as input (pretty input preferably) so I can call a Python function and return a value. I would like it all to happen in javascript so it's seemless. Does anyone know how I can do that? It may involve doing something to the following- h = t.append("g").classed("body-group", !0); return h.append("image").classed("body-box", !0).attr("xlink:href", "{% static 'body box bg.png' %}").attr("width", 1e-6).attr("height", 1e-6) Here is the JSFiddle. Hopefully it helps you understand what I mean by childless node. -
Nginx not serving multiple uploaded images over about 200kb | Will serve when uploaded one at a time
I am new to nginx, and deployment in general. I've succesfully deployed a Python/django site that has a page with various "listings", and each listing has its own page with 20-30 images. When all the images are uploaded through the admin area for each listing, at only 200kb or so each, the images are not served and show blank on the front-facing website -- but when i upload between 1-6 at a time, they are served. So adding a few at a time and reloaded is the only way to upload all the images, and its a pain. I imagine this gives Nginx a chance to cache the few images before the next 1-6 images are uploaded -- so the solution could lie here somewhere. Below are my settings. I've sifted through other stack overflow questions and adjusted a few settings according to answers to other related questions ive found. Ive tried increasing the "client_max_body_size" to 20M, and have now set it to 0, so it will be disregarded - neither seem to fix the problem. Would greatly appreciate y'alls help in troubleshooting this. Thanks! http { client_max_body_size 0; proxy_max_temp_file_size 0; proxy_buffering off; sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout … -
psycopg2.IntegrityError: duplicate key value violates unique constraint “engine_attackimage_pkey” DETAIL: Key (id)=(19) already exists
I am not setting the primary key manually. How could this be happening? relevant code: for im_url in image_urls: print(im_url) if im_url.split('.')[-1] != 'gif' and '/' in im_url.split('.com/')[1]: img_temp = NamedTemporaryFile(delete=True) img_temp.write(urllib.request.urlopen(im_url).read()) img_temp.flush() img_filename = slugify(im_url.split('.com/')[1].split('/')[1])[:50] print(img_filename) try: attack_image_object = AttackImage.objects.create( title=img_filename, source_url=im_url, creator=mike ) except Exception as e: print(e) continue attack_image_object.image.save(img_filename, File(img_temp)) attack_item_object = AttackItem.objects.create( attack_image=attack_image_object, attack='SPA', creator=mike, ) attack_item.hidden_data_found = (attacks.spa(attack_image.image) > 0.05) attack_item.save() print('%s created' % (img_filename)) models class AttackImage(models.Model): title = models.CharField(max_length=255) image = models.ImageField(upload_to='attack_images', blank=True, null=True) source_url = models.URLField(blank=True,null=True) domain = models.ForeignKey(Domain, on_delete=models.CASCADE, blank=True, null=True) creator = models.ForeignKey(User, on_delete=models.CASCADE, blank=True,null=True) slug = models.SlugField(blank=True,null=True) def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.title)[:50] if self.source_url and not self.image: result = urllib.request.urlretrieve(self.source_url) self.image.save( os.path.basename(self.source_url), File(open(result[0], 'rb')) ) if self.source_url: if '//' in self.source_url: d = self.source_url.split('//')[1].split('/')[0] else: d = self.source_url.split('/')[0] try: domain = Domain.objects.get(domain_url=d) except Exception as e: print(e) domain_object = Domain.objects.create(domain_url=d) domain = domain_object self.domain = domain return super(AttackImage, self).save(*args, **kwargs) def get_absolute_url(self): return reverse("attack_image_detail", kwargs={ 'pk': str(self.id), 'slug': str(self.slug)}) traceback Traceback (most recent call last): File "crawl_ebaumsworld.py", line 91, in <module> crawl(first_url) File "crawl_ebaumsworld.py", line 65, in crawl creator=mike File "/home/michael/projects/deepsteg/venvdeepsteg/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/michael/projects/deepsteg/venvdeepsteg/lib/python3.6/site-packages/django/db/models/query.py", line 422, in … -
Django automatically performing the collectstatic command
In my project, I have a main static folder and a sub folder named static. When I make changes in my sub folder named static (which I specified in COLLECTSTATIC_DIRS within the settings file), I save the file and run the collectstatic command. This successfully saves the changes, however is really inefficient as I am constantly changing css and Javascript files inside my project, which I store as static files. I browsed the web, and came across a solution named whitenoise, which is a pip package. But this package only works for a short period of time, and after a few times of closing and opening my project folder, it completely stopped working. Does anybody have another solution to deal with this problem? Thank you. -
View doesn't recognise list index?
i am driving myself mad with the below issue, the View wont recognise the 2nd item on the list, and will return the error below. Although if i print it, the console prints it just fine? Please help views.py def statement(request,action,param): if request.method=="POST": transaction=Transaction() filecsv = request.FILES["fileToUpload"] file_data = filecsv.read().decode("utf-8") lines = file_data.split("\n") for line in lines: linex=line.split(",") #Comment: it recognises linex[0] just fine, but when moving to [2] the following error appears(included below) transaction.name=linex[0] transaction.number=CreditCard.objects.get(pk=1) transaction.date=linex[2] transaction.postingdate=linex[3] transaction.description=linex[4] transaction.employee=linex[5] transaction.internalnote=linex[6] transaction.city=linex[7] transaction.category=linex[9] transaction.originalcurrencyamount=linex[10] transaction.currency=linex[11] transaction.amount=linex[12] transaction.save() return render(request,'sandbox/uploadstatement.html') else: print("no post") return render(request,'sandbox/uploadstatement.html',{'data':"no data"})``` error indexError at /sandbox/statement/view/view list index out of range Request Method: POST Request URL: http://127.0.0.1:8000/sandbox/statement/view/view Django Version: 3.0 Exception Type: IndexError -
Django rest framework ordering - set the location of None values
Using Django Rest Framework 'ordering_fields' for allowing sorting by all the model fields. I've added a new field that allows sorting by, but the requirement is that when sorting ASC - the None values will be first, and when sorting DESC - they will be last. The default behavior seems to be the opposite. Is there a quick way to tell the view where I want to put the None values results? Django version is 2.1.5. Django rest Framework version is 3.7.7 This is part of the model - class Item(models.Model): PRIORITIES = ( ('1', 'Low'), ('2', 'Normal'), ('3', 'High'), ) identifier = models.IntegerField(default=-1) title = models.CharField(max_length=1000) priority = models.CharField(max_length=50, choices=PRIORITIES, null=True, blank=True) Part of the view: class ItemViewSet(viewsets.ModelViewSet): ordering_fields = tuple(serializer_class.Meta.fields) -
could not translate host name "db" to address when running Django test in Docker through PyCharm
I have a simple Django project with a PostgreSQL backend: version: '3' services: db: image: postgres:12 ports: - '5432:5432' volumes: - postgres_data:/var/lib/postgresql/data/ environment: POSTGRES_USER: pycharm POSTGRES_PASSWORD: pw123 POSTGRES_DB: pycharm app: build: . command: python manage.py runserver 0.0.0.0:8000 ports: - '8000:8000' volumes: - .:/app depends_on: - db volumes: postgres_data: With the following database settings in settings.py: DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql", "NAME": "pycharm", "USER": "pycharm", "PASSWORD": "pw123", "HOST": "db", } } And a simple test: from django.test import TestCase class MyTestCase(TestCase): def test_example(self): assert 1 == 1 Everything works fine when I run the project with docker-compose: docker-compose up I can exec into the container running the django app and successfully execute the test: docker-compose run app bash $ python manage.py test demo.tests.MyTestCase Creating test database for alias 'default'... System check identified no issues (0 silenced). . ---------------------------------------------------------------------- Ran 1 test in 0.002s OK Destroying test database for alias 'default'... I want to run the test in PyCharm, instead of having to exec into the container every time. I've setup the remote interpreter using Docker. However, when I run the test in PyCharm I get the following error: django.db.utils.OperationalError: could not translate host name "db" to address: Name or … -
Django form values not getting posted in database
Django form is not posting any values to the database. I was initially making the mistake of using <button type = 'submit'/> but I change it to <input type="submit" value="save"/> still nothing is posting to database. Form {%extends "main/base.html" %} {%block title%}create{%endblock%} {%block content%} <form method="POST" action=""> {% csrf_token %} {{form.as_p}} <input type="submit" value="save"/> </form> {%endblock%} views.py if request == 'POST': form = createnewlist(request.POST) if form.is_valid(): n = form.cleaned_data['Name'] t = ToDoList(name = n) t.save() return HttpResponseRedirect("/%i" %t.id) else: form = createnewlist() return render(request,"main/create.html",{'form':form}) contents class createnewlist(forms.Form): name = forms.CharField(label = 'Name',max_length = 300) check = forms.BooleanField(required = False) I tried all the other solutions to similar problems but its not working. I might be making a very silly mistake but I am not able to figure it out. Any help will be appreciated. -
Setup apache and django with letsencrypt
In produktion i have successfully pointed apache with wsgi to my django service. However when i try to setup an SSL sertificate with letsencrypt, i can make the redirect from http :80 to https :443 work just fine. But when my browser tries to load the https site, it gets a timeout. My apache conf files looks like this, and i am using apache 2.4 on raspbian, and django version 2.2. I really hope one of you can help me find the error. 000-default.conf <virtualHost *:80> ServerName hansenbrew.dk ServerAdmin admin@example.com ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined # This is optional, in case you want to redirect people # from http to https automatically. RewriteEngine On RewriteCond %{SERVER_PORT} !^443$ RewriteRule ^(.*)$ https://%{HTTP_HOST}$1 [R=301,L] RewriteCond %{SERVER_NAME} =hansenbrew.dk RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent] </virtualHost> # vim: syntax=apache ts=4 sw=4 sts=4 sr noet default-ssl.conf <VirtualHost *:443> # The ServerName directive sets the request scheme, hostname and port that # the server uses to identify itself. This is used when creating # redirection URLs. In the context of virtual hosts, the ServerName # specifies what hostname must appear in the request's Host: header to # match this virtual host. For the default virtual host (this file) this … -
Default image in Django model ImageField does't work
I have a huge problem with default image in my django model, in model.ImageField. My users/models.py: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) title = models.CharField(max_length=120) image = models.ImageField(default='default.jpg', upload_to='profile_pics') And my project/urls.py: if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) In my project/settings.py I have: MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' On website, src of my image is (unknown)... Every image I upload in my admin panel is ok. Just this default, when user has no image. What is wrong with this? I done it once in the past and everthing worked. Could you help me? -
python ../manage.py collectstatic - RuntimeError: Max post-process passes exceeded
I have a Django app with a React frontend deployed on Heroku. When I try to make changes then run python ../manage.py collectstatic it seems to be post-processing an infinite amount of files. It just goes on forever until it finally times out. When I run the same command in my development mode everything works fine. I can't figure out what's wrong. Is the files being brought over incorrectly? Here is the full message: Post-processing 'All' failed! Traceback (most recent call last): File "../manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/home/hzren/dev/t_and_b_website/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/home/hzren/dev/t_and_b_website/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/hzren/dev/t_and_b_website/venv/lib/python3.6/site-packages/django/core/management/base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "/home/hzren/dev/t_and_b_website/venv/lib/python3.6/site-packages/django/core/management/base.py", line 335, in execute output = self.handle(*args, **options) File "/home/hzren/dev/t_and_b_website/venv/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 189, in handle collected = self.collect() File "/home/hzren/dev/t_and_b_website/venv/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 135, in collect raise processed RuntimeError: Max post-process passes exceeded. npm ERR! Linux 5.0.0-37-generic npm ERR! argv "/usr/bin/node" "/usr/bin/npm" "run" "collectstatic" npm ERR! node v8.10.0 npm ERR! npm v3.5.2 npm ERR! code ELIFECYCLE npm ERR! frontend-app@0.1.0 collectstatic: `python ../manage.py collectstatic --no-input` npm ERR! Exit status 1 npm ERR! npm ERR! Failed at the frontend-app@0.1.0 collectstatic script 'python ../manage.py collectstatic --no-input'. npm ERR! Make sure you have the … -
Django: Adding 2 variables and getting a response on the same page
Any help would be greatly appreciated index.html {% extends 'base.html' %} {% block content %} <div> <h1>Welcome Home</h1> <form action="{% url 'calc:home' %}" method="GET"> <!-- {% csrf_token %} --> Enter 1st Number : <input type="text" name="num1"><br><br> Enter 2nd Number : <input type="text" name="num2"><br> <input type="submit" name="" value="Add"><br><br> </form> Result of the game is : {{result}} </div> {% endblock %} views.py from django.shortcuts import render from django.http import HttpResponse def home_view(request): if request.GET.get('num1'): val1 = int(request.GET.get("num1")) val2 = int(request.GET.get("num2")) res = val1 + val2 return render(request, 'calc/index.html',{'result':res}) urls.py from django.urls import path from . import views app_name = 'calc' urlpatterns = [ path('', views.home_view, name='home'), ] i get this error when running the server: UnboundLocalError: local variable 'res' referenced before assignment