Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting a error "coInitialize has not been called" while converting a uploaded word file to pdf in django using docx2pdf
I am trying to convert an uploaded Docx file to pdf in Django using the docx2pdf module.But when I pass the file into the convert function I am getting the following error, pywintypes.com_error: (-2147221008, 'CoInitialize has not been called.', None, None) My views.py: def post(self, request): files=request.FILES.getlist("files") for f in files: file_type=getFileType(f)[-1] final_pdf=f file_type == ".docx": new_file= File() fs = FileSystemStorage() file_name = fs.save(f.name, f) uploaded_file_url = fs.url(file_name) convert('media/'+f.name) new_file.file.save(f.name.split(".")[0]+".pdf",f,save=False) new_file.save() resp={"message": "Files Uploaded"} return Response(resp, status=status.HTTP_200_OK) Thanks in advance. -
Blocks are not highlighting in django vs code
Is there any extension to do this? It is just not showing any type of highlighting in blocks. This is how it should be This is how they look -
Exception Type: AttributeError / Exception Value: 'function' object has no attribute 'objects'?
No puedo ver datos de la tabla post? models.py class Post(models.Model): user=models.ForeignKey(User, on_delete=models.CASCADE, default='1') tiempo =models.DateTimeField(default=timezone.now) servicio=models.CharField(max_length=50, blank=True, null=True, choices=servicio) descripcion=models.TextField() beneficios=models.TextField() img=models.ImageField() class Meta: ordering = ['-tiempo'] def __str__(self) : return f'Post {self.descripcion} ' creo este formulario para el ingreso de datos en forms forms.py class PostForm(forms.ModelForm): class Meta: model=Post fields=['Servicio','descripcion','beneficios','img'] Al querer visualizar los datos ingresados, tengo error en esa linea de codigo views.py def view(request): posts=Post.objects.all() #this error? data={ 'post':posts } return render(request, 'view.html', data) enter image description here -
Django Rest Framework authentication and user session
I'm trying to add authentication to my django-react app. At this point I am able to login/register users and it works fine but I want to get only data which is related with user logged in so posted or updated by them. Now I get all data regardless of user which is authenticated. I assume I have to change it in my views but how to do this? This is one of my classes class ListView(viewsets.ModelViewSet): serializer_class = ListSerializer queryset = List.objects.all() And on frontend side I get data this way: const getList = async () => { try { const response = await axiosInstance.get('/list/') if(response){ setList(response.data) } }catch(error){ throw error; } } -
Django REST Framework Error - TemplateDoesNotExist at /
I just deployed my Django REST Framework API ( with React ) app on Heroku and when I open the app I get this error saying that the "TemplateDoesNotExist at /" here's the log of the error : Environment: Request Method: GET Request URL: https://bionems-dj-react.herokuapp.com/ Django Version: 3.2.7 Python Version: 3.9.6 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'corsheaders', 'base.apps.BaseConfig'] Installed Middleware: ['corsheaders.middleware.CorsMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template loader postmortem Django tried loading these templates, in this order: Using engine django: * django.template.loaders.filesystem.Loader: /app/frontend/build/index.html (Source does not exist) * django.template.loaders.app_directories.Loader: /app/.heroku/python/lib/python3.9/site-packages/django/contrib/admin/templates/index.html (Source does not exist) * django.template.loaders.app_directories.Loader: /app/.heroku/python/lib/python3.9/site-packages/django/contrib/auth/templates/index.html (Source does not exist) * django.template.loaders.app_directories.Loader: /app/.heroku/python/lib/python3.9/site-packages/rest_framework/templates/index.html (Source does not exist) Traceback (most recent call last): File "/app/.heroku/python/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/handlers/base.py", line 204, in _get_response response = response.render() File "/app/.heroku/python/lib/python3.9/site-packages/django/template/response.py", line 105, in render self.content = self.rendered_content File "/app/.heroku/python/lib/python3.9/site-packages/django/template/response.py", line 81, in rendered_content template = self.resolve_template(self.template_name) File "/app/.heroku/python/lib/python3.9/site-packages/django/template/response.py", line 63, in resolve_template return select_template(template, using=self.using) File "/app/.heroku/python/lib/python3.9/site-packages/django/template/loader.py", line 47, in select_template raise TemplateDoesNotExist(', '.join(template_name_list), chain=chain) Exception Type: TemplateDoesNotExist at / Exception Value: index.html And here is my settings.py file : import os from pathlib import Path import dj_database_url (I've tried … -
django cannot compute sum on nested SUM
I am running this query where I do price*inventory1 and it works but when I try do do price*(inventory1+inventory2) django throws a error. this works results = ( Card.objects.values("rarity") .annotate(price=Sum(F("price") * F("inventory1"))) .order_by() ) this doesn't :( results = ( Card.objects.values("rarity") .annotate( price=Sum( F("price") * Sum( F("inventory1") + F("inventory2") ) ) ) .order_by() ) I am think I am doing something wrong. so, How can I do this in django ORM. -
Reverse for 'allproduct' not found. 'allproduct' is not a valid view function or pattern name
urls.py from django.urls import path from . import views app_name='shop' urlpatterns = [ path('',views.allproduct,name='allproductcat'), path('<slug:c_slug>/',views.allproduct,name='product_by_catagory') ] views.py from django.shortcuts import render, get_object_or_404 from . models import catagory,product # Create your views here. def allproduct(request,c_slug=None): c_page=None products=None if c_slug!=None: c_page=get_object_or_404(catagory,slug=c_slug) products=product.objects.all().filter(catagory=c_page,available=True) else: products=product.objects.all().filter(available=True) return render(request,'catagory.html',{'catagory':c_page,'products':products}) model.py from django.db import models # Create your models here. from django.urls import reverse class catagory(models.Model): name=models.CharField(max_length=250,unique=True) slug=models.SlugField(max_length=250,unique=True) description=models.TextField(blank=True) image=models.ImageField(upload_to='catagory',blank=True) class Meta: ordering=('name',) verbose_name='catagory' verbose_name_plural='catagories' def __str__(self): return '{}'.format(self.name) def get_url(self): return reverse('shop:product_by_catagory',args=(self.slug,)) class product(models.Model): name = models.CharField(max_length=250, unique=True) slug = models.SlugField(max_length=250, unique=True) description = models.TextField(blank=True) image = models.ImageField(upload_to='product', blank=True) price=models.DecimalField(max_digits=10,decimal_places=2) stock=models.IntegerField() available=models.BooleanField() created=models.DateTimeField(auto_now_add=True) updated=models.DateTimeField(auto_now=True) catagory=models.ForeignKey(catagory,on_delete=models.CASCADE) class Meta: ordering = ('name',) verbose_name = 'product' verbose_name_plural = 'products' def __str__(self): return '{}'.format(self.name) catagory. html {% extends 'base.html' %} {% load static %} {% block metadiscription %} {% if catagory %} {{catagory.discription}} {% else %} welcome {% endif %} {% endblock %} {% block title %} {% if catagory %} {{catagory.name}}--ABC store {% else %} see our new collection {% endif %} {% endblock %} {% block content %} {% if catagory %} <div> <div> <a href="{% url 'shop:allproduct' %}">OUR PRODUCT COLLECTION</a> </div> </div> {% endif %} <div> {% if catagory %} <img src="{{catagory.img.url}}" alt="{{catagory.name}}"> </div> <br> <div> … -
Experience working with .NET or Django framework
My name is Farhad Dorod. I'm Full stack developer. This is my question. Which framework do you prefer? .NET or Django? And why? I want to publish this poll in my article. Please accompany. -
Django POST form accepted by all except 1 button. Potential bug?
I am completely stumped. I have a working Django view, which displayed 'posts' for each post in a list handed into it. list.html {% for p in posts %} #code to display post in a list> <form action="{% url 'archive_commit' p.oid %}" method="post"> {% csrf_token %} <input type="hidden" name="next" value="{{ request.path }}"> {% if p.is_archived %} <input type="hidden" name="action" value="unarchive"> <button type="submit", name="p_oid", value="{{ p.oid }}", class="btn btn-primary btn-sm">Unarchive</button> {% else %} <input type="hidden" name="action" value="archive"> <button type="submit", name="p_oid", value="{{ p.oid }}", class="btn btn-primary btn-sm">Archive</button> {% endif %} </form> When I click the archive button it calls the following URL pattern and view. urls.py url(r'^archive/(?P<oid>.+)/$', views.archive_view, name='archive_post'), views.py def archive_view(request, oid): post = get_object_or_404(models.Post, oid=request.POST.get('p_oid')) archive_query_param = '' if request.POST.get('action') == 'archive': post.is_archived = True post.save() messages.success(request, ('Post ' + oid + ' has been archived')) else: post.is_archived = False post.save() messages.success(request, ('Post ' + oid + ' has been restored')) archive_query_param = '?archived=True/' next = request.POST.get('next', '/') return HttpResponseRedirect(next + archive_query_param) Here's the issue I'm having. EVERY single post on the page behaves as excepted, going to the view and archiving the post and then returning to next, except for the first post of the list. This post just … -
User cannot logout from the page where in the url pk is passed
I have a page search.html that has a link associated with a pk that when clicked redirects to page doc.html which outputs the contents related to that pk This doc.html extends a page consult_home.html. This page contains the logout button. In all the other pages that extends this consult_home.html the logout button works perfectly. But in the doc file I get the following error and the logout link does not work: ValueError at /consultancy/doc/logout Field 'id' expected a number but got 'logout'. Below are the codes of the view functions and the url patterns and also the template codes: consult_home.html* <button type="button" class="button log_out" onclick="location.href='logout';">LOGOUT</button> view function for logout def logoutUser(request): logout(request) return redirect('/') search.html <a class="judge-ttle" href="{% url 'doc' searches.pk %}">{{searches.title}} &nbsp <i class="fas fa-external-link-alt"></i></a> views for doc.html class DocDetailView(DetailView): model= Laws template_name = 'doc.html' urls.py urlpatterns=[ path('logout', views.logoutUser, name='logout'), path('doc/<str:pk>', DocDetailView.as_view(), name='doc' ), ] Please suggest me what to do. -
why name 'self' is not defined in django even self is included
I'm making web blog app with django and it's work pretty well before I added like functionality.Is that something I miss with view (Do i need to create class based view for this ).I tried it but didn't work either.whenever I rendered a url for post I got this error.Do you have any suggestion.Help in advance post_detail() missing 1 required positional argument: 'self' so here is code views.py def post_detail(request,slug,self): template_name = "post_detail.html" post = get_object_or_404(Post, slug=slug) stuff = get_object_or_404(Post, id=self.kwargs['pk']) total_likes = stuff.total_likes() liked = False if stuff.likes.filter(slug=self.request.user.id).exists(): liked = True context["total_likes"] = total_likes context["liked"] = liked comments = post.comments.filter(active=True).order_by("-created_on") new_comment = None # Comment posted if request.method == "POST": comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): # Create Comment object but don't save to database yet new_comment = comment_form.save(commit=False) # Assign the current post to the comment new_comment.post = post # Save the comment to the database new_comment.save() else: comment_form = CommentForm() return render( request, context, template_name, { "post": post, "comments": comments, "new_comment": new_comment, "comment_form": comment_form, }, ) def LikeView(request, pk): post = get_object_or_404(Post, id=request.POST.get('post_id')) liked = False if post.likes.filter(id=request.user.id).exists(): post.likes.remove(request.user) liked = False else: post.likes.add(request.user) liked = True return HttpResponseRedirect(reverse('post_detail', args=[str(pk)])) urls.py path('like_post/<int:pk>', LikeView, name="like_post") models.py class Post(models.Model): title … -
How to write a unit test on Django REST API endpoint that has permission_classes = (IsAuthenticated,)
Hello everyone I'm looking to write unit test on my django app, in order to test the different API endpoint but it seems like i can't figure our the problem here is a snap code of what i have done so far : urls.py : path('translate/display/', DisplayTranslation.as_view(), name='display_translation'), it's corresponding DRF view.py : class DisplayTranslation(generics.ListAPIView): queryset = Translation.objects.all() serializer_class = TranslationSerializers permission_classes = (IsAuthenticated,) and here is what I have done so far on my unit test.py : apiclient = APIClient() class TranslationTestCases(APITestCase): def setUp(self): self.role = baker.make(Roles) self.user = baker.make(Users, user_role=self.role) self.token = reverse('token_obtain_pair', kwargs={'email': self.user.email, 'password': self.user.password}) self.translation = baker.make(Translation, _quantity=10) def test_get_all_translations(self): header = {'HTTP_AUTHORIZATION': 'Token {}'.format(self.token)} response = self.client.get(reverse('display_translation'), {}, **header) self.assertEqual(response.status_code, 200) self.assertEqual(len(response.data), 10) This is the error I'm getting when I run the test : in _reverse_with_prefix raise NoReverseMatch(msg) django.urls.exceptions.NoReverseMatch: Reverse for 'token_obtain_pair' with keyword arguments '{'email': 'dZbQNWCjif@example.com', 'password': 'PfQzPqqVVLAdLZtJyVUxVjkGJEgRABYdHxMRhCGZJWxnZxpxEgUkgUKklENrWlBiYOCxhaDtJXdtXCtNdOJYtSWTzIrdvPnrmezXBNjEYYTpyZWjOLMnMIBMAfYnLwcC'}' not found. 1 pattern(s) tried: ['token/$'] Some more info, in the authentication on my Django app, I worked with DRF, rest_auth & SimpleJWT library. What I could do to improve my code? or an alternative solution? I couldn't find a similar problem to mine. -
How to use Django message framework in React component?
I am creating a website in which I want to use React in the frontend and Django for the backend. I want to know how can I use Django's message framework in react's component? {% if messages %} <ul class="messages"> {% for message in messages %} <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li> {% endfor %} </ul> {% endif %} -
How to debug dockerized Django-React app?
My Django-React app works fine locally, but after I dockerize it and run both Django and Nginx containers, all API calls (which require token) become Unauthorized. How would I debug the app, while it's running with Docker? -
no such column: AGC.id Django
i've been working with an existing datatable so i create the models using "inspectdb", my class doesn't have a primary key so django adds a automatically primary key named="id" when i makemigrations and migrate. Later, when i define the template,views and urls to see the class table at my website there is an error like this one: no such column: AGC.id I don´t know how to fix it, please help me i'm a noob using django Model: class Agc(models.Model): index = models.BigIntegerField(blank=True, null=True) area = models.TextField(db_column='AREA', blank=True, null=True) # Field name made lowercase. periodo = models.BigIntegerField(db_column='PERIODO', blank=True, null=True) # Field name made lowercase. demanda = models.TextField(db_column='DEMANDA', blank=True, null=True) # Field name made lowercase. This field type is a guess. class Meta: db_table = 'AGC' Template: {% extends "despachowebapp/Base.html" %} {% load static %} {% block content %} <table class="table table-bordered"> <thead> <tr> <th scope="col">#</th> <th scope="col">Index</th> <th scope="col">Area</th> <th scope="col">Periodo</th> <th scope="col">Demanda</th> </tr> </thead> <tbody> {% if AGCs %} {% for AGC in AGCs %} <tr> <th scope='row'>{{ Agc.id }}</th> <td>{{ Agc.index }}</td> <td>{{ Agc.index }}</td> <td>{{ Agc.area }}</td> <td>{{ Agc.periodo }}</td> <td>{{ Agc.demanda }}</td> </tr> {% endfor %} {% else %} <h1>No hay datos </h1> </tbody> </table> {% endblock … -
Setting Django environment variables for specific Pycharm project
I have multiple Django Pycharm projects, each with a different DATABASE_URL and DJANGO_SECRET_KEY Windows environment variable. Is there a way to set these variables specifically for individual projects so I can switch back and forth with ease? Also: in a way that makes them available in the terminal? I've read suggestions for setting them in the project's virtual environment or with the Run/Debug Configurations panel in Pycharm, but in neither case have I been able to get things to work. -
Django Rest Framework: one project, multiple apps, one server per app?
I've one project with 3 apps, using Django Rest Framework and would like to serve each app on a dedicated server, like so: api.app1.tld api.app2.tld api.app3.tld Reason: the apps are having a lot in common (models, ...), but are for different customers. I was thinking about passing an argument (not sure if possible), like so: python manage.py runserver --app=app1 python manage.py runserver --app=app2 python manage.py runserver --app=app3 Any idea? Thanks in advance! -
Update counter with max value from table with one query
I have certification_counter field that is 0 by default. I need to increment it by getting previous max value in table, but minimum value must be MIN_CERTIFICATION_COUNTER. I wrote query like that: last_value_qs = Project.objects.order_by("-certification_counter") Project.objects.filter(id=project.id).annotate( last_counter=Subquery( last_value_qs.values("certification_counter")[:1], output_field=IntegerField() ), max_counter=Greatest( F("last_counter"), MIN_CERTIFICATION_COUNTER ), ).update(certification_counter=F("max_counter") + 1) And I'm getting: django.db.utils.OperationalError: (1093, "You can't specify target table 'project' for update in FROM clause") I want to implement this as one transaction, to avoid race condition that's why I didn't use two queries like: max_value = Project.objects.order_by("-certification_counter").last().certification_counter Project.objects.filter(id=project.id).update(certification_counter=max(max_value, MIN_CERTIFICATION_COUNTER) + 1 ) -
When generating PDF from HTML in Django using PyQT5 the server crashes in a few times. Why?
When generating PDF from HTML in Django using PyQT5 the application manages to generate the file only a few times and after a while the server crashes. Why? I want to create a simple endpoint that recieves some parameters from front and from then, generate an PDF file. I've tried using pdfkit, weasyprint and PyPDF2, but i'm looking for something wihout extern dependencies like wkhtmltopdf. Here's my code: At first and second API call, the file returns from server as expected, but after that the django aplication simply exit. Can anyone say something about it? -
How to call variable from one method in another in Django?
I am trying to use only one View Class in Django with two methods post() and get(). Post is being used to get user session Token that I want to make available in "get()", so that I can identify the current user and send user details using the same view via Serializer. I want to use that token to get the name by user = Tokens.objects.get(key=token) to get the username and then filter User.objects.get(username=user) to post user data in the front end. How could I make "token" available inside def get() so I can work with it? Thank you! This is my View.py: class UserDetails(APIView): def post(self, request, *args): serializer = UserAccountTokenSendSerializer(data=request.data) if serializer.is_valid(): global token token = serializer.validated_data['token'] self.get(token) # user = Token.objects.get(key=token).user # global current_user # current_user = User.objects.get(username=user) # email = User.objects.get(email=user) # print(current_user, email) return Response(serializer.data) def get(self, request, *tokens): username = Token.objects.get(key=token).user email = User.objects.get(username=username).email serializer = UserAccount(username, email, many=True) return Response(serializer.data) These are my 2 serializers to post and get data: class UserAccountTokenSendSerializer(serializers.ModelSerializer): class Meta: model = UserAccountTokenSend fields = ( 'token', ) class UserAccount(serializers.ModelSerializer): class Meta: model = User fields = ( 'first_name', 'last_name', 'email', 'username', ) This is my urls.py: path('get-user-tokens/', views.UserDetails.as_view()), … -
How to get data from database mongodb without models in django?
my problem is that my database is too large and I don't want to create any models since it's legacy one, and I will have to call different tables dynamically, so I just want to pull data from it. Is that possible in Django? -
How to deploy a django project github repo on GoDaddy cPanel?
I have a Django Project that I want to deploy on GoDaddy cPanel. and I have Github Repository of Project but I haven't deployed any dynamic website project on cPanel yet. can you please help and guide me to how can I upload and connect my github repo to cPanel and, Do I need to install python and django first on panel so can you please guide me for how can I run the django project on server. Thank You! -
Django: Sending data from backend to frontend without page refresh
I am developing a Website with django. Now, let's say I have a database where values can change at any time. Every time the DB changes, I want to execute a function (no problem with that) and update some data I passed to a template without a page refresh. At first, I thought about AJAX, but as it seems an AJAX-Request must be started from the frontend, right? Long story short: What I want specifically is to update some CSS depending on some data changes in the backend without any page refresh. Hope someone can help me 😁 -
Django How to check if Boolean out of ModelField is True
So I have this code in my views.py @login_required(login_url='home:login') def profile_view(request): packetfree = Account.objects.get(packet_free=request.user) packetpremium = Account.objects.get(packet_premium=request.user) packetbusiness = Account.objects.get(packet_business=request.user) if packetfree is True: abo = "Free" elif packetpremium is True: abo = "Premium" elif packetbusiness is True: abo = "Business" context= { 'person': request.user, 'abo': abo } return render(request, 'home/profile.html') And I want to check if the Value of the boolean from the model is true so I can find out which of the 3 booleans is true and know which subscription the user has as a Char to use it in my html template. -
Which is most expensive query in django among these?
I have 5 models which needs to be populated using a key from 6th model: I have two options, please suggest the most effective Option1: I can fetch all the five one by one and send via context to template and then show the each via html tabs Option2: Have seprate page for each model and fetch when ever user goes to that page, like if user goes to page1 then i fetch data from model1 and so on Which is good and effective ? Like querying only needed or just query all and show up in a html tabs ?