Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I connect my django project with a pycharm as code editor and Mysql Database using MySqlWorkbench
I am very new with python, just started today. I'm trying to connect and migrate django project database apps to my MYSQL Database using MYSQL Workbench I have tried a several steps, but I keep getting error from one solution to another. My mysqlserver and workbench is running perfectly. enter image description here I tried to follow the steps from this website on how to connect django project to a mysql database https://www.dev2qa.com/how-to-connect-mysql-database-in-django-project/. And a couple other more steps from youtube and other sites. Now, when I try to migrate Django project apps database with this code. python manage.py migrate the first error I got was something like a version error mysqlclient 1.2.13 or newer is required; you have 0.9.3 So I read the forum Django - installing mysqlclient error: mysqlclient 1.3.13 or newer is required; you have 0.9.3 and followed all the steps that was in the forum. but nothing seems to worked. in my settings.py I have already edited the code to: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'NewConnection', 'HOST': '127.0.0.1', 'PORT': '3306', 'USER': 'root', 'PASSWORD': 'mypassword', } } and also edited the code in init.py to import pymysql pymysql.install_as_MySQLdb() but still I keep getting those … -
Cannot assign "'1'": "dropdown.drp1" must be a "basedrop" instance
I am new to django, I know similar type of error have been posted on stackoverflow but, still not able to understand what I am missing in my code.I am stuck on this from a while. I am including all my code down below. models.py class basedrop(models.Model): name = models.CharField(max_length=50,blank=False,null=False) def __str__(self): return self.name class subdrop(models.Model): name = models.CharField(max_length=100,blank=False,null=False) bsdrop = models.ForeignKey(basedrop,null=False,blank=False,on_delete=models.CASCADE) def __str__(self): return self.name class lastdrop(models.Model): name = models.CharField(max_length=100,blank=False,null=False) sbdrop = models.ForeignKey(subdrop,null=False,blank=False,on_delete=models.CASCADE) def __str__(self): return self.name class dropdown(models.Model): name = models.CharField(max_length=50,blank=False,null=False) drp1 = models.ForeignKey(basedrop,max_length=50,on_delete=models.CASCADE) drp2 = models.ForeignKey(subdrop,max_length=50,on_delete=models.CASCADE) drp3 = models.ForeignKey(lastdrop,max_length=50,on_delete=models.CASCADE) def __str__(self): return self.name forms.py class dropdownForm(forms.ModelForm): bdrop_choices = [('---------','---------')] bdrop_choices.extend([(bs.get('id'),bs.get('name')) for bs in basedrop.objects.all().values('id','name')]) drp1 = forms.ChoiceField(choices=bdrop_choices) class Meta: model = dropdown fields = '__all__' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['drp2'].queryset = subdrop.objects.none() self.fields['drp3'].queryset = lastdrop.objects.none() self.fields['name'].required = True if 'drp1' in self.data: try: country_id = int(self.data.get('drp1')) self.fields['drp2'].queryset = subdrop.objects.filter(id=country_id).order_by('name') except (ValueError, TypeError): pass elif 'drp2' in self.data: try: country_id = int(self.data.get('drp2')) self.fields['drp3'].queryset = lastdrop.objects.filter(id=country_id).order_by('name') except (ValueError, TypeError): pass elif self.instance.pk: self.fields['drp2'].queryset = self.instance.drp1.city_set.order_by('name') self.fields['drp3'].queryset = self.instance.drp2.city_set.order_by('name') views.py def create_drop(request): if request.method == 'POST': form = dropdownForm(request.POST) if form.is_valid(): form.save() return HttpResponse('<p>this is working</p>') form = dropdownForm() return render(request,'drop.html',{'form':form}) def load_subdrop(request): drp1_id = request.GET.get('drp1') subd = … -
Django select_related with condition "and"
I have a query with SELF JOINed table payment_source in views.py paymentsss = Transaction.objects.all().select_related('currency', 'payment_source__payer', 'deal__service', 'deal__service__contractor',).filter( payment_date__range=[date1, date2], ).order_by('-id') Which turns into: SELECT "processing"."transaction"."id", "processing"."transaction"."currency_id", "processing"."transaction"."deal_id", "processing"."transaction"."payment_source_id", "processing"."transaction"."payment_date", "processing"."transaction"."amount", "processing"."transaction"."status", "processing"."transaction"."context", "processing"."currency"."id", "processing"."currency"."iso_name", "processing"."currency"."minor_unit", "processing"."deal"."id", "processing"."deal"."service_id", "processing"."service"."id", "processing"."service"."contractor_id", "processing"."service"."name", "processing"."service"."description", "processing"."contractor"."id", "processing"."contractor"."name", "processing"."payer_payment_source"."id", "processing"."payer_payment_source"."payer_id", "processing"."payer_payment_source"."payment_type_id", "processing"."payer_payment_source"."source_details", T7."id", T7."payer_id", T7."payment_type_id", T7."source_details" FROM "processing"."transaction" LEFT OUTER JOIN "processing"."currency" ON ("processing"."transaction"."currency_id" = "processing"."currency"."id") LEFT OUTER JOIN "processing"."deal" ON ("processing"."transaction"."deal_id" = "processing"."deal"."id") LEFT OUTER JOIN "processing"."service" ON ("processing"."deal"."service_id" = "processing"."service"."id") LEFT OUTER JOIN "processing"."contractor" ON ("processing"."service"."contractor_id" = "processing"."contractor"."id") LEFT OUTER JOIN "processing"."payer_payment_source" ON ("processing"."transaction"."payment_source_id" = "processing"."payer_payment_source"."id") LEFT OUTER JOIN "processing"."payer_payment_source" T7 ON ("processing"."payer_payment_source"."payer_id" = T7."id") I want to add a condition and, to get it: LEFT OUTER JOIN "processing"."payer_payment_source" T7 ON ("processing"."payer_payment_source"."payer_id" = T7."id" and T7."payment_type_id" = 'bank_card_details') models.py class PayerPaymentSource(models.Model): id = models.BigIntegerField(blank=True, null=False, primary_key=True) payer = models.ForeignKey("self", null=True, on_delete=models.CASCADE, ) payment_type = models.ForeignKey(PaymentType, max_length=64, blank=True, null=True, on_delete=models.CASCADE) source_details = models.TextField(blank=True, null=True) class Meta: managed = False db_table = '"processing"."payer_payment_source"' class Transaction(models.Model): id = models.BigIntegerField(blank=True, null=False, primary_key=True) currency = models.ForeignKey(Currency, null=True, on_delete=models.CASCADE) deal = models.ForeignKey(Deal, null=True, on_delete=models.CASCADE) # service_instance = models.ForeignKey(ServiceInstance, null=True, on_delete=models.CASCADE) payment_source = models.ForeignKey(PayerPaymentSource, null=True, on_delete=models.CASCADE) payment_date = models.DateTimeField(blank=True, null=True) amount = models.IntegerField(blank=True, null=True) class Meta: managed = False db_table … -
how to add bg video file in js using Django
I'm trying to add background video to my Django website using Bideo library but when I load the page it returns 404 error for my video file here's my code how can I point to bgvideo.mp4 in video directory? /mywebsite /ctrlcntr /static /video bgvideo.mp4 /js Bideo.js theme.js (function () { var bv = new Bideo(); bv.init({ // Video element videoEl: document.querySelector('#home_main_pic'), // Container element container: document.querySelector('body'), // Resize resize: true, // autoplay: false, isMobile: window.matchMedia('(max-width: 768px)').matches, playButton: document.querySelector('#play'), pauseButton: document.querySelector('#pause'), // Array of objects containing the src and type // of different video formats to add src: [ { src: '../video/bgvideo.mp4', type: 'video/mp4' }, { src: '../video/bgvideo.webm', type: 'video/webm;codecs="vp8, vorbis"' } ], // What to do once video loads (initial frame) onLoad: function () { document.querySelector('#video_cover').style.display = 'none'; } }); }()); -
Password Reset activation Link
I have 2 views . 1) For user Registration . 2) For Password Reset. Activation Link for both task is generated and send to mail. My activation link for first time registration is working fine . When I create my activation Link for password Reset , It is not get expired after use. @csrf_protect def changing_password_confirmation(request, uidb64, token): try: uid = force_bytes(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except(TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None and passord_reset_token.check_token(user, token): print('user is not None and passord_reset_token.check_token(user, token)') if request.method == 'POST': password1 = request.POST.get('password1') password2 = request.POST.get('password2') if password1 == password2: user.set_password(password1) user.save() return render(request=request, template_name='website/password_reset_complete.html') else: return HttpResponse('<h1>Password doesnt match</h1>') return render(request=request, template_name='website/password_reset_confirm.html') else: print('User', user) result = 'Activation link is invalid!' return render(request=request, template_name='website/password_reset_confirm.html', context={'result': result}) from django.contrib.auth.tokens import PasswordResetTokenGenerator from django.utils import six class TokenGenerator(PasswordResetTokenGenerator): def _make_hash_value(self, user, timestamp): return ( six.text_type(user.pk) + six.text_type(timestamp) + six.text_type(user.is_active) ) class PasswordTokenGenerator(PasswordResetTokenGenerator): def _make_hash_value(self, user, timestamp): return ( six.text_type(user.pk) + six.text_type(timestamp) + six.text_type(user.is_active) ) account_activation_token = TokenGenerator() passord_reset_token = PasswordTokenGenerator() Reset Password Template {% extends "website/header.html" %} {% block title %}Enter new password{% endblock %} {% block content %} {% if validlink %} <h1>Set a new password!</h1> <form method="POST"> {% … -
Change src attribute in <img> tag created by ckeditor in django
I am using django-ckeditor which includes image upload. Code created by editor is following: <p><img alt="" class="img-fluid" height="687" src="/media/uploads/2019/11/04/yoga_m.jpg" width="1030" /></p> I have added class="img-fluid" by this JS code: CKEDITOR.on('instanceReady', function (ev) { ev.editor.dataProcessor.htmlFilter.addRules( { elements : { img: function( el ) { // Add bootstrap "img-responsive" class to each inserted image el.addClass('img-fluid'); } } }); }); problem is I have to send content in API and I need absolute path in src (src="http://127.0.0.1:8000/media/uploads/2019/11/04/yoga_m.jpg" not src="/media/uploads/2019/11/04/yoga_m.jpg") Can anyone help please? -
Unique filename of uploaded file using the django FORM
I'm trying to generate a unique filename for the uploaded file using the Django forms. I've tried uuid_upload_path app but that app doesn't work with the form. Below is my code Forms.py class HelpGuideForm(forms.ModelForm): title = forms.CharField(max_length = 50) image = forms.ImageField(required = False) class Meta: model = Helpguide fields = ['title', 'image'] I want a unique name for all uploaded files. something like sd564sadasd61.jpg. I'm using Django 2.2 -
Django refrence non field value at database level
class Author(models.Model): ... class Book(models.Model): author = models.ForeignKey(Author) book_seq = models.PositiveIntegerField() class Meta: unique_together = ('author', 'book_seq') def create_book_for_author(cls, author): book_seq = Book.objects.filter(author=author).count() + 1 Book.objects.create(author=author, book_seq=book_seq) Is there any way to reference this book_seq = Book.objects.filter(author=author).count() + 1 at database level because if this line concurrently then the unique constraint will fail and the second one to reach the database with insert query will fail. I know one option is transaction but is there any other way? F() object only works with concrete field not with database query. -
Django get ForeignKey of not created object
I have Post and UploadFile models: class Post(models.Model): title = models.CharField(max_length=150) content = models.TextField() author = models.ForeignKey(settings.AUTH_USER_MODEL, default=1, on_delete=models.CASCADE, related_name="post_author") objects = PostManager() UploadFile object link to Post via ForeignKey class UploadFile(models.Model): file = models.FileField(null=True, blank=True, upload_to='files/', ) post = models.ForeignKey(Post, on_delete=models.CASCADE, null=True, related_name="file_post") I am creating a post in the editor on the admin page. For this I use RichTexteditor Tinymce. The fact is that when I'm creating a post in the editor, the UploadFile object (file) is immediately uploaded to the server via Ajax request and wants to refer to the post object. But the post object has not been created since I am editing it. How to solve this problem? While ForeignKey is not assigned(null=True). Could it be to rewrite the save method or use post_save signals, or update the ForeignKey value of Uploadfile.post after creating the post object? But I do not know how to implement this yet. This is the file upload handler function in views.py. @require_POST def file_upload(request): reqfile = UploadFile.objects.create(file=request.FILES['file']) return JsonResponse({'fileurl': reqfile.file.url}) -
Django rest framework response if exists
I want to show an error when trying to create a profile but user already has one in my views.py class ProfileViewSet(viewsets.ModelViewSet): serializer_class = ProfileSerializer def get_queryset(self): queryset = Profile.objects.filter(owner=self.request.user) return queryset def get_permissions(self): permission_classes = [] if self.action == 'create': permission_classes = [IsAuthenticated] elif self.action == 'retrieve' or self.action == 'update' or self.action == 'partial_update': permission_classes = [IsOwner] elif self.action == 'list': permission_classes = [IsAuthenticated] elif self.action == 'destroy': permission_classes = [IsAdminUser] return [permission() for permission in permission_classes] def perform_create(self, serializer): profile = Profile.objects.filter(owner=self.request.user) if not profile.exists(): serializer.save(owner=self.request.user) else: return Response(data={'detail': 'This user already has a profile'}, status=status.HTTP_400_BAD_REQUEST) when I create a profile on a user who already has one I don't get to show the error -
Expandable Lists with Django
I'm currently developing a small web app with Django, where user can search for cards in a trading card game and the results shall be shown in a list. Since there could be quite a lot of results returned I thought of doing a dynamic list where only 50 items a time are shown and then the user can select the next 50 results via a button. Is there a specific Django way of doing this? This his how the page currently looks like (and I would prefer to have the button for the next results on the end of the page): -
How to aggregate in cross-tab style items in a linked model to its parent?
I wish to construct a cross-tab view from the model structure shown below. I want a matrix with Calendar dates down the LHS, Course names across the top, and something in each cell denoting presence of a Booking instance on that date/course. Simplified model structure: class Calendar(models.Model): crCalDate = models.DateField(primary_key=True) class Course(models.Model): ceName = models.CharField() class CourseBooking(models.Model): cbCourse = models.ForeignKey(Course, on_delete=models.CASCADE, related_name='booked_course') cbDay = models.ForeignKey(Calendar, on_delete=models.CASCADE, related_name='booked_day') My view function's queryset at present: class DayView(ListView): def get_queryset(self): # construct index of course tuples course_index = [(cn['id'], 'course' + str(i)) for i, cn in enumerate(Course.objects.order_by('id').values('id'))] coursebookings = CourseBooking.objects.filter(cbDay__crCalDate__gte=dt.datetime.today()).values('id', 'cbDay__crCalDate', 'cbCourse__id', 'cbCourse__ceName') calendar_dates = list(Calendar.objects.filter(crCalDate__gte=dt.datetime.today()).order_by('crCalDate').values('crCalDate', 'crSunrise', 'crSunset')) for cb in coursebookings: for i, cal in enumerate(calendar_dates): if cal['crCalDate'] == cb['cbDay__crCalDate']: course = [ci[1] for ci in course_index if ci[0] == cb['cbCourse__id']] if course: calendar_dates[i][course[0]] = 'Occupied' break return calendar_dates This all feels rather tedious and expensive, and I wonder am I going about this the wrong way, having unsuccessfully tried annotate() and aggregate() functions to achieve a suitable summary query. As a bonus, I really want to be able to show the number of booking lines for each Course on each Calendar day, rather than the text I presently insert there. The … -
Django manage.py: error: unrecognized arguments: runserver
My django Application with Gmail_Api is not working properly which causes the error in starting the server I Googled and tried this .. manage.py: error: unrecognized arguments: runserver 8000, Google Analytics API Django but still it is not working ```python def Gmail_Call(): try: import argparse flags = tools.argparser.parse_args([]) except ImportError: flags = None SCOPES = 'https://www.googleapis.com/auth/gmail.send' CLIENT_SECRET_FILE = 'credentials.json' APPLICATION_NAME = 'reportingtool' authInst = auth.auth(SCOPES,CLIENT_SECRET_FILE,APPLICATION_NAME) credentials = authInst.get_credentials() http = credentials.authorize(httplib2.Http()) service = discovery.build('gmail', 'v1', http=http) from . import Gmail_Msg_Function as from_google sendInst = from_google.send_email(service) msg = sendInst.create_message(sender='frommail_ID@gmail.com',to='tomail_ID@gmail.com',subject='test mail',message_text='testmsg') sendInst.send_message(user_id='me',message=msg) ``` C:\Users\www\Desktop\New\Project>python manage.py runserver Watching for file changes with StatReloader Performing system checks... usage: manage.py [-h] [--auth_host_name AUTH_HOST_NAME] [--noauth_local_webserver] [--auth_host_port [AUTH_HOST_PORT [AUTH_HOST_PORT ...]]] [--logging_level {DEBUG,INFO,WARNING,ERROR,CRITICAL}] manage.py: error: unrecognized arguments: runserver -
Django permissions.IsAuthenticated can check on middleware
I have issue with django middlware I am try to implement permissions.IsAuthenticated in django custom middlware if any solution please provide me. I am unable to solve issue authontication with middleware -
How to ask if table1.id == table2.id inside for?
I want to identify if table1.id_sitio and table2.id_sitio are the same to do A in the template. If not do B I think my if sentence is wrong... This is my first try on Django so maybe im missing something This is what i have tried and my code: Models.py class Comprobante(models.Model): id_sitio = models.ForeignKey('Sitio', models.DO_NOTHING, db_column='id_sitio', blank=True, null=True) class Sitio(models.Model): id_sitio = models.IntegerField(primary_key=True) sitio = models.CharField(max_length=100, blank=True, null=True) def __str__(self): return self.sitio Views.py def topsitios(request): sitio = Sitio.objects.all()[0:100] comprobante = Comprobante.objects.all()[0:100] context = {'sitio': sitio, 'comprobante': comprobante} return render(request, "sitio_ptc/topsitios.html", context) Template.html {% block content %} {% for s in sitio %} <tr> <th scope="row"> {{ forloop.counter }}</th> <td> {{ s.sitio }} </td> <td> {% for c in comprobante %} {% if s.id_sitio == c.id_sitio %} comprobante ok {% else %} no payments {% endif %} {% endfor %} </td> </tr> {% endfor %} {% endblock %} -
How can I display the column ID in the django-admin users table?
How can I show besides the columns username, email, first name, last name, staff user a 5th column with the users ID. I think I have to write some code into admin.py like: class CustomUserAdmin(UserAdmin): readonly_fields = ('id',) admin.site.register(CustomUserAdmin) -
How do I declare new app in Django rest framework? It seems everything is OK but i have RuntimeError
I want to declare new app in python using Django rest framework. I declared new model and then create a line in INSTALLED_APPS configuration class in the settings.py file. Here is my INSTALLED_APPS configuration class: INSTALLED_APPS = [ 'sarox.apps.SaroxConfig', ... ] My new app declared like this in sarox/apps.py from django.apps import AppConfig class SaroxConfig(AppConfig): name = 'sarox' But when I run python manage.py runserver 0.0.0.0:2281 command it raises an run time error: E:\MyApps\Plot\djrest>python manage.py runserver 0.0.0.0:2281 Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\AMoha\AppData\Local\Programs\Python\Python37\lib\threading.py", line 926, in _bootstrap_inner self.run() File "C:\Users\AMoha\AppData\Local\Programs\Python\Python37\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\AMoha\AppData\Local\Programs\Python\Python37\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "C:\Users\AMoha\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "C:\Users\AMoha\AppData\Local\Programs\Python\Python37\lib\site-packages\django\utils\autoreload.py", line 77, in raise_last_exception raise _exception[1] File "C:\Users\AMoha\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "C:\Users\AMoha\AppData\Local\Programs\Python\Python37\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "C:\Users\AMoha\AppData\Local\Programs\Python\Python37\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\AMoha\AppData\Local\Programs\Python\Python37\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\AMoha\AppData\Local\Programs\Python\Python37\lib\site-packages\django\apps\config.py", line 116, in create mod = import_module(mod_path) File "C:\Users\AMoha\AppData\Local\Programs\Python\Python37\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in … -
Adding two fields from two different modules django module
I’m making a stock management app where I would like to add a class field quantity (value) with a quantity_prod field from module production. The result of this operation should populate another field quantity_in_stock in the class Article. I have tried the annotate with the F expression and the override save method with article_set but I don’t find a good result I’m wondering if there is a direct method to make mathematic operation between fields without using a complex method class Article(models.Model): code = models.CharField(max_length=20, blank=False, default='0216') designation = models.CharField(max_length=200, blank=False) unit = models.CharField(max_length=10, choices=choices_unite, default='') quantity = models.FloatField(default=0) quantity_in_stock = models.FloatField(default=0) def __str__(self): return self.designation class ProductionArticle(models.Model): article = models.ForeignKey(Article, on_delete=models.CASCADE) planned quantity = models.FloatField(default=0) production date = models.DateTimeField(default=timezone.now, verbose_name="Date d'ajout") unit = models.CharField(max_length=10, choices=choices_unite, default='') operator = models.CharField(max_length=200, default='Ahmed') quantity_prod = models.FloatField(defaut=0) -
How to annotate a field from a related model to queryset?
I have two models: Lot: class Lot(models.Model): name = models.CharField(max_length=150, db_index=True, unique=True) step = models.DecimalField(max_digits=2, decimal_places=2) and Bid: class Bid(models.Model): auction = models.ForeignKey('Lot', on_delete=models.CASCADE) user_id = models.ForeignKey(User, on_delete=models.CASCADE, to_field='username') value = models.DecimalField(max_digits=5, decimal_places=2) Every instance of Lot can have a few Bids, however any instance of Bid is only related to a particular Lot. I have a working annotation for Lot that gives me the max_bid and next_bid values: self.auc_set = Lot.objects.annotate(max_bid=Max('bid__value'), next_bid=(Max('bid__value') + F('step'))) And what i can't achieve is getting 3 annotated fields: max_bid, next_bid and last_bidder. Something like: self.auc_set = Lot.objects.annotate(max_bid=Max('bid__value'), next_bid=(Max('bid__value') + F('step')), last_bidder=F(bid_set).get('auction_id'= F('id'), 'value'=max_bid)['user_id']) but working. -
Django + Postgre + highcharts
how to counting row on postgresql database from django and show using highchart? ex: i wanna show how much record/row from 7.00am to 7.00 am next day. models : from django.db import models from datetime import datetime, date class hujan(models.Model): id = models.AutoField(primary_key=True) tanggal = models.DateTimeField(auto_now_add=True) dtinms = models.IntegerField() hujan = models.FloatField() serializers : from rest_framework import serializers from .models import hujan, cahayasuhukelembapan class hujanSerializer(serializers.ModelSerializer): class Meta: model = hujan fields = ('tanggal','dtinms','hujan') views : from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse, JsonResponse from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.renderers import TemplateHTMLRenderer from .models import hujan from .serializers import hujanSerializer def homePageView(request): return render(request,'homepage.html') class hujanlistall(APIView): def get(self, request): Hujan = hujan.objects.all() serializer = hujanSerializer(Hujan, many=True) return JsonResponse(serializer.data,safe=False) -
Writing xls from python row wise using pandas
I have sucessfully created .xlsx files using pandas df = pd.DataFrame([list of array]) ''' :param data: Data Rows :param filename: name of the file :return: ''' df = pd.DataFrame(data) # my "Excel" file, which is an in-memory output file (buffer) # for the new workbook excel_file = BytesIO() writer = pd.ExcelWriter(excel_file, engine='xlsxwriter') df.to_excel(writer, sheet_name='Sheet1_test') writer.save() writer.close() # important step, rewind the buffer or when it is read() you'll get nothing # but an error message when you try to open your zero length file in Excel excel_file.seek(0) # set the mime type so that the browser knows what to do with the file response = HttpResponse(excel_file.read(), content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') # set the file name in the Content-Disposition header response['Content-Disposition'] = 'attachment; filename=' + filename + '.xlsx' return response But I have issue here, There is unnecessary SNo. which i dont want, how to do I remove that. There is SNo. as first row and column, How do i remove that? -
Limit ModelForm choices to options from a specific model
I tried this approached to allow project_id to be dynamic, but i get an error:"init() missing 1 required positional argument: 'project_id'". forms.py class CreateCostForm(forms.ModelForm): def __init__(self,project_id,*args, **kwargs): super(CreateCostForm, self).__init__(*args, **kwargs) self.fields['cost_name'].queryset = ProjectCost.objects.filter(project_name_id=project_id) class meta: model = ProjectCost When i hard-code the value of project_id like: self.fields['project_name'].queryset = ProjectCost.objects.filter(project_name_id=4) or ProjectCost.objects.filter(project_name_id= 8), i get the correct filtered options on the form.So how can i make project_id dynamic? Thanks. -
Setup a static homepage in django
I am building a website where part of it is normal static (pure HTML) pages (about, FAQ, and contact info) How to arrange the URLS so that those pages don't use Django dynamic engine? -
Is there any built-in functionality in django to call a method on a specific day of the month?
Brief intro of the app: I'm working on MLM Webapp and want to make payment on every 15th and last day of every month. Calculation effect for every user when a new user comes into the system. What I do [ research ] - using django crontab extension Question is: -- Concern about the database insertion/update query: on the 15th-day hundreds of row generating with income calculation for users. so is there any better option to do that? how to observe missed and failed query transaction? Please guide me, how to do this with django, Thanks to everyone! -
how do I fix or change redirect url in the "begin proccess" for django social auth
I am using django-social, the problem is when I want to begin the process of authenticating with google-oauth2 by using the below request: http://example.com:8080/social-auth/login/google-oauth2/ it will get mismatch error from google, the error is occurring because my Django application is running with a port, but I can see the real request to google is something like this: https://accounts.google.com/o/oauth2/auth?client_id=XXX&redirect_uri=http://example.com/social-auth/complete/google-oauth2/&state=xxx&response_type=code&scope=openid+email+profile so obviously redirect_uri was set to http://example.com/social-auth/complete/google-oauth2/ without port I mean. in the above request, redirect_uri is not same with something I set in google-console for redirecting, in google console I've set: http://example.com:8080/social-auth/complete/google-oauth2 , because my application is running with port:8080 so with which setting or something I can tell social auth to set redirect url has a port? in addition, my Django app is running by a docker-composer file.