Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django @swagger_auto_schema properties
my json data { "User": { "login_id": "admin", "password": "qwer1234" } } I want to put this response in swagger doc too! I use drf_yasg app in django. I've written this code: @swagger_auto_schema(method='post', request_body=openapi.Schema( type=openapi.TYPE_OBJECT, properties={ 'login_id': openapi.Schema(type=openapi.TYPE_STRING, description='ID'), 'password': openapi.Schema(type=openapi.TYPE_STRING, description='password'), } )) I don't know how to provide json data -
How to update/insert query database automatic in django
This is a digital library system. When borrow end_date has expired, borrow status will be updated automatically to 1 (End), table book column stock will be updated adding one stock, and automatically inserting new content value in table notification. class Borrow(models.Model): status = models.CharField(max_length=1, choices=[('0', 'Process'),('1', 'End')], default=0) book = models.ForeignKey('models.Book', on_delete=models.CASCADE, related_name='borrow_book') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) end_date = models.DateTimeField() class Book(models.Model): stock = models.IntegerField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Notification(models.Model): content = models.CharField(max_length=255, blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) How to make an automatic update query in table borrow column status, table book column stock, and insert in table notification when end_date > DateTime.now() ? -
Django domain and webhosting
I have a django web application and my database is postgresql. I am thinking of buying the hosting and domain in godaddy. Is it recommended or cheaper? If godaddy which should I buy should I buy the shared hosting? Thanks -
Django Ignoring invalid foreign key with migrate?
When I do the migrate I get the below error. can I ignore it to continue the migration. django.db.utils.IntegrityError: The row in table 'pages_dataupload' with primary key '15734098' has an invalid foreign key: pages_dataupload.Customer_Address_id contains a value '' that doesn't have corresponding value in pages_bo -
Cannot assign "'Sample Category'": "Product.category" must be a "Category" instance
While creating new products I'm getting such kind of error. Can someone help me? class Product(models.Model): user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) name_geo = models.CharField(max_length=200, null=True, blank=True) image = models.ImageField(null=True, blank=True, default='/placeholder.png') brand = models.CharField(max_length=200, null=True, blank=True) category = models.ForeignKey(Category, null=False, default=0, on_delete=models.CASCADE) price = models.DecimalField(max_digits=7, decimal_places=2, null=True, blank=True) countInStock = models.IntegerField(null=True, blank=True, default=0) createdAt = models.DateTimeField(auto_now_add=True) _id = models.AutoField(primary_key=True, editable=False) def __str__(self): return self.name_geo class Category(models.Model): _id = models.AutoField(primary_key=True, editable=False) name = models.CharField(max_length=200, null=True, blank=True) createdAt = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name @api_view(['POST']) def createProduct(request): user = request.user product = Product.objects.create( user=user, name_geo="Sample Name", category="Sample Category", price=0, brand='Sample Brand', countInStock=0, ) serializer = ProductSerializer(product, many=False) return Response(serializer.data) Without separating category class in models.py everything works fine. I mean If i didn't use ForeignKey in Products class for category -
How do I get an error message from an object
I'm trying to create an authentication in my project after signing in. I created my models and form. I want the user to get an error message if he doesn't get the correct pin in the models and successful if he puts in the right pin. I create the pin in my models already class Data(models.Model): name = models.CharField(max_length=100) body = models.CharField(max_length=1000000) first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) other_name = models.CharField(max_length=200) email = models.EmailField() profile_image = models.ImageField(blank=True) city = models.CharField(max_length= 100) title = models.TextField(null=True, blank=True) middlename = models.TextField(null=True, blank=True) adreess = models.TextField(null=True, blank=True) country = models.TextField(null=True, blank=True) state = models.TextField(blank=True, verbose_name="Biography (Age, Language, Location...)") pin = models.IntegerField() available = models.TextField(null=True, blank=True) checkings = models.TextField(null=True, blank=True) savings = models.TextField(null=True, blank=True) phone_number = models.TextField(null=True, blank=True) first_his = models.TextField(null=True, blank=True) second_history = models.TextField(null=True, blank=True) third_history = models.TextField(null=True, blank=True) last_history = models.TextField(null=True, blank=True) newstate = models.TextField(null=True, blank=True) def __str__(self): return self.first_name this is my HTML file <style> h5{ color: red; } </style> {% for message in messages %} <h5> {{message}}</h5> {% endfor %} <form action="portfolio" method="POST" class="row g-3"></form> {% csrf_token %} <div class="col-md-12"> <label for="validationDefault02" class="form-label"></label> <input type="text" name = 'pin' class="form-control" id="validationDefault02" value="" required> </div> <div class="col-12"> <button class="btn btn-primary" type="submit">Send</button> </div> </form> … -
Search template page not Found
I am trying to implement search in my project so that users can search for anything with ease but I keep getting Page not Found error.The errors seems like it's coming from my urls.py but I don't know where exactly. Below are my codes urls.py from .import views app_name = 'app' urlpatterns = [ path('', views.product_list, name='product_list'), path('<slug:category_slug>/', views.product_list, name='product_list_category'), path('search/', views.search_list, name='search_list'), path('<int:id>/<slug:slug>/', views.product_details, name='product_details'), ] views.py from .models import Category, Product from cart.forms import CartAddProductForm from django.db.models import Q # Create your views here. def product_list(request, category_slug=None): category = None categories = Category.objects.all() products = Product.objects.filter(available=True) if category_slug: category = get_object_or_404(Category, slug=category_slug) products = products.filter(category=category) return render(request, 'products/list.html', {'category': category, 'categories': categories, 'products': products}) def product_details(request, id, slug): product = get_object_or_404(Product, id=id, slug=slug, available=True) cart_product_form = CartAddProductForm() return render(request, 'products/detail.html', {'product': product, 'cart_product_form': cart_product_form}) def search_list(request): search_post = request.GET.get('q') search_query = Product.objects.filter(Q(name__icontains=search_post) | Q(category__name__icontains=search_post)) return render(request, 'products/search.html', {'search_post': search_post, 'search_query': search_query, 'category': category, 'categories': categories}) -
how to get variation in a product id
I'm not getting a return on the color and size, only the product name is coming. And yes my request.POST['color'] and request.POST['size'] are receiving the values, but in the form of names and not in id. def add_to_cart(request, product_id): product = Product.objects.get(id=product_id) variation_list = [] if request.method == "POST": color = request.POST['color'] size = request.POST['size'] try: variation = Variation.objects.get(product=product, color__name__exact=color, size__name__exact=size) variation_list.append(variation) except: pass return HttpResponse(variation_list) HttpResponse -
DRF function based view HTTP 405 Method Not Allowed
I'm trying to use function based view to create a new object, but keeps shows this error: HTTP 405 Method Not Allowed Allow: GET, OPTIONS Content-Type: application/json Vary: Accept { "detail": "Method "POST" not allowed." } I've read alot stackoverflow questions, but none of them worked for me, here is my code: @api_view(['POST']) @permission_classes([permissions.IsAuthenticated]) def todo_create(request,format=None): if request.method == 'POST': serializer = TodoSerializer(data=request.data) if serializer.is_valid(): serializer.owner = request.user serializer.save() return Response(serializer.data) return Response(serializer.errors) urls urlpatterns = [ path('',todo_links,name='todo_links'), path('lists/',todo_lists,name='todo_lists'), path('create/',todo_create,name='todo_create'), path('lists/<int:pk>/',todo_detail,name='todo_detail'), path('lists/<int:pk>/update',todo_update,name='todo_update'), path('lists/<int:pk>/delete',todo_delete,name='todo_delete'), path('data',template,name='template'), ] main url from snippet.views import api_root urlpatterns = [ path('admin/', admin.site.urls), path('auth/',include('django.contrib.auth.urls')), path('posts/',include('post.urls')), path('api-auth/',include('rest_framework.urls')), path('',include('snippet.urls')), path('todo/',include('todos.urls'),name='todos-app'), ] my settings.py REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly' ], 'DEFAULT_PAGINATION_CLASS':'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE':1 } serializers.py class TodoSerializer(serializers.HyperlinkedModelSerializer): owner = serializers.HyperlinkedIdentityField(view_name='user-detail',format='html') class Meta: model = Todo fields = ['id','owner','title','describe','complete'] my models.py class Todo(models.Model): owner = models.ForeignKey(User,on_delete=models.CASCADE,related_name='todos') title = models.CharField(max_length=255) describe = models.TextField(null=True,blank=True) complete = models.BooleanField(default=False) def __str__(self): return self.title i know how to implement it with class based view, i'm not sure why it shows that error with function based view. thank you in advance -
how to fix raise ImproperlyConfigured("settings.DATABASES is improperly configured. in django
so i'm having issue deploying my django on railway but once the deployment is complete the app crash with this err raise ImproperlyConfigured("settings.DATABASES is improperly configured. " django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details. and below is my django settings and railway setting DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'HOST': os.environ.get('PGHOST'), 'NAME': os.environ.get('PGDATABASE'), 'USERNAME': os.environ.get('PGUSER'), 'PASSWORD': os.environ.get('PGPASSWORD'), 'PORT':os.environ.get('PGPORT') } } can anyone help out pls -
How Do I Loop Through Two Different ManyToMany Quersets in Python Django?
I am trying to do something seemingly simple and it won't cooperate. I am trying to use the django template language to loop through a model. Easy enough. The challenge here is that the model contains two manytomany fields that I am trying to compare. In my model... owner_confirm = models.ManyToManyField(User,related_name='meeting_minutes_action_item_owner_confirm') owner = models.ManyToManyField(User) Simple enough... I have a model that populates these two fields...and that's all working. The problem is when I loop through the template...it's not recognizing them when I try to compare them doing something like... {% if action_item.owner.all == action_item.owner_confirm.all %} What am I doing incorrectly? I have been at this for 2 days and am beginning to lose my mind. The condition above passes as false even if it's true...when I loop through all other types of fields it works fine...manytomany is not. -
Issues with deleting cookie in Django
I am having an issue deleting a HubSpot cookie in Django. I have a landing page with a form, and we were at a Trade Show capturing leads and since all leads used my computer and the hubspotutk cookie tracking user id was added, all new leads coming in were 'reconversions' instead of new contacts. I am attempting to simply delete the COOKIE on page load if it is there so the hubspotutk cookie gets reset on every refresh of the page, but it appears the cookie is never actually removed although it is there. Unfortunately with the code below I get an infinite redirect, only assuming that the hubspotutk cookie is not deleted as expected. Can anyone show me what I am doing wrong? def request_demo_landing(request): if request.COOKIES.get('hubspotutk'): response = HttpResponseRedirect('site.com/request-demo-landing/') response.delete_cookie('hubspotutk') return response ... -
Django score ranking
I am completely new in development. I write a small tool in Django where I can add users and games and then see them in a table. Now I want to add the rank, but I have no idea how to do it. I hope I get some tips here how I can solve it. Here is a screenshot how my table currently looks like Ranking -
How to send a link to an image in a response
I want to send a link to a photo in the response, which is on the hosting, I'm running a django application on the hosting via python manage.py runserver 0.0.0.0:8000 . How do I make it so that in the response to the request there is a link to the image that is on the hosting. Example: I get this response when accessing the API { "title": "add", "description": "some text", "image": "http://127.0.0.1:8000/media/photo_2022-09-12_20-57-08.jpg", "created_at": "2022-09-12T22:24:42.449098+03:00" } I want to get this answer: { "title": "add", "description": "some text", "image": "domain.api/media/photo_2022-09-12_20-57-08.jpg", "created_at": "2022-09-12T22:24:42.449098+03:00" } -
Django Page not found (404) - The current path, Didn't match any of these
I am trying to add a clinic from a users profile, However, i am getting a 404 page not found and i noticed that a single quote is getting appended to the URL: http://127.0.0.1:8000/profile/'/clinic/add_clinic/ Any help would be appreciated. Below are my Project URLS: urlpatterns = [ # django admin path('admin/', admin.site.urls), # User management path('accounts/', include('allauth.urls')), # local apps path('', include('pages.urls')), # new path('clients/', include('clients.urls')), # new path('behaviors/', include('behaviors.urls')), path('clientsessions/', include('clientsessions.urls')), path('profile/', include('users.urls')), path('clinic/', include('clinic.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Here are URLs from the users app urlpatterns = [ path('', views.profile, name='profile'), ] Here is the profile view @login_required def profile(request): if request.method == 'POST': user_form = UpdateUserForm(request.POST, instance=request.user) profile_form = UpdateProfileForm(request.POST, request.FILES, instance=request.user.profile) if user_form.is_valid() and profile_form.is_valid(): user_form.save() profile_form.save() messages.success(request, 'Your profile is updated successfully') return redirect(to='users-profile') else: user_form = UpdateUserForm(instance=request.user) profile_form = UpdateProfileForm(instance=request.user.profile) return render(request, 'users/profile.html', {'user_form': user_form, 'profile_form': profile_form}) Here are the URLs rom the clinic app urlpatterns = [ path('clinic/', views.clinic, name='clinic'), path('add_clinic/', views.add_clinic, name='add_clinic'), ] And here is the add_clinic view @login_required @allower_users(allowed_roles=['admin']) def add_clinic(request): if request.method == 'POST': name = request.POST.get('name') if name: name = Clinic.objects.create(name=name, created_by=request.user) clinic.members.add(request.user) clinic.save() userprofile = request.user.profile userprofile.active_clinic_id = clinic.id userprofile.save() return redirect(to='users-profile') return render(request, 'clinic/add_clinic.html') -
How to integrate Webssh with Django?
I am running a Django Nginx Gunicorn server and also running a web SSH service with a systemd process. Basically, Nginx runs the main domain example.com and then a systemd process listens on port 4433 at example.com:4433. The reason for this is so users can remote login in to different computers using the website instead of having to use a local shell. The rest of the website is behind a login because Django controls the views. However, the part of the website behind the port is being served by systemd and webssh. Is there a way I can integrate Django with Webssh in order to lock the domain example.com:4433 behind a login? -
Django: How can I override login error message?
I have a custom user model class from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager CustomUser(AbstractBaseUser, PermissionsMixin) ... And related view class CustomUserViewSet(viewsets.ModelViewSet): pagination_class = BasePagination queryset = CustomUser.objects.all() ... def create(self, request, *args, **kwargs): serializer = CustomUserSerializer(data=request.data) if serializer.is_valid(): user = serializer.save() if user: json = serializer.data send_invitation_email( user=user, email=json["email"], password=request.data["password"], phone=json["phone_number"] ) create_chats(user) return Response(json, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) In case of email, username duplicate I have the following error message: {"user_name":["custom user с таким user name уже существует."]} How can I override error this message with my custom message: {"user_name":["Пользоватль с таким именем уже существует."]} -
I can't just delete the db django.db.migrations.exceptions.InconsistentMigrationHistory
I know that there are similar questions on the stackoverflow, however, I can’t just take and erase the database and create it again important data is stored there, I think it’s about the migrations themselves, if you have a solution to this problem, I will be very glad to hear it: python manage.py migrate raise InconsistentMigrationHistory( django.db.migrations.exceptions.InconsistentMigrationHistory: Migration members.0001_initial is applied before its dependency company_directory.0002_initial on database 'default'. -
Select choice from models.py in html form DJANGO
I have model in models.py with field living_countries: LIVING_COUNTRIES = [ ('AFGANISTAN', 'Afganistan'), ('ALBANIA', 'Albania'), ('ALGERIA', 'Algeria'), ('ANGORRA', 'Andorra')] country_living = models.CharField(max_length=50, choices=LIVING_COUNTRIES, default='AFGANISTAN', blank=True) I want user who has html form in front of him to be able to choose one of those choices. I've tried: in view: living_countries = models.Employee.objects.all() in html: <select name="category" id="id_category"> {% for category in living_countries %} <option value="{{ category }}">{{ category }}</option> {% endfor %} </select> It just makes weird shape like: . I can click it but it doesn't do anything. I want user to see dropdown menu or something like this. Thanks:) -
Django ModuleNotFoundError after creating models
I've started learning Django and struggling with creating/migrating a model. Everytime I try to type python manage.py migrate(or anything), I get the error ModuleNotFoundError: No module named 'People'. Here's my directory structure; |- VLCase |- VLCase |- models.py |- urls.py |- settings.py |- asgi.py |- __pycache__ |- wsgi.py |- manage.py |- db.sqlite3 Here's my models.py; from django.db import models class People(models.Model): name = models.CharField(max_length=200) I added People into INSTALLED_APPS; INSTALLED_APPS = [ 'People', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] I couldn't find the answer. I would be greatly appreciated. Thanks in advance. -
Django FilterSet with annotations always returns blank response
I do have a rather simple FilterSet that I want to use on a queryset with annotations, but the issue is that it always return an empty result for some reason. This is the filter I'm having issues with class BaseGroupFilter(django_filters.FilterSet): joined = django_filters.BooleanFilter(lookup_expr='exact') class Meta: model = Group fields = dict(id=['exact'], name=['exact', 'icontains'], direct_join=['exact']) And this is the service: def group_list(*, fetched_by: User, filters=None): filters = filters or {} joined_groups = Group.objects.filter(id=OuterRef('pk'), groupuser__user__in=[fetched_by]) qs = _group_get_visible_for(user=fetched_by).annotate(joined=Exists(joined_groups)).all() return BaseGroupFilter(filters, qs).qs -
Django rest framework not returning all fields
I am trying to make a model that stores favorite shows for users, and I have been using viewsets. I have a users and shows viewset that work just like I expect them to, and I have another model that simply stores relationships between users and shows. When I add that as a viewset though, I get the id, and user, and I don't get a show. Here are the results for the favorites: [ { "id":2, "user":{ "username":"poduck", "first_name":"", "last_name":"", "email":"poduck@gmail.com", "image":null, "url":"http://0.0.0.0:8000/api/users/poduck/?format=json" } } ] There isn't even a show field. It's not like the data isn't there either. I have been able to use queries on the data with no trouble. I have access to both the show and the user from the favorite. I thought that maybe that the fact that the show points to a user, and the favorite points to a user that there may be some circular conflict there, but beyond excluding the user field from the Show serializer, I don't know what to do to fix that, and yes, I did try excluding it from the Show serializer. shows.models: from django.db import models from django.utils.translation import gettext_lazy as _ from localflavor.us.models import … -
Problem when import ModelResource from tastypie.resources
I am new to Django and I want to create some API with tastypie, but when I import ModelResource from tastypie.resource I face with error :/ I just do this: from tastypie.resources import ModelResource I get this error: Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 954, in _bootstrap_inner self.run() File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 892, in run self._target(*self._args, **self._kwargs) File "/Users/macbook/.local/share/virtualenvs/PriceList-ofEay4QN/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Users/macbook/.local/share/virtualenvs/PriceList-ofEay4QN/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "/Users/macbook/.local/share/virtualenvs/PriceList-ofEay4QN/lib/python3.9/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception raise _exception[1] File "/Users/macbook/.local/share/virtualenvs/PriceList-ofEay4QN/lib/python3.9/site-packages/django/core/management/__init__.py", line 375, in execute autoreload.check_errors(django.setup)() File "/Users/macbook/.local/share/virtualenvs/PriceList-ofEay4QN/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Users/macbook/.local/share/virtualenvs/PriceList-ofEay4QN/lib/python3.9/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/macbook/.local/share/virtualenvs/PriceList-ofEay4QN/lib/python3.9/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/Users/macbook/.local/share/virtualenvs/PriceList-ofEay4QN/lib/python3.9/site-packages/django/apps/config.py", line 301, in import_models self.models_module = import_module(models_module_name) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 790, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "/Users/macbook/Documents/PriceList/api/models.py", line 4, in <module> from tastypie.resources import ModelResource File "/Users/macbook/.local/share/virtualenvs/PriceList-ofEay4QN/lib/python3.9/site-packages/tastypie/resources.py", line 22, in <module> from django.contrib.gis.db.models.fields import … -
rtk query session id
I'm hosting a django site locally. If baseQuery has relative path like that baseQuery: fetchBaseQuery({ baseUrl: '/api' }), then session id is sent inside headers automatically headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', 'X-CSRFToken': Cookies.get('csrftoken') } if front-end and back-end parts are hosted on different ports and the path in baseQuery is absolute fetchBaseQuery({ baseUrl: 'http://localhost:8000/api' }) (while React is running on :3000) then session id is not attached to requests and Django sends a new one with every response. Is it normal behaviour and how can it be changed? -
How to display the label from models.TextChoices in the template?
The Django docs says that one can use .label, but it does not work in the template. class Model(models.Model): class ModelChoices(models.TextChoices): ENUM = 'VALUE', 'Label' model_choice = models.CharField(choices=ModelChoices.choices) In the template object.model_choice displays the value ('VALUE'). object.model_choice.label displays nothing. How is it possible to get the label ('Label') in the template? Thanks for your time and help, it is appreciated.