Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
React Axios - download excel file from Django backend
I am trying to download excel file which is generated by Django backend: class GenerateExcel(APIView): def get(self, request): filename = 'File.xlsx' wb = Workbook() ws = wb.active ws.title = "Workbook" response = HttpResponse(save_virtual_workbook(wb), content_type='application/ms-excel') response["Content-Disposition"] = 'attachment; filename="' + filename + '"' return response If I send request with a postman I get success response and I can download the file via option Save Response -> Save to a file and it works fine. If I try to download it in my frontend with axios I am able to download the excel file but it has different size then the file from a postman and it is not possible to open the excel file. I receive the file is corrupted error. I am using redux so this code is in actions file: export const getYhrtaskgrpExcel = (fromDate, toDate) => async dispatch => { const url = `http://127.0.0.1/excel-report/`; try { dispatch({ type: GET_EXCEL_REQUEST }); const res = await axios.get(url, {responseType: 'arraybuffer'}) dispatch({ type: GET_EXCEL_SUCCESS, payload: res.data }); console.log('this is data: ', res.data); var FileSaver = require('file-saver'); var blob = new Blob([res.data], {type:'application/ms-excel'}); FileSaver.saveAs(blob, "excel.xlsx"); } catch (error) { dispatch({ type: GET_EXCEL_FAIL, payload: error.data }); } } -
How to use Logstash to import data to Django?
I have a Django application which acts as an bridge between multiple data resources using ETL and CRUD tasks; monitor a resource for new or updated data (input) ingest & transform the data using business logic store the transformed data in a PostgresSQL database use Django model signals to automatically queue CRUD operations to sync data with another external resource (output) execute all queued CRUD operations against the other external resource The amount of application coded dedicated to monitoring, ingesting, and transforming the incoming data is non-trivial. As ETL requirements grow and new input resources are added, I would like to minimize or eliminate the need for building more ETL-related application code. It seems like Logstash might be a good candidate for this, since it can monitor external resources and automatically extract and load data and pass it on to some other resource. On Google, I am seeing plenty of tutorials on how to use Logstash to import data from a database such as PostgreSQL and keep Logstash in sync with other relational databases. There are also plenty of tutorials on how to use Logstash to import Django logs to something like ElasticSearch. However I am not seeing any recommended … -
Calling serializer.save() on a list of serialisers Django
I'm trying to save objects for a list of serialised data in my views: myData1 = {...} myData2 = {...} mySerial1 = MySerializer(data=myData1) mySerial1.is_valid(raise_exception=True) mySerial2 = MySerializer(data=myData2) mySerial2.is_valid(raise_exception=True) saveList = [mySerial1, mySerial2] for serial in saveList: serial.save() Unfortunately I'm getting this error: AttributeError: 'function' object has no attribute 'save' Is there something I'm missing in how I try to save an object using serialised data? -
Return the total of a group with Jinja
I have an object to return by group and then display the number of grouped items. example : <table> <thead> <tr> <th>Name</th> <th>Total</th> </tr> </thead> <tbody>> {% set count = 0 %} {% for item in data.items|groupby(attribute="name") %} <tr> <td>{{ item.grouper }}</td> <td>{% for number in item.list %}{% set count = count + 1 %}{{ count }}{% endfor %}</td> </tr> {% endfor %} </tbody> </table> I also tried : <table> <thead> <tr> <th>Name</th> <th>Total</th> </tr> </thead> <tbody>> {% for item in data.items|groupby(attribute="name") %} <tr> <td>{{ item.grouper }}</td> <td>{% for number in item.list %}{{ loop.length }}{% endfor %}</td> </tr> {% endfor %} </tbody> </table> But the return for a total of 3 is: "111" or "333" and i want display "3", avez-vous une idée ? -
Filter by annotated array's length
class Language(models.Model): iso_code = models.CharField() class Publisher(models.Model) name = models.CharField() class Book(modle.Model): name = models.CharField() language = models.ForeignKey(Language) publisher = models.ForeignKey(Publisher, related_name='books') lang_ids = [1,2] qs = Publisher.objects.annotate( x=ArrayAgg( Case( When( books__language__in=lang_ids, then="books__name" ) ) ) ) I want to filter the qs as shown here - https://docs.djangoproject.com/en/3.1/ref/contrib/postgres/fields/#len qs.filter(x__len=2) Why is it impossible to filter the qs this way? I am getting an error IndexError: tuple index out of range. Output field in ArrayAgg is ArrayField class ArrayAgg(OrderableAggMixin, Aggregate): function = 'ARRAY_AGG' template = '%(function)s(%(distinct)s%(expressions)s %(ordering)s)' allow_distinct = True @property def output_field(self): return ArrayField(self.source_expressions[0].output_field) def convert_value(self, value, expression, connection): if not value: return [] return value -
Can't login to Django admin panel
Made custom user, made custom user manager, can't log in into Django admin panel Tried (means don't offer it): manage.py synced manage.py createsuperuser checked that my users actually is staff and active set AUTHENTICATION_BACKENDS to 'django.contrib.auth.backends.ModelBackend' set AUTH_USER_MODEL = 'users.User' DB - postgres, im also using rest framework models.py from django.contrib.auth.base_user import BaseUserManager, AbstractBaseUser from django.contrib.auth.models import PermissionsMixin from django.db import models, transaction # Create your models here. class UserManager(BaseUserManager): """ Custom user model manager where email is the unique identifiers for authentication instead of usernames. """ def create_user(self, deviceId, **extra_fields): """ Create and save a User with the given email and password. """ if not deviceId: raise ValueError('The device id must be set') user = self.model(deviceId=deviceId, **extra_fields) user.save() return user def create_superuser(self, deviceId, **extra_fields): """ Create and save a SuperUser with the given email and password. """ extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self.create_user(deviceId, **extra_fields) class User(AbstractBaseUser, PermissionsMixin): deviceId = models.TextField(max_length=255, unique=True, db_column='device_id') email = models.EmailField(max_length=255, unique=True, null=True) password = models.CharField(max_length=255, blank=True, null=True) name = models.CharField(max_length=255, db_column='name') fcmToken = models.TextField(blank=True, null=True, db_column='fcm_token') picture = models.ImageField(upload_to='UserAvatars', null=True) pictureUrl = … -
importing data into django model
i'm having so many issues with timezones its insane. following this thread, i've written a python script that passes the contents of the input file into my django model, but given how much i'm struggling with this i'm wondering if the Models.object.create() function is a good way of loading the data in. for context, i'm using python2.7 and django 1.6.11. this is my models.py: ORDER_STATUS = ( ('NC', 'NoCar'), ('UC', 'UserCancelled'), ('CC', 'Completed') ) PAYMENT_METHOD = ( ('CA', 'cash'), ('CC', 'creditCard'), ) class Member(models.Model): member_hash = models.CharField(max_length=32) member_loc_lat = models.FloatField(max_length=20) member_loc_long = models.FloatField(max_length=20) # blank to be able to pass in null values, null to tell the DB to accept null values member_locality = models.TextField() member_display_name = models.TextField() member_created_time = models.DateTimeField(auto_now=False, auto_now_add=False) def __str__(self): return self.member_id class Driver(models.Model): driver_hash = models.CharField(max_length=32, unique=False, null=True) # docs say null=True shouldn't be specified on CharField class Order(models.Model): # status and payment method defined above status = models.CharField(max_length=2, choices=ORDER_STATUS, default='NC', db_index=True) payment = models.CharField(max_length=2, choices=PAYMENT_METHOD, default='CA', db_index=True) order_id = models.CharField(max_length=32, primary_key=True) tips = models.BigIntegerField(unique=True) special_req = models.CharField(max_length=100) order_ended_time = models.DateTimeField(auto_now=False, auto_now_add=False) member = models.ForeignKey(Member, null=True, default=None) driver = models.ForeignKey(Driver, null=True, default=None) and this is the script, load.py, that loads my raw data into models.py: … -
Place (?) tooltip next to field-name Django
In my_model I have field1 and field2. In my form I would like to have a (?) tool-tip next to the label of field2 such that I can display some tooltips for it when users hover over the (?). I have found something which works in a html-file but I don't really know how to load the labels from the html file to the label class MyModelForm(forms.ModelForm): class Meta: model = my_model fields = ["field1","field2"] labels = {"field2":load_html("my_hmtl_file.html") Is there a better way to add this (?) tool-tip to a field(s)? -
How to sort queryset based on foreign key with no duplicates
I would like to feature the 5 most recently reviewed books on my website. I am trying to order the books based on the time they were reviewed. The problem is if a book has recently been reviewed more than once, it will appear more than once. How do I get 5 unique books from this query? (I tried adding .distinct() to the query and it didn't work!) reviewed = Book.objects.order_by('-review__date_posted')[:5] -
Real estate website in Django. How to build some functions?
I had a question about Django. I want to create a real estate website where people can publish their homes by themselves? So, How can I do this? What do you recommend me to do? -
How does deploying a project to a subdomain work?
I am familiar with deploying a Django project to its own domain, however I am not familiar with deploying to a subdomain (app.domain.com) where domain.com is pointing to another site. I can't seem to find any support in the docs on this, so do I just deploy this as usual or are there extra steps needed to ensure all my URLS are resolvable & the app functions as it should? -
how to create an ubuntu environment when using Docker on MAC computer with django
I am super new to Docker and i am trying to grasp a concept. Goal: I am trying to create this tech stack create a Ubuntu OS install python install django/DRF install postgresql install reactJS So far I have only been able to install python, django... Dockerfile FROM python:3.7 ENV PYTHONUNBUFFERED 1 WORKDIR /code COPY requirements.txt /code RUN pip install -r requirements.txt COPY . /django-docker/ Docker compose version: '3.7' services: web: build: . command: python /code/manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - 8000:8000 My question is mainly on how do I install or add Ubuntu on the tech stack mentioned above or is it really necessary to have Ubuntu if i intend to deploy my tech stack to AWS in the future so other developers work on the same project quickly when they setup their machines? -
Calculate total price from selected menu
I created a restaurant web using django frameworks. so i have a problem when i want to calculate all the menu prices are selected. This is the simple Flowchart: Login → user selecting customer → create customer order → billing but i not yet create the billing here this my models.py from django.db import models from django.contrib.auth.models import User class Menu(models.Model): name = models.CharField(max_length=255) price = models.FloatField() def __str__(self): return self.name + ', Rp ' + str(self.price) + '00' class Customer(models.Model): name = models.CharField(max_length=255) slug = models.SlugField(default='', max_length=255) gender = models.CharField(max_length=255) phone = models.CharField(max_length=255) address = models.TextField() def __str__(self): return self.name + ', phone = ' + self.phone def absolute_url(self): return self.slug class Order(models.Model): menu = models.ManyToManyField(Menu, related_name='order') customer = models.ForeignKey(Customer, on_delete=models.CASCADE) total_prc = models.FloatField() user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.customer + ', total price = ' + self.total_prc class Transaction(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE) total = models.FloatField() paid = models.FloatField() def __str__(self): return self.order so the menu and order models that i've been create with many to many relationship then form.py for the create customer order menu_choices = Menu.objects.all().values_list('pk', 'name') menu_choices_list = [] for menu in menu_choices: menu_choices_list.append(menu) class CreateOrder(forms.ModelForm): class Meta: model = Order fields = … -
Django admin display only one option in a drop down list created via the use of foreign key depending on the logged in user
Am using django admin dashboard to manage both customers and admin in an online mall. The customers are the owners of the shop while the admin is the one who creates customers and assign shops to them. models.py class Shop(models.Model): name = models.CharField(max_length=20) class Product(models.Model): name = models.ForeignField(Shop) After creating a customer, the admin gives the customers the permissions to add, view, edit, and delete products. When the customer logs into the same admin dashboard he is able to add, view, edit, and delete products. The problem is when it comes to selection of a shop to add products to, the customer is able to see other shops hence data leakage. Also the customer is able to view products of other shops when the he clicks the products -
raise DecodeError( jwt.exceptions.DecodeError: It is required that you pass in a value for the "algorithms" argument when calling decode()
I see this raise DecodeError( jwt.exceptions.DecodeError: It is required that you pass in a value for the "algorithms" argument when calling decode(). when i am trying to decode like this class UserView(APIView): def get(self,request): token = request.COOKIES.get('jwt') if not token: raise AuthenticationFailed('Unauthenticated!') try: payload = jwt.decode(token,'secret', algorithm=["HS256"]) except jwt.ExpiredSignatureError: raise AuthenticationFailed('Unauthenticated!') user = User.objects.filter(id=payload['id']).first() serializer = UserSerializer(user) return Response(serializer.data) Its mainly happening for this line: payload = jwt.decode(token,'secret', algorithm=["HS256"]) Do you have any suggestion for this. I am struggling with this issue. Any suggestion will be great help. Solutions i got so far: 1 downgrade jwt version to PyJWT==1.7.1. 2. downgrade azureml-core==1.18.0.post1 (is this necessary?) do i need to perform these 2. since i am using jwt 2.0.1 will it acceptable if i downgrade my jwt to fit with the only current issue of saying decodeerror. Thanks, -
How can I monitoize my django rest api requests
Hi I have a django rest api for my android app. I would like to monitorize requests. Also I am using nginx. How can I do it with open source tools. -
Django Rest Framework - @csrf_exempt not working with custom JWT-HTTPOnly Cookie authentication
Forgive me if this question was already posted, I could not find a solution for hours so felt a need to ask here. I am doing custom authentication for DRF where JWT Token will be set as HTTP-Only cookie and alongside CSRF token will be set as simple cookie so that I can read it with JS and add to header. So the code is as below. Authentication works and CSRF check is done only for unsafe methods however now, csrf_exempt decorator is not working. I have tried it with almost all the possible ways, setting it over dispatch method, other methods, created func based views and added there but still csrf is required. I think after diving deep in Django source code I found the problem is related that I am calling process_view function and givin callback_view as None so the check is returning false. In anyway, I would like to know how I can solve this issue? import jwt from rest_framework.authentication import BaseAuthentication from django.middleware.csrf import CsrfViewMiddleware from rest_framework import exceptions from django.conf import settings from django.contrib.auth import get_user_model class CSRFCheck(CsrfViewMiddleware): def _reject(self, request, reason): # Return the failure reason instead of an HttpResponse return reason class MyJWTAuthentication(BaseAuthentication): … -
PypeR suddenly stops working when two or more users use it
I am using Pyper as a way to connect Python to R using Django framework ,I am using it in a way that i am running r script through pyper using r.run("source('"+path2script+"')"). But i am running into an issue where pyper suddenly stops when two or more users try to access it. I do not understand why it is happening and how pyper stops suddenly. Also r script i am using performs lot of calculations. My idea is calculation is filling the r session and then pyper stops. Can anybody help me with this. Thanks in advance. -
How can I reduce the number of SQL queries in my view?
I have a functional view but it makes too many SQL queries and I can't optimize it to reduce the number of SQL queries. My Model : class MbGroups(models.Model): """ groups for users """ name = models.CharField("Nom", max_length=70) club = models.ForeignKey("clubs.Club", verbose_name="Club", on_delete=models.CASCADE) peoples = models.ManyToManyField(User, verbose_name="Liste des personnes", blank=True, related_name="groups_user") parent_group = models.ForeignKey("utilisateurs.MbGroups", related_name="sub_group", blank=True, null=True, verbose_name="Groupe parent", on_delete=models.CASCADE) level = SmallIntegerField(verbose_name="niveau", default=0) @property def has_subgroup(self): return MbGroups.objects.filter(club=self.club) \ .filter(parent_group=self) \ .exists() class Meta: verbose_name = "Groupe ou sous groupe" verbose_name_plural = "Groupes ou sous groupes" ordering = ['name'] def __str__(self): full_path = [self.name] k = self.parent_group while k is not None: full_path.append(k.name) k = k.parent_group return ' -> '.join(full_path[::-1]) def save(self, *args, **kwargs): if self.parent_group: self.level = self.parent_group.level + 1 else: self.level = 0 super(MbGroups, self).save(*args, **kwargs) The purpose of this model is to be able to create groups and sub-groups with people in them. I created a view to assign some groups to an user : @login_required @manager_required def add_groups_to_user(request, pk): """ add one or many groups to an user """ club_pk = request.user.profil.club_administrator.pk user = User.objects.filter(pk=pk).prefetch_related("groups_user").first() if not request.method == "POST": mbgroups = cache.get_or_set("get_list_groups_club_{}" \ .format(club_pk), MbGroups.objects.filter(club__pk=club_pk) \ .order_by("name") \ .prefetch_related("sub_group") \ .prefetch_related('peoples') \ .only("pk", "name", … -
Model Admin Error: Cannot Exclude Field because it is a Foreign Key to the parent model
My goal is to be able to select a location and Input part numbers without seeing this quote field. I dont even completely understand what this select box is looking for. I have Quote objects saved and yet these are not coming up as selectable options. Not that I want them to, Im just saying. My thinking regarding the seelctable options is that this would be auto-populated? You can probably tell my confusion even in my explanation. Ultimately, I dont want to see a select box at all as Im not really interested in whatever this pointing to, but just for kicks would like to know what it is trying to point to. quote/Models.py class Quote(models.Model): QUOTE_ENVIRONMENTS = ( ('testing', 'Test'), ('production', 'Production') ) SALES_SOURCE=((1, 'Marketplace'), (2, 'Webstore'), (3, 'Physical Store'), (4, 'Phone') ) environment = models.CharField(max_length=20, choices=QUOTE_ENVIRONMENTS, default="testing") sales_source = models.IntegerField(choices=SALES_SOURCE, null=True) order_notes = models.TextField(blank=True) locations = models.ManyToManyField('products.ProductSelection') products/models.py class Product(models.Model): pass class Warehouse(models.Model): pass class ProductSelection(models.Model): location = models.ForeignKey('Warehouse', on_delete = models.CASCADE) product = models.ManyToManyField('Product') Admin.py class ProductOrderForm(forms.ModelForm): locations = forms.ModelChoiceField(queryset= Warehouse.objects.all()) part_number = forms.IntegerField() def clean_product_id(self): cd = self.cleaned_data logger.info(cd) value = cd['part_number'] if value not in Products.objects.list_part_numbers(): raise forms.ValidationError("Not a valid partnumber") class ProductSelectionTabularInline(admin.TabularInline): form = … -
How to manage partial dates with django-partial-date and SelectDateWidget?
I have to manage partial date I have declare a date as PartialDateField() in my model and I want to render this date as 3 differents select in my form so I use SelectDateWidget But doing that, form validation failed is it possible? how shoud I manage partial date in forms? class mymodel(models.Model): _safedelete_policy = SOFT_DELETE_CASCADE ide = models.AutoField(primary_key=True) dat = PartialDateField("my date", null=True, blank=True) log = HistoricalRecords() class myform(forms.ModelForm): dat = forms.DateField( label= "my date", widget=forms.Select() ) class Meta: model = mymodel fields = "__all__" -
./runtests (in django) ImportError: cannot import name 'NullTimeKeeper'
The following command was executed in the tests directory inside the development version of django ./runtests.py Traceback (most recent call last): File "./runtests.py", line 26, in <module> from django.test.utils import NullTimeKeeper, TimeKeeper, get_runner ImportError: cannot import name 'NullTimeKeeper' I am using python 3.8 and am following the instructions for contributing to django from https://docs.djangoproject.com/en/3.1/intro/contributing/ where I have resolved all errors up to this point. Could someone explain what I would have to do as I already ran python3.8 -m pip install -r requirements/py3.txt in my virtual environment that I created using python3.8 -m venv /path/to/venv -
PREVIOUS AND NEXT BUTTONS with Javascript to handle a List of DATA from an API
I have a function to set two buttons " PREVIOUS AND NEXT" to display a list that I sourced from an API. There is a maximum amount of results to be displayed of 11. I am not coming up with the right logic to display when page == 0, only the next button, and when page > 0, the next button AND the previous button, and if the page < 0, only the Next Button to be showing. this is my JS function: function appendData(Data) { var newselement = document.getElementById('newselement'); var previous = document.getElementById('previous'); var next = document.getElementById('next'); var fulllist = []; var page = 0; previous.style.display = 'none'; for (var i = 1; i < Data.length; i++) { var Containersummary = document.createElement("div"); Containersummary.setAttribute('id','artsum'); Containersummary.innerText = Data[i].body; var Containerimage = document.createElement("img"); Containerimage.setAttribute('id','artimg'); Containerimage.src = Data[i].imageurl; var Containername = document.createElement("div"); Containername.setAttribute('id','arttit'); Containername.innerText = Data[i].title; var Containerurl = document.createElement("a"); Containerurl.setAttribute('href', Data[i].url); Containerurl.innerText = Data[i].url; var arrayList = document.createElement("div"); var hr = document.createElement("hr") hr.setAttribute('id','brake'); var br = document.createElement("br") arrayList.appendChild(Containername); arrayList.appendChild(Containerimage); arrayList.appendChild(Containersummary); arrayList.appendChild(Containerurl); arrayList.appendChild(br); arrayList.appendChild(hr); fulllist.push(arrayList); } for (var i = 0; i < page + 11; i++){ newselement.appendChild(fulllist[i]); } next.addEventListener("click", () => { if (page > 0){ previous.style.display = 'block'}; page == fulllist.lenght … -
Python, Django: ForeignKey with dependencies (models.py)
Good day, I would like to ask, if it's possible to determine an additional dependencie on a models.ForeignKey-field? For example ... models.py class Object_A(models.Model): name = models.Charfield(max_length=50, null=False, blank=False, unique=True) date_created = models.DateTimeField(auto_now_add=True) class Object_B(models.Model): name = models.Charfield(max_length=50, null=False, blank=False, unique=True) object_a = models.ForeignKey(Object_A, null=False, blank=False, on_delete=models.CASCADE) date_created = models.DateTimeField(auto_now_add=True) class Object_C(models.Model): name = models.Charfield(max_length=50, null=False, blank=False, unique=True) object_a = models.ForeignKey(Object_A, null=False, blank=False, on_delete=models.CASCADE) object_b = models.ForeignKey(Object_B, null=False, blank=False, on_delete=models.CASCADE) date_created = models.DateTimeField(auto_now_add=True) forms.py class Create_Object_C_Form(ModelForm): class Meta: model = Object_C exclude = [ 'object_a', 'date_created', ] What I'm trying to do... As you can see, I'm excluding the object_a, because at this point inside my app where the form is used, the user doesn't have to choose for an object_a. His own steps have anticipated this choice! The same - or at least almost the same - goes for object_b: Is it possible to only show choices that are related to the same object_a? Hoping I could explain my problem understandably and somebody can help or has an idea!? Have a great day! -
Not able to post the form
So i have a table in ms sql database.the connections is open but the form wont submit. def add(request): print('start') if request.method == "POST": print('post') if request.POST.get('name') and request.POST.get('contact_person') and request.POST.get( 'address') and request.POST.get('ph_no') and request.POST.get('tele') and request.POST.get( 'mail') and request.POST.get('is_active') and request.POST.get('last_update'): print('get') insertstvalues = Company() # insertstvalues.company_id = request.POST.get('company_id') insertstvalues.name = request.POST.get('name') insertstvalues.contact_person = request.POST.get('contact_person') insertstvalues.address = request.POST.get('address') insertstvalues.ph_no = request.POST.get('ph_no') insertstvalues.tele = request.POST.get('tele') insertstvalues.mail = request.POST.get('mail') insertstvalues.is_active = request.POST.get('is_active') # insertstvalues.last_update = request.POST.get('last_date') print('values') cursor.execute( "insert into Company values ('" + insertstvalues.name + "','" + insertstvalues.contact_person + "','" + insertstvalues.address + "','" + insertstvalues.ph_no + "','" + insertstvalues.tele + "','" + insertstvalues.mail + "','" + insertstvalues.is_active + "')") print('execute') cursor.comit() print('record added') return render(request, 'addRecord.html') else: print('Rerun') return render(request, 'addRecord.html') this is the functions i have in views.py.connections and cursor strings are all working. here is the html code for the from to take in the values so when i run the app this is what i see cmd terminal after i click the insert button basically as far as i can see is that the program never runs the second if statement. I want to add data to my table so i am open to any …