Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
related_name doesn't work in Django about some different objects
I have trouble about calling related models. my models: class Product(models.Model): product_model = models.CharField(max_length=255, default='') product_url = models.SlugField(max_length=200, default='') product_category = models.ForeignKey(Category, on_delete=models.CASCADE, default='', null=True, related_name="products", ) product_subcategory = models.ForeignKey(Subcategory, on_delete=models.CASCADE, default='', null=True, related_name="products", ) description = tinymce_models.HTMLField(verbose_name="text") product_img = models.ImageField(upload_to="product_imgs/" ,default='') class Stock(models.Model): ONE = '1' TWO = '2' FREE = 'free' PRODUCT_SIZES = [ (ONE, '1'), (TWO, '2'), (FREE, 'free'), ] size = models.CharField(max_length=60,default=" ", choices=PRODUCT_SIZES) quantity = models.PositiveIntegerField(default=0) price = models.FloatField(default=0, null=True) product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name="pro") each product can has 3 stock object with different sizes, I want show a product quantity in stock with all sizes, for example (size1 has 10, size2 has 10, sizefree has 10, I want show 30) my views: def products(request): if request.user.is_staff or request.user.is_superuser: products = Product.objects.filter() ctx = {'products':products} return render(request, 'staff/products_list.html',ctx) else: return redirect('/staff') and my html <td class="text-info"> {% for product in product.pro.quantity.all %} {{product}} {% endfor %} </td> how can I solve this problem ? -
Django Model ListAPIView serializer for counting objects
I have a model as follows, Entity : class Entity(models.Model): uuid = models.CharField(max_length=12, default=None) description = models.CharField(max_length=255, default="") I want to provide a serialization for the all entity objects where the response will provide the count of each description type that is available in the database. For instance, the table has the following content: 1.cat 2.dog 3.cat 4.dog 5.bird 6.bird 7.dog The serialization will be : dog : 3 cat : 2 bird :2 How should I modify the following serializer code to make this happen ? #Entity Count(per Intelligence) Search class EntityFilterSerializer(serializers.ModelSerializer): class Meta: model = Entity fields = ('description') class StandardResultsSetPagination(PageNumberPagination): page_size = 10 page_size_query_param = 'page_size' max_page_size = 100 class EntityList(generics.ListAPIView): model = Entity serializer_class = EntityFilterSerializer filter_backends = [filters.SearchFilter] queryset = Entity.objects.order_by('id') search_fields = ['=uuid', ] pagination_class = StandardResultsSetPagination -
permission login django redirects to login
I'm trying to implement user permission. Based on the user logged in different pages will be shown. But for some reason, it keeps redirecting me to same the login page with a path that includes the desired direction something like that (dashboard/login/?next=/dashboard/index/) instead of the admin view or user view (based on the inputs). I suspect that the issue is in login.html but not sure where it is login.html <form method="POST" action="" class="user"> {% csrf_token %} <div class="form-group"> <input type="text" class="form-control form-control-user" id="exampleInputEmail" aria-describedby="emailHelp" placeholder="Enter Username..."> </div> <div class="form-group"> <input type="password" class="form-control form-control-user" id="exampleInputPassword" placeholder="Password"> </div> <a href="{% url 'index'%}" class="btn btn-primary btn-user btn-block"> Login </a> <hr> </form> <hr> <div class="text-center"> <a class="small" href="{% url 'forgot_pass'%}">Forgot Password?</a> </div> <div class="text-center"> <a class="small" href="{% url 'register'%}">Create an Account!</a> </div> decorators.py from django.http import HttpResponse from django.shortcuts import redirect def unauthenticated_user(view_func): def wrapper_func(request, *args, **kwargs): if request.user.is_authenticated: return redirect('index') else: return view_func(request, *args, **kwargs) return wrapper_func def allowed_users(allowed_roles=[]): def decorator(view_func): def wrapper_func(request, *args, **kwargs): group = None if request.user.groups.exists(): group = request.user.groups.all()[0].name if group in allowed_roles: return view_func(request, *args, **kwargs) else: return HttpResponse('You are not authorized to view this page') return wrapper_func return decorator def admin_only(view_func): def wrapper_function(request, *args, **kwargs): group = … -
Django radio widget with free input value
I'd like to implement/find a multiple radio select with an "other" option that allow users to enter their own answer. Something like that: http://garmoncheg.blogspot.com/2014/05/implementing-multiple-radio-select.html I'm affraid this link points to a code that is outdated (I'm using django 2.2) Do you know such a module? If not, what approach would you take to implement it? -
Pagination in DRF gives "'list' object is not callable"
Using Django Rest Framework I'm trying to expose a read-only endpoint. Unfortunately I get an error which (if I read it correctly) relates to the pagination. Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/usr/local/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/usr/local/lib/python3.8/site-packages/rest_framework/viewsets.py", line 125, in view return self.dispatch(request, *args, **kwargs) File "/usr/local/lib/python3.8/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/usr/local/lib/python3.8/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/usr/local/lib/python3.8/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/usr/local/lib/python3.8/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "/usr/local/lib/python3.8/site-packages/rest_framework/mixins.py", line 40, in list page = self.paginate_queryset(queryset) File "/usr/local/lib/python3.8/site-packages/rest_framework/generics.py", line 169, in paginate_queryset if self.paginator is None: File "/usr/local/lib/python3.8/site-packages/rest_framework/generics.py", line 162, in paginator self._paginator = self.pagination_class() Exception Type: TypeError at /api/v1/machines/ Exception Value: 'list' object is not callable I've got no pagination set up for this viewset though. My serializer looks like this: class MachineSerializer(serializers.Serializer): class Meta: model = Machine fields = '__all__' my viewset like this: class MachineDataViewSet(viewsets.ReadOnlyModelViewSet): queryset = Machine.objects.all() serializer_class = MachineSerializer and in my setting I've got my pagination class set up like this: DEFAULT_PAGINATION_CLASS=('rest_framework.pagination.LimitOffsetPagination',), Does anybody know what … -
Django social media Login(google)
i have a problem in google login. after login with google auth in my django proj, i can't do anything with it tokne! in other app,i can easily take username with request.user but with google loging,i cant! djnago said you are loging with AnonymousUser.i konw why but i cant handle it. Token list's are Separately in google login and Local Login. in my other app, i do everything with request.user, but now, i stucking. how can i get information from user's who logged in with google login? -
'AssertionError' object has no attribute 'message'
I'm dealing with form in django that once its filled sends an email to the user but im getting the following error: error image I have checked in my code and my problem comes from this function: def send_manually_exception_email(request, e): exc_info = sys.exc_info() reporter = ExceptionReporter(request, is_email=True, *exc_info) subject = e.message.replace('\n', '\\n').replace('\r', '\\r')[:989] message = "%s\n\n%s" % ( '\n'.join(traceback.format_exception(*exc_info)), reporter.filter.get_request_repr(request) ) mail.mail_admins(subject, message, fail_silently=True, html_message=reporter.get_traceback_html()) What can I do? -
Django - How to declare IntegerChoice & IntegerField for the whole django project (globally)
I defined following class: class LocationInterestRegion(models.Model): class LocationInterestRegionTypes(models.IntegerChoices): CITY = 0 , _('city level') COUNTY = 1 , _('province level') STATE = 2 , _('regio/state level') COUNTRY = 3 , _('country level') INTERNATIONAL = 4 , _('international level') __empty__ = _('Select the region from where to find candidates.') location_interest_region = models.IntegerField(choices=LocationInterestRegionTypes.choices, null=True) And then tried to use this in another model as a ForeignKey class Job(models.Model): location = models.ForeignKey(Location, on_delete=models.CASCADE, blank=True, null=True) location_interest_region = models.ForeignKey(LocationInterestRegion, on_delete=models.CASCADE,blank=True, null=True) Now I cannot access the options in my form. class JobCreateForm(forms.ModelForm): class Meta: model = my_model fields = [ 'location', 'location_interest_region', ] I could solve the issue by not using the foreign key and intergrating the first model in the second one. But if I want to use these "choices" in several other models. I need to redefine them in every model. Is there a way to define these choices globally ? -
Django values_list() lowercase
I have query set that I am exporting to CSV. models.One2OneInfoLog.objects.filter(one_2_one_info=pk).values_list('name', 'location', 'created').order_by('created') I want the 'name' field to be in lowercase. Is their a way to do that? -
Django ModelTranslation
Hello guys i need a help for translating models values. I use django-modeltranslation package. I have managed to register my models. class Institution(models.Model): title = models.CharField(_('Title'),max_length = 200) address = models.CharField(_('Address'),max_length=50) pobox = models.CharField(_('Pobox'),max_length=5) city = models.CharField(_('City'),max_length=64) country = models.CharField(_('Country'),max_length=50) telephone = models.CharField(_('Telephone'),max_length = 10) def __str__(self): return self.title class Department(models.Model): title = models.CharField(_('Title'),max_length = 200) address = models.CharField(_('Address'),max_length=50) pobox = models.CharField(_('Pobox'),max_length=5) city = models.CharField(_('City'),max_length=64) country = models.CharField(_('Country'),max_length=50) telephone = models.CharField(_('Telephone'),max_length = 10) institution=models.ForeignKey(Institution,on_delete=models.CASCADE,verbose_name=_('User')) def __str__(self): return self.title Register @register(Institution) class InstitutionTranslationOptions(TranslationOptions): fields = ('title', 'address','city','country') @register(Department) class DepartmentTranslationOptions(TranslationOptions): fields = ('title', 'address','city','country') Here is how i change language: <form action="{% url 'set_language' %}" method="post">{% csrf_token %} <input name="next" type="hidden" value="{{ redirect_to }}"> <select name="language"> {% get_current_language as LANGUAGE_CODE %} {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} {% for language in languages %} <option value="{{ language.code }}"{% if language.code == LANGUAGE_CODE %} selected{% endif %}> {{ language.name_local }} ({{ language.code }}) </option> {% endfor %} </select> <input type="submit" value="Go"> </form> Ok i open admin i put values for the 2 languages but in template i cant get them... I get only the default value... I use: {{ department.title }} Am I doing something wrong? -
when i enter the django admin using python manage.py runserver, occur 'ValueError at /admin'
when operate runserver, and then enter ther url 'http://127.0.0.1:8000/admin', occur this error. At the terminal, occur this error ValueError: Field 'id' expected a number but got 'favicon.ico'. At the browser, occur thie error ValueError at /admin Field 'id' expected a number but got 'admin'. Request Method: GET Request URL: http://127.0.0.1:8000/admin Django Version: 3.2.4 Exception Type: ValueError Exception Value: Field 'id' expected a number but got 'admin'. code here How can solve this problem?? -
How to make a generic List Filter in Django using django-filters?
I want to have a FilterSet class that allows all of the fields to be filtered as a list. I was thinking of overriding the default FilterSet class of django-filters and having the fields be dynamically set as well as setting a method to each one. So, something like this for example: ModelName_fields = {'names': 'name', 'ids': 'id', 'second_ids': 'second_id'} class ListFilter(FilterSet): def __init__(self, *args, **kwargs): # self._meta.fields = [field_name for field_name in modelNameHere + '_fields'] super(FilterSet).__init__(*args) class SomeAPIView(mixins.ListModelMixin): model = ModelName filterset_class = ListFilter Basically, ModelName_fields is a declared constant that maps the query parameter to the field name of the model. In this case, I declare the model on the view as well as the filterset class and in the __init__ method of the filterset class, I dynamically attach the fields as well as the query parameter name. In all essence, I just want to make the ListFilter as generic as possible to be used on different views as well. My question is, is this the correct way or is there some other better way to accomplish this? Also, how can I get the name of the model, which is an attribute of the view class, in the … -
I Can't able to pass a values(id) in urls in django
After user login their account, it is redirect to home page. In that home page i added profile option for user to edit and view their profile. but logged user only view his profile.so i need add id in url for show the specific profile page for the user.but i cant do that with my code. I need like this [" 121.0.0.1:8000/profile/1 or 121.0.0.1:8000/1/profile]..But i got this ['121.0.0.1:8000/profile/'] cant add id in url and it throws page not found error Views.py class ShowProfilePageView(DetailView): model = Profile template_name = 'bgmiapp/user_profilepage.html' def get_context_data(self,*args,**kwargs): context = super(ShowProfilePageView,self).get_context_data(*args,**kwargs) page_user = get_object_or_404(Profile,id=self.kwargs['pk']) context["page_user"] = page_user return context views.py/home def home(request): profile=Profile.objects.all() return render(request,'bgmiapp/home.html',{'profile':profile}) URLS.py from django.contrib import admin from django.urls import path from . import views from .views import ShowProfilePageView urlpatterns = [ path('home/',views.home,name='home'), path('register/',views.register,name='register'), path('login/',views.login_view,name='login'), path('<int:pk>/profile/',ShowProfilePageView.as_view(),name='show_profile_page') templates : home.html {% extends 'bgmiapp/base.html' %} {% load static %} {% block title %} Home {% endblock %} {% block content %} <h3> homepage coming soon!!!!</h3> <a href="/profile/{{ profile.id }}">profile</a> {% endblock %} -
Django : Not able to add solution to a particular question using CBV
I am having an app where people can ask and answer questions views.py class SolutionsCreateView(CreateView): model = Solutions template_name = "log/add_solution.html" slug_url_kwarg = 'solution' slug_field = 'slug' context_object_name = 'solution' fields = ['solution', 'image'] def form_valid(self, form): solution = form.save(commit=False) solution.author = self.request.user #solution.log = I need to set this solution.save() return super(SolutionsCreateView, self).form_valid(form) There is a model Log and another model Solutions models.py: class Log(models.Model): title = models.CharField(blank=False, max_length=500) content = models.TextField(blank=False) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) slug = models.SlugField(max_length=50, null=False, unique=True) author = models.ForeignKey(User, on_delete=models.CASCADE,null=True, blank=True) image = models.ImageField( upload_to='images', blank=True) def save(self, *args, **kwargs): super().save() self.slug = self.slug or slugify(self.title + '-' + str(self.id)) super().save(*args, **kwargs) class Meta: verbose_name = ("Log") verbose_name_plural = ("Logs") def __str__(self): return f"{self.title}" def get_absolute_url(self): return reverse("log-detail", kwargs={"question": self.slug}) class Solutions(models.Model): log = models.ForeignKey( Log, on_delete=models.CASCADE, blank=True, null=True) author = models.ForeignKey(User, on_delete=models.CASCADE,null=True, blank=True) solution = models.TextField(null=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) slug = models.SlugField(max_length=50, null=False, blank=True) image = models.ImageField( upload_to='images', blank=True) def save(self, *args, **kwargs): self.slug = self.slug or slugify(self.solution) super().save(*args, **kwargs) class Meta: verbose_name = ("Solution") verbose_name_plural = ("Solutions") def __str__(self): return f" {self.solution} " def get_absolute_url(self): return reverse("log-solution", kwargs={"solution": self.slug}) How do I access log in Log model … -
daphne.service failed to boot
Just wondering if anyone could give me a little direction with my daphne.service file. I am struggling with getting this service to boot. When running systemctl status daphne.service, the service active status is being returned as failed. [Unit] Description=WebSocket Daphne Service After=network.target [Service] Type=simple User=root WorkingDirectory=/home/myapp ExecStart=/usr/bin/python3.6 /usr/local/bin/daphne -e ssl:8001:privateKey=/etc/letsencrypt/live/mydomain.com/privkey.pem:certKey=/etc/letsencrypt/live/mydomain.com/fullchain.pem myapp.asgi:application Restart=on-failure [Install] WantedBy=multi-user.target Where it says "mydomain.com" and "myapp", these are just placeholders for whee I have the actual domain and app name configured correctly. I have opened up port 8001 and within the code I have displayed above, I'm trying to pass through my SSL configuration through to Daphne. I'm guessing it must be a file path related issue, but from what I can see, I have the correct PYTHONPATH and path to Daphne. Any suggestions are welcome! Thank you :-) -
Cannot resolve keyword 'created' into field django rest framework
i have follwing structure: class FullTreeAdminUserSerializer(serializers.ModelSerializer): class Meta: model = User fields = '__all__' class AdminFullTreeListView(generics.ListAPIView): queryset = User.objects.all() serializer_class = FullTreeAdminUserSerializer When i query users/all i have following error: Cannot resolve keyword 'created' into field The user model looks like class User(AbstractBaseUser, PermissionsMixin): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) username = models.CharField(max_length=255, unique=True, db_index=True) first_name = models.CharField(max_length=255, blank=True) last_name = models.CharField(max_length=255, blank=True) email = models.EmailField(max_length=255, unique=True, db_index=True) is_verified = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) date_joined = models.DateTimeField(auto_now=True) balance = models.FloatField(default=0.0) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] objects = UserManager() I cannot figure out where the problem is. I simply wanna get list of all user and i didn't expect such problems. I don't have created filed in my user model -
I have recently shifted from sqlite3 to SQL. What should be the correct SQL option?
I have recently shifted from sqlite3 to SQL and I have a blog website while running migrations I get a warning message "?: (mysql.W002) MariaDB Strict Mode is not set for database connection 'default' HINT: MariaDB's Strict Mode fixes many data integrity problems in MariaDB, such as data truncation upon insertion, by escalating warnings into errors. It is strongly recommended you activate it. See: https://docs.djangoproject.com/en/3.2/ref/databases/#mysql-sql-mode" I have set my SQL mode to transactional, Now I am not getting this warning. Am I using the correct option? What are the other options and when should I use those? -
docker doesn't install package enviirons
I am trying to install a package "environs" in docker using the command docker-compose exec web pipenv install 'environs [django] == 8.0.0', however nothing happens in the terminal and the package is not installed in the container. What is the reason? docker-compose.yml version: '3.8' services: web: build: . command: python /code/manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - 8000:8000 depends_on: - db environment: - "DJANGO_SECRET_KEY=django-insecure-c@p4-@$$@#0deu2p5&-59#-1kv&@(ayfu*b+a+wt(i9j5p7&=p3" db: image: postgres:11 volumes: - postgres_data:/var/lib/postgresql/data/ environment: - "POSTGRES_HOST_AUTH_METHOD=trust" volumes: postgres_data: dockerfile FROM python:3.8 # Set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Set work directory WORKDIR /code # Install dependencies COPY Pipfile Pipfile.lock /code/ RUN pip install pipenv && pipenv install --system # Copy project COPY . /code/ -
django authentication using another api
how do I authenticate users using another api that is not built in django, also I need to store the session cookie from that api. Is it possible to avoid django's authentication and use an external api to do so? I just need to send credentials using post method with a cookie and store it throughout the session. Also, what about using model backend? if after the post request I get 200 status code then authenticate user -
How to connect models between two projects with same database in django
How to take models from project 1 to project 2 in django, both projects sharing same database -
NLTK: The nltk messages is showing on the console screen every time I perform the migration
I am working on a django project where I am using nltk library. I have created an virtual environment to work on this project and every time I perform migration it shows nltk messages which it was not showing previously on the console screen and the address given in that too are not from virtual environment. (django-ai) C:\gsData\venv\django-ai\src>python manage.py runserver Watching for file changes with StatReloader Performing system checks... [nltk_data] Downloading package averaged_perceptron_tagger to [nltk_data] C:\Users\pc\AppData\Roaming\nltk_data... [nltk_data] Package averaged_perceptron_tagger is already up-to- [nltk_data] date! [nltk_data] Downloading package punkt to [nltk_data] C:\Users\pc\AppData\Roaming\nltk_data... [nltk_data] Package punkt is already up-to-date! [nltk_data] Downloading package stopwords to [nltk_data] C:\Users\pc\AppData\Roaming\nltk_data... [nltk_data] Package stopwords is already up-to-date! [nltk_data] Downloading package averaged_perceptron_tagger to [nltk_data] C:\Users\pc\AppData\Roaming\nltk_data... [nltk_data] Package averaged_perceptron_tagger is already up-to- [nltk_data] date! [nltk_data] Downloading package punkt to [nltk_data] C:\Users\pc\AppData\Roaming\nltk_data... [nltk_data] Package punkt is already up-to-date! [nltk_data] Downloading package stopwords to [nltk_data] C:\Users\pc\AppData\Roaming\nltk_data... [nltk_data] Package stopwords is already up-to-date! System check identified no issues (0 silenced). June 16, 2021 - 18:53:11 Django version 3.2.4, using settings 'django_ai.settings' Starting development server at http://127.0.0.1:8080/ Quit the server with CTRL-BREAK. -
What is the use of writing custom QuerySet classes in Django
I was going through Django documentation for model managers. I saw that in this section i saw that that model.QuerySet class is overriden by a custom QuerySet class which has two methods which returns the queryset by filtering role='A' or role='E'. class PersonQuerySet(models.QuerySet): def authors(self): return self.filter(role='A') def editors(self): return self.filter(role='E') class PersonManager(models.Manager): def get_queryset(self): return PersonQuerySet(self.model, using=self._db) def authors(self): return self.get_queryset().authors() def editors(self): return self.get_queryset().editors() class Person(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) role = models.CharField(max_length=1, choices=[('A', _('Author')), ('E', _('Editor'))]) people = PersonManager() But I don't understand what was the need of filtering in the QuerySet class when we could have done that in model manager itself like this. class PersonManager(models.manager): def authors(self): return self.filter(role='A') def editors(self): return self.filter(role='E') Please help to understand the difference. Thank you in advance. -
django - get() returned more than one Phones -- it returned 4
I am working on a small api in django. I have 2 models/tables 1st user , 2nd phones _____________ **models.py** _____________ class Users(models.Model): userId = models.AutoField(primary_key=True,default=None) name = models.CharField(max_length=10) status = models.CharField(max_length=10 , default='BLOCKED') address = models.TextField(null=False,default=None) class Meta: db_table = 'users' class Phones(models.Model): phoneId = models.AutoField(primary_key=True,default=None) userId = models.IntegerField(null=False) numbers = models.CharField(max_length = 15, null=True) phonesCountryCode = models.CharField(max_length=5,null=True) class Meta: db_table = 'phones' I have written the code to get data from json object. the json object looks like this ______________ **json input** ______________ { "name": "abc", "status": "ACTIVE", "address": "xyz", "phones": [ { "numbers": { "numbers": "23378", "phonesCountryCode": "+91" } }, { "numbers": { "numbers": "12390", "phonesCountryCode": "+91" } }, { "numbers": { "numbers": "7890", "phonesCountryCode": "+91" } }, { "numbers": { "numbers": "45221", "phonesCountryCode": "+91" } } ] } inserting data into database works fine. but when i want to update the data it is giving me the error I have multiple data in the database that is why getting multiple data error if using get() and if use filter() it gives me error that no attribute _meta. I am not finding any answer a help will be very appreciated. ____________ **views.py** ____________ @api_view(['PUT']) def ListUpdate(request,pk): data … -
GitHub Actions Django Testing errors with ValueError: Port could not be cast to integer value as 'None'
I have a Django and Django REST app, and when I run my unit testing locally, every test runs and passes. However, when I create a GitHub Action to run my unit testing, 6 of my unit tests failure with the following message: File "/opt/hostedtoolcache/Python/3.9.5/x64/lib/python3.9/urllib/parse.py", line 178, in port raise ValueError(message) from None ValueError: Port could not be cast to integer value as 'None' These 6 tests test sending data to my api endpoints. Here is my Action: django-test-lint: runs-on: ubuntu-latest services: postgres: image: postgres:12.3-alpine env: POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres POSTGRES_DB: github_actions ports: - 5432:5432 options: --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5 steps: - name: Checkout uses: actions/checkout@v2 - name: Set up Python 3.9 uses: actions/setup-python@v1 with: python-version: 3.9 - name: Install dependencies run: | python -m pip install --upgrade pip pip install -r requirements.txt - name: psycopg2 prerequisites run: sudo apt-get install libpq-dev - name: Run migrations run: python app/manage.py migrate - name: Run tests and lint with coverage run: | cd app coverage erase coverage run manage.py test && flake8 coverage report -m The impression I get, is this happens when I run my tests to test my endpoints using DRF. It's like Github Actions can't … -
Pycharm Pro connection to PostgreSQL database via SSH tunnel doesn't work with Django
I have added a PostgreSQL datasource in Pycharm Pro, which uses a SSH tunnel to access to the database, on a distant server accessible via VPN. I want to access this database in my Django project. The database parameters are the following (the white bar hides the public IP of the distant server) and the SSH parameters like this (my username and the server public IP are hidden too). I use the same credentials in my settings.py file: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'rhu4bdd', 'USER': 'rhu4gres', 'PASSWORD': <password>, 'HOST': <public IP>, 'PORT': '5432' } } Django returns this error: django.db.utils.OperationalError: could not connect to server: Connection timed out Is the server running on host "<public IP>" and accepting TCP/IP connections on port 5432? How can I use my Pycharm database connection in my Django project ? Thank you, MB