Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Slow Database Model Query
I am having issues with performance of a couple of queries in my Django app... all others are very fast. I have an Orders model with OrderItems, the query seems to be running much slower that other queries (1-2 seconds, vs. 0.2 seconds). I'm using MySQL back-end. In the serializer I do a count to return whether an order has food or drink items, I suspect this is causing the performance hit. Is there a better way to do it? Here is my models setup for Order and OrderItems class Order(models.Model): STATUS = ( ('1', 'Placed'), ('2', 'Complete') ) PAYMENT_STATUS = ( ('1', 'Pending'), ('2', 'Paid'), ('3', 'Declined'), ('4', 'Manual') ) shop= models.ForeignKey(Shop,on_delete=models.DO_NOTHING) customer = models.ForeignKey(Customer,on_delete=models.DO_NOTHING) total_price = models.DecimalField(max_digits=6, decimal_places=2,default=0) created_at = models.DateTimeField(auto_now_add=True, null=True) time_completed = models.DateTimeField(auto_now_add=True, null=True,blank=True) time_cancelled = models.DateTimeField(auto_now_add=True, null=True,blank=True) status = models.CharField(max_length=2, choices=STATUS, default='1',) payment_method = models.CharField(max_length=2, choices=PAYMENT_METHOD, default='3',) payment_status = models.CharField(max_length=2, choices=PAYMENT_STATUS, default='1',) type = models.CharField(max_length=2, choices=TYPE, default='1',) def __str__(self): return str(self.id) class OrderItem(models.Model): order = models.ForeignKey(Order,on_delete=models.CASCADE) type = models.CharField(max_length=200,default='DRINK') drink = models.ForeignKey( Drink, blank=True,null=True,on_delete=models.DO_NOTHING ) food = models.ForeignKey( Food, blank=True, null=True, on_delete=models.DO_NOTHING ) quantity = models.IntegerField(blank=True,null=True) price = models.DecimalField(max_digits=6, decimal_places=2,default=0) created_at = models.DateTimeField(auto_now_add=True, null=True) delivered = models.BooleanField(default=False) def __str__(self): return str(self.id) In my rest order … -
Converting images from html to pdf using xhtml2pdf
Recently I've used the tutorial from YT and other websites on how to convert HTML to PDF in Django. But it didn't work with the images. Views.py from django.shortcuts import render from io import BytesIO from django.http import HttpResponse from django.template.loader import get_template from django.views import View from xhtml2pdf import pisa #Generates PDF def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None data = { "company": "Dennnis Ivanov Company", "address": "123 Street name", "city": "Vancouver", "state": "WA", "zipcode": "98663", "phone": "555-555-2345", "email": "youremail@dennisivy.com", "website": "dennisivy.com", } #Opens up page as PDF class ViewPDF(View): def get(self, request, *args, **kwargs): pdf = render_to_pdf('html_to_pdf/pdf_template.html', data) return HttpResponse(pdf, content_type='application/pdf') I've looked for many StackOverflow posts as well as many docs, but as I'm just beginning in Django I don't understand how to solve this problem(I'm not the only one). I hope someone can modify this code and explain it clearly why it doesn't work. I'm loading images in pdf_template.html using <img src="{% static "html_to_pdf/images/img.jpg" %}" alt="My image"> Django 3.0.8 Python 3.6.3 -
How to fetch the text of a HTML tag in view of Django
I have the following dropdown: <select class="form-control" id="exampleFormControlSelect1" name="exampleFormControlSelect1"> <option value="value">text</option> </select> I want to fetch the text from option in my Django view.How can I implement this?For my code reasons, text and value cannot be changed. -
Django Stripe Subscription
I'm trying to create a subscription recurring for my Django project. And I'm facing a problem connecting to stripe. Whenever I click the subscribe button my function seems like not working .it doesn't work and the subscription doesn't show up in my stripe payments. I'm following this tutorial "https://levelup.gitconnected.com/using-django-and-stripe-for-monthly-subscriptions-465de92dd34f" to complete my project. views.py from django.shortcuts import render, redirect import stripe import json from django.http import JsonResponse from djstripe.models import Product import djstripe from django.http import HttpResponse # Create your views here. stripe.api_key = "sk_test_51GzcRAIhklFM3EVMjTgtlwpMiWDaOAiTdsGNonj9ekBku2Jy4f7qLRDd1UbR9GwMba4ZZkQkrC39EIocrCf1qRcf003ax2gTBZ" def homepage(request): return render(request, "home.html") def checkout(request): products = Product.objects.all() return render(request,"checkout.html",{"products": products}) def create_sub(request): if request.method == 'POST': # Reads application/json and returns a response data = json.loads(request.body) payment_method = data['payment_method'] stripe.api_key = djstripe.settings.STRIPE_SECRET_KEY payment_method_obj = stripe.PaymentMethod.retrieve(payment_method) djstripe.models.PaymentMethod.sync_from_stripe_data(payment_method_obj) try: # This creates a new Customer and attaches the PaymentMethod in one API call. customer = stripe.Customer.create( payment_method=payment_method, email=request.user.email, invoice_settings={ 'default_payment_method': payment_method } ) djstripe_customer = djstripe.models.Customer.sync_from_stripe_data(customer) request.user.customer = djstripe_customer # At this point, associate the ID of the Customer object with your # own internal representation of a customer, if you have one. # print(customer) # Subscribe the user to the subscription created subscription = stripe.Subscription.create( customer=customer.id, items=[ { "price": data["price_id"], }, ], expand=["latest_invoice.payment_intent"] … -
Printing Form Data Among Non-Form Data
I have data attached to users and books. In my template I'm looping through a User's Books and printing the id, title, and a checkbox of whether or not they have finished reading it. The id and title are coming straight from the db as they cannot be changed, while the checkbox is part of a form. My problem is displaying the checkbox corresponding to the right book, in among the data which is not part of the form. I have included my attempt below, but this isn't working. I also believe I am not getting the correct UserBookDataForm. I need to get all instances associated with the current user, but the way I'm doing it is how I would get a one-to-one related model. models.py class UserBookData(models.Model): user = models.ForeignKey(User, related_name='user_book_data', on_delete=models.CASCADE) book = models.ForeignKey(Book, on_delete=models.CASCADE) completed = models.BooleanField() view.py # i am unsure if this is right form = UserBookDataForm(instance=request.user) template.html {% for book in books.all %} <tr> <td>{{ book.id }}</td> <td>{{ book.title}}</td> <!-- display checked if completed --> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {% for field in form %} {% if field.book_id == book.id %} {{ field.book_id }} {% endif %} {% endfor %} </form> </tr> … -
How i send email or sms in django with otp
Hello i create a project which in i want to create send email or S M S such for reset password or change password with O T P in Django such as Instagram or Facebook i want to send email if user will enter email or if user enter phone then i will send S m s but i am confused in lots of tutorials have you complete code for this problem so please can you tell me thank you I Used below code but not satisfied urls.py path('password_change/done/', auth_views.PasswordChangeDoneView.as_view(template_name='registration/password_change_done.html'), name='password_change_done'), path('password_change/', auth_views.PasswordChangeView.as_view(template_name='templates/registration/password_change.html'), name='password_change'), path('password_reset/', auth_views.PasswordResetView.as_view (template_name='registration/password_reset_form.html'), name='password_reset'), path('password_reset/done/', auth_views.PasswordResetCompleteView.as_view(template_name='templates/registration/password_reset_done.html'), name='password_reset_done'), path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(), name='password_reset_confirm'), path('reset/done/', auth_views.PasswordResetCompleteView.as_view(template_name='templates/registration/password_reset_complete.html'), name='password_reset_complete'), -
django-filter DateTimeFilter support input with timezone?
I have set up a model "Customer" with timezone field and while I use django-filter DateTimeFilter, the input is always in UTC timezone (as per setting). How can the input can be modified by reference to timezone field in "Customer" model as if I can do it in template which convert the UTC into specific timezone as per the timezone field stipulated in the model. Below is the extracts of the codes: in models.py import pytz TIMEZONES = tuple(zip(pytz.all_timezones, pytz.all_timezones)) class Customer(models.Model): timezone = models.CharField(max_length=32, choices=TIMEZONES, default='Asia/Hong_Kong') in filters.py class OrderFilter(django_filters.FilterSet): start_edd_date = DateTimeFilter(field_name="edd_date", lookup_expr='gte', label="EDD date >=") end_edd_date = DateTimeFilter(field_name="edd_date", lookup_expr='lte', label="EDD date <=") class Meta: model = Order fields = '__all__' In views.py def userPage(request, slug): orders = request.user.customer.order_set.all().order_by('-date_created') myFilter = OrderFilter(request.GET, queryset=orders) orders = myFilter.qs context = { 'orders': orders, 'customer': customer, 'myFilter': myFilter, } The problem is when I select one of the customer and change the timezone to, say, Pacific/Honolulu. In the user page, it can display properly based on the timezone I set in html, <td>{{order.edd_date|timezone:customer.timezone|date:"F j, Y a"}}</td> which show one of the record with edd_date is, June 29, 2020 p.m., when I try to filter it with EDD date >= 6/30/2020, the … -
How to save form with multiple foreignkey
I have list of posts in newfeeds from different users, I am trying to implement a report form so that when i click on the ellipsis on a user post and click report, then a modal popup with list of options like "Hate Speech, Violence, etc.." when selected an option and click on submit button, I want both the user who is reporting and user reported to be saved in admin. Request.user (queen_glory) is saved in admin but the user_is_reported (the user's post you're reporting) is empty, i want that user also be saved in admin. How can i do this using one form? Model: class Report(models.Model): user_is_reporting = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE, related_name='user_reporting', blank=True,null=True) user_is_reported = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user_reported', null=True, blank=True) post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='reports', null=True, blank=True) why_reporting = models.TextField(blank=True) reporting_user_for = models.CharField(max_length=100, blank=True) date = models.DateTimeField(auto_now_add=True) Form: REPORT_POST_CHOICES = ( ('Nudity', 'Nudity'), ('Violence', 'Violence'), ('Hate speech or symbols', 'Hate speech or symbols'), ('Harassment or Bullying', 'Harassment or Bullying'), ('Suicide or Self-Injury', 'Suicide or Self-Injury'), ('Sale of illegal or regulated goods', 'Sale of illegal or regulated goods'), ('False information', 'False information'), ('I just do not like it', 'I just do not like it'), ) class ReportPostForm(forms.ModelForm): reporting_user_for = forms.ChoiceField(label='',widget=forms.RadioSelect, choices=REPORT_POST_CHOICES) class … -
Django Rest Api adding members (users) to a Class model
I wanted to implement a student class system where anyone can create a class and others can join. So far I have it so each class has a creator and members in it. I'm trying to get it so that when the user creates the class they are automatically added as a member as well, but I'm not sure how to add members to a class. Im able to do it through the python shell but not in the Class view through the api. Eventually I want you to be able to go to /auth/classes//join and have that user join that class as well as /auth/classes//leave. Any help is greatly appreciated :) model.py class Class(models.Model): name = models.CharField(max_length=30) class_discription = models.CharField(max_length=30) created = models.DateTimeField(auto_now_add=True) creator = models.ForeignKey('users.User', related_name='creator', on_delete=models.CASCADE) members = models.ManyToManyField('users.User') class Meta: ordering = ['created'] def addMember(self, *vars, **kwargs): self.membebrs.add(User) return super().save(*vars, **kwargs) def deleteMember(self, *vars, **kwargs): self.membebrs.remove(User) return super().save(*vars, **kwargs) view.py from django.contrib.auth.models import Group from rest_framework import viewsets from classes.serializers import ClassSerializer from rest_framework import permissions from rest_framework.response import Response from classes.models import Class from rest_framework.decorators import action from rest_framework import status, viewsets from users.models import User # Create your views here. class ClassViewSet(viewsets.ModelViewSet): """ API … -
How to Implement FullCalender Draggable Events with django using ajax
This is my models: class Activity(models.Model): """ Activity Model """ name = models.CharField(max_length=100,null=True, unique=True) description = models.CharField(max_length=500,null=True, unique=True) def __str__(self): return self.name class ScheduleActivity(models.Model): """ Activity Schedule Model """ user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="user_activity_schedule") activity = models.ForeignKey(Activity, on_delete=models.CASCADE, related_name="activity_schedule") start_date_and_time = models.DateTimeField(blank=True,null=True) end_date_and_time = models.DateTimeField(blank=True,null=True) def __str__(self): return str(self.activity.name) My Javascript: <script> document.addEventListener('DOMContentLoaded', function () { var Draggable = FullCalendarInteraction.Draggable /* initialize the external events -----------------------------------------------------------------*/ var containerEl = document.getElementById('external-events-list'); new Draggable(containerEl, { itemSelector: '.fc-event', eventData: function (eventEl) { return { title: eventEl.innerText.trim(), } } }); calendar.render(); }); </script> <script> document.addEventListener('DOMContentLoaded', function () { var Calendar = FullCalendar.Calendar; var calendarEl = document.getElementById('calendar'); var calendar = new Calendar(calendarEl, { plugins: ['interaction', 'dayGrid', 'timeGrid', 'list'], header: { left: 'prev,next today', center: 'title', right: 'dayGridMonth,timeGridWeek,timeGridDay,listWeek' }, navLinks: true, // can click day/week names to navigate views editable: true, droppable: true, // this allows things to be dropped onto the calendar eventLimit: true, // allow "more" link when too many events events: [ { title: 'All Day Event', start: '2020-07-01' }, { title: 'Long Event', start: '2020-07-07', end: '2020-07-10' }, { groupId: 999, title: 'Repeating Event', start: '2020-07-09T16:00:00' }, { groupId: 999, title: 'Repeating Event', start: '2020-07-16T16:00:00' }, ] }); calendar.render(); }); </script> I … -
How to rewrite urls to get slug in view
Django 3.0.7 urls.py urlpatterns = [ path('<slug:categories>/', include(('categories.urls', "categories"), namespace="categories")), ] categories/urls.py urlpatterns = [ path('', CategoryView.as_view(), name='list'), ] views.py class CategoryView(ListView): model = Post def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["object_list"] = context["object_list"].filter(category__slug="linux") # Hardcoded so far return context def get_template_names(self): return ["categories/post_list.html"] Then I request http://localhost:8000/linux/ Problem In the request that arrived kwargs is empty. Could you help me understand why it happens and how to cope with this. -
Boolean Field is not updating Correctly Django
my models.py contains a boolean variable. and default set as true. boolean variable is not updating correctly in database. my models.py class Attendance(models.Model): AttendanceId = models.AutoField(primary_key=True, db_column='AttendanceId') Employee = models.ForeignKey(Employee, on_delete=models.CASCADE, db_column='EmployeeId') PunchTime = models.DateTimeField() AttendanceStatus = models.BooleanField(default=True) PunchType = models.SmallIntegerField() Device = models.ForeignKey(Device, on_delete=models.CASCADE, db_column='DeviceId') DeviceType = models.ForeignKey(DeviceType, on_delete=models.CASCADE, db_column='DeviceTypeId') class Meta: db_table = "Attendance" my serializer.py class AttendanceSerializer(serializers.ModelSerializer): class Meta: model = Attendance fields = '__all__' my views.py @api_view(["POST"]) @permission_classes([IsAuthenticated]) def add_attandance(request): try: attandance_serializer = AttendanceSerializer(data=request.data) if attandance_serializer.is_valid(): attandance_serializer.save() return Response(attandance_serializer.data, status=status.HTTP_200_OK) else: return Response(attandance_serializer.errors, status=status.HTTP_400_BAD_REQUEST) except Exception as ex: return Response({'Message': repr(ex)}, status=status.HTTP_400_BAD_REQUEST) my postman resultResult How can i solve this? i am using djangorestframework==3.11.0 Django==3.0.3 -
Why am I getting a 404 error when requesting my css in Django
Im making a 'learning website' along with the treehouse course and when I run my website server the GET for the CSS returns a 404 error, below I will provide the details I think will help you help me. Thank you for any help this is annoying for trying to learn Django. Ive looked everywhere and cannot find something to help me, I will happily give more info in the comments! Here is my file structure: ~/PycharmProjects/learning_site |--.idea |--assets | |--css | |--layout.css |--courses |--learning_site |--templates db.sqlite2 manage.py This is my static variables defined in the settings.py file. STATIC_URL = '/static/' STATICFIILES_DIRS = ( os.path.join(BASE_DIR, 'assets'), ) This is my layout.html template where the css is called. {% load static %}<!doctype html> <html> <head> <title> {% block title %} {% endblock %}</title> <link rel = "stylesheet" href="{% static '/css/layout.css' %}"}> </head> <body> <div class="site-container"> {% block content %}{% endblock content %} </div> </body> </html> This is the homepage where the CSS would be displayed. {% extends "layout.html" %} {% block title %} Well hello there! {% endblock %} {% block content %} <h1>Welcome!</h1> {% endblock %} <a href="127.0.0.1/courses/"> Courses offered </a> -
Algebric expression simplification in python program
I need help on Writing a program to implement a system that processes mathematical expressions according to the rule for only the 'B' part. i.e - Brackets. The input expressions should not be solved to get an answer but only modified according to the specified 'B' rule in BODMAS. For example: if the input is "a - (b + c)" then the output should be a-b-c. The output should remove all spaces between the characters. Some important notes about the rules: 1. +(-ve no) gives a -ve number. So, +(b-c) is +b-c +(+ve no) gives a +ve number. so, +(h+i) is +h+i -(-ve no) gives a +ve number. so -(d-e) is -d+e -(+ve no) gives a negative number. so -(f+g) = -f-g Examples Input: "a+(b - c) - (d - e) - (f+g)+ (h+i)" Output: a+b-c-d+e-f-g+h+i Input: "-(d-e)" Output: -d+e -
How to get a data API from another function in python django
I am doing an project that pulling user API from github and I successfully done that but I'm working on how to show that data on a chart. I'm using Chart.js Here is my views.py: def user(req, username): username = str.lower(username) # Get User Repo Info with urlopen(f'https://api.github.com/users/{username}/repos') as response: source = response.read() sorted_by_stars = json.loads(source) def sort_user_repo_by_stars(sorted_by_stars): return sorted_by_stars['stargazers_count'] sorted_by_stars.sort(key=sort_user_repo_by_stars, reverse=True) context = { 'username': username, 'sorted_by_stars': sorted_by_stars[:8], } return render(req, 'user.html', context) class ChartData(APIView): authentication_classes = [] permission_classes = [] def get(self, request, format=None): labels = ["Blue", "Yellow", "Green", "Purple", "Orange"] default_items = [ DATA ] data = { "labels": labels, "default": default_items, } return Response(data) I want to get data that I pulled from github which is sorted_by_stars = json.loads(source) and it put in ChartData. How can I do that? -
Paginator not working while subclassing view?
Here I am subclassing view but it is not working properly.The pagination is not working in my second view but searching works fine. Why my paginator not working in my second view ? views class SearchCategories(PermissionRequiredMixin, View): permission_required = 'user_groups.data_perm' model = TargetCategory template = 'list_categories.html' context_object_name = 'categories' def get(self, request): q = request.GET.get('q', '') qs = self.model.objects.filter(title__icontains=q).order_by('-created') paginator = Paginator(qs, 10) results = paginator.get_page(request.GET.get('page')) return render(request, self.template, {self.context_object_name: results, 'q': q}) class SearchKeywords(SearchTargetCategories): template = 'list_keywords.html' model = Keyword context_object_name = 'keywords' -
How to limit nubmer of Foreign key relations in Django ORM?
I have a model which is recursively related to itself. It's content is as follows. class Category(models.Model): name = models.CharField(max_length=200) parent = models.ForeignKey( 'self', blank=True, null=True, related_name='children', on_delete=models.CASCADE) class Meta: verbose_name_plural = "Categories" def __str__(self): path = [self.name, ] node = self.parent while node is not None: path.append(node.name) node = node.parent return '->'.join(path[::-1]) What I want to achieve is a little validation that prevents more than 3 children to parent Category. For example if I create as state above, it will be saved as follows: Programming->Back-end->Python->ifelse. My question: How can I prevent parent category to have more then 3 children? -
Custom object level DRF permission not working
In the code i am trying to implement profile part of the user where he can see his profile and update it. Here i apply some restriction at object level so that only a logged in user can see only his profile.but the custom permission part of the code is not executing Please find the code below from rest_framework import permissions class IsProfilePermission(permissions.BasePermission): def has_object_permission(self, request, view, obj): print("getting here") #checking whether code is coming here or not print(obj.__dict__) print(request.user) return True code for the profile view class ProfileView(APIView): authentication_classes = [TokenAuthentication] permission_classes = [IsAuthenticated,IsProfilePermission] def get(self,request,*args,**kwargs): try: profile_obj = User.objects.get(pk=self.kwargs['pk']) except: return Response({"error":"Invalid profile"},status = status.HTTP_400_BAD_REQUEST ) prof_serialize = ProfileSerializer(profile_obj) return Response(prof_serialize.data) def put(self,request,*args,**kwargs): try: profile_obj = User.objects.get(pk=self.kwargs['pk']) except: return Response({"error":"Invalid profile"},status = status.HTTP_400_BAD_REQUEST ) serializer = ProfileSerializer(profile_obj,data=request.data) data = {} if serializer.is_valid(): serializer.save() data['sucess']="profile successfully updated" return Response(data,status= status.HTTP_201_CREATED) else: return Response(serializer.errors,status = status.HTTP_400_BAD_REQUEST) -
Unable to COPY from STDIN in Postgresql PGadmin
giving this type of ERROR Kindly help me to copy the whole bunch of data -
Annotating a queryset Duplicating Items
I am trying to annotate a queryset so that a button can appear in the home page (Listview) what there are posts more than one and when there Posts are admin_approved=True So far the I have reached when there items in the list view with designers related to each item and in the for each post there is a user, in the queryset it checks if there posts related to the designer and these posts should by approvedby_Admin=True so that the button appears. The issue is that when a user has 2 posts one which is approved and another not approved, 2 items appears and duplication takes place in the homepage List view I have tried to use .distinct() but it didn't work items are still duplicated Here is the models.py class Post(models.Model): designer = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=100, unique=True) admin_approved = models.BooleanField(default=False) here is the views from .models import Item from django.db.models import Case, When, BooleanField class HomeView(ListView): model = Item paginate_by = 12 template_name = "home.html" ordering = ['-timestamp'] def get_queryset(self): has_post = Case( When(designer__post__isnull=False, default=False, output_field=BooleanField() ) return super().get_queryset().annotate(has_post=has_post) here is the template {% for item in object_list %} {{ item.title }} {% if item.has_post %} … -
Permission_required decorator not working on view in Django
I have an model called client, and a group called managers that has the permission "can view clients" granted in Django admin. I have a view using the permission_required decorator like so: @permission_required('client.can_view', raise_exception=True) When logged in as a user who is a member of group managers, I am unable to access the view as I get a 403 Forbidden message. Why is this? If the user is a member of the group with the appropriate permission, why is access not authorized? -
Make variables in settings.py configurable in Django admin site
In my deployed Django web backend application, some variables (e.g. react_app_url, log_level) are specified in settings.py. I can reconfigure them and make them effective by relaunching the Django app. But the relaunching procedure pauses the whole service and can affect others who is interacting with the Django APIs. It is possible to configure those variables during run time via the Django admin site? -
Deploying Keras model to use with Django project
I'm having a big data Django project with a bunch of SQL logic inside, hosted on google cloud App engine; and a Keras LSTM time series model. The project works like this: Whenever there is new data coming in (streaming), the Django app will save the incoming data and extract the relevant one. Then, the app sends that data through my Keras model to get prediction. The prediction is saved into the database, and business decisions are made. Let's focus on step 2. Could someone suggest where I should host my Keras? There are two possible ways that I can think of: a) Host the model inside the django app (can I have a reference for this?) b) Host the model on google cloud AI platform (https://cloud.google.com/ai-platform/prediction/docs/deploying-models#console) -
Exporting Date from a django model to excel sheet using XLWT
I am creating an api to export daate from model to excel sheet.But in the excel sheet output of the date is e.g(44013) not in a proper date form. models.py class Task(models.Model): Id=models.IntegerField() Name=models.CharField(max_length=50,null=False,blank=True) Image1=models.FileField(blank=True, default="", upload_to="media/images",null=True) Image2=models.FileField(blank=True, default="", upload_to="media/images",null=True) Date=models.DateField(null=True,blank=True) def __str__(self): return str(self.Name) views.py class TaskViewSet(viewsets.ViewSet): def list(self, request): try: response=HttpResponse(content_type='application/ms-excel') response['Content-Disposition']='attachment; filename="users.xls"' wb=xlwt.Workbook(encoding='utf-8') ws=wb.add_sheet('Tasks', cell_overwrite_ok=True) row_num=0 font_style=xlwt.XFStyle() font_style.font.bold=True columns=['Id','Name','Image1','Image2','Date'] for col_num in range(len(columns)): ws.write(row_num,col_num,columns[col_num],font_style) font_style=xlwt.XFStyle() data=Task.objects.values_list('Id','Name','Image1','Image2','Date') date_format=xlwt.XFStyle() date_format.num_format_str='dd/mm/yyyy' for row in data: row_num+=1 print(row) for col_num in range(len(row)): if isinstance(row[col_num],date): ws.write(row_num,col_num,row[col_num],font_style) else: ws.write(row_num,col_num,row[col_num],font_style) wb.save(response) #print(row.Date) return response except Exception as error: traceback.print_exc() return Response({"message": str(error), "success": False}, status=status.HTTP_200_OK) -
python manage.py runserver exits with 'Performing system checks'
I am trying to host my django webapp on Amazon EC2 Instance. I have cloned this repository to ec2 instance. But when i try to start the server with python manage.py runserver or python manage.py runserver 0.0.0.0:8000, it outputs 'Performing system checks' and exits without starting the server. I also created a django sample app on ec2 instance to check if django is installed properly and this sample app is starting with python manage.py runserver. I'm also activating virtualenv before starting the server. I am out of ideas, please help! settings.py ''' import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '*******************************' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'accounts', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'suggest', 'profiles', 'movies', 'rekemendo', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', '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', ] ROOT_URLCONF = 'rekemendo.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['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', …