Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to overwrite Django app to Pythonanywhere?
After the second times deploying the Django app to Pythonanywhere, (I re-edited and overwritten in VS code and did git push) I got the following error. subprocess.CalledProcessError: Command'['/home/hogehoge/.virtualenvs/hogehoge.pythonanywhere.com/bin/pip','show','django']' returned non-zero exit status 1. The command is $ pa_autoconfigure_django.py https://github.com/[user_name]/[project_name].git --nuke The first deployment succeeded but the second one is not. I don't know the cause and how to overwrite it... -
Django Admin: Display unique field values and its count in the list_display
I have EmployeePoint Model to track the points of the employee. The object is saved when deal is successful. if obj.deal_status == 'Successful': point_obj = EmployeePoint(employee=lead.employee, created_at=obj.created_at) point_obj.save() Currently the list_display() displays all the objects. list_display of EmployeePoint Instead of displaying all the objects of EmployeePoint, I want something like list_display= ('employee','count') to display employee name and number of objects with that employee name created in current year. -
Error no such table: forms_complain in django
I have created a html file 'Complain' and its supposed to take input from user and store in in the database. My complain.html is <!DOCTYPE html> <html> <head> <title></title> </head> <body> <h1>Hello People</h1> <form action="/complain/" method="post"> {% csrf_token %} <label for="name">Your Name</label> <input type="text" name="Std_name" placeholder="John Doe"><br><br> <label for="Std_id">Your Student ID</label> <input type="number" name="Std_id" placeholder="01"><br><br> <label for="Std_class">Your Class</label> <input type="text" name="Std_class" placeholder="Class 1"><br><br> <label for="email">Your Email</label> <input type="email" name="email" placeholder="abc@gmail.com"><br><br> <label for="desc">Your Complaint</label> <input type="text" name="desc"><br><br> <button type="submit">Submit</button> </form> </body> </html> and models.py is from django.db import models from django.forms import ModelForm from django.utils import timezone class Complain(models.Model): Std_no = models.AutoField(primary_key=True) Std_id = models.IntegerField(max_length=None) Std_class = models.TextField() name = models.CharField(max_length=40) email = models.CharField(max_length=40) desc = models.TextField() time = models.DateTimeField(auto_now_add=True) Views.py is from django.shortcuts import render from django.http import HttpResponse from django.db.models import Q from .models import Complaint, Complain def complain(request): if request.method=='POST': name = request.POST.get("name") Std_id = request.POST.get("Std_id") Std_class = request.POST.get("Std_class") email = request.POST.get("email") desc = request.POST.get("desc") instance = Complain(name=name, Std_id=Std_id, Std_class=Std_class, email=email, desc=desc) instance.save() return render(request,'forms/complain.html', { 'title' : 'Complain'}) I have run python manage.py makemigration python manage.py migrate python manage.py sqlmigrate forms and someone recommended on stack overflow to run python manage.py migrate --run-syncdb so I tried it … -
Filter query using headers in DRF
I have a use case where I need to show the data of the company the user belongs to. I don't want the url to show something like: 127.0.0.1:8000/api/document?company=somecompany rather I want to pass the company within the header and return the data related to the company. Is there any way to achieve this in Django REST Framework? Else, how can I avoid 127.0.0.1:8000/api/document?company=somecompany. -
Updating database when a user clicks a button (django)
I have been working on a project, in which I found, that we have to send a post request to another view(ex. update_item) when a button is clicked. And we use that same view to fetch the data to be added to database. Please explain the working on how this is done in django. -
RapidSMS Installation Error in Ubuntu 20.10
Please help my issue. I doing like this, but migrate step in error. #pip install rapidsms #pip install django #django-admin.py startproject --template=https://github.com/rapidsms/rapidsms-project-template/zipball/release-0.21.1 --extension=py,rst start_rsms1 #virtualenv start_rsms1-env #source start_rsms1-env/bin/activate #cd start_rsms1 #pip install -U -r requirements/base.txt #python manage.py migrate #python manage.py runserver ------------------Error class Message(models.Model): RuntimeError: class not set defining 'Message' as <class 'rapidsms.contrib.messagelog.models.Message'>. Was classcell propagated to type.new? -
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 …