Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
How to make connection between two django apps in two different docker containers?
I have created two apps 'myapi' and 'minombre' where the 'minombre' will make a simple GET request to 'myapi' and put them in two separate docker containers.After I run 'docker-compose up' the containers run but the api don't pass the data. The views.py of the 'minombre' where the GET request is made is given below: def index(request): response = requests.get('http://myapi') print(response) data = response.json() name = data['user'] message = data['message'] return HttpResponse('<h2> {} </h2> <br> <h5> {} </h5>'.format(name, message)) This is the docker-compose.yml that I have used to get the containers running. version: '3' services: myapi: build: ./myapi container_name: myapi ports: - "8001:8001" command: python manage.py runserver 0.0.0.0:8001 minombre: build: ./minombre container_name: minombre ports: - "8000:8000" command: python manage.py runserver 0.0.0.0:8000 depends_on: - myapi This is the exception: Exception Type: ConnectionError Exception Value: HTTPConnectionPool(host='myapi', port=80): Max retries exceeded with url: / (Caused by NewConnectionError(': Failed to establish a new connection: [Errno 111] Connection refused')) Please help me solve this problem. -
Django loop all existing record to save but only one record save
this is my code in html <tr> <td colspan="2" style="text-align: center;"><h2 style="font-weight: bold;">Required Documents:</h2></td> </tr>{% for d in doc %} <tr> <td style="text-align: left;"> <input type="file" name="myfile-{{d.id}}" value="{{d.id}}" style="outline: none;" required/>{{d.id}}{{d.Description}}</td> <td></td> </tr> {% endfor %} what I tried in my views.py myfile = request.FILES['myfile-6'] fs = FileSystemStorage() filename = fs.save(myfile.name, myfile) uploaded_file_url = fs.url(filename) insert_doc = StudentsSubmittedDocument( Students_Enrollment_Records = V_insert_data, Document = myfile ) insert_doc.save() I don't have idea on how to loop this myfile = request.FILES['myfile-6'] with the existing id of Table Documents. please help me guys, im stuck on this problem 3days -
Run Django without server
I have a small Django site, mysite. I want to be able to run my Django app without running a web server. Instead of using an HTTP client to make requests, I'd like to write something like: django.run() result = django_request('/foo/bar') So Django would still do URL parsing, etc, just not serve through UWSGI. Is this reasonable? -
How to get user data and user group from Active Directory using Django ? Using LDAP or PYAD
Anyone have idea about how to access the Active directory(AD) using python script in Django ? I need to access AD and fetch user data and user group details. Like add or remove user, assign user to specific groups, delete user data. Access AD database (ntds.dts) How to access AD ? Using LDAP or PYAD - which is better -
Writing xls from python row wise using pandas
I have sucessfully created .xlsx files using pandas but in this the writing of data is done column wise. df = pd.DataFrame({'Data': [10, 20, 30, 40, 50]}) I want to know is there a way by which I can write row wise data to xlsx sheet using pandas only? def gstin_export_xls(request): df = pd.DataFrame({'Data': [10, 20, 30, 40, 50]}) # 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=myfile.xlsx' return response Thanks! -
Button in django template doesn't put data in database
I have a app named "mysite". I want to put dummy data in database(add row) for now(originally i will be pulling data from a API) when button is clicked but button is not responding. urls.py path('', views.index), views.py from .fetch_data import get_data def index(request): if (request.method == 'POST' and 'script' in request.POST): get_data() return render(request, 'mysite/index.html') index.html in "mysite/templates/mysite" folder <form method="POST" name='script'> {% csrf_token %} <button type="submit" >Fetch data from source</button> </form> fetch_data.py from .models import Hosts import time, sys def get_data(): print('here in function') p = Hosts(hostname="first data") p.save() But when i click button, nothing happens. View should remain the same even after successful button click. Note: fetch_data.py is on same folder as views.py and urls.py. -
Django/bootstrap datepicker not working in dynamic formset
I cannot get the bootstrap datepicker to load in the new lines of a Django formset. Using inline_formsetfactory and Django-dynamic-formset package, the initial date time fields work fine, but not when adding new lines. Below is the script for adding and removing new lines. I am using the Django-Bootstrap-Datepicker-Plus package. <script type="text/javascript"> $('.formset_row-{{ formset.prefix }}').formset({ addText: '<button class="btn btn-secondary btn-sm">Add History</button>', deleteText: 'Remove', prefix: '{{ formset.prefix }}', }); </script> The calendar icons appears, but the dropdown does not. -
NoReverseMatch at /kitty_view Reverse for 'kitty' with arguments '(5,)' not found. Same url i have tried for another app and that is working
//While rendering this kitty_view I am getting this error. Exactly the same thing I have copied from another app that is working properly. Kindly help. view.py ------------------ def kitty_view(request): kitty_list = kitty.objects.all().order_by('-cretime') code1 = str(request.GET.get('Code')) name1 = str(request.GET.get('nam')) status1 = str(request.GET.get('stat')) if (name1 is not None and name1 != ''): kitty_list = kitty_list.filter(name=name1) if (code1 is not None and code1 != ''): kitty_list = kitty_list.filter(code='K00001') if (status1 is not None and status1 != ''): kitty_list = kitty_list.filter(status = 'A') ctx = {'kitty': kitty_list} return render(request, 'kitty/kitty_view.html', ctx) Url.py ----- urlpatterns = [ path('',views.index,name='index'), path('kitty_view',views.kitty_view,name='kitty_view') ] template --------- <form class="form-signin" action="{% url 'kitty_view' %}" method="get"> {% csrf_token %} <div class="form-row"> <div class="mb-3"> <select class="custom-select center-block" name="code" id="code"> <option value="">Choose Kitty...</option> <!-- <option>{{ kitty1.code }}</option> {% for i in kitty1 %} <option value="{{ i.code }}"> {{ i.code|add:' - '|add:i.name }} </option> {% endfor %} --> <option>K00004</option> <option>K00005</option> </select> </div> <div class="mb-3"> <input type="text" name="nam" id="nam" class="form-control-sm center-block" placeholder="Name" autofocus> </div> <div class="mb-3"> <select class="custom-select center-block" name="stat" id="stat" placeholder="Status"> <option value="">Choose Status...</option> <option>A</option> <option>I</option> </select> </div> <div class="mb-3"> <!-- <a href="{% url 'customer_view' %}" class="btn btn-primary btn-sm" role = "button">Search</a> --> <button type="submit" class=" btn btn-info " role="button">Search</button> </div> </div> </form> <table class="table …