Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Not able to Login once user has been created in Django admin
I am able to create the user with permissions and groups. But I am not able to login with the created user in django admin.Creation of the user and permissions -
Why error handler is triggered when i'm trying send django file response?
I upload video file on my django server and saving it in my FileSystemStorage. After I get some frames of this video using python library(PIL) and saving them in fss too. Next i want to display those images on page, so i'm sending(as response) frames_number, fps, filename. def loop(request): if request.method == 'POST': # save video file in vile storage file = request.FILES['file'] fss = FileSystemStorage() fss.save(file.name, file) # set up class, for work with video vt = VideoTools(file.name) # save frames in media storage frames, fps = vt.get_frames() # return frames_number and fps return JsonResponse({ 'frames': frames, 'fps': fps, 'filename': file.name, }) return render(request, 'main/loop.html') In my frontend I count how many frames I need and make the corresponding number of POST requests, each of which give my one frame, but while receiving frame my error handler is trigged. Why? success: function(response) { let fps = response['fps'] let frames = response['frames'] let filename = response['filename'] let frames_needed = Math.round(frames / fps + 1) for(let i=0; i<=frames_needed; i+fps) { // making request let img = get_each_frame(0, filename) img.done(function(response) { console.log(response, 'get_frame_response') }) // getting this handler triggered img.fail(function(error) { console.log(error, 'get_frame_error') }) } }, function get_each_frame(frame_number, filename) { let request … -
How can I check if a foreign key has an attribute on its model?
I have a model named Product class Product(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE) I am at Product views.py, how can I check if an attribute exist in the 'Order' model? What I'm trying to do is this -> hasattr(Product, "order__name") -
how to covert utc time fiekd into json?
I want to convert the following object into json but i'm unabe to do that because i'm getting the following error TypeError: can not serialize 'datetime.datetime' object on "create_time":notification_object.create_time.. i'm send back to server the following object by converting into json.. notification = { "id": notification_object.id, "sender": notification_object.sender, "receiver": notification_object.receiver, "message": notification_object.message, "create_time":notification_object.create_time, } I have tried to convert time into string but that is returning me 2021-12-27 10:11:46.395138+00:00 this time format. But i want 2021-12-27T10:16:20.611423Z time format. -
The 'image' attribute has no file associated with it in django
productscreate.html <form method="post"> {% csrf_token %} <table border="1"> <tr> <td>Title: <input type="text" name="title" id="title" data-bind="value: title"></td> <br> </tr> <tr> <td>Description: <textarea name="description" id="description">Description</textarea></td> <br> </tr> <tr> <td>Image: <input type="file" name="image" id="image"></td> <br> </tr> <tr> <td><button type="submit" id="submit" data-bind="submit: mySubmit">Submit</button></td> </tr> </table> </form> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.5.0/knockout-min.js"></script> <script> var formData1 = new FormData(); $(document).on('click', '#submit',function(e){ e.preventDefault() var viewModel = { title:ko.observable(),description:ko.observable(), mySubmit : function(formElement) { var formData = { 'title' : viewModel.title() , 'description' : viewModel.description(), }; formData1.append('image', $('#image')[0].files[0]) $.ajax({ type: "POST", url: '{% url "productscreate" %}', data: formData,formData1, cache: false, processData: false, enctype: 'multipart/form-data', contentType: false, success: function (){ window.location = '{% url "productslist" %}'; }, error: function(xhr, errmsg, err) { console.log(xhr.status + ":" + xhr.responseText) } }); } }; ko.applyBindings(viewModel); </script> views.py class ProductsList(ListView): model = products context_object_name = 'products' template_name = "productslist.html" class ProductsCreate(CreateView): model = products fields = ['title','description','image'] template_name = "productscreate.html" success_url=reverse_lazy('productslist') class ProductsDetailView(DetailView): template_name = "productsdetail.html" queryset = products.objects.all() context_object_name = 'products' model = products models.py class products(models.Model): title = models.CharField(max_length=200) description = models.CharField(max_length=200) image = models.FileField(blank=True,null=True) def __str__(self): return self.title productsdetail.html <form> Title:- {{products.title }} <br><br> Description:- {{ products.description}}<br><br> Image :- <img src="{{products.image.url}}" alt="image"><br><br> <img src="/static/images/book.jpg"> <button><a href="/edit/{{ products.id}}">Edit</a></button> </form> Image is not displaying … -
How to select distinct coloumn values from mysql database in django?
I need to retrieve distinct value from query set and display it on a div. Here is my model.py: class Persons(models.Model): id = models.IntegerField(primary_key=True) firstname = models.CharField(max_length=100) lastname = models.CharField(max_length=100) address = models.CharField(max_length=100) dob = models.CharField(max_length=100) salary = models.IntegerField doj = models.DateField() class Meta: db_table = "test" Here is my view.py: def calender(request): years={} persons = Persons.objects.all() for person in persons: if person.doj.year not in years: years[person.firstname]=person.doj.year return render(request, "home.html", years) Here is my html : <div> {% for item in Persons %} <div class="numbers">{{ item.doj }}</div> {% endfor %} </div> My code is not working. Any help will be highly appreciated. Thank You! -
Django query as string array from checkboxes form
I would like to get multiple inputs from a checkboxes form something and then filter it out from my database. That would be something similar to: http://127.0.0.1:8000/data/?class_type=[class_C,class_M] However what I am receiving from the query is: http://127.0.0.1:8000/data/?class_type=class_C&class_type=class_M This is how it is coded, in .html: Data class <br> <div class="form-check"> <input class="form-check-input" type="checkbox" value="class_C" id="class_C" name="class_type"> <label class="form-check-label" for="class_C"> C </label> </div> <div class="form-check"> <input class="form-check-input" type="checkbox" value="class_M" id="class_M" name="class_type"> <label class="form-check-label" for="class_M"> M </label> </div> <div class="form-check"> <input class="form-check-input" type="checkbox" value="class_X" id="class_X" name="class_type"> <label class="form-check-label" for="class_X"> X </label> </div> In views.py: data_class = request.GET.get('class_type') [...] if data_class == "class_C": database = database.filter(class_l__contains = "C") elif data_class == "class_M": database = database.filter(class_l__contains = "M") elif data_class == "class_X": database = database.filter(class_l__contains = "X") Any help is pretty appreciated! Thank you! -
How create a link in templates with relational table in django app
I have question : my classes on models.py `class Actes(models.Model): acte_id = models.AutoField(primary_key=True) title = models.TextField() contenue = models.TextField() vector_column =SearchVectorField(null=True) # new field fullpath = models.CharField(max_length=255) date_atce_add = models.DateField(null=True, blank=True) author = models.ForeignKey('Author', on_delete=models.SET_NULL, null=True) type_acte = models.ManyToManyField(Type_acte, help_text='Select a genre for this acte') pdf = models.ForeignKey('PdfModel', on_delete=models.SET_NULL, null=True)` class PdfModel(models.Model): pdf_field = models.CharField(max_length=255) title_pdf = models.CharField(max_length=255) def __str__(self): return ', '.join(['pdf_field' + str(self.pdf_field), 'title_pdf=' + self.title_pdf]) def filename(self): return os.path.basename(self.file.name) def __str__(self): """String for representing the Model object.""" return f'{self.pdf_field}, {self.title_pdf}' class Meta: ordering = ['title_pdf'] my views on views.py class Dlpdf(View): model = Actes, PdfModel context_object_name ="dlpdf_context" template_name = "search_result.html" def Link_Title (request): if Actes.title : TextField == PdfModel.title_pdf return PdfModel.pdf_field title pdf , and title on actes have a same name in db (for example : title is 'moon' on actes title and 'moon" (title_pdf) in pdfmodel my template search_result.html i try this but i d'ont how to write it. <!-- <li>{{ quote.headline | safe }} - <b>By <i>{{ quote.name }}</i></b></li> --> <span class=""> <li class="list-group-item list-group-item-action list-group-item-secondary"><p class="">{{ actes.contenue | safe |striptags |truncatewords:200 | wordwrap:40 }}</p> {% with Actes PdfModel %} {%for pdf_field in dlpdf_context %} - nom du document <i>{{ actes.title }}</i> </li>ici le … -
(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?