Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Custom Grouping on OpenAPI endpoints with Django Rest Framework
I have a Django project and I am using Django REST framework. I am using drf-spectacular for OpenAPI representation, but I think my problem is not tied to this package, it's seems a more generic OpenAPI thing to me (but not 100% sure if I am right to this). Assume that I have a URL structure like this: urlpatterns = [ path('admin/', admin.site.urls), path('api/', include([ path('v1/', include([ path('auth/', include('rest_framework.urls', namespace='rest_framework')), path('jwt-auth/token/obtain', CustomTokenObtainPairView.as_view(), name='token_obtain_pair'), path('jwt-auth/token/refresh', CustomTokenRefreshView.as_view(), name='token_refresh'), path('home/', include("home.urls")) ])) ])), # OpenAPI endpoints path('swagger/', SpectacularSwaggerView.as_view(url_name='schema-swagger-json'), name='schema-swagger-ui'), path('swagger.yaml/', SpectacularAPIView.as_view(), name='schema-swagger-yaml'), path('swagger.json/', SpectacularJSONAPIView.as_view(), name='schema-swagger-json'), path('redoc/', SpectacularRedocView.as_view(url_name='schema-swagger-yaml'), name='schema-redoc'), ] In the corresponding swagger UI view, I get all endpoints grouped under api endpoint, e.g.: If add more endpoints under v1, all go under the api endpoint. What I want to achieve is, to have the endpoints in Swagger grouped differently, e.g. by app. So I'd have home, jwt, another_endpoint, instead of just api, so it will be easier to navigate in Swagger (when I add more endpoints, with the current method it's just showing a massive list of URLs, not very user friendly). I've read that those groups are being extracted from the first path of a URL, in my case this is … -
get() takes 1 positional argument but 2 were given :Django Rest
I'm currently making a simple get/post api with django 3. After i run the server and go to the employee/article/ url it return an error VIEW.PY from django.shortcuts import get_object_or_404 from django.http import HttpResponse from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from .models import employees from .serializer import employeeSerializer class employeeList(APIView): def get(self): employess1 = employees.objects.all() serializer = employeeSerializer(employess1 ,many=True) return Response(serializer.data) serializer.py from rest_framework import serializers from .models import employees class employeeSerializer(serializers.ModelSerializer): class Meta: model = employees fields = ['first_name','last_name','salary'] urls.py from django.urls import path from . import views urlpatterns = [ path('employees/',views.employeeList.as_view()), ] -
Case conditional expression and duplicates
Django 3.0.8 Purpose: organize sorging by a calculated field is_featured. Posts are tagged: django-taggit is used. The virtual vield is_featured shows whether a post has tag featured. class PostAdmin(admin.ModelAdmin): list_display = ("id", "updated", "title", 'category', "tags", "is_featured",) def get_fields(self, request, obj=None): fields = [a_field.name for a_field in self.model._meta.fields if a_field.name not in ["id",]] return fields def get_readonly_fields(self, request, obj): return get_readonly_fields_aux(obj=obj, readonly_fields=self.readonly_fields, request=request) def tags(self, obj): return list(obj.tags.names()) def get_queryset(self, request): queryset = super().get_queryset(request) # <QuerySet [<Post: 7: asdf>]> queryset = queryset.annotate( _is_featured=Case(When(tags__name__in=[SPECIAL_TAGS.FEATURED.value], then=Value(1)) , default=Value(0), output_field=CharField(), )) return queryset # <QuerySet [<Post: 7: asdf>, <Post: 7: asdf>]> def is_featured(self, obj): return obj._is_featured Problem: duplicates in the result queryset that is returned from get_queryset(). In the database there is definitely one post with id 7 (I checked in the database). But a post usually has several tags. This post with id 7 has two tags. That is why the result contains a duplicate post. So far I did: return queryset.distinct(). And it solved the problem. Could you tell me whether this an acceptable solution or ther might be a better one? -
Why do I get "Failed to save attachment" error in Django-summernote?
So I'm using django-summernote in my Django application, deployed with AWS EC2, running on Ubuntu and nginx server. I've tried to attach an image in the editor, but got an error saying "failed to save attachment". Below are my codes regarding it. mvp.conf (the name of the project is 'mvp') server { listen 80; server_name (my url) charset utf-8; client_max_body_size 128M; location / { uwsgi_pass unix:///tmp/mvp.sock; include uwsgi_params; } location /static/ { alias /srv/hiim/staticfiles/; } } settings.py ... MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') ... What do you think is the problem? If you need any further code, please let me know. Thank you very much in advance. :) -
How to set up a local dev environment for Django
Python web development newbie question here. I'm coming from PHP/Laravel and there you have Homestead which is a pre-configured Vagrant box for local development. In a so-called Homestead file, you configure everything such as webserver, database or PHP version. Are there any similar pre-configured dev environments for Django? I already googled and there don't seem to be any official or widely-used Vagrant boxes for Django. The official Django tutorial even tells you how to install and set up Apache and your preferred database. This is a lot of work everytime you want to create a new Django project, especially if those projects run in different production environments. All the other tutorials I've found just explain how you set up virtual environments with venv or the like. But that doesn't seem to be sufficient to me. What you obviously want is a dev environment that is as close as possible to your production environment, so you need some kind of virtual machines. I'm a little bit confused right now. Do you just grab some plain Ubuntu (or any other OS) Vagrant box and install everything yourself? Don't you use Vagrant at all but something else? Did I miss something and the … -
TypeError: expected string or bytes-like object.in django
When I migrate below model its occure error i dont understand why occure error any solve it. File "C:\Users\Aqib\AppData\Local\Programs\Python\Python38\lib\site-packages\django\utils\dateparse.py", line 107, in parse_datetime match = datetime_re.match(value) TypeError: expected string or bytes-like object** In my models:. models.py from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.conf import settings from django.utils.translation import ugettext_lazy as _ from .managers import LikeManager class Like(models.Model): """ """ user = models.ForeignKey(getattr(settings, 'AUTH_USER_MODEL', 'auth.User'), on_delete=models.CASCADE) target_content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) target_object_id = models.PositiveIntegerField() target = GenericForeignKey('target_content_type', 'target_object_id') timestamp = models.DateTimeField(auto_now_add=True, db_index=True) objects = LikeManager() class Meta: ordering = ["-timestamp"] get_latest_by = "timestamp" unique_together = ("user", "target_content_type", "target_object_id") verbose_name = _("like") verbose_name_plural = _("likes") def __unicode__(self): return u"{} liked {}".format(self.user, self.target) In my manager.py file manager.py from django.contrib.contenttypes.models import ContentType from django.db import models from django.apps import apps def _get_content_type_and_obj(obj, model=None): if isinstance(model, str): model = apps.get_model(*model.split(".")) if isinstance(obj, (int, int)): obj = model.objects.get(pk=obj) return ContentType.objects.get_for_model(type(obj)), obj class LikeManager(models.Manager): """ A Manager for Like objects """ from django import VERSION if VERSION > (1,8): def get_query_set(self): return self.get_queryset() def for_user(self, user, model=None): """ Returns a Like objects queryset for a given user. If a model params is provided, it returns only the liked objects of that model class Usage: … -
Application profile not returning proper name in Django app
Recently started learning django and as an initial step, i created an application called profiles within my django app. Now from the admin page i opened that app and added a profile with a name and description however when i save it, it doesnt return the proper name, it just returns "profile name(1)" where as i have specifically asked it to return name. here is the models.py code from __future__ import unicode_literals from django.db import models #Create your models here. class profile(models.Model): name = models.CharField(max_length=120) description = models.TextField(default='description default text') def __unicode__(self): return self.name added the app in settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'profiles', ] here is the admin.py file from django.contrib import admin # Register your models here. from .models import profile class profileAdmin(admin.ModelAdmin): class Meta: model=profile admin.site.register(profile,profileAdmin) its probably something very silly which I am not able to point out but I checked and recheckeed if I am using the right 'profiles' and 'profile' everywhere. Also asking so that i can get a better understanding of what this actually is. I am also addind a pic from my sublime editor the circled part shows in a different color in the tutorial I am … -
Upload multiple images within single upload button Django-rest framework without forms
I understand this is old question but i didn't get proper answer for this. I have seen answers for this questions like creating more than two upload buttons and calling them multiple uploading, well what im asking is, how to upload images like more than 1000 within a single upload button? please if anybody knows answer this and post links related to my question. Thank you ! <----i'm asking with Django rest framework without forms. because i will use react as frontend. -
Image upload error 'Check the encoding type on the form.'
In my project, i need to upload an image as an avatar for my players as shown in my models.py : class Player(models.Model): number = models.IntegerField() photo = models.ImageField(upload_to=upload_path, null=True, blank=True) firstname = models.CharField(max_length=24) lastname = models.CharField(max_length=24) tag = models.CharField(max_length=8, blank=True) color = models.CharField(max_length=10, null=True, blank=True) selected = models.BooleanField(null = False, blank=True) post = models.ForeignKey(Post, on_delete=models.SET_NULL, null=True) def __str__(self): return "#{}".format( self.number, ) I'm using angular to send my image using : <input type="file" (change)="onNewPlayerPhotoChanged($event)" accept="image/jpeg, image/png, image/jpg" /> & in my typescript onNewPlayerPhotoChanged(event) { this.newPlayerPhoto = event.target.files[0]; } then on my submit button i got createPlayer() { this.newPlayer.selected = false; this.newPlayer.photo = this.newPlayerPhoto; this.newPlayer.post_id = parseInt(this.newPlayerPost, 10); this.playerService.create(this.newPlayer).subscribe( res => { this.getPlayerList(); this.openNewModal = false; this.alertService.success('Joueur créé avec succès !'); setTimeout(() => this.alertService.clear(), 2000); }, error => { this.alertService.error(error); setTimeout(() => this.alertService.clear(), 2000); } ); } But i got the error : photo: ["The submitted data was not a file. Check the encoding type on the form."] Here is my **views.py : ** class PlayerViewSet(viewsets.ModelViewSet): """ API endpoint that allows Player to be viewed or edited. """ parser_classes = [JSONParser] queryset = Player.objects.all() serializer_class = PlayerSerializer permission_classes = [IsAuthenticated, HasPermission, ] def post(self, request, *args, **kwargs): return HttpResponse({"message":request.FILES}, status=200) … -
Advance python scheduler with celery task
I want to add scheduling task to Advance python scheduler using a celery task. The scheduler, I am using scheduler = BackgroundScheduler({'apscheduler.timezone': 'Asia/Calcutta'}) This is how the celery task will use the scheduler scheduler.add_job( send_email_to_candidate, trigger='date', next_run_time=instance.scheduled_time, args=[instance.pk] ) Problem: The task is submitted to the scheduler but is not executed. date format is 2020-07-10 13:14:00+0530 -
In Django I'm trying to display the output of "for loop"
In Django I'm trying to display the output of "for loop" one next to another but i'm getting the boxes one below the other. how to display the contents of for loop side by side template file {% for post in post_list %} <div class="box"> <div class="content"> <h1><a href="{% url 'post_detail' pk=post.pk %}">{{post.title}}</a> </h1> {% if post.photo %} <img src="{{ post.photo.url }}" class='' height='235' width='235'> {% endif %} <h3>{{ post.text|safe|linebreaksbr }} </h3> <p>published on {{post.published_date|date:"D M Y"}}</p> <ul> <li><form action="{% url 'like_post' post.pk %}" method="POST"> {% csrf_token %} <a> <button type="submit" name="post_id" value="{{ post.id }}" > Like </button> </a> {{ post.likes.count }} </form></li> <li><a href="{% url 'post_detail' pk=post.pk %}">Comments</a>{{ post.approve_comments.count }} </li> </ul> <br> </div> </div> css file .box{ position: relative; width: 400px; height: 500px; display: flex; justify-content: center; align-items: center; background: #222222; } .content { padding: 10px; color: #fff; } -
Unable to login & register to Django dashboard
I am having below Django dashboard project: https://github.com/wittymindstech/IoTGlobalMap I cloned this repo and executed: python manage.py migrate python manage.py runserver In the login dashboard when i am entering username and password, it says username and password doesn't match. Attached is the screenshots. Below is the terminal output: python manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). July 10, 2020 - 13:13:33 Django version 3.0.7, using settings 'GlobDash.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. [10/Jul/2020 13:13:39] "GET /login/ HTTP/1.1" 200 3628 [10/Jul/2020 13:13:39] "GET /login/ HTTP/1.1" 200 3628 [10/Jul/2020 13:13:42] "POST /login/ HTTP/1.1" 200 3670 [10/Jul/2020 13:13:42] "GET /login/ HTTP/1.1" 200 3628 [10/Jul/2020 13:13:45] "GET /register/ HTTP/1.1" 200 3953 [10/Jul/2020 13:13:45] "GET /register/ HTTP/1.1" 200 3953 [10/Jul/2020 13:13:58] "POST /register/ HTTP/1.1" 200 3965 [10/Jul/2020 13:13:58] "GET /register/ HTTP/1.1" 200 3953 -
How to make drop-down search location. When i clicked on particular location so fetch data and display
I am trying to make Django web application. In which i want top trending tweets fetch through (API) location wise. Can anyone known how its make. Any idea??? Make drop-down search location. When i clicked on particular location so fetch data and display???. image [For Example][1] Views.py #import json #import requests import tweepy import twitter import yweather def trends(request): auth = tweepy.OAuthHandler(consumerKey, consumerSecret) auth.set_access_token(accessToken, accessTokenSecret) api = tweepy.API(auth) woeid = 2151330 trend = api.trends_place(woeid) final_trend = [] for trending in trend[0]['trends'][:10]: final_trend.append(trending) return render(request, "trend.html",{'final_trend':final_trend}) trend.html {% for t in final_trend %} <td>1</td> <td>{{t.name}}</td> {% if t.tweet_volume == None %} <td><10k tweets</td> {% else %} <td>{{t.tweet_volume|slugify|slice:":2"}}k tweets </td> {% endif %} <!-- <td><a href="{{t.url}}">Tweet</td> --> </tr> {% endfor %} -
Update data with BaseModelFormSet as pre-filled in Django
I have a data adding form which it's been created with BaseModelFormSet. The working logic of my form is as follows: for example, there are 12 attributes in my model class, but the user only uses 8 of them. The users choose this first when they register, then this data adding form is created according to the attributes their chooses. So my forms.py file such as below; class BaseDataFormSet(BaseModelFormSet): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.queryset = Data.objects.none() and I have created the form in following way; DataFormSet = modelformset_factory(Data, fields=selected_features, formset=BaseDataFormSet) form = DataFormSet(request.POST or None, request.FILES or None) There's no issue while adding a new data but I'm getting trouble when I try to update the exist data. When the user presses the update button, I want the form to be created according to the attributes that the user chooses and to fill the form with the values that the user entered before. So I have created my update form as following; class BaseDataUpdateFormSet(BaseModelFormSet): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.queryset = kwargs['queryset'] and my updateData view; @login_required(login_url = "user:login") def updateData(request,id): features = request.user.profile.selected_features instance = get_object_or_404(Data, id = id) queryset = Data.objects.filter(id = instance.id).values(*features) DataFormSet = … -
Nothing is happening in the login page? (When the sign in button is clicked, same page is shown)
When I try to login through the login page,nothing happens.The same page is displayed.When I put the right credentials too,nothing happens. But,the login with facebook is running. The registration is working fine and the details can also be seen in the admin dashboard. views.py from django.shortcuts import render, redirect from django.contrib.auth.models import User from .models import UserModel from django.contrib.auth import authenticate,login,logout def loginview(request): if request.user.is_authenticated: return redirect('index') if request.method=="POST": username=request.POST.get('username') password=request.POST.get('password') user=authenticate(request, username=username, password=password) if user is not None: login(request,user) next=request.GET.get('next') if next: return redirect(next) else: return redirect('index') else: return redirect('login') else: return render(request, 'userapp/login.html') I tried using next option too: views.py def loginview(request): if request.method=="POST": username = request.POST.get('username') password = request.POST.get('password') user = auth.authenticate(request, username=username, password =password) if user is not None: auth.login(request, user) return redirect('index') else: messages.info(request,'invalid credentials') return redirect('login') if request.user.is_authenticated: return redirect('index') else: return render(request, 'newspaper/login.html') userapp/login.html {% extends 'newspaper/base.html' %} {% load static %} {% block title %} Login : {% endblock %} {% block main_content %} <form method="POST" class="form-signin"> {% csrf_token %} <img class="mb-4" src="{% static 'img/logo.png' %}" alt="" width="72" height="72" /> <h1 class="h3 mb-3 font-weight-normal">Please sign in to Raila Khabar</h1> <label for="inputEmail" class="sr-only">Username</label> <input type="text" id="inputEmail" class="form-control" placeholder="Username" required autofocus name="username" /> <label … -
DRF, allauth and dj-rest-auth - Authenticate with inactive users return None instead the user object
I'm using all-auth and dj-rest-auth to implement registration and login via email. Everything work fine but when making test, inactive users return invalid credentials message instead inactive account message. In the LoginSerializer, it seems that django.contrib.auth authenticate method doesn't return the user, but None. Here is the code: settings.py AUTHENTICATION_BACKENDS = [ "django.contrib.auth.backends.AllowAllUsersModelBackend", "allauth.account.auth_backends.AuthenticationBackend" ] REST_AUTH_REGISTER_SERIALIZERS = { 'REGISTER_SERIALIZER': 'user.serializers.RegisterSerializer', } REST_AUTH_SERIALIZERS = { 'LOGIN_SERIALIZER': 'user.serializers.LoginSerializer', 'USER_DETAILS_SERIALIZER': 'user.serializers.UserDetailSerializer', } serializers.py class LoginSerializer(serializers.Serializer): email = serializers.EmailField(required=True, allow_blank=False) password = serializers.CharField(style={'input_type': 'password'}) def authenticate(self, **kwargs): return authenticate(self.context['request'], **kwargs) def _validate_email(self, email, password): user = None if email and password: user = self.authenticate(email=email, password=password) else: msg = _('Must include "email" and "password".') raise exceptions.ValidationError(msg) return user def validate(self, attrs): email = attrs.get('email') password = attrs.get('password') user = None if 'allauth' in settings.INSTALLED_APPS: from allauth.account import app_settings # Authentication through email if app_settings.AUTHENTICATION_METHOD == app_settings.AuthenticationMethod.EMAIL: user = self._validate_email(email, password) # Did we get back an inactive user? if user: if not user.is_active: msg = _('User account is disabled.') raise exceptions.ValidationError(msg) else: msg = _('Unable to log in with provided credentials.') raise exceptions.ValidationError(msg) # If required, is the email verified? if 'dj_rest_auth.registration' in settings.INSTALLED_APPS: from allauth.account import app_settings if app_settings.EMAIL_VERIFICATION == app_settings.EmailVerificationMethod.MANDATORY: try: email_address = … -
Django the best way to create an edit modal form?
In one of my django app I have set the following model: class Income(models.Model): price = models.DecimalField() quantity = models.DecimalField() date=models.DateField() So after that I have created all the structure to get a form in my template (so form.py and views.py files). In my template.html file I have set the following {% load crispy_forms_tags %} <form id="" method="post"> <div class="form-group col-2 0 mb-0" > {{form.quantity|as_crispy_field}} </div> <div class="form-group col-2 0 mb-0" > {{form.price|as_crispy_field}} </div> <div class="form-group col-2 0 mb-0" > {{form.date|as_crispy_field}} </div> </div> After that I have created a table that list all data filled. Now I want to create a button for each row that open a modal form that give me the possibility to modify the specific data for each id dataset. I have tried to perform it with an ajax call, but I have had difficults to perform the form and the type of data (becouse in this manner I don't have the possibility to use crispy form or the forms model of the django framework). So my question is: there is a simple way to achive my aim? -
How to deploy Django apps on cwp Cent Os 7 using gunicorn and nginx
I have tried many times this artical https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-centos-7 but I am not getting the result. I using dedicated server with CentOs 7 and CWP but I am not able to connect my wsi.py file through nginx server I am doing first time deployment on centos7 cwp,So feel free to suggest me as fresher. -
How to restrict the recipient of PasswordResetView in Django?
Sorry if the title of this post isn't self-explanatory enough. I've implemented a simple blog application using Django in which I've added the functionality of sending password reset emails in case the users forget their login credentials. For the sake of clarity, assume that I have two users who are already registered: user1 and user2, and their emails are: user1@mail.com and user2@mail.com. The problem occurs when I give my default PasswordResetView an email that does not belong to any of my users, say userX@mail.com. And when I go and log into that email address, I indeed see that I received the password reset email, which I definitely shouldn't have. So, my question is, how can I modify my PasswordResetView so that it first checks whether the given email address actually belongs to one of the existing users and if not, gives back an error? My project's urls.py file: from django.contrib import admin from django.contrib.auth import views as auth_views from django.urls import path, include from users import views as user_views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path("admin/", admin.site.urls), path("blog/", include("blog.urls")), path("register/", user_views.register, name="register"), path("login/", auth_views.LoginView.as_view(template_name='users/login.html'), name="login"), path("logout/", auth_views.LogoutView.as_view(template_name='users/logout.html'), name="logout"), path("password-reset/", auth_views.PasswordResetView.as_view(template_name='users/password_reset.html'), name="password_reset"), path("password-reset/done/", auth_views.PasswordResetDoneView.as_view(template_name='users/password_reset_done.html'), name="password_reset_done"), path("password-reset-complete/", … -
i want my posts to show latest first and does but when i edit any post it shows up on top where i want only the posts which were recently added
i want my posts to show latest first and does but when i edit any post it shows up on top where i want only the posts which were recently added. Everything works fine but i dont want the edited post to come on top of list views.py def home(request): return render(request, 'List/home.html') def task_list(request): context = { 'posts': Post.objects.all().order_by('-date') } return render(request, 'List/task.html', context) def edit_task(request, post_id): post = Post.objects.get(id=post_id) form = TaskForm(instance=post) if request.method == 'POST': print(request.POST) form = TaskForm(request.POST) if form.is_valid(): form.save() return redirect('task') context = {'form': form} return render(request, 'List/add_task.html', context) models.py from django.db import models from django.utils import timezone class Post(models.Model): Task = models.CharField(max_length=50, default='pythons') Detail = models.TextField(max_length=100, default='python') date = models.DateTimeField(default=timezone.now) def __str__(self): return self.Task -
Assign html class to generated Django form input elements
I have this form: class ZeroIntegrationConfigForm(ModelForm): class Meta: model = ZeroIntegrationEntry fields = ['tab_title', 'description', 'country', 'operations', 'locale', 'company_name'] That I generate with: <form method="post">{% csrf_token %} {{ form.as_p }} <input type="submit" value="Save"> </form> But I can't figure out / find how to assign html class to each input element generated, is the only way to do this writing the html manually for each element? -
How safe is using if statements in html with django?
How safe is using if statements in html templates with django? Eg. {% if post.visibility == 'PUBLIC' %} show something.... {% endif %} How easy is it to change that from public to private if we don't filter it accordingly in the backend for hackers or other people? -
Python Initialization Failed With No Modules named 'encodings' error
As I was trying to install mysqlclient for my django project, I encountered a issue which is getting very difficult to resolve despite of other helps in similar questions already asked. I almost tried many but could not sort it out since my environment is set correctly. The issue is: Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding Python runtime state: core initialized ModuleNotFoundError: No module named 'encodings' Looking at the syspath, I diagnosed that the issue might be with the syspath sys.path = [ 'C:\\Users\\atifm\\Envs\\Django\\Scripts\\python38.zip', '.\\DLLs', '.\\lib', 'c:\\users\\atifm\\appdata\\local\\programs\\python\\python38-32', ] But actually python38-32 doesnot exist. I have Python38 only which is 64 bit. Does that make sense? Can anyone help me out with this? -
How to change url to show description instead of id with django?
I am building my first website. But instead of the page being products/15 (where 15 is the product id), I want it to show the description of the product. How can I achieve that? Here are my models.py: class Product(models.Model): name = models.CharField(max_length=100) category = models.CharField(max_length=100) description = models.TextField() def __str__(self): return self.name views.py: def product(request, id): return render(request, 'product.html', {}) urls.py: urlpatterns = [ path('products/<id>/', post, name='sub-detail'), ] Thanks in advance for the help! -
how Django microservices communicate within multiple microservices using Django REST API end points. please share the code
how Django microservices communicate within multiple microservices using Django REST API end points. please share the code