Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django-filter finds a match if you enter the full name
django-filter finds a match if you enter the full name. For example, I try to filter by the name "Titanic" and I type "Titan" into the search, nothing will be found until I type in the entire text "Titanic". How do I search by partial match? class ProjectFilter(django_filters.FilterSet): address__name = django_filters.CharFilter(field_name='address', lookup_expr='street') approve = django_filters.BooleanFilter(field_name='approve') ordering = django_filters.OrderingFilter(choices=CHOICES, required=True, empty_label=None,) class Meta: model = Project exclude = [field.name for field in Project._meta.fields] order_by_field = 'address' View class FilterTable(SingleTableMixin, FilterView): table_class = TableAll model = Project template_name = "table.html" filterset_class = ProjectFilter -
Optimizing DRF performance
I am trying to optimize a DRF view that has very low performance, is there a way to make it faster? This is where I am right now Models: class CategoryVideos(models.Model): class Meta: verbose_name = 'Category' verbose_name_plural = 'Categories' name = models.CharField(max_length=100, null=False, blank=False) def __str__(self): return f"{self.name} and {self.id}" class Videos(models.Model): category = models.ManyToManyField(CategoryVideos, null=True, blank=True) illustration = models.FileField(null=True, blank=True) video = models.FileField(null=True, blank=True) title = models.CharField(max_length=255, null=True, blank=True) description = models.CharField(max_length=255, null=True, blank=True) url_video = models.CharField(max_length=255, null=True, blank=True) url_image = models.CharField(max_length=255, null=True, blank=True) Serializers: class CategorySerializer2(serializers.ModelSerializer): class Meta: model = CategoryVideos fields = ["name"] class VideoSerializer(serializers.ModelSerializer): category = CategorySerializer2(many=True, read_only=True) class Meta: model = Videos fields = ["id", "description", "title", "url_video", "url_image", "category"] read_only=True View: class OfferListAPIView(generics.ListAPIView): queryset = Videos.objects.prefetch_related('category').all() serializer_class=VideoSerializer For the moment, with 400 videos and just 6 categories, it takes approx 2.8 secs to get an answer which is way too high. Many thanks -
Django Rest How do I call objects that are under my reference object?
I cannot call the movies under a Director. I want to make a page where you click the name of the director and it will show the list of movies that are directed by the director. What shown below is the codes for models, serializers, and views. models.py class Director(models.Model): _id = models.AutoField(primary_key=True) firstname = models.CharField(max_length=100, null=True, blank=True) lastname = models.CharField(max_length=100, null=True, blank=True) def __str__(self): return "%s %s" % (self.firstname, self.lastname) class Product(models.Model): _id = models.AutoField(primary_key=True) name = models.CharField(max_length=100, null=True, blank=True) image = models.ImageField(upload_to=upload_image_path, null=True, blank=True) description = models.TextField(null=True, blank=True) director = models.ForeignKey(Director, on_delete=models.CASCADE) def __str__(self): return self.name serializers.py class ProductSerializer(serializers.ModelSerializer): director = serializers.StringRelatedField() class Meta: model = Product fields = '__all__' class DirectorSerializer(serializers.ModelSerializer): class Meta: model = Director fields = '__all__' views.py @api_view(['GET']) def getProducts(request): products = Product.objects.all() serializer = ProductSerializer(products, many=True) return Response(serializer.data) @api_view(['GET']) def getProduct(request, pk): product = Product.objects.get(_id=pk) serializer = ProductSerializer(product, many=False) return Response(serializer.data) @api_view(['GET']) def getDirector(request): director = Director.objects.all() serializer = DirectorSerializer(director, many=True) return Response(serializer.data) I already tried what is shown above. -
Django namespacing still produces collision
I have two apps using same names in my django project. After configuring namespacing, I still get collision. For example when I visit localhost:8000/nt/, I get page from the other app. (localhost:8000/se/ points to the right page). I must have missed something. Here is the code: dj_config/urls.py urlpatterns = [ path("se/", include("simplevent.urls", namespace="se")), path("nt/", include("nexttrain.urls", namespace="nt")), # ... ] dj_apps/simplevent/urls.py from . import views app_name = "simplevent" urlpatterns = [ path(route="", view=views.Landing.as_view(), name="landing") ] dj_apps/nexttrain/urls.py from django.urls import path from . import views app_name = "nexttrain" urlpatterns = [ path(route="", view=views.Landing.as_view(), name="landing"), ] dj_config/settings.py INSTALLED_APPS = [ "dj_apps.simplevent.apps.SimpleventConfig", "dj_apps.nexttrain.apps.NexttrainConfig", # ... ] Note that reversing order of apps in INSTALLED_APPS will reverse the problem (/se will point to nexttrain app). -
Can you convert a Django 'DateField()' to 'date'?
I was using the 'DateField()' in Django, and I wanted to find the time between two dates that are stored in the 'DateField()' field. How can I do this? This is what I was trying originally: length = datetime.timedelta(start, end) It gives me this error: TypeError: unsupported type for timedelta seconds component: DateField -
Django with flutter
How to do Django backend for flutter app if I don't know flutter? I expect the guidance on how can I do the backend project of flutter in Django without having knowledge in flutter. -
SerializerMethodField and circular import
I need help with REST Framework. I have to do my test for internship position and I have two models with circular import 'Pokemon' model and 'Team' mode. In serializer of 'Team' I have this code class TeamDetailsSerializer(ModelSerializer): """Serializer for details of Team instances""" pokemon_1 = SerializerMethodField() pokemon_2 = SerializerMethodField() pokemon_3 = SerializerMethodField() pokemon_4 = SerializerMethodField() pokemon_5 = SerializerMethodField() trainer = UserSerializer() class Meta: model = Team fields = ( "trainer", "name", "pokemon_1", "pokemon_2", "pokemon_3", "pokemon_4", "pokemon_5", ) read_only_fields = ("id",) # Methods to relate each Pokemon object def get_pokemon_1(self, obj): pokemon_1 = obj.pokemon_1 if not pokemon_1: return None serializer = pokemon.serializers.PokemonDetailsSerializer(pokemon_1) return serializer.data def get_pokemon_2(self, obj): pokemon_2 = obj.pokemon_2 if not pokemon_2: return None serializer = pokemon.serializers.PokemonDetailsSerializer(pokemon_2) return serializer.data def get_pokemon_3(self, obj): pokemon_3 = obj.pokemon_3 if not pokemon_3: return None serializer = pokemon.serializers.PokemonDetailsSerializer(pokemon_3) return serializer.data def get_pokemon_4(self, obj): pokemon_4 = obj.pokemon_4 if not pokemon_4: return None serializer = pokemon.serializers.PokemonDetailsSerializer(pokemon_4) return serializer.data def get_pokemon_5(self, obj): pokemon_5 = obj.pokemon_5 if not pokemon_5: return None serializer = pokemon.serializers.PokemonDetailsSerializer(pokemon_5) return serializer.data and problem that I get this kind of schema name* [...] trainer* User{...} pokemon_1 integer nullable: true pokemon_2 [...] pokemon_3 [...] pokemon_4 [...] pokemon_5 [...] but I would like to get object … -
'NoneType' object has no attribute 'save' when saving a new user in a Django with a custom user model
When I try to register a user, adapting what I learnt from Building a Custom User Model with Extended Fields youtube tutorial, I get an AttributeError: 'NoneType' object has no attribute 'save': views.py from django.shortcuts import render, redirect, get_object_or_404 from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from django.contrib.auth import get_user_model from django.conf import settings User = settings.AUTH_USER_MODEL from django.db import IntegrityError from django.contrib.auth import login, logout, authenticate from .forms import TodoForm from .models import Todo from django.utils import timezone from django.contrib.auth.decorators import login_required def home(request): return render(request, 'todo/home.html') def signupuser(request): if request.method == 'GET': return render(request, 'todo/signupuser.html', {'form':UserCreationForm()}) else: if request.POST['password1'] == request.POST['password2']: try: db = get_user_model() user = db.objects.create_user(request.POST['email'], request.POST['username'], request.POST['firstname'], request.POST['company'], request.POST['mobile_number'], password=request.POST['password1']) user.save() The user is still registered but I can't login with the profvided password ... What could be the reason ? Here is the full error: Environment: Request Method: POST Request URL: http://127.0.0.1:8000/signup/ Django Version: 4.1.5 Python Version: 3.8.2 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'todo'] Installed 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'] Traceback (most recent call last): File "/Users/remplacement/Documents/Work/4eme/django3-todowoo-project-master/tod_env/lib/python3.8/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/Users/remplacement/Documents/Work/4eme/django3-todowoo-project-master/tod_env/lib/python3.8/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/remplacement/Documents/Work/4eme/django3-todowoo-project/todo/views.py", line 26, in … -
Django get Keyerror while set permissions in CustomUserAdmin
Hi I am a Python/Django beginner and have a problem with the implementation of a permission thing. I have also copied this from a tutorial, but it doesn't seem to work within my app. What do I want to achieve: It's about the admin module. There I want that only administrators can change the field with the same name. Should only a user or staff user have logged in, this field should be grayed out. with the following code, this also works wonderfully. However, if I then a new user then create / add I get a Keyerror, which also refers to the built-in code. Attached my code question segments that belong to the topic: admin.py from django.contrib import admin from django.contrib.auth import get_user_model from django.contrib.auth.admin import UserAdmin from .forms import CustomUserCreationForm, CustomUserChangeForm from .models import JobTitle, JobSkill, SkillSet CustomUser = get_user_model() @admin.register(CustomUser) class CustomUserAdmin(UserAdmin): # see tutorial to this stuff: https://www.youtube.com/watch?v=wlYaUvfXJDc def get_form(self, request, obj=None, **kwargs): form = super().get_form(request, obj, **kwargs) is_superuser = request.user.is_superuser if not is_superuser: form.base_fields["is_superuser"].disabled = True form.base_fields["user_permissions"].disabled = True form.base_fields["groups"].disabled = True return form add_form = CustomUserCreationForm form = CustomUserChangeForm model = CustomUser readonly_fields = ["last_login", "date_joined"] list_display = [ "username", "employed", "email", "job_title", "is_active", … -
RelatedObjectDoesNotExist at /users/edit/ User has no profile
I ran into a situation where I had developed a method called edit and passed both the profile and user forms into it when I wanted to modify a profile. @login_required def edit(request): if request.method == 'POST': user_form = UserEditForm(instance=request.user,data=request.POST) profile_form = ProfileEditForm(instance=request.user.profile,data=request.POST,files=request.FILES) if user_form.is_valid() and profile_form.is_valid(): user_form.save() profile_form.save() else: user_form = UserEditForm(instance=request.user) profile_form = ProfileEditForm(instance=request.user.profile) return render(request,'users/edit.html',{'user_form':user_form,'profile_form':profile_form}) this is my views.py where i have written the logic and coming to urls.py path('edit/',views.edit,name='edit'), and the edit.html code follows like this {% extends 'users/base.html' %} {% block body %} <h2>Edit profile form</h2> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ user_form.as_p }} {{ profile_form.as_p }} <input type="submit"/> </form> {% endblock %} This is my models.py file from django.db import models from django.conf import settings # Create your models here. class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) photo = models.ImageField(upload_to='users/%Y/%m/%d',blank=True) def __str__(self): return self.user.username The main project urls.py from django.contrib import admin from django.urls import path,include from django.conf.urls.static import static from django.conf import settings urlpatterns = [ path('admin/', admin.site.urls), path('users/',include('users.urls')) ] urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) the output shows me like this I am expecting a better solution to resolve this issue -
How properly assign permissions when to user when saving model?
I want to assign Permissions to a user when I Change Group inside the Django admin. I'm adding this permission inside the custom User model in the save method. When I Save changes in the admin panel, no errors are raised, but permissions are not created in my local DB Here is how my model looks like class UserProfile(AbstractUser, PermissionsMixin): name = models.CharField(max_length=255, unique=False, default=None) email = models.EmailField(max_length=50, unique=True) email_verified = models.BooleanField(default=False) date_joined = models.DateTimeField(default=timezone.now) password = models.CharField(max_length=100, null=False) USERNAME_FIELD = "email" REQUIRED_FIELDS = ["name"] objects = CustomAccountManager() def is_member(self, group_name: Roles): return self.groups.filter(name=group_name.value).exists() def save(self, *args, **kwargs): if self.is_member(Roles.STAFF): permissions = Permission.objects.filter(codename__in=settings.STAFF_PERMISSIONS) self.user_permissions.add(*permissions) logger.info(f"Permissions {list(permissions)} added for user {self.email}") super().save(*args, **kwargs) For some reason, I can add permissions from CLI when creating a User instance, but not in the save method, what might be wrong here? -
why records are not being inserted into postgresql database in pytest-django?
I tried to use postgres database with pytest-django and I've encountered a problem. I have a fixture named populate_db which creates some records in the database. To check if pytest actually creates records, I put a 60-seconds sleep after creating the model objects and checked the panel admin but none of the created objects were present there. I think the pytest can't connect to my database and doesn't create any records in the database. Below are the functions that I have in my conftest.py file and I have another test file which tries to retrieve a database record from the API. Here is my code for the populate_db fixture: @pytest.fixture(autouse=True) def populate_db(): sport = Vertical.objects.create(name='sport') bazar = Vertical.objects.create(name='bazar') time.sleep(60) yield -
Unknown domain is connected to my server. Is it Bad purpose? [closed]
I am deploying Web application Using Elastic beanstalk Currently I've found out that unknown domain is conneted to my server. Ex) Our service domain is onenonly.io But test.hellobot.com is connected to my server too. Maybe I've got to set Allowed Host to secure it. But I want to know How bad people takeover secret infos by doing this. q1. some weird domain is connected to my server. Is it accident? or bad intention? q2. If it is bad purpose, then how they takeover secret infos by just pointing their domain to my server ip? I am using Application Loadbalancer with assigned Elastic IP. -
Why is for loop not working in django html?
yesterday i wrote an application using for loop that worked exactly as I wanted it to work, but today when I opened it up without changing a thing it is not working. and this is happening every time I try to make something similar. i also tried inspecting the page but I only see an empty div while there is actually for loop inside it. any help would be appreciated. thanksfor loop inspect window I also created new app and did exact same things. i just coppied code and it worked. but when i try to do same in this application it remains the same. -
How to install `distro-info===0.18ubuntu0.18.04.1`?
Trying to modernize an old Django project (2.2), and its requirements.txt (generated via pip freeze) has some lines that make pip install throw fits: distro-info===0.18ubuntu0.18.04.1 I interpreted the errors I got for the first one (see the error output in its entirety at the bottom) as the version string not conforming to PEP-518, but it doesn't even mention the === operator. This SO thread, What are triple equal signs and ubuntu2 in Python pip freeze?, has a similar issue, but: The errors they got is different (ValueError as opposed to my ParseError). The solution was to upgrade pip, but I'm already using the latest one. Now, pip install distro-info works so should I just go with that? update: The project I'm trying to update has been conceived around 2020, and according to the PyPI history of distro-info, it had a 0.10 release in 2013 and a 1.0 in 2021. Could this anything have to do with the weird pip freeze output? (From this PyPI support issue.) The error: ERROR: Exception: Traceback (most recent call last): File "/home/old-django-project/.venv/lib/python3.10/site-packages/pip/_vendor/pkg_resources/__init__.py", line 3021, in _dep_map return self.__dep_map File "/home/old-django-project/.venv/lib/python3.10/site-packages/pip/_vendor/pkg_resources/__init__.py", line 2815, in __getattr__ raise AttributeError(attr) AttributeError: _DistInfoDistribution__dep_map During handling of the above exception, another … -
Cannot assign "<django.contrib.auth.models.AnonymousUser object at 0x7f81fe558fa0>": "Post.author" must be a "UserData" instance
I'm trying to write simple tests for some endpoints but the second one keeps failing. Here's the test.py from rest_framework.test import APITestCase, APIRequestFactory, APIClient from rest_framework import status from django.urls import reverse from .views import PostViewSet from django.contrib.auth import get_user_model User = get_user_model() class PostListCreateTestCase(APITestCase): def setUp(self): self.factory = APIRequestFactory() self.view = PostViewSet.as_view({"get": "list", "post": "create"}) self.url = reverse("post_list") self.user = User.objects.create_user( email="testuser@gmail.com", name="testuser" ) self.user.set_password("pass") self.user.save() def test_list_posts(self): request = self.factory.get(self.url) response = self.view(request) self.assertEqual(response.status_code, status.HTTP_200_OK) def test_create_post(self): print(User) print(self.user) client = APIClient() login = client.login(email="testuser@gmail.com", password="pass") self.assertTrue(login) sample_post = { "title": "sample title", "body": "sample body", } request = self.factory.post(self.url, sample_post) request.user = self.user print(isinstance(request.user, get_user_model())) response = self.view(request) self.assertEqual(response.status_code, status.HTTP_201_CREATED) And here's the view: class PostViewSet(viewsets.ModelViewSet): serializer_class = PostSerializer queryset = Post.objects.all() def get_queryset(self): posts = Post.objects.all() return posts def get_object(self): post = get_object_or_404(self.get_queryset(), pk=self.kwargs["pk"]) self.check_object_permissions(self.request, post) return post def create(self, request, *args, **kwargs): try: post = Post.objects.create( title=request.data.get("title"), body=request.data.get("body"), author=request.user, ) post = PostSerializer(post) return Response(post.data, status=status.HTTP_201_CREATED) except Exception as ex: print(str(ex)) return Response(str(ex), status=status.HTTP_400_BAD_REQUEST) def list(self, request, *args, **kwargs): posts = self.get_queryset() serializer = self.get_serializer(posts, many=True) return Response( data=dict(posts=serializer.data, total=len(serializer.data)), status=status.HTTP_200_OK, ) And here's what I get: Found 2 test(s). Creating test database for alias … -
How to select data from filtered Data to send POST request using ModelViewSet in DRF?
I have a model. class MyClass(models.Model): field1 = models.ForeignKey("Class1", on_delete=models.PROTECT) field2 = models.ForeignKey("Class2", on_delete=models.CASCADE) field3 = models.ForeignKey("Class3", on_delete=models.PROTECT) This is my ViewSet: class MyViewSet(ModelViewSet): serializer_class = serializers.MySerializer def create(self, request, *args, **kwargs): value1 = Class1.objects.filter(id__in={x.id for x in self.request.user.organization_modules}) value2 = Class2.objects.filter(organization=self.request.user.organization) value3 = Class3.objects.get(id=self.kwargs["pk"]) obj = MyClass(field1=value1, field2=value2, field3=value3) obj.save() return Response(status=status.HTTP_201_CREATED) This is the URL: path("api/", MyViewSet.as_view({"post":"create"})) In the above example,I am overriding create method of ModelViewSet and performing the data selection to save the data. But when I hit the API, I want to select values of field1, field2 and field3 from filtered data, not from all the data of Class1, Class2 and Class3. But in current implementation, all the data of Class1, Class2 and Class3 is shown. How to do that? -
Django, TokenAuthentication, REST Framework API, Authentication credentials were not provided
I'm new to backend. I'm trying to fetch my data in the backend via API token, and I followed this tutorial: https://www.django-rest-framework.org/api-guide/authentication/ When I add these two lines in my View code, I can't fetch my data: authentication_classes = [SessionAuthentication, BasicAuthentication] permission_classes = [IsAuthenticated] The error is { "detail": "Authentication credentials were not provided." } and on my backend I got "GET /hello/ HTTP/1.1" 403 58 But if I delete those two lines, I can fetch my data successfully. This is my View class: `class HelloView(APIView): authentication_classes = [SessionAuthentication, BasicAuthentication] permission_classes = [IsAuthenticated] def get(self, request, format=None): print(request.auth) content = { 'user': str(request.user), 'auth': str(request.auth), } return Response(content)` In the tutorial, it says when I have those two lines, I will be able to view my user name and token in the user router. But I got none for my "auth". However, if I delete those two lines, I can view my "user" and "auth" on my Windows side. Screenshots: backend side, with those two lines frontend side, with those two lines frontend side, without those two lines Could anybody explain this to me please? Any help would be nice! Thank you so much! -
How to push data from html form to firebase realtime database in django(using pyrebase)?
I'm having a problem with pushing data from a form to firebase realtime database. Here is my view funcction. Just updated to include user token but hasn't helped. The data isn't displaying in the db. def post_add(request): name = request.POST.get('name') phone = request.POST.get('phone') location = request.POST.get('location') city = request.POST.get('city') website = request.POST.get('website') data = {"name": name, "phone": phone, "location": location, "city": city, "website": website} user = authe.get_account_info(request.session['uid']) db.child("restaurant").push(data,user['users'][0]['localId']) return render(request, 'restaurants.html') here is the db Just updated to include user token but hasn't helped. The data isn't displaying in the db. -
'WSGIRequest' object has no attribute 'front_page'
I want to link my post_create to frontpage.And im getting this error. Im a beginner and I dont really know how to link.Can you guy give me advice plz. This is error im getting.enter image description here This is my code in view.pyenter image description here This is my code in model.pyenter image description here This is my code in urls.pyenter image description here This is my code in templateenter image description here -
RelatedObjectDoesNotExist at /users/edit/ User has no profile
I ran into a situation where I had developed a method called edit and passed both the profile and user forms into it when I wanted to modify a profile. @login_required def edit(request): if request.method == 'POST': user_form = UserEditForm(instance=request.user,data=request.POST) profile_form = ProfileEditForm(instance=request.user.profile,data=request.POST,files=request.FILES) if user_form.is_valid() and profile_form.is_valid(): user_form.save() profile_form.save() else: user_form = UserEditForm(instance=request.user) profile_form = ProfileEditForm(instance=request.user.profile) return render(request,'users/edit.html',{'user_form':user_form,'profile_form':profile_form}) this is my views.py where i have written the logic and coming to urls.py path('edit/',views.edit,name='edit'), and the edit.html code follows like this {% extends 'users/base.html' %} {% block body %} <h2>Edit profile form</h2> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ user_form.as_p }} {{ profile_form.as_p }} <input type="submit"/> </form> {% endblock %} the output shows me like this I am expecting a better solution to resolve this issue -
Django query data in template using JS and python functions
Let's say I have a form for a booking system based on a one-to-many relations with the visitors table..as in the attached image, I'm trying to implement a "Find" function linked to the visitor passport table so we don't need to re-enter the visitors data again. abasically we can enter the passport number and run a query so if his data is there it will come back and fil the form, otherwise we have to reenter it manually using a different form. The following JS function will query the visitor table by passport # and bring back data correctly. However I don't know how to fill out the booking form with the new data so it can be saved, because the data I get is in html format as a table. In my real case, I need to save two fields only from the returned data including the passport number in the booking form, so how I extract the passport # from the returned data, or maybe there is a better way to do so. function visitor_details(pass_num){ url = 'booking_vis_details' $.ajax({ type: "GET", url : url, data: { num: pass_num, csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val() }, success: function(data) { $('#table_details').html(data); } }) } View: … -
Getting Back Python Frameworks
I'm accidentally deleted my Python Frameworks on my mac so i can't work learning Django can your guys help me to get back Python Frameworks Mac-MacBook-Pro:~ mac$ python3 --version Python 3.11.1 Mac-MacBook-Pro:~ mac$ python3 -m django --version Traceback (most recent call last): File "<frozen runpy>", line 198, in _run_module_as_main File "<frozen runpy>", line 88, in _run_code File "/Users/mac/django/django/__main__.py", line 9, in <module> management.execute_from_command_line() ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ AttributeError: module 'django.core.management' has no attribute 'execute_from_command_line' Mac-MacBook-Pro:~ mac$ python -m django --version python: posix_spawn: /System/Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python: No such file or directory Mac-MacBook-Pro:~ mac$ -
Failed to establish a new connection: [Errno 113] No route to host'))
I am trying to connect Readthedocs and Gitlab to each other via gitLab OAuth 2.0, I say connect with gitlab without any problem via readthedocs, gitlab connects and I select authorize, but the following error appears, what could be the source of this problem? thankyou for support. HTTPSConnectionPool(host='gitlab.tutel', port=443): Max retries exceeded with url: /oauth/token (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x7f22cac5fc10>: Failed to establish a new connection: [Errno 113] No route to host')) -
NoReverseMatch at /cars Reverse for 'car_details' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['carscars/(?P<id>[0-9]+)/
stackoverflow * ` In views.py def car_details(request, id): single_car = get_object_or_404(Car, pk=id), # id = 1 data = { 'single_car': single_car, # 'url': url, } # reverse('single_car', args=(id)) return render(request, 'cars/car_details.html', data) In urls.py urlpatterns = [ path('', views.cars, name='cars'), path('<int:id>/car_details', views.car_details, name='car_details'), ] In car.html {% for car in cars %} <div class="detail"> <h1 class="title"> <a href="{% url 'car_details' pk=car.id %}">{{car.car_title}}</a> </h1> <div class="location"> <a href="{% url 'car_details' pk=car.id %}"> <i class="flaticon-pin"></i>{{car.state}}, {{car.city}} </a> </div> {% endfor %} In models.py class Car(models.Model): id=models.IntegerField(primary_key=True,default=True) also tried with revrser function on views.py it gives same error ``*` also tried with revrsere function on views.py it gives same error