Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Perform operation on pdf file in Django
I have one function in python that parse contents of pdf files and later on converting it to csv files which is created. Now what i need to do is to create a webapp in django where user will upload files pdf ones and we will fetch that pdf file and pass it as an attribute in that function created in python and our UI will give succes page after successfully converting it to csv file. Any idea how should i do it? -
django-celery vs django-celery-beat with Django 2.2
We have been working with celery and django-celery till now but recently we planned to migrate our codebase to Django==2.2 and looks like django-celery doesn't have support for Django==2.2 yet. With django-celery we could configure periodic tasks from django admin. Is it safe to assume that if I want the similar functionality then apart from Celery package and running celerybeat instance I would have to install django-celery-beat package instead of django-celery - without doing massive code changes? -
Django Error On updating based on DateTime
I have been working on certain Bus schedule. class Schedule(BaseModel): bus_company_route = models.ForeignKey(BusCompanyRoute, on_delete=models.PROTECT) bus = models.ForeignKey(Bus, on_delete=models.PROTECT) travel_date_time = models.DateTimeField() seat_discounted_price_for_user = models.PositiveIntegerField() def clean(self): if not self.bus_company_route.shift: raise DjangoValidationError( { 'bus_company_route': _('Shift does not exist in {}'.format( bus_company_route.route )) } ) try: if self.travel_date_time: if Schedule.objects.filter( bus_company_route=self.bus_company_route, bus=self.bus, travel_date_time__date=self.travel_date_time.date() ).exists(): raise DjangoValidationError({ 'travel_date_time': _('Cannot assign same bus on same date') }) except ObjectDoesNotExist: pass Logic is I have made clean method to check if there exists travel date time first. Next logic is if bus_company_route, bus ,travel_date_time is on suppose Dec 24 then you cannot add same bus on the same date.The problem is when I create a Schedule & tried updating seat_discounted_price_for_user when date is still Dec 24 I get error saying Cannot assign same bus on same date. what can I do so that I can update Schedule details after adding Schedule. -
Django adding additional field on query set result
i have these code on my Django def get(self, request): movie = Movie.objects.all().order_by('name').first() serializer = MovieSerializer(movie) serializer_data = serializer.data return Response(serializer_data, status=status.HTTP_200_OK) and it returns this data { { "description": "Haunted House Near You", "id": 1, "name": "Scary Night", }, { "description": "Netflix and Chill", "id": 2, "name": "Movie Night", }, } i want to add custom field , called 'alias' like this { { "description": "Haunted House Near You", "id": 1, "name": "Scary Night", "alias": "SN" }, { "description": "Netflix and Chill", "id": 2, "name": "Movie Night", "alias": "MN" }, } My Question is, how do i add the custom field using ORM on Django? -
How can I get multiselect fields from one product into dropdown in Django?
I need that type of field. See the example in the image. How can I get the multi-select field into the dropdown in the Django template? Screenshot -
The solution to the problem with the uniqueness of the slug or how to find the slug that I need
Colleagues, good afternoon! There is a model book and a model chapter. Each book has many chapters. Each chapter is tied to a specific book, and if the slug of the chapter is made unique, then when book1 - chapter1, I cannot create book2 - chapter 2, an error is generated. If you make the slug non-unique, then an error is issued that one argument was expected, but 2 was passed. How can I solve this problem? I want the slug to be a number and django understands that along the path / book1 / 1 / you need to take a slug with number 1, which is tied to book1 specifically, and not to pay attention to the slug with number 1, but tied to book2. if the slug is unique, then I calmly end up in the right book and the right chapter, but everything collapses when I need to get there as intended. The path is built like this: / book1 / 1 (chapter) / etc. book2 / 1 / etc class Book(models.Model): some code class Chapter(models.Model): book= models.ForeignKey(Book, verbose_name="title", on_delete=models.CASCADE) number = models.PositiveIntegerField(verbose_name="num chapter") slug = models.SlugField(unique=True, verbose_name="slug_to", null=True, blank=True) def save(self, *args, **kwargs): self.slug = … -
Profile a celery task using cProfile
I've a django app which runs some asynchronous tasks in the background with celery. I'd like to profile the tasks running inside the celery worker. I found these questions but they weren't very useful. How do I profile a specific celery task in a django app? -
Deploying a software with django backend and flutter front end in tomcat
I'm working of this project in Android studio and here is my project structure. https://i.stack.imgur.com/mgZkG.png Issue is, there I could not find a way to deploy this kind of a project anywhere in the internet. Could you please give me a link or tell me how to do this? -
Django - How to filter children of a nested queryset?
I have this model called Menu which has a many-to-many relationship with another model called category. Both this models have a field called is_active which indicates that menu or category is available or not. Alright, then I have an api called RestaurantMenus, which returns all active menus for a restaurant with their categories extended, the response is something like this: Menu 1 Category 1 Category 2 Menu 2 Category 3 Menu 3 Category 4 Category 5 Category 6 Now what I try to achieve is to only seriliaze those menus and categories which are active (is_active = True). To filter active menus is simple but to filter its children is what I'm struggling with. P.S. Category model itself has a many-to-many relationship with another model Called Item, which has an is_active field too. I want the same effect for those too but I cut it from the question cause I think the process should be the same. So actually the api response is something like this: Menu 1 Category 1 Item 1 Item 2 Item 3 Category 2 Item 4 -
How to take a file as a form-field input without defining it as a Model in Django?
I have written a simple API for Tax Analysis through a ZIP file sent by our supplier using the FastAPI framework. (As you can see below). However, I had to start shifting my APIs to Django for some technical reasons. I have been searching for a way to input a file as form-data in Django, but all of them require a Model to be created for that, however, for my requirement, I don't need that file stored anywhere permanently, just temporarily in the memory for further analysis. Below is an example of how I was taking the file as an input through FastAPI. @app.get('/xtracap_gst/files') async def gst(file: UploadFile = File(any)) Any inputs would be appreciated -
Unable to load template from a given location in Django
I am unable to load product_create.html using following url http://127.0.0.1:8000/create/ Following is the error As you can see in the last line under heading Template-loader postmortem, it is searching for template in following location where my template is present (check project layout). C:\trydjango\products\templates\products\product_create.html Following is my project layout . Relevant part of settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR),"templates"], #'DIRS': [path.joinpath(BASE_DIR, "templates")], #'DIRS': [BASE_DIR / 'templates' ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] urls.py from django.contrib import admin from django.urls import path from pages.views import home_view, contact_view, about_view from products.views import product_detail_view,product_create_view #its better fom the alternate version #from pages import views and then using views.home_view urlpatterns = [ path('', home_view ,name = 'home'), #the 1st argument to path gives the url path('admin', admin.site.urls), path('contact/', contact_view ,name = 'contact'), path('about/', about_view ,name = 'about'), path('product/', product_detail_view), path('create/', product_create_view), ] products/views.py from django.shortcuts import render from .forms import ProductForm from .models import Product # Create your views here. def product_create_view(request): form = ProductForm(request.POST or None) if form.is_valid(): form.save() context={ 'form':form } return render(request,"products/product_create.html",context) def product_detail_view(request): obj=Product.objects.get(id=1) # context={ # 'title':obj.title, # 'description':obj.description # } context={ 'object':obj } return render(request,"products/product_detail.html",context) -
cannot show list items in html for using for loop
I cannot show list items in html for using for loop. But there is no problem when try show seperately x and i. models.py def dp1(): result=list(engine.execute("select a,b,c,d from my_Table where a='201811' and rownum<4")) return result Views.py def dp (request): con() result=dp1() y=range(0,len(result[0])) return render(request, 'pages/detail.html', {'result': result,'y':y}) html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <table BORDER='1'> {% for x in result %} <tr > {% for i in y%} <th > {{x.i}} </th> {% endfor %} </tr> {% endfor %} </table> </body> </html> -
Generating unique id in a model with prefix of field value of another model
I created two models "Category" and "Item". There is a field "title" in category model, I want the value of the "title field" to be prefix of my unique id field in Item module can anyone suggest me a solution for this problem. Thank you -
Cant add add_child to the Page table
When adding add_child to the Page table obj_cruise = self.obj_cruise_index.add_child ( instance = Cruise (** options)) an error comes out ERROR: NULL in column "translation_key" of relationship "wagtailcore_page" violates NOT NULL constraint But translation_key has to be generated itself, right? What is the problem here? Thanks in advance for your help! -
'function' object has no attribute 'all' on DetailView
Can someone please give me a quick explanation as to what I'm doing wrong I got, 'function' object has no attribute 'all', this error. and i've used DetailView. Views.py from django.views.generic import ListView, DetailView from main import models class BlogDetail(DetailView): model_name = models.BlogTitle template_name = 'main/blog.html' context_object_name = 'object' def queryset(self): return models.BlogTitle.objects.order_by('title') models.py from django.db import models from django.contrib.auth.models import User class BlogTitle(models.Model): title = models.CharField(max_length = 64) def __str__(self): return self.title class Blog(models.Model): author = models.CharField(max_length = 64, default = False) title = models.OneToOneField(BlogTitle, on_delete=models.CASCADE) category = models.CharField(max_length = 64) content = models.TextField() def __str__(self): return self.author urls.py path('blogs/<int:pk>', auth(views.BlogDetail.as_view()), name = 'blog'), blog.html {% extends 'base.html' %} {% block content %} {{ object.title }} {{ object.category }} {{ object.content }} {% endblock %} i tried objects.all() this also, but i didn't work. -
how to convert python to html in django template
I am using json2html to convert json values to html tables in my views.py render(request, 'home.html', {'value': json2html.convert(json=result)}) where result has json data. The above gives me html for json but in home.html template it is not displayed in html table format instead it is displaying like below on the site <ul><li><table border="1"><tr><th>name</th><td>Test</td></tr><tr><th> my home.html the code looks like this <html> <body> {{ value }} </body> </html> the variable value has the converted html table code but it is displaying as raw instead it should render as html code. How to do this ? -
django project giving 500 internel server error
I have a Django project which was working fine till last night. And now I'm getting this error and this is what I'm getting in my terminal All I did was tried changing my virtualenv I deleted my last virtualenv because it was installing packages in my global environment and created a new one, reinstalled requirements.txt, and ran manage.py runserver. Now I'm getting this error. I have no idea what went wrong. I'm using Windows10, Python3.6, and Django 3.0 -
'tuple' object has no attribute 'splitlines' while sending email notification in django
I am trying to send email notifications using the SMTP Gmail host. But when I try to send user information in the message field, it shows the above error. This is my booking view: class BookingCreateAPIView(ListCreateAPIView): permission_classes= [IsAuthenticated] queryset = Booking.objects.all() serializer_class = BookingSerializer def perform_create(self, serializer): # user = self.request.user package = get_object_or_404(Package, pk= self.kwargs['pk']) serializer.save(user=self.request.user,package=package) # data = self.request.data name = serializer.data['name'] email = serializer.data['email'] phone = serializer.data['phone'] send_mail('New booking ',(name,email,phone), email , ['saroj.aakashlabs@gmail.com'], fail_silently=False) This is my serializer: class BookingSerializer(serializers.ModelSerializer): # blog = serializers.StringRelatedField() class Meta: model = Booking fields = ['name', 'email', 'phone', 'bookedfor'] # fields = '__all__' How to solve this?? -
How to retrieve and display data from multiple tables with no foreign keys using django-betterforms
I'm trying to implement the CRUD function using GenericView + ClassBaseView, but I'm stumped on the ListView display part. If anyone has a solution, please let me know. I'm not very experienced with django and web apps, and I'm not familiar with the English language, so I apologize if I'm misrepresenting things. (Note that we have already implemented the CRUD functionality (without django-betterforms) in ClassBaseView for a single table only.) ■Remarks There are no foreign keys between all tables. Duplicate column names and variable names in some related tables. (→variable names become the same when you do an inspectdb). I tried looking at the official site and stackoverflow's related questions (questions/569468), but it didn't work because I didn't know how to write it properly. ■Hope (constraints) I don't want to make any changes to the existing DB side as much as possible for the DB in production. For the sake of readability, we want to implement it as much as possible using a combination of ORM and ClassBaseView. Due to the (old) style of development, where DB table definitions are directly changed, I would like to only use models.py as a result of inspectdb. We want to only use models.py … -
Jquery autocomplete with images in django
I am trying to upload an image/poster along with the title in the dropdown when it is searched in the search form. I was able to display the titles before I added the image logic. But now neither are working. This is my views: if 'term' in request.GET: term = request.GET.get('term') qs = Pilot.objects.filter(Q(title__icontains=term) | Q(writer__icontains=term)).distinct()[:10] results = list() for title in qs: results.append(title.poster) results.append(title.title) return JsonResponse(results, safe=False) This is my js script: <script> $( function() { $( "#search_data" ).autocomplete({ source: '{% url "index" %}', minLength: 2 })._renderItem = function(ul, item) { return $("<li>") .data("item.autocomplete", item) .append("<div><img src='" + item.poster + "' /> " + item.title + "</div>") .appendTo(ul); }; }); </script> This is the model: class Pilot(models.Model): title = models.CharField(max_length=200) description = models.TextField() count = models.IntegerField() writer = models.CharField(max_length=200) year = models.IntegerField() script = models.FileField(blank=True, null=True, upload_to="scripts") poster = models.ImageField(blank=True, null=True, default='default.jpg', upload_to="posters") created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) -
Django queryset for a multiple table query
For the below sample schema # schema sameple class A(models.Model): n = models.ForeignKey(N, on_delete=models.CASCADE) d = models.ForeignKey(D, on_delete=models.PROTECT) class N(models.Model): id = models.AutoField(primary_key=True, editable=False) d = models.ForeignKey(D, on_delete=models.PROTECT) class D(models.Model): dsid = models.CharField(max_length=255, primary_key=True) class P(models.Model): id = models.AutoField(primary_key=True, editable=False) name = models.CharField(max_length=255) n = models.ForeignKey(N, on_delete=models.CASCADE) # raw query for the result I want # SELECT * # FROM P, N, A # WHERE (P.n_id = N.id # AND A.n_id = N.id # AND A.d_id = \'MY_DSID\' # AND P.name = \'MY_NAME\') What will be the queryset for this kinda raw query ? or is there a better way to do it ? Above code is here https://dpaste.org/DZg2 -
Django Python | Returning Render(request) and HTTP Reponse at the same time?
I'm trying to return a Render(request) and an HTTPReponse at the same time.. def home(request): db_userpull = user.objects.all().values_list('userkey', flat=True) http_resp = HttpResponse() http_resp.set_cookie('foo', 'bar') #return render(request, 'home.html', {"db":db_userpull}) #return http_resp return render(request, 'home.html', {"db":db_userpull, "sesstest":request.session['user_s_key']}) , http_resp Essentially the goal is, on load the page displays stuff from the database, and create a Cookie using an http response at the same time.. When I return them separately, they work fine (either creates a cookie, or returns the database data) I'm trying to get it to return both, but I'm getting an Attribute Error; AttributeError at / 'tuple' object has no attribute 'get' Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.1.4 Exception Type: AttributeError Exception Value: 'tuple' object has no attribute 'get' -
Django with CherryPy - ModuleNotFound errors
I found a gist that feasibly would allow me to integrate a CherryPy webserver into my program, and run a Django project via that CherryPy webserver. However I'm having some difficulties getting the thing to work properly. Here's the Class in my code from the gist, largely unchanged class ClientThread(object): HOST = "127.0.0.1" PORT = int("3852") DIR = "/home/user/project/" STATIC_ROOT = DIR + '/clientFiles/static/' def mount_static(self, url, root): """ :param url: Relative url :param root: Path to static files root """ config = { 'tools.staticdir.on': True, 'tools.staticdir.dir': root, 'tools.expires.on': True, 'tools.expires.secs': 86400 } cherrypy.tree.mount(None, url, {'/': config}) def run(self): cherrypy.config.update({ 'server.socket_host': self.HOST, 'server.socket_port': self.PORT, 'engine.autoreload_on': False, 'log.screen': True }) self.mount_static(settings.STATIC_URL, self.STATIC_ROOT) cherrypy.tree.graft(WSGIHandler()) cherrypy.engine.start() print("[Info]: Client started. Use http://{0}:{1} to access the WebApp.".format(self.HOST,self.PORT)) cherrypy.engine.block() def init(self): print("[Info]: Starting Client WebApp...") cThread = Thread(target=self.run) cThread.start() This entire class is initiated via ClientThread().init() The first few lines of the gist at the top of my app (in order): import os from threading import Timer os.environ["DJANGO_SETTINGS_MODULE"] = "clientFiles.settings" import django django.setup() import cherrypy from django.conf import settings from django.core.handlers.wsgi import WSGIHandler My project is laid out like this: . ├── clientFiles │ ├── clientFiles │ │ ├── asgi.py │ │ ├── __init__.py │ │ … -
designing an api to send same response code with different meaning
What is the proper way to design an API response that could have the same response status code but with a different meaning for the fronted to display? Here is my example: On our frontend, the user can submit an address and our backend validates the submitted address. It checks if the address is real. The response could be that the address does not exist, or that more information about the address is required to find it. In both scenarios the API returns 400. We want the frontend to be able to distinguish between the 2 because the type of alert we show the user changes color based on the bad request type. This is how we are currently achieving it: {"message": "Missing field in api", "type": 1}, 400 {"message": "123 Apple Wood Drive.", "type": 2}, 400 If the frontend gets the type 1, the color of the alert is red, while 2 it is orange. How can we improve this approach so that we arent instructing the client how to display? -
Updating the quantity of items in a shopping Cart not working properly
I am working on a Django E-commerce Project, and I have been following a tutorial and afterwards I decided to redo it on my own without the tutorial but I am stuck in a small issue which I don't understand the logic behind it. When a user adds an Item to Cart I want it to reflect on the no. of items that are showing on the navbar cart icon, but I am getting Invalid filter: 'cart_item_count' Here is my Item model.py class Item(models.Model): title = models.CharField(max_length=100) image = models.ImageField(blank=False, upload_to=upload_design_to) class OrderItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ordered = models.BooleanField(default=False) item = models.ForeignKey(Item, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) variation = models.ManyToManyField(Variation) The application name is store, so here is what I have been done in the tutorial Added a new folder in the app with the name of templatetags and inside the template tags folder created file called cart_template_tags and here is what is inside it: from django import template from store.models import Order register = template.Library() @register.filter def cart_item_count(user): if user.is_authenticated: qs = Order.objects.filter(user=user, ordered=False) if qs.exists(): return qs[0].items.count() return 0 My question is how do I fix this error and I want to understand behind the logic of having …