Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Celery crontab to schedule 1 of the month and quarterly in year
I have a celery task which executes quarterly on 1 of the month how can my month_of_year can be written { 'task': 'mytask', 'schedule': crontab(day_of_month='1', month_of_year='') }, -
VSCode unable to autoimport python functions
I am currently able to auto-import python functions from external typings such as from typing import List. However, I am unable to detect local functions for import. For example: If I have the data class SomethingData in dataclasses.py, and I reference it in a function in do_something.py, VSCode is unable to detect it and I have to manually type out the import path for the dataclass. I have the following extensions enabled: Python Pylance Intellicode My settings.json includes: { "python.envFile": "${workspaceFolder}/.env", "python.languageServer": "Pylance", "python.analysis.indexing": true, "python.formatting.provider": "black", "python.analysis.autoImportCompletions": true, "python.analysis.autoSearchPaths": true, "python.autoComplete.extraPaths": ["~/Development/<django repo name>/server"], "python.analysis.extraPaths": ["~/Development/<django repo name>/server"], "vsintellicode.features.python.deepLearning": "enabled", } I am using poetry for my virtual environment which is located at ~/Development/<django repo name>/.venv Is there something that I'm missing? -
Question regarding uploading files to the internal website
I am encountering a problem on my internal website. Everything was working fine until someone turned the server off, so I had to turn on the server via Docker. The site was up and running fine after that. However, my colleagues quickly realized that they could not add files to the website, i.e. you first upload files to the site, select save and then it will save the uploaded file. Upon further inspection, I found out that you could upload files from some pages only, i.e. both pages 1 and 2 allow you to upload documents, but only page 2 accepts the upload request and successfully uploads it to the site; page 1 will attempt to upload and return saved successfully, but the files will not have been uploaded. To provide some context to the situation, I inputted "sudo pkill -f uwsgi -9" before running the server again using Docker. More importantly, the internal website is vital for everyday operations and cannot be down under any circumstances, so I am a bit reluctant to mess with the server in fear of destroying whatever that can still be used. My colleagues are still getting by because they can upload from another … -
Cannot log in the django admin site with nginx
I have an issue with logging into django admin site which is almost the same question five years ago. Unfortunately, there is no specific answer until now. Here is the brief introduction for the question. My nginx serves the 80 port and it will proxy all the URL starts with prefix to 8000 port which Django is listening. location /prefix/ { proxy_pass http://0.0.0.0:8000/; } access /prefix/admin/, it gives me a 302 and redirect to /admin/login/?next=/admin/. However, if we access /prefix/admin/login, it works and we have the Django Administration login page as below. However, if we are trying to login(url is /admin/login/) with username and password, it gives me a 404. Let me make a summary, here we have two issues in total. prefix/admin not working, prefix/admin/login works. Logging into the admin site(admin/login) not working. The first issue has been solved by location /prefix/admin/ { proxy_pass http://0.0.0.0:8000/admin/login/; } The second issue, however, not working by the following. location = /admin/login { proxy_pass http://0.0.0.0:8000/admin/; } It told me that I have too many redirects. How can I fix this? Thanks in advance. -
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