Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
(Django)please help me, I not sure is the post function is error
when i press the button to post something, it will return me to the main page, not stay in the forum page and show me what i just post. here is the view.py def forum(request): profile = Profile.objects.all() if request.method == "POST": user = request.user image = request.user.profile.image content = request.POST.get('content','') post = Post(user1=user, post_content=content, image=image) post.save() alert = True return render(request, "forum.html", {'alert':alert}) posts = Post.objects.filter().order_by('-timestamp') return render(request, "forum.html", {'posts':posts}) def discussion(request, myid): post = Post.objects.filter(id=myid).first() replies = Replie.objects.filter(post=post) if request.method=="POST": user = request.user image = request.user.profile.image desc = request.POST.get('desc','') post_id =request.POST.get('post_id','') reply = Replie(user = user, reply_content = desc, post=post, image=image) reply.save() alert = True return render(request, "discussion.html", {'alert':alert}) return render(request, "discussion.html", {'post':post, 'replies':replies}) -
Passing image link in Django Template from model/context
Does anyone know how to pass a dynamic data entry (from Model) into a img src? One that cannot be saved statically and accessed there in Django? A bit like this <div class="border-8 border-border p-10 w-auto ml-5 rounded-2xl text-base text-white bg-black h-full"> <p class="pb-2">User Profile</p> <img src="{{ Avatar }}"> {% for instance in UserProfile %} {% for field, value in instance.fields.items %} <p> {{ field }} : {{ value }} </p> {% endfor %} {% endfor %} </div> Avatar is just loaded in the context and is a JSON entry containing a URL -
Left Join: Set value to zero if there is no record in the right table
I have two tables called user and point that have a 1-N relationship with each other. Left table: user id name 1 John 2 Willem Right table: point user date score 1 2021/12/01 1 2021/12/02 2 2021/12/01 2 2021/12/03 How can I apply a Left Join that, like the output below, if it does not have a user in the right table according to date field, set score=0. Desired Output according to date: user date score 1 2021/12/01 5 1 2021/12/02 3 1 2021/12/03 0 <------ 2 2021/12/01 5 2 2021/12/02 0 <------- 2 2021/12/03 4 I did the following attempt but it only returns users that have a record in the point table. from django.db import connection cursor = connection.cursor() cursor.execute( '''SELECT users.id,users.username, point.sp FROM users LEFT JOIN point ON users.id = point.user_id WHERE point.date <= '{0}' and point.date >= '{1}';'''.format(sprint.end, sprint.start)) row = cursor.fetchall() -
I have an existing Django Webapp, how do I make a rest API to integrate the webapp with an android app?
I have an existing django webapp, I have two model classes in my models.py for different functionalities in my app. I have used django allauth for all of the login/logout/social sign ins. Note: I have not used django rest framework at all so far in creating my app. Now, I have to do the same for the android version of my webapp using Java. What exactly do I need to do right now to create the rest APIs and then connect them to the android app? please give some suggestions -
Change form based on attribute
class Client(models.Model): name = models.CharField(verbose_name='UID', max_length=80) type = models.CharField(verbose_name='Type', choices=BUSINESS_CHOICES, max_length=80, default='b-2') I have a model like above, what I want to do is based the type attribute need to change the form in update view. I tried the following way in views class ClientEditView(UpdateView): model = Client template_name = 'client_edit_form.html' success_url = reverse_lazy('xxxx') def get_form_class(self): if self.object.type == 'b-2': form_class = ClientEditForm elif self.object.type == 'b-3': form_class = ClientEditForm2 return super(ClientEditView, self).get_form_class() But it is throwing error. Using ModelFormMixin (base class of ClientEditView) without the 'fields' attribute is prohibited. -
How can I do unit testing for def checkout(request) method?
from django.shortcuts import render from django.http import JsonResponse import json import datetime from .models import * from .utils import cookieCart, cartData, guestOrder def store(request): data = cartData(request) cartItems = data['cartItems'] order = data['order'] items = data['items'] products = Product.objects.all() context = {'products':products, 'cartItems':cartItems} return render(request, 'store/store.html', context) def cart(request): data = cartData(request) cartItems = data['cartItems'] order = data['order'] items = data['items'] context = {'items':items, 'order':order, 'cartItems':cartItems} return render(request, 'store/cart.html', context) def checkout(request): data = cartData(request) cartItems = data['cartItems'] order = data['order'] items = data['items'] context = {'items':items, 'order':order, 'cartItems':cartItems} return render(request, 'store/checkout.html', context) -
how to add line break in django admin panel
if I enter a space there, then the text on the site will be glued. But I need a line break to be added there, how can I do this? image -
PyODBC get return value of a stored procedure
I have this code calling stored procedure. with connections["mssql_database"].cursor() as cursor: try: cursor.execute("EXEC [dbVyroba].[dbo].[UlozitCinnost] %s, %s, %s, %s, %s, %s, %s, %s, %s", \ [id_pracoviste, osobni_cislo, id_cinnost, id_klient, pocet, program, cas_od, cas_do, idod]) query = "EXEC [dbVyroba].[dbo].[UlozitCinnost] @idpracoviste=%s, @OsobniCislo=%s, @IDcinnost=%s, @idklient=%s ,@pocet=%s, @program=%s, @CasOd=%s, @CasDO=%s, @IdOd=%s" ret = cursor.execute(query , (id_pracoviste, osobni_cislo, id_cinnost, id_klient, pocet, program, cas_od, cas_do, idod)).fetchall() print ("return value of stored procedure: ", ret) except Exception as e: print( str(e)) It prints [(datetime.datetime(2021, 12, 1, 7, 55, 39), )] How can I get a return value of a stored procedure? -
Nullable one to one vs foreign key in django
History: I have three models, 1.Users 2.Student 3.Institution. At the beginning a user can be either a student or institution, once a user register as student then need to fill their profile (Student Model). Now the Student model is an OneToOne bonded with Users. this is how the old system works. class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) Problem: Now my new requirement is that "Institution" can add any number of new students under them. Which means they can add new students under their portal For this problem i found two approach, Approach 1: In Student model - make the one to One Field as null=True, blank=True and then add a extra field like institution and then keep track for the students added by institution or Approach 2: In Student Model - make one to one into an Foreign field so that any one can hold the student. Which is the correct approach ? Please help -
Custom S3Boto3Storage with django-storages
I developed a Django app that I'm using VM's disk for saving and serving media and static files but in one of my models, I want to save my files in a FileField connected to my MinIO object storage. I set up the settings like this in the settings.py AWS_ACCESS_KEY_ID = '###' AWS_SECRET_ACCESS_KEY = '###' AWS_S3_ENDPOINT_URL = '###' and in my model I used S3Storage like this: class CustomStorageBucket(S3Boto3Storage): bucket_name = "files" class Document(BaseModel): document_file = models.ImageField(storage=CustomStorageBucket(),upload_to='documents') with these codes, I can save my files into the storage but the URLs in the admin panel do not works properly because it points to the media files URL something like this : http://localhost:8000/media/documents/file.jpg but I want it to be like this ( presigned URL) : https://object-storage.app/files/documents/file.jpg?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=XXX&X-Amz-Date=XXX&X-Amz-Expires=432000&X-Amz-SignedHeaders=host&X-Amz-Signature=XXX -
Is there a way to automatically update a webpage using Django?
I am trying to create a countdown timer into a webpage using Django. I made the requisite time calculations in the view for the template, and passed them in as context to the template, and displayed it using the context. However, the timer only updates as I refresh the webpage. Is there any way I can have the timer auto-update? View Function for template: def home(request): #Time Calculations Performed Here time_dict={'days': days, 'hours': hours, 'minutes': minutes, 'seconds': seconds} context={'participants':participants, 'time':time_dict} return render(request, 'base/home.html', context) Template Section Where Timer is Displayed: <hr> <h3>Countdown Timer</h3> <div><h5> Days: {{time.days}}, Hours: {{time.hours}}, Minutes: {{time.minutes}}, Seconds: {{time.seconds}} <h5></div> <hr> -
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!!