Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django 3.1 fix Admin Category name to Categories
How do I change some models name from "Categorys" to "Categories" on admin site in django version 3.1? below is my code snippet class Category(models.Model): category_name = models.CharField(max_length=50, unique=True) slug = models.CharField(max_length=100, unique=True) description = models.TextField(max_length=255, blank=True) cat_image = models.ImageField(upload_to='photos/categories', blank=True) class Meta: verbose_name = "category" verbose_name_plural = "categories" def __str__(self): return self.category_name I run python manage.py makemigrations command and got a No changes detected response. Please note that i inserted the lines of code below last hoping for changes to take effect but i still got a No changes detected response. verbose_name = "category" verbose_name_plural = "categories" I also tried changing the category name max field from 50 to 100 like this category_name = models.CharField(max_length=100, unique=True) and when i run the python manage.py makemigrations command i got the response below $ python manage.py migrate Operations to perform: Apply all migrations: admin, auth, category, contenttypes, sessions Running migrations: Applying category.0002_auto_20211227_0931... OK -
Image not loading in Django application
models.py have below row image1 = models.ImageField(default='default.jpg', upload_to='post_pics') settings.py as follow STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' urls.py if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) in template I load static files `{% load static %}` {% for post in posts %} <img src={{ post.image1 }} > {% endfor %} But still resulting in no image found -
How to add text to foreign key field in Django
I am using a foreign key in Django. If the data you want to add is not in the foreign key, you want to enter it directly and save it in the db. After Googling for hours, I couldn't find a solution. Is there any way? -
Page Not Found if I Using Share I object with Email in Django
we creating a blog project I want to share object data email then the for page through a error page not found view.py ```from django.core import paginator from django.shortcuts import get_list_or_404, render,get_object_or_404 from.models import Post from django.core.paginator import Paginator,PageNotAnInteger,EmptyPage from django.views.generic import TemplateView # Create your views here. def post_view(request): post=Post.objects.all() post_list=Post.objects.all() paginator=Paginator(post_list,3) page_number=request.GET.get('page') try: post_list=paginator.page(page_number) except PageNotAnInteger: post_list=paginator.page(1) except EmptyPage: post_list=paginator.page(paginator.num_pages) return render(request,'blog/home.html',{'post':post ,'post_list':post_list}) def detail_view(request,year,month,day,post): post=get_object_or_404(Post,slug=post,status='published',publish__year=year,publish__month=month,publish__day=day) return render(request,'blog/detail.html',{'post':post}) #from django.core.mail import send_mail from django.core.mail import send_mail from Blog.forms import EmailsendForm def emailSend_view(request,id): post=get_object_or_404 (Post,id=id,status='published') form=EmailsendForm() return render(request,'blog/emailshare.html',{'post':post,'form':form})``` if I use to define a URL patterns for email view function it thorough a error urls.py from django.contrib import admin from django.urls import path from Blog import views ```urlpatterns =[ path('admin/', admin.site.urls), path('', views.post_view ), path(r'^(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/(?P<post>[-\w]+)/$', views.detail_view,name='post_detail'), path('(<id>)/share/$', views.emailSend_view),``` there we are using link to add form page in detail page detail.html <h1>This Is Your Content</h1> <div> <h2>{{post.title|title}}</h2> </div> <div> {{post.body|title|linebreaks}} <p>Publised of {{post.publish}} Published By {{post.author<title}}</p> <a href="{{post.id}}/share" class='btn btn-lg btn-primary'>Share Post By Email</a> {%endblock%}``` if I use some other URL patterns then also it generate same Error **url.py** `path('(?P<id>/d+)/share/$', views.emailSend_view),` error of page I m adding in image [error showing in the image][1] [1]: https://i.stack.imgur.com/X0ZFX.png -
The specified value does not conform to the required format
I have this code snippet in django template <td><input type="datetime-local" id="tdId_{{i.0}}5" value="{{i.4|date:'Y-m-d H:i'}}"/></td> The console writes The specified value ... does not conform to the required format. ... Which mask should I use to match the required format of datetime-local? -
Alternative in factory boy for _fill_optional=True which is used in model_mommy
I am replacing model_mommy with factory_boy in Python Django. Here I need to replace _fill_optional=True to work with factory_boy library. In the test case it is being used for model factory classes. Is it necessary to replace _fill_optional=True in factory_boy library? If yes what is suitable alternative for it? -
Getting error as -> Could not parse the remainder: '-2021' from '2020-2021'
I need to display some information based on the condition that the "fiscal year" should be "2020-2021". Following is the condition, I am writing in Django template:- {% if awp.Fiscal_year == 2020-2021 %} I tried putting 2020-2021 in quotes but that didn't work, as follows:- {% if awp.Fiscal_year == '2020-2021' %} After after writing the fiscal year in quotes, the data is not rendering while without quotes, it is producing the error -> django.template.exceptions.TemplateSyntaxError: Could not parse the remainder: '-2021' from '2020-2021'. Type of fiscal year (data type) is -> <class 'pmisminema.dataEntry.models.Fiscal_year'> Here is how it is defined in models.py:- Fiscal_year = models.ForeignKey( Fiscal_year, on_delete=models.CASCADE, default=1,) Class for the "Fiscal_year" is as follows:- class Fiscal_year(models.Model): ackFlag = models.SmallIntegerField(default=DEFAULT_ID) approveFlag = models.SmallIntegerField(default=DEFAULT_ID) createdTime=models.DateTimeField(default=timezone.now) modifiedTime=models.DateTimeField(default=timezone.now) Userid = models.ForeignKey(User, on_delete=models.CASCADE,default=DEFAULT_ID) Financial_Year = models.TextField() def __str__(self): return self.Financial_Year Can anyone help me with this issue? -
JsonResponse in Django app returns 200 irrespective of status code
Import statement: from django.http.response import JsonResponse return statement: return JsonResponse(msg, safe=False, status=400) I get a status code of 200 as my return code irrespective of whatever status field i set to in JsonResponse object. How do i fix this? -
how I can set ID in Django REST Framework JSON:API response?
I am using Django REST Framework JSON:API. Then, I want to set ID in the response. I know the response gets ID from Django model instance. But, if I set the instance to the serializer, the ID will be null. Example class Tag(models.Model): name = models.CharField(max_length=64, unique=True) class TagSerializer(serializers.Serializer): name = serializers.CharField() class TagDetailView(views.APIView): def get(self, request, pk): tag = Tag.objects.get(pk=pk) serializer = TagSerializer(data={"name": tag.name, "memo": "memo"}) serializer.is_valid(raise_exception=True) return Response(data=serializer.data, status=200) Expected { "data": { "type": "TagDetailView", "id": 1, "attributes": { "name": "name", "memo": "memo" } } } As-Is { "data": { "type": "TagDetailView", "id": null, // I WANT TO SET THE ID HERE "attributes": { "name": "name", "memo": "memo" } } } -
Gunicorn async and threaded workers for django
Async For input/output(IO) bound we need to use async code and django is not async by default, but we can achieve this running gunicorn with the gevent worker and monkey patching: gunicorn --worker-class=gevent --worker-connections=1000 --workers=3 main:app Gunicorn changelog from 2014 https://docs.gunicorn.org/en/stable/2014-news.html?highlight=monkey#gevent-worker: fix: monkey patching is now done in the worker Do i still need to monkey patch my app or it's done by default from a worker ? How did gevent achieve async functionality for my django code ? Threads If we have a CPU bound we need to use a gthread worker with threads: gunicorn --workers=5 --threads=2 --worker-class=gthread main:app If we use this configuration for i/o bound, does it work? When one thread is waiting because of i/o, will the other thread be able to work? I see the point in (3) (if I'm right) because of the wait time in i/o, but if this is a CPU bound, how in our case will the second thread help us or will it only help if the core is not fully loaded by one thread and there is room for another to run? Are (3) and (4) useless because of GIL ? For example, 4 people sending request to server … -
Django. Cannot upload Image in models
I am doing Online School project. When i want to add a new language in the Teacher, image of this languages gets null. I got the similar code, but in Admin Page(not default admin). And code in Admin page is working and successfull uploading image for Language. So, i have question, why it is not uploading My views. @user_passes_test(is_teacher) def teacher_add_language_view(request): languageForm=LanguageForm() if request.method=='POST': languageForm=LanguageForm(request.POST, request.FILES) if languageForm.is_valid(): language=languageForm.save(commit=False) author = TMODELS.Teacher.objects.get(user__username=request.user) language.author = author languageForm.save() else: print("you got error") return HttpResponseRedirect('teacher-languages') return render(request,'teacher/teacher_add_language.html',{'languages':languageForm}) My forms class LanguageForm(forms.ModelForm): class Meta: model=QMODEL.Language fields=['title', 'image'] Language model class Language(models.Model): class Meta: verbose_name='Язык' verbose_name_plural='Языки' title = models.CharField(max_length=100, verbose_name='Язык') author = models.ForeignKey(Teacher, on_delete = models.SET_NULL, null = True, blank=True) slug = models.SlugField(default='None', editable = False) image = models.ImageField(upload_to='main_menu_picture/', null=True, blank=True) it gets null? Can you help? Thanks for your att -
How to change Django default message in django.contrib.auth.form
I used Django default AuthenticationForm for login. Here is my code: from django.contrib.auth.forms import ( AuthenticationForm,PasswordResetForm,UsernameField ) class ProfiledAuthenticationForm(AuthenticationForm): username = UsernameField( label=_("username"), max_length=254, widget=forms.TextInput(attrs={'autofocus': True,'placeholder': 'username'}), ) password = forms.CharField( label=_("password"), strip=False, widget=forms.PasswordInput(attrs={'placeholder': 'password'}), ) When the login is failed, an default alert is appeared. I need to customize the alert. How should I handle it? -
How to use inner join tables in the DRF?
How to implement inner join data on DRF. I have two model classes one is user and client. When I am adding a client that time I am selecting a list of users which is handled by that client. Now when I am fetching the list of users from the API then I need the client name as well in that API. My modal classes are: class User(AbstractBaseUser, PermissionsMixin): identifier = models.UUIDField(default=uuid.uuid4, editable=False, serialize=False, verbose_name='identifer') email = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=255) image = models.ImageField(null=True, upload_to=user_image_file_path) contact_no = models.CharField(max_length=255, default='') class Client(models.Model): name = models.CharField(max_length=200) main_contact = models.ForeignKey( 'User', on_delete=models.CASCADE, related_name="main_contact", null=True ) users = models.ManyToManyField( User, related_name="users" ) views.py class GetAllUserList(generics.ListAPIView): permission_classes = (permissions.IsAuthenticated, jwtPermissions.IsSSOAdminOrReadOnly,) queryset = User.objects.all() pagination_class = PostLimitOffsetPagination serializer_class = GetAllUserSerializer serializers.py class GetAllUserSerializer(serializers.ModelSerializer): class Meta: model = get_user_model() fields = '__all__' Any suggestions is of great help! -
Display data from mysql database in a calendar django
I want to design a calender and display the data from mysql database in django as per the below image: Here the year values are retrieved from the mysql database. Any help will be highly appreciated! Thank You!! -
Bug different SQL Queries generated by Django when requested from different application
I have a question related to Django Application and Django REST Framework. I have posted GET request to same API from 3 different device, ReactNative with axios, Browser, and Postman. All these 3 devices trigger different number of queries to database. enter image description here I checked the SQL query detail, and here is the result for each devices. enter image description here Please share some insight on why is this happening, or any other details that I need to provide to find the reason or fix the issue -
Django makemigrations error: "__init__() got an unexpected keywork argument 'max_Length'
I am trying to make migrations to a new app 'users' and keep receiving the error: "TypeError: Field.init() got an unexpected keyword argument 'max_Length'" I previously encountered this error when making migrations on my last app and was able to find the issue on a stackoverflow post which I can't seem to relocate. I know that max_Length is valid because it worked last time but can't seem to remember what I did to make the migrations work. My settings.py files with the users app activated My models.py in my users app: I've spent a lot of time trying to figure out what I am missing but can't seem to get it. Python manage.py makemigrations worked last time with the projects app having the same 'max_Length' constraints. Any ideas on how I can fix this? Thanks in advance -
How can disptach method be implemented in function based views in django
I have started a new project and Trying to do this : Login Required to Checkout in Ecommerce website. If not logged in redirect page to /login/?next=/checkout/ How dispatch method can be implemented here : views.py checkout def checkout(request): form = CheckoutForm(request.POST or None) cart_id = request.session.get("cart_id", None) if cart_id: cart_obj = Cart.objects.get(id=cart_id) if form.is_valid(): form.instance.cart = cart_obj form.instance.subtotal = cart_obj.total form.instance.discount = 0 form.instance.total = cart_obj.total form.instance.order_status = "Order Received" del request.session['cart_id'] form.save() form=CheckoutForm() return redirect("/") else: cart_obj = None return render(request,"checkout.html",{'cart':cart_obj,'form':form}) login def login(request): error="" form = CustomerLoginForm(request.POST or None) if form.is_valid(): uname = form.cleaned_data.get("username") pword = form.cleaned_data.get("password") usr = authenticate(username=uname, password=pword) if usr is not None and Customer.objects.filter(user=usr).exists(): auth_login(request, usr) return redirect("/") else: error="Invalid credentials" return render(request,"login.html", {"form": form, "error": error}) -
I cannot use Django
I want to use Django. I installed it but after that I wanted to create file and I got this error. django-admin.exe startproject mysite . django-admin.exe : The term 'django-admin.exe' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path wa s included, verify that the path is correct and try again. At line:1 char:2 django-admin.exe startproject mysite . + CategoryInfo : ObjectNotFound: (django-admin.exe:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException what is the problem? -
aws ec2 and gcp e2 instances constantly become unresponsive
I've deployed a Django app on AWS-ec2-micro instance and a React app on GCP-e2-micro instance before, but I encountered almost the exact same problem: Server will randomly become unresponsive and unreachable while doing some heavy I/O operations. It happens almost all the time if I try to install some large packages such as tesseract, but it sometimes freezes even when I'm just trying to run a react app using npm start. I've looked at the monitoring and they all have one thing in common: super high CPU usage. Especially after the server becomes unreachable, the CPU meters continue to rise. AWS-ec2 usually will reach almost 100% while GCP-e2 instance will reach beyond 100% to something like 140%. At a certain time, the CPU usage will become stabilized at about 50%, but the server is still unreachable using SSH. The server sometimes recovers itself after hours of being unreachable, but usually, it ends up having to force stop and restart the server. This will cause the public ipv4 to change which I really don't like, so I want to find out why my server is constantly unresponsive. Here is what I've installed on my server: ssh-server vscode-server And then on GCP-e2, … -
Unable to add post in Django getting TypeError: 'AnonymousUser' object is not iterable
When I am clicking on the modal button to add a new post in Django. I am getting the below traceback Traceback (most recent call last): File "D:\Django_AJAX_Latest\env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "D:\Django_AJAX_Latest\env\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\Django_AJAX_Latest\src\posts\views.py", line 22, in post_list_and_create author = Profile.objects.get(user = request.user) File "D:\Django_AJAX_Latest\env\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "D:\Django_AJAX_Latest\env\lib\site-packages\django\db\models\query.py", line 428, in get clone = self._chain() if self.query.combinator else self.filter(*args, **kwargs) File "D:\Django_AJAX_Latest\env\lib\site-packages\django\db\models\query.py", line 974, in filter return self._filter_or_exclude(False, args, kwargs) File "D:\Django_AJAX_Latest\env\lib\site-packages\django\db\models\query.py", line 992, in _filter_or_exclude clone._filter_or_exclude_inplace(negate, args, kwargs) File "D:\Django_AJAX_Latest\env\lib\site-packages\django\db\models\query.py", line 999, in _filter_or_exclude_inplace self._query.add_q(Q(*args, **kwargs)) File "D:\Django_AJAX_Latest\env\lib\site-packages\django\db\models\sql\query.py", line 1375, in add_q clause, _ = self._add_q(q_object, self.used_aliases) File "D:\Django_AJAX_Latest\env\lib\site-packages\django\db\models\sql\query.py", line 1396, in _add_qn _add_q child_clause, needed_inner = self.build_filter( n build_filter File "D:\Django_AJAX_Latest\env\lib\site-packages\django\db\models\sql\query.py", line 1302, in build_filter n check_related_objects self.check_related_objects(join_info.final_field, value, join_info.opts) File "D:\Django_AJAX_Latest\env\lib\site-packages\django\db\models\sql\query.py", line 1136, iner return func(self._wrapped, *args)n check_related_objects for v in value: nctional.py", line 249, in inner return func(self._wrapped, *args)s) TypeError: 'AnonymousUser' object is not iterable Below are my files: posts/views.py from django.shortcuts import render from .models import Post from django.http import JsonResponse from .forms import PostForm from profiles.models import Profile def is_ajax(request): return request.META.get('HTTP_X_REQUESTED_WITH') == … -
how to acess query set values in to html page?
def futsal_user(request): futsal_user = FutsalUser.objects.all() print(futsal_user) for users in futsal_user: users_list = users.company_details print(users_list) for company_name in users_list: print(company_name.name , ) context = {'futsal_user':futsal_user, 'users_list':users_list } return render(request,'futsalusers.html',context) -
Django Jquery get selected value
Hi I'm having issue with passing data to jquery. In my select I have added onchange method and it calls getProductData and pass this select element. In getProductData I get the element and display the selected value. I tried using few methods but the output of alert is [object Object] or undefined. forms.py PD_name = forms.ModelChoiceField( label = "Product Name", queryset = Product.objects.only('name').order_by('id'), to_field_name = 'id', empty_label = "", widget = forms.Select( attrs = { 'class': 'form-control', 'onblur': """form_validation({ 'element' : this, })""", 'onchange': """getProductData({ 'element' : this, })""" } ) ) html <td>{{ Productform.PD_name }}</td> JQuery function getProductData(element) { alert(element.value); } -
Invalid file path or buffer object type: <class 'NoneType'> python-django
I have a issue on read excel file uploaded by user,here my code if request.method == 'GET': add_file = request.FILES.get('monthly_file') df = pd.read_excel(add_file) When i give request.Files['monthly_file] it gave multidict key value error,. So im using request.FILES.get('monthly_file') to get user uploaded file. But it gives Invalid file path or buffer object type: <class 'NoneType'> value error,. How can i resolve it.. Thanks in advance,.. -
[Django][DRF] How to get UNORDERED queryset using .filter?
first of all, I'm not a native at ENG so plz be patient my ENG skills or give me some advice. I'm writing API creating a post by using drf serializer. And I've been facing a problem with "the order of tags adding to the post". post and tag models are connected through M2M field which means, let's say I add tags a, b, and c on a post. The logic I use as follows. # class Serializer # def create(instance): # instance : specific post instance tags = ['t', 'a', 'g', 's'] Tag.objects.bulk_create([Tag(name = tag) for tag in tags]) instance.add.tags(*[tag for tag in Tag.objects.filter(name__in = tags)]) run this at first. tags are added in this order TagQuerySet[Tag<'t'>, Tag<'a'>, Tag<'g'>, Tag<'s'>] And my API takes the other create request that include the tags of the existing like, tags = ['g', 'a', 's'] django add in the sorted order, not in the order I want like, # tags new created instance TagQuerySet[Tag<'a'>, Tag<'g'>, Tag<'s'>] I know the method that adding tags following my list order using for loop for tag in tags: instance.tags.add(Tag.objects.get(name=tag)) but it's not efficient. So my question is how to get queryset using .filter following my list order. … -
I am working on a project in django and thining a way to save the .json file in django which comes from javascript file
But the problem is that the json data comes from javaScript file . once we upload it on the database i want to fetch it again and use it with the javaScript is there any way to upload the json file from javascript and after fetching it send it again to javascipt file thank you