Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
is there any way to make my dynamic django webpage as realtime webpage
please any suggest me anything how to make my django website as realtime website. i my case iam doing a auction site so i need to make the products soldout=True automatically when the period of the time ends for a particular product -
How to register users in Django while maintaining frontend bootstrap template?
I am trying to register users for a multi user complaint management system using django. The frontend is already ready and I just have to do the backend. I am fairly new at django and this is my first project so I'm very confused in how to maintain the bootstrap view while being able to register users and authenticate them. The bootstrap template is: ```<div class="col-lg-4 login-bg"> <h4 class="reg-title"><strong>Get Started...</strong></h4> <p class="login-reg">Already have an account? <a class="log-reg-link" href="login.html">Log In </a> here</p> <hr> <form class="" action="/Dashboard/" method="post"> <p class="reg-field-title"><strong>First Name*</strong></p> <input type="text" class="form-control col-lg-10 log-inp-field" placeholder="First Name" required> <p class="reg-field-title"><strong>Last Name*</strong></p> <input type="text" class="form-control col-lg-10 log-inp-field" placeholder="Last Name" required> <p class="reg-field-title"><strong>Email ID*</strong></p> <input type="email" class="form-control col-lg-10 log-inp-field" placeholder="Enter email" required> <p class="reg-field-title"><strong>Password*</strong></p> <input type="password" class="form-control col-lg-10 log-inp-field" placeholder="Enter Password" required> <button type="submit" class="btn btn-dark btn-lg col-lg-10 reg-btn">Register</button> </form>``` this is my accounts model: ```from django.db import models class Person(models.Model): first_name = models.CharField(max_length=130) last_name = models.CharField(max_length=130) email = models.EmailField(blank=True) Password = models.CharField() I don't understand what to do? What to put in the views and the forms? -
Is this a problem Deploying Heroku before working in AWS?
I've deployed my site on Heroku with no problems. After that, I've uploaded my static and media folder to AWS and i get this error: raise ImproperlyConfigured("Could not load Boto3's S3 bindings. %s" % e) django.core.exceptions.ImproperlyConfigured: Could not load Boto3's S3 bindings. No module named 'boto3' I've installed everything, I've done pip freeze < requirements.text. Please help me. -
How can i add multiple address in django?
I am trying to add multiple addresses but only 1 address is getting created This is models.py class Customer(models.Model): user = models.ForeignKey(User, on_delete = models.CASCADE) name = models.CharField(max_length = 100) locality = models.CharField(max_length = 200) city = models.CharField(max_length = 50) zipcode = models.IntegerField() state = models.CharField(choices = STATE_CHOICES, max_length=50) This is views.py def address(request): add = Customer.objects.filter(user=request.user) return render(request, 'app/address.html', {'add':add}) This is address.py {% for ad in add %} <div class="col-sm-6"> <div class="card"> <div class="card-body"> <h3>Address {{forloop.counter}}</h3> <p>Name: {{ad.name}}</p> <p>Locality: {{ad.locality}}</p> <p>City: {{ad.city}}</p> <p>Pin Code: {{ad.zipcode}}</p> <p>State: {{ad.state}}</p> </div> </div> </div> {% endfor %} -
Parent directory symbol not working in html
<meta charset="utf-8"> <title>Exam Page</title> <link rel="stylesheet" href="../../../static/css/teststyle.css"> </head> Im using this code in exam folder and i wanted to go to parent directory so i used ../../ but it is showing the below error Not Found: /exam/static/css/teststyle.css -
automatically creating a PDF file from pytesseract in django
I m creating an OCR mobile application with django on backend, so i created two seperate applications: 1 for the image processing and another for prefroming the OCR, i want for my app to automatically create an PDF file once an image is added on my Image model however i m getting this error 'bytes' object has no attribute '_committed'. This is my Image model from tesseract.models import File from tesseract.ocrImage import Create_Pdf from django.db import models import uuid import pytesseract import PIL.Image import cv2 # Create your models here. class Image(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title=models.CharField(max_length=50) image=models.ImageField(upload_to='media',unique=True) created_at = models.DateTimeField(auto_now_add=True) def save(self, *args, **kwargs): super(Image, self).save(*args, **kwargs) if self.id : File.objects.create( file=Create_Pdf(self.image)) def __str__(self): return str(self.id) and this is my File model: class File(models.Model): label=models.CharField(max_length=50, default='none') file=models.FileField(upload_to='files') created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.id) This is my OCR use case: import io import PIL.Image import pytesseract #from reportlab.pdfgen import canvas pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe' def Create_Pdf(image): buffer = io.BytesIO() doc=pytesseract.image_to_pdf_or_hocr(PIL.Image.open(image)) return doc and this is my error: Traceback (most recent call last): File "C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\admin\options.py", line 616, in wrapper … -
Generate Dynamic Links in Django : Company and Employee
I am making a project in Django which is an Employee Management System. I made the Company Home page where we have options to add a new Company, Delete Previous Company or Delete it. Now I want when I click on that Company Name, it generates a dynamic link for that particular company name (which will have the same features of adding, deleting and editing the Employee) Currently, I am stuck. Not able to generate Dynamic links for each Company which gives Employee details. Here is my Models.py File from datetime import date, datetime from django.db import models from django.db.models.fields.related import ForeignKey from django.utils import timezone # Create your models here. class companyModel(models.Model): company_name = models.CharField(max_length=100,blank=False) company_created = models.DateField(default=datetime.now,blank=False) class employeeModel(models.Model): employee_company_name = models.ForeignKey(companyModel,on_delete=models.CASCADE) employee_name = models.CharField(max_length=100,blank=False) employee_created = models.DateField(default=datetime.now,blank=False) Forms.py File from django import forms from django.forms import widgets from empman.models import companyModel,employeeModel class companyForm(forms.ModelForm): class Meta: model = companyModel fields = ['company_name','company_created'] widgets = { 'company_name' : forms.TextInput(attrs={'class':'form-control '}), 'company_created':forms.TextInput(attrs={'class':'form-control'}) } class employeeForm(forms.ModelForm): class Meta: model = employeeModel fields = ['employee_company_name','employee_name','employee_created'] Views.py File from django import forms from django.shortcuts import render,HttpResponsePermanentRedirect from empman.forms import companyForm,employeeForm from empman.models import companyModel,employeeModel # Create your views here. def companyShowView(request): if request.method … -
matching query does not exist, DoesNotExists
Tell me how to do that in the absence of an object in the database, not an exception "DoesNotExists" would be displayed, but that my error text would be displayed. def get_queryset(self): try: city_name = self.request.GET.get('name') return City.objects.get(name__iexact=city_name) except DoesNotExist: return HttpResponse('Not found') Doesn't help, if there is no object, just a blank page. -
Ajax Django add button not adding on first click
So I have a dynamically rendered table in Django, the items in the table represent the order items so for each order item I have added to cart, it will show in the table on my Cart page. Now I have a quantity, a product name, order item total and so on. Now I'm using two buttons, add and subtract. Here's a code so that you can get the idea. <tbody> {% for order in orders %} <tr> <th scope="row"> <div class="order-quantity"> <span class="order_quantity">{{order.quantity}}</span> <button data-url="{% url 'add' order.id %}" class="edit-quantity plus" id="plus">+</button> <button data-url="{% url 'subtract' order.id %}" class="edit-quantity subtract" id="subtract">-</button> </div> </th> <td><img src="{{order.item.product_image.url}}" alt="" width="70" height="70"></td> <td>{{order.item.product_name}}</td> <td> <span>&#8369;</span> {{order.total_item_price}}</td> </tr> {% endfor %} </tbody> </table> Now notice that I have two buttons, each with a data url so that Jquery can make AJAX calls for me to a specified url in Django. Everything is working fine but when I click the add button, on my logs it shows that the item is not yet changed but rather just printed out. But when I click for the second time, the action just takes place, but not during the first click. How to solve this? Here's an example. … -
How to save JSON array data in POSTGRESQL database using DJANGO python?
How to save JSON array data in POSTGRESQL database table using Python Django API? I am getting belowJSON array data from JAVASCRIPT API call in the body of the http request which I want to save in POSTGRESQL database table. #JSON ARRAY DATA [ { "id": 16, "todoItem": "shopping", "checked": false, "todoitemid": "1", "Date": "26/06/2021" }, { "id": 17, "todoItem": "grocery", "checked": false, "todoitemid": "14646", "Date": "26/06/2021" }, { "id": 18, "todoItem": "dropoff", "checked": false, "todoitemid": "1467", "Date": "26/06/2021" }, { "id": 19, "todoItem": "movie", "checked": false, "todoitemid": "297", "Date": "26/06/2021" } ... ... ... ... ] #Model class Todo(models.Model): todoItem=models.CharField(max_length=100,blank=False,default='') checked=models.BooleanField(default=False) todoitemid=models.CharField(max_length=20 , blank=False,default='') Date=models.CharField(max_length=20 , blank=False,default='') #serializer class todoserializer( serializers.ModelSerializer): class Meta: model= Todo fields=('id', 'todoItem', 'checked', 'todoitemid', 'Date' ) #Views.py @api_view(['POST']) def todo_list(request): request.method == 'POST': todo_data = JSONParser().parse(request) todo_serializer =todoserializer(data=todo_data) if todo_serializer.is_valid(): todo_serializer.save() return JsonResponse(todo_serializer.data, status=status.HTTP_201_CREATED) return JsonResponse(todo_serializer.errors, status=status.HTTP_400_BAD_REQUEST) what am I making wrong ? OR How do I Iterate through parsed JSON Array Data from request? -
hi, I have a problem with how I can show errors in the template like username is already taken? please, help me
how i can show errors like email or username is alerdy taken in this page Aaccounts/sign-up.html because when try to to put a username and this username is already taken the page only refrech without any message before enter image description here after enter image description here class SignUpView(CreateView): form_class = CustomUserCreationForm success_url = reverse_lazy('login') template_name = 'Aaccounts/sign-up.html' def login (request) : if request.method=='POST': passwordtest=request.POST ['password'] usernametest=request.POST ['username'] user=auth.authenticate(username=usernametest,password=passwordtest) if user is not None : auth.login(request,user) current_user = request.user correctUSER = get_object_or_404(CustomUser, pk=current_user.id) need_to_cheack=correctUSER.main_affilitee kain=False if need_to_cheack !="": objs=CustomUser.objects.all() for aleratwar in objs: if kain==False: if aleratwar.username==need_to_cheack and aleratwar.afilliteuser==True and aleratwar.username !=correctUSER.username : kain=True if kain== False: correctUSER.main_affilitee='' correctUSER.save() return redirect('home') else: return render(request,'Aaccounts/login.html',{'eroor':True}) else: return render(request,'Aaccounts/login.html') -
django accoubts/login overwrite
path('accounts/login/', auth_views.LoginView.as_view(template_name ='users/registration /login.html')), I using this path for login and this is working but I want to show authentication error in login page i use this html code for this purpose <small class="message" style="color: red;">{{form.non_field_errors}}</small> <small class="message" style="color: red;">{{form.errors}}</small> <form class="form" id="signin-form" method="POST"> {% csrf_token %} {{form}} <input type="submit" value="Login" class="btn btn-block btn-secondary"> But I just show fields error if any fields will be empty but not show authentication error if I enter wrong password or email this screen will be show as a error How I overwrite accounts/login path Also when I logedin my session and I re enter login path login page will be appear, I want handle also this bug with accounts/login I write my own function for this purpose but my clients require that no write extra function and just use accounts/login url. -
django factory boy couldn't import
I've created directory cheeses(myapp)/test/factories.py with code from django.template.defaultfilters import slugify import factory import factory.fuzzy from ..models import Cheese class CheeseFactory(factory.django.DjangoModelFactory): name = factory.fuzzy.FuzzyText() slug = factory.LazyAttribute(lambda obj: slugify(obj.name)) description = factory.Faker('paragraph', nb_sentences=3, variable_nb_sentences=True) firmness = factory.fuzzy.FuzzyChoice( [x[0] for x in Cheese.Firmness.choices] ) class Meta: model = Cheese then in shel_plus i typed this from cheeses.tests.factories.py import CheeseFactory and got ModuleNotFoundError: No module named 'cheeses.tests.factories'; 'cheeses.tests' is not a package. What have i done wrong? -
How to handle MethodNotallowed exception in django rest framework by creating seperate file for exceptions
In my Django RestApi project I want to apply Exceptions errors. I create a separate file (common.py) for all my exceptions file is located out side the project where our manage.py file located. this is in my file: HTTP_VERB_STRING = { 'get': 'get', 'post': 'post', 'put': 'put', 'patch': 'patch', 'delete': 'delete', } Also I set it in settings.py: REST_FRAMEWORK = { 'EXCEPTION_HANDLER': 'rest_framework.views.exception_handler', Now In my view I create a modelviewset. In modelviewset we get all built in functions to perform oprations like (put, patch, delete, create, update) but in this view I don't need put, patch, and delete. So I want to block this and want to give exception on it I tried this : from rest_framework import viewsets from common_strings import HTTP_VERB_STRING class MeterReadingModelViewSet(viewsets.ModelViewSet): queryset = MeterReadingModel.objects.all() serializer_class = MeterReadingModelSerializer def update(self, request, pk=None): raise MethodNotAllowed(method=HTTP_VERB_STRING['put']) def partial_update(self, request, pk=None): raise MethodNotAllowed(method=HTTP_VERB_STRING['patch']) def destroy(self, request, pk=None): raise MethodNotAllowed(method=HTTP_VERB_STRING['delete']) But giving error on MethodNotAllowed is not defined. Why this is happenning? -
ManyToManyField value in Django REST Framework
So when I am routing to api/ to view my models I am not seeing what I expected to see. I wanted to see the names of the strats that I grouped in Strat_Basket model in the variable basket but instead I see their ids which is generated by DJANGO automatically. I want to see the names rather than numbers in the strat_basket view. It is more informative that's why. models.py class Strats(models.Model): name = models.CharField(max_length=64) class Strats_Basket(models.Model): name = models.CharField(max_length=64) basket = models.ManyToManyField(Strats, blank=True, related_name='list') serializers.py: class StratsSerializer(serializers.ModelSerializer): class Meta: model = Strats fields = ('id', 'name') class Strats_BasketSerializer(serializers.ModelSerializer): class Meta: model = Strats_Basket fields = ('id', 'name', 'basket') views.py: class StratsView(viewsets.ModelViewSet): serializer_class = StratsSerializer queryset = Strats.objects.all() class Strats_BasketView(viewsets.ModelViewSet): serializer_class = Strats_BasketSerializer queryset = Strats_Basket.objects.all() urls.py: router = routers.DefaultRouter() router.register(r'strats', views.StratsView, 'strats') router.register(r'strats_basket', views.Strats_BasketView, 'strats_basket') API OUTPUT: strats: [ { "id": 1, "name": "strat1" }, { "id": 2, "name": "strat2" }, { "id": 3, "name": "strat3" }, { "id": 4, "name": "strat4" }, { "id": 5, "name": "strat5" }, { "id": 6, "name": "strat6" } ] strats_basket: Instead of 1,2,4 I want to see strat1, strat2, strat4. [ { "id": 1, "name": "Basket 1", "basket": [ 1, 2, … -
How to convert datetime like `2021-06-25 15:00:08+00:00` to local timezone datetime.datetime python?
I have many datetime.datetime object like 2021-06-25 15:00:08+00:00 where the timezone is different for different data.Eg.another data is 2021-06-24 06:33:06-07:00 .I want to save all of them by converting into a local tmezone.How can I do that? -
Django 'ManyToManyDescriptor' object has no attribute 'count'
I am writing an application where users can add events and other users can add likes to them. I'm stuck at the point where Django needs to sum up all likes for all posts. Based on similar answers, I tried the code below for one event: views.py @login_required(login_url='/oauth2/login') def Events(request, *args): ... likes = EventModel.likes.count() return render(request, 'base/events.html', {..., 'likes': likes}) models.py class EventModel(models.Model): ... likes = models.ManyToManyField(User, related_name='event_likes') But when I refresh it returns an error 'ManyToManyDescriptor' object has no attribute 'count' How can I count all likes for all posts? I think it is too naive to execute loops and write them all in, for example, a dictionary. Here is how the site looks like. I am happy to provide more details regarding my problem. -
Django Setting for Default Related Name Pattern
The Django documentation: Models page mentions that the default related_name for foreign keys uses the pattern f"{ModelClass.__name__.lower()}_set" (or childb_set in the specific example). Is there a way to configure Django to convert CapWords to cap_words (instead of capwords) when creating these default related_names? For example, take the following models: from django.db import models class BlogChannel(models.Model): name = models.CharField(max_length=100) tagline = models.TextField() def __str__(self): return self.name class ArticleAuthor(models.Model): name = models.CharField(max_length=200) email = models.EmailField() def __str__(self): return self.name class TextEntry(models.Model): blog_channel = models.ForeignKey(Blog, on_delete=models.CASCADE) headline = models.CharField(max_length=255) body_text = models.TextField() article_authors = models.ManyToManyField(Author) number_of_comments = models.IntegerField() number_of_pingbacks = models.IntegerField() rating = models.IntegerField() def __str__(self): return self.headline Accessing BlogChannel records through TextEntry is intuitive: >>> text_entry = TextEntry.objects.first() >>> blog_channel = text_entry.blog_channel But the reverse is not: >>> blog_channel.text_entry_set # should be `blog_channel.textentry_set` --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-19-0402bfca7d1f> in <module> ----> 1 blog_channel.text_entry_set AttributeError: 'BlogChannel' object has no attribute 'text_entry_set' Rather than modifying every foreign key field of every model to specify a related_name that uses underscores, I'm curious if there is a setting or something to effect this style change. -
How to change span value inside dynamically rendered table with Django using AJAX response
So I have a website with Django. I have a products page that when I add to cart that specific item using a "Add to Cart" button, the item gets added as an order item based on the item primary key. Now I have a Cart page where I can view the specific products that are already an order item this is dynamically rendered using this piece of code: My cart.html page <tbody> {% for order in orders %} <tr> <th scope="row"> <div class="order-quantity"> <span id="order_quantity">{{order.quantity}}</span> <button data-url="{% url 'add' order.id %}" class="edit-quantity" id="plus">+</button> <button data-url="{% url 'subtract' order.id %}" class="edit-quantity" id="subtract">-</button> </div> </th> <td><img src="{{order.item.product_image.url}}" alt="" width="70" height="70"></td> <td>{{order.item.product_name}}</td> <td> <span>&#8369;</span> {{order.total_item_price}}</td> </tr> {% endfor %} </tbody> Now notice that I have an add quantity button with a data url because I wanted to change the span quantity automatically with AJAX response. Now I figured out how to console log the specific quantity when an order item is clicked for example if I click on the order item Nike, on my console I will see the order quantity but I can't figure out how to change the span text because it is dynamically rendered. Please help! my Cart page … -
Variable image paths in xhtml2pdf with django
I need to display images with variable path, because, the user input's the image.. If I provide a url like <img height='200px' src="http://127.0.0.1:8000/media/images/photo.jpeg" alt="Image of student"> it works, but then, it does not work when I change it to <img src="{{ result.image_of_student.url }}" alt="Image of student"> How do I make this work, as each url is different. In the tutorial, they used <img src={{ result.image_of_student.path}} alt="Image of student"> which worked for them but not for me -
why does heroku server does not play my mp4 video
here i am using Django in backend. on my local machine there is not an problem but when i upload it on Heroku it shows all the files but video is messing.? <video width="540" autoplay muted loop> <source src="{% static 'home/img/Inbodyshot.mp4' %}" type="video/mp4"> <source src="movie.ogg" type="video/ogg"> Your browser does not support the video tag. </video> -
Select all fields except one Django
There is a class-based view and I want to know how I can use all fields except the user field in the fields instead of '__all__' and also I don't want to write all the fields in a list because there are too many fields and I want to exclude one item. here is the code: class TaskCreate(LoginRequiredMixin, CreateView): model = Task fields = '__all__' # ! here success_url = reverse_lazy('Tasks') def form_valid(self, form): form.instance.user = self.request.user return super(TaskCreate, self).form_valid(form) many thanks in advance. -
How to zip dynamically generated pdfs using weasyprint then returning it as a response in django?
Here is my view to generate a pdf: def download_pdf(request, id): document = Document.objects.get(id=id) response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename=document_name.pdf' response['Content-Transfer-Encoding'] = 'binary' html_string=render_to_string('portal/pdf/document.html', {'document': document}) html = HTML(string=html_string, base_url="/") result = html.write_pdf() with tempfile.NamedTemporaryFile(delete=True) as output: output.write(result) output.flush() output.seek(0) response.write(output.read()) return response Now how do I generate multiple pdfs when I decide to Document.objects.filter(some parameter) then sending it as a zip? -
How can I add an extra property to django-rest-framework's ModelSerializer?
I am creating my first django API with django-rest-framework. I have a list of Posts. Each post can have many Likes. Therefore, I have added a ForeignKey to the Like model, which points to its corresponding Post. When I retrieve the information of a post, I'd like to get the number of likes that this post has. Here is my url: path(BASE_URL + "get/slug/<slug:slug>", GetPost.as_view()), This is my view: class GetPost(generics.RetrieveAPIView): queryset = Post.objects.all() serializer_class = PostSerializer lookup_field = "slug" And this is my serializer: class PostSerializer(serializers.ModelSerializer): likes_amount = serializers.SerializerMethodField(read_only=True) def get_likes_amount(self, post): return post.likes class Meta: model = Post fields = '__all__' Unfortunately, as soon as I add the extra property likes-amount to the serializer, the API endpoint stops working and I get the following error: Object of type RelatedManager is not JSON serializable. I'd like to know how I can extend the ModelSerializer with extra fields like the number of likes of my Post, so that I can get. I have read the documentation but haven't found any information on that topic. -
JavaScript function not working on form submission
I've got an HTML form, and when it is submitted, I want a JavaScript function I have defined to run. However, no matter what, the function I've written is not recognised. Here is the HTML form: <form id="compose-form"> <div class="form-group"> From: <input disabled class="form-control" value="{{ request.user.email }}"> </div> <div class="form-group"> To: <input id="compose-recipients" class="form-control"> </div> <div class="form-group"> <input class="form-control" id="compose-subject" placeholder="Subject"> </div> <textarea class="form-control" id="compose-body" placeholder="Body"></textarea> <input type="submit" class="btn btn-primary"/> </form> And then here is my JavaScript code: document.addEventListener('DOMContentLoaded', function() { // #compose is the id of the div the form #compose-form is in document.querySelector('#compose').addEventListener('click', compose_email); document.querySelector('#compose-form').addEventListener('submit', () => send_email(event)); }); function send_email(event) { event.preventDefault(); // Note this isn't the actual content of my function, but even this simple code doesn't work alert('Hello'); return false; } function compose_email() { document.querySelector('#emails-view').style.display = 'none'; document.querySelector('#compose-view').style.display = 'block'; // Note: this function does work completely. document.querySelector('#compose-recipients').value = ''; document.querySelector('#compose-subject').value = ''; document.querySelector('#compose-body').value = ''; } WHAT I'VE TRIED: I've moved the functions above the event listener in my JavaScript I've alternately removed both the event.preventDefault(); and the return false;, removed both, kept both. I've tried defining the function separately, as I have it here, and doing the code as an anonymous function I've …