Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Different outputs reading the same pdf file on different machines (with python textract.process())
I wrote a program (part of a django web app) that's extracting text from pdf file using textract.process(path_to_file). I managed to get it to work fine on my local machine (outputs are consistent - for different pdf files I'm always getting similar outputs that I'm using later in the process.). When I deployed the code to production, the outputs are different. Lines extracted from pdf are displayed in different order on my local pc and on production server (checked on the same version of python - only gcc is 1 version lower, but i don't think it's the case). Have anyone had similar problem with textract? import textract text_lines = textract.process(filepath).decode('utf-8').split('\n') for i in range(0, len(text_lines)): print(f'{i}, {text_lines[i]}') -
Microsoft 365 ics file issue while sending last name with ','
From my django application I'm sending emails to customers. Gmail, outlook are working fine but in Outlook 365 if the last name contains ',' it is breaking and showing as '/' in mail view and also in ics file. Is outlook 365 cannot parse ',' in first name and last name? -
Download generated excel file using xslxwriter on Python(Django)
I am working with Python using the Django framework, at this moment I am generating some reports in Excel, for that I use the xslxwriter library, the user tries to download the file from the platform, I do not get the download and instead it The answer is strange characters, I think that's the Excel file, anyway I don't know how to make that file download. This snippet is the one that is supposed to download the file workbook.close() output.seek(0) response = HttpResponse(output.read(), content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") response['Content-Disposition'] = "attachment; filename=test.xlsx" output.close() return response This is the response I get from the frontend Thank you very much in advance. -
TypeError: create_superuser() missing 1 required positional argument: 'username'
I am using Django REST Framework and Django for creating a user auth endpoint. I now have the following error, whenever I try to create a super user. Here is my code: from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager from django.contrib.auth.models import UserManager from django.db import models import time # Create your models here. class MyAdmin(BaseUserManager): def create_user(self, username, first_name, last_name, email, password, **kwargs): if(not email): raise ValueError("No Email Provided!") user = self.model(first_name, last_name, email, **kwargs) user.is_admin = False user.is_superuser = False user.is_staff = False user.is_active = True user.set_password(password) user.save() return user def create_superuser(self, username, first_name, last_name, email, password, **kwargs ): kwargs.setdefault('is_staff', True) kwargs.setdefault('is_superuser', True) kwargs.setdefault('is_active', True) if(kwargs.get('is_staff') is not True): raise ValueError("Super User must be a staff in order to be in!") if(kwargs.get('is_superuser') is not True): raise ValueError("User must be a SuperUser!") if(kwargs.get('is_active') is not True): raise ValueError("Super User must be active!") user = self.model(email= email) user.is_admin = True user.is_superuser = True user.is_staff = True user.is_active = True user.set_password(password) user.save() return user class MyUser(AbstractBaseUser): first_name = models.CharField(max_length= 200, blank= False) last_name = models.CharField(max_length= 200, blank= False) email = models.EmailField(unique= True, blank= False) phone_number = models.IntegerField() company_name = models.CharField(max_length= 200, blank= False) date_joined = models.DateTimeField(auto_now= True) last_login = models.DateTimeField(auto_now= True, null= False) … -
Commenting on a comment django
I am currently working on a blog app with django handling the backend. I want users to be able to comment on comments .. for this I tried using two generic views for the same view class like PostListView(CreateView, ListView) which is kind of weird. But I kept on getting integrity errors for the id of the posts. Is there any better way to implement this functionality?? Thanks in advance. -
How do you make sync_to_async work in a one to one model in django?
I made a model for users of my website which contains a one to one field with the model user. I'm using the model because I was intstructed to make it but now i cannot use it to send messages in my chat app as it isn't sync_to_async. Is there a way to make the function async? Or is it possible to make it so changes to to member model affect the changes to user model. Model.py: class Member(TimeStamped): user = models.OneToOneField(User,on_delete=models.CASCADE) username=models.CharField(max_length=200,unique=True,default="") email=models.CharField(max_length=200,default="") password=models.CharField(max_length=200,default="") profile_pic = models.ImageField(default='uploads/default.png') def __str__(self): return self.username[:80] The code that doesn't work with the member model. If im just using the normal user model it works. consumers.py: from channels.generic.websocket import AsyncJsonWebsocketConsumer import json from django.contrib.auth import get_user_model User = get_user_model() async def send_message(self,message): await self.channel_layer.group_send( "tribe_chatroom_1", { "type": "chat.message", "profile_image": self.scope["user"].member.profile_pic.url, "username": self.scope["user"].member.username, "user_id": self.scope["user"].member.id, "message": message, } ) async def chat_message(self, event): """ Called when someone has messaged our chat. """ # Send a message down to the client print("TribeChatConsumer: chat_message from user #" + str(event["user_id"])) await self.send_json( { "profile_image": event["profile_image"], "username": event["username"], "user_id": event["user_id"], "message": event["message"], }, ) -
Django question on assigning the created news/team to the user who created it
please help me with one question, if possible. I have a profile model that has a OneToOneField to User and there is a team field in the Profile model, there is also a Team model with a name, tag, etc. I would like to ask how to make the user who creates the team immediately be in it, so that the team field of the Profile model is assigned this team automatically, so that he is its creator and captain immediately. Maybe someone can help, explain, throw a banal example for understanding. The creation was done like this, in a separate application. But I don't understand how to give the browser the created tim. models.py from django.db import models from django.contrib.auth.models import User from slugify import slugify from django.urls import reverse class BaseModel(models.Model): objects = models.Manager() class Meta: abstract = True class Profile(BaseModel): user = models.OneToOneField( User, on_delete=models.CASCADE, null=True, blank=True ) nickname = models.CharField(max_length=30, unique=True, null=True) team = models.ForeignKey('Team', on_delete=models.SET_NULL, blank=True, null=True) def save(self, *args, **kwargs): super(self.__class__, self).save(*args, **kwargs) if self._state.adding is True: Profile.objects.create() def __str__(self): return self.nickname class Meta: verbose_name = "Автор" verbose_name_plural = "Авторы" class Team(BaseModel): name = models.CharField('Название', max_length=50) tag = models.CharField('Тег', max_length=16, unique=True) slug = models.SlugField(unique=True, … -
Django delete records that sum up to a given value
Is there a simple way to delete records from a table that sum up to a given value? I have created a fintech app used to manage loan repayments and share holders in the company. Some shareholders would like to repay loans by their shares being deducted. How can I put a script that whenever the app user enters the share value to be deducted, the random share records of an individual aggregating or annotating to that input value are the only ones deleted? What i have tried in views.py `class ShareLoanProgressPaymentView(View, BaseObject): def post(self, *args, **kwargs): member_id = self.get_memberobject(kwargs['id']) loan = self.get_object(kwargs['id'])[0] _paid = self.request.POST['paid'] #number of shares to be deducted totals1 = Share.objects.filter(member_id=loan.member_id)[:(int(_paid)/2)].values_list('id', flat =True) totals = Share.objects.filter(member_id=loan.member_id)[:int(_paid)].values_list('id', flat =True) #totals = Share.objects.values('member_id')[int(_paid):].values_list('id', flat =True) while (int(_paid)) >= 0: Share.objects.filter(id__in=list(totals1)).delete() _paid = int(_paid) - 1 break` This seems to be deleting records basing on id. What I am trying to achieve is delete records that sum up to a given value(entry from form) -
Django Crispy Forms Layout Not Working Inside forms.Modelform
I've gotten CrispyForms to load a custom layout when using a form inside the generic CreateView, as shown below: class editEvent(UpdateView): model = Event fields = [field.name for field in model._meta.fields if field.name not in 'organization'] template_name = 'event_edit_modal.html' def get_success_url(self): org = self.request.user.profile.organization.url_name messages.success(self.request, 'Success: event updated.') return reverse('manage', kwargs={'org_name':org}) def get_form(self): form = super().get_form() form.fields['location'].queryset = Location.objects.filter(organization=Organization.objects.get(url_name=self.request.user.profile.organization.url_name)) form.fields['event_group'].queryset = EventGroup.objects.filter(organization=Organization.objects.get(url_name=self.request.user.profile.organization.url_name)) form.fields['register_start'].widget = DateTimePickerInput() form.fields['register_end'].widget = DateTimePickerInput() form.fields['start'].widget = DateTimePickerInput() form.fields['end'].widget = DateTimePickerInput() form.helper = FormHelper() form.helper.add_input(Submit('submit', 'Update', css_class='btn-primary')) form.helper.layout = Layout( Row( Column('name', css_class='col-8'), Column('event_group', css_class='col-4'), ), 'location', Row( Column('start'), Column('end'), ), Row( Column('register_start'), Column('register_end'), ), 'details', 'team_event', Row( Column('min_team_members'), Column('max_team_members'), ), ) return form However, inside a different form I'm needing to render the CrispyForms layout inside a forms.Modelform. However, for some reason the layout is being loaded. The help_texts, loaded by Django are loading, but the FormHelper layout is not: class organizationForm(forms.ModelForm): allowed_email_domains = forms.CharField(max_length=40) owner_email = forms.EmailField(max_length=254) owner_first_name = forms.CharField(max_length=60) owner_last_name = forms.CharField(max_length=60) owner_password = forms.CharField(widget=forms.PasswordInput()) confirm_owner_password = forms.CharField(widget=forms.PasswordInput()) class Meta: model = Organization fields = ['name', 'url_name', 'about_text'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['allowed_email_domains'].help_text = 'Optionally restrict users joining your organization to certain email domains. Example input: college.edu (do not include @ symbol)' … -
value is not in range with pandas
here is my code : import pandas as pd tmp_data=pd.read_csv("../data/geo/public.geo_commune.csv",sep=';') #id;created;uuid;modified;name;geohash_file;gps_lat_file;gps_long_file;geohash_bing;gps_lat_bing;gps_long_bing;geohash_goog;gps_lat_goog;gps_long_goog;code_insee;code_cadastre;code_postal;departement;region;code_postal2 print(tmp_data[tmp_data['id'] == 6217]) communes = [ Commune( id = tmp_data.loc[row]['id'], uuid = tmp_data.loc[row]['uuid'], name = tmp_data.loc[row]['name'], geohash_file = tmp_data.loc[row]['geohash_file'], gps_lat_file = tmp_data.loc[row]['gps_lat_file'], gps_long_file = tmp_data.loc[row]['gps_long_file'], code_insee = tmp_data.loc[row]['code_insee'], code_postal = tmp_data.loc[row]['code_postal'], code_postal2 = tmp_data.loc[row]['code_postal2'], ) for row in tmp_data['id'] ] Commune.objects.bulk_create(communes) I have this error : Traceback (most recent call last): File "/home/bussiere/.local/share/virtualenvs/GeoTransport-6Rxd3Krq/lib/python3.7/site-packages/pandas/core/indexes/range.py", line 351, in get_loc return self._range.index(new_key) ValueError: 6217 is not in range The above exception was the direct cause of the following exception: Traceback (most recent call last): File "importPandasGeo.py", line 34, in for row in tmp_data['id'] File "importPandasGeo.py", line 34, in for row in tmp_data['id'] File "/home/bussiere/.local/share/virtualenvs/GeoTransport-6Rxd3Krq/lib/python3.7/site-packages/pandas/core/indexing.py", line 895, in getitem return self._getitem_axis(maybe_callable, axis=axis) File "/home/bussiere/.local/share/virtualenvs/GeoTransport-6Rxd3Krq/lib/python3.7/site-packages/pandas/core/indexing.py", line 1124, in _getitem_axis return self._get_label(key, axis=axis) File "/home/bussiere/.local/share/virtualenvs/GeoTransport-6Rxd3Krq/lib/python3.7/site-packages/pandas/core/indexing.py", line 1073, in _get_label return self.obj.xs(label, axis=axis) File "/home/bussiere/.local/share/virtualenvs/GeoTransport-6Rxd3Krq/lib/python3.7/site-packages/pandas/core/generic.py", line 3739, in xs loc = index.get_loc(key) File "/home/bussiere/.local/share/virtualenvs/GeoTransport-6Rxd3Krq/lib/python3.7/site-packages/pandas/core/indexes/range.py", line 353, in get_loc raise KeyError(key) from err KeyError: 6217 but this line works well : print(tmp_data[tmp_data['id'] == 6217]) and it gaves me : id created uuid ... departement region code_postal2 1795 6217 2020-01-08 17:20:08.091659+01 78DA163B1494401CBD6832AF048406FF257 ... NaN NaN NaN [1 rows x 20 columns] -
Django Admin Panel Custom header for some of the tables under the app name header
In the Django Admin panel, all the models(database tables) are displayed under the App name header. I need to separate out some of the tables under the app name. In the attached Image we can see the App name "SR" as a separator for the two tables which are present in the same "SR" application. I need to add two more header under the "SR" and add add two different tables under the two headers. Example: "SR" is the main application name(Main header name), "Sr1" is the one header under the "SR" app. In that "Sr1" i will add "Sr Choices" model present in the attached screenshot. and "Sr2" is another header under the "SR" app. need to display rest of the models present in the "SR" application. Is there any way to customize the admin panel based on my requirement. or Is any there any options in the existing djnago admin panel to satisfy my requirements. -
Creating a pgadmin server (for viewing database) from django app
I am creating a django project where I need to link pgadmin viewer with my app. Currently I am starting a pgamin server seprately and then using " > in the html page i have linked the server. Is there a way to start the server inside django itself and link it? -
How to implement bulk deletion in Django Rest Framework
Could someone explain how this could be achieved? Somehow passing in ids to the delete request and somehow delete instances using the ids. -
Django Channels - Real time Notifications
Suppose, if user is online, websocket connection is created and user will get all the realtime notification. But, if user went offline, websocket connection breaks, then if any realtime notification has to be delivered during offline period, will it be again delivered if user comes online again(means when websocket connection is made again of that user)?? -
Does the pre ping feature in SqlAlchemy db pools automatically reconnect and send the SQL command in case the pre ping check fails?
I want some clarification on how the pre ping feature exactly works with SqlAlchemy db pools. Let's say I try to make a SQL query to my database with the db pool. If the db pool sends a pre ping to check the connection and the connection is broken, does it automatically handle this? By handling I mean that it reconnects and then sends the SQL query? Or do I have to handle this myself in my code? Thanks! -
Is there any library like arch unit for Django?
I've been searching for a library or tool to test my Django project architecture, check the dependencies, layers, etc. like Arch Unit for Java. But until now, I didn't find anything. I even don't know if is viable doing these kinds of tests in Python/Django projects. I know that Django itself already checks for cyclic dependencies. -
Django: Can I edit other profile info while logging in different user?
the below codes are from views.py, there's no error in that. It just that the code below can only edit the info of the 'logged in' user. What I want is to edit other user info using 'admin user' what I know is editing a data depends on "instance=request.user" from "form = UserEditForm(request.POST, instance=request.user)" can I change the "request.user" to the user I wanted to edit the info without login it?? Take the 'elton' username from the below image of dashboard as example. I'm logged in as another user but I wanted to edit the 'elton' row without login it. Is that possible? dashboard data def edit_profile(request): if 'established' in request.session: return redirect('bhome') elif not 'logged_in' in request.session: return redirect('login') else: if request.method == 'POST': form = UserEditForm(request.POST, instance=request.user) email = request.POST['email'] palotype = request.POST['palotype'] suffix = request.POST['suffix'] first_name = request.POST['first_name'] middle_name = request.POST['middle_name'] last_name = request.POST['last_name'] birth_date = request.POST['birth_date'] region = request.POST['region'] city = request.POST['city'] barangay = request.POST['barangay'] unitno = request.POST['unitno'] floorno = request.POST['floorno'] bldgname = request.POST['bldgname'] housebldgno = request.POST['housebldgno'] streetname = request.POST['streetname'] villagedistrict = request.POST['villagedistrict'] mobileno = request.POST['mobileno'] landline = request.POST['landline'] context= {'email': email, 'palotype':palotype, 'suffix':suffix, 'first_name':first_name, 'middle_name':middle_name, 'last_name':last_name, 'birth_date':birth_date, 'region':region, 'city':city, 'barangay':barangay, 'unitno':unitno, 'floorno':floorno, 'bldgname':bldgname, 'housebldgno':housebldgno, 'streetname':streetname, … -
How can i use tag user using @ in django
I am building a BlogApp and I am trying to add tag user system in creating post using @. I did't find any libraries to implement it in django app. What i am trying to do I am trying to build tagging user with @. So when user press @ and press of users(friends) appears. Same like stack overflow while someone add @ then user involved in that post appears. What have i tried I saw few answers on tagging user using @ but they didn't work for me. Like :- THIS. I also tried mark_down to tag immediately ( Like autocomplete ). BUT FAILED. :- THIS I don't know what to do. Any help would be appreciated. Thank You in Advance. -
How to validate and get nested serializer values in django rest framework?
I am using 2 serializers for validating this request: { "name":"Dade Waste Facility", "email":"example@mailinator.com", "mobile":"1234567", "street":"Street 1", "city":"Miami", "zipcode":"123456", "state":"Florida", "material_types": [{ "name": "Metal", "cost_per_ton": 20 }, { "cost_per_ton": 50, "name": "Food" }] } Django code: class MaterialTypeSerializer(serializers.Serializer): name = serializers.CharField( required=True, max_length=255, error_messages={ "required": "Material type name is required.", "max_length": "Material type name can be maximum 255 characters.", }, ) cost_per_ton = serializers.IntegerField( required=True, error_messages={"required": "Material type cost per ton is required.",}, ) class Meta: fields = "__all__" class WasteFacilityPostSerializer(serializers.ModelSerializer): name = serializers.CharField( required=True, max_length=255, error_messages={ "required": "Name is required.", "max_length": "Name can be maximum 255 characters.", }, ) contact_person_name = serializers.CharField( required=False, max_length=255, error_messages={ "max_length": "Contact person name can be maximum 255 characters.", }, ) email = serializers.EmailField( required=False, max_length=255, error_messages={ "invalid": "Email address not valid.", "max_length": "Email can be maximum 255 characters.", }, ) mobile = serializers.CharField( required=True, validators=[ RegexValidator( regex=r"^\d{10,14}$", message="Phone number must be entered in format: '+999999999'. Up to 14 digits allowed.", ) ], max_length=15, error_messages={ "required": "Mobile is required.", "max_length": "Mobile can be maximum 14 digits.", }, ) street = serializers.CharField( required=True, max_length=255, error_messages={ "required": "Street is required.", "max_length": "Street can be maximum 255 characters.", }, ) suite = serializers.CharField( required=False, max_length=255, error_messages={"max_length": "Suite … -
Is it better to have several different tables for similar objects, or one big table?
I have an optimisation problem for my tables : I have Items that can have a price by one, by ten and by hundred. Right now i have three tables for that : class Prix_x1(models.Model): def __str__(self): return self.item.name prix = models.IntegerField(null=True) saved_at = models.DateTimeField() item = models.ForeignKey(Item, on_delete=models.CASCADE) class Prix_x10(models.Model): def __str__(self): return self.item.name prix = models.IntegerField(null=True) saved_at = models.DateTimeField() item = models.ForeignKey(Item, on_delete=models.CASCADE) class Prix_x100(models.Model): def __str__(self): return self.item.name prix = models.IntegerField(null=True) saved_at = models.DateTimeField() item = models.ForeignKey(Item, on_delete=models.CASCADE) But often i need to check which of these prices is the lowest on a per unit basis. So i have to check each price table for each Item every time i need to do that. So my question is : Is it a better way to optimse that ? For exemple, is it better to have one big table Price with a field number_of_unit that can take 1, 10 or 100 as value ? Thanks for your help !! -
how to filter the foreignkey objects if exists in the manytomany django
i have to make a queryset for only returns that object which is in the M2M field class Item(models.Model): items = models.CharField(max_length=20) class Main(models.Model): admin = models.ForeignKey(User,on_delete=models.CASCADE) items = models.ManyToManyField(Item,on_delete=models.CASCADE) #others class TestModel(models.Model): admin = models.ForeignKey(User,on_delete=models.CASCADE) items = models.ForeignKey(Item,on_delete=models.CASCADE) i have to make query to filter in TestModel to only the items which is in the Main model! i tried this in my views.py get_id_from_user = request.GET.get('user_input') main_obj = Main.objects.get(id=get_id_from_user) test_objects = TestModel.objects.filter(items__in=main_obj.items.all() but test_objects still returns all the Item object! is it possible please thank you -
MultiValueDictKeyError while submitting Django form
I am new to Django and I am working on a site which should take user input and use it for further operations. I am using a simple text field and I am trying to access the input using request.POST method, however this is giving MultiValueDictKeyError on the name of the text field. Kindly help me out in this. PFA my codes. views.py from django.shortcuts import render from django.http import HttpResponse import openpyxl import math def index(request): if "GET" == request.method: return render(request, 'index.html') else: excel_file = request.FILES["excel_file"] wb = openpyxl.load_workbook(excel_file) # getting a particular sheet by name out of many sheets # USING TEXT BOX sheet_id = request.POST["leadtime"] sheet_name = str(sheet_id) + "_Day_Lead" worksheet = wb["Observed"] worksheet1 = wb[sheet_name] index.html <div class="md:flex flex-col w-full items-center"> <div class="relative mb-4"> <form action="index" method="POST"> {% csrf_token%} <label for="full-name" class="leading-7 text-sm text-gray-600">Duration of Lead Time in Day(s)</label> <input type="text" id="full-name" placeholder="1 to 5 or ALL" name="leadtime" class="w-full bg-white rounded border border-gray-300 focus:border-green-500 focus:ring-2 focus:ring-green-200 text-base outline-none text-gray-700 py-1 px-3 leading-8 transition-colors duration-200 ease-in-out"> </form> </div> <div class="relative mb-4"> <form action="index" method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="file" title="Upload excel file" name="excel_file" style="border: 3px solid green ; padding: 5px;" required="required"> </div> <button type = … -
How to turn off pagination for a particular viewset in Django Rest Framework?
This is a snippet of the code that I tried to disable pagination as suggested in answers to similar questions. But this is not working for me. I even tried overriding the default paginate_queryset method but ended up observing that it wasn't even getting called(maybe I am doing it the wrong way) class TestViewSet(viewsets.ModelViewSet): queryset = Test.objects.all() serializer_class = TestSerializer filter_backends = (django_filters.DjangoFilterBackend, SearchFilter) filterset_fields = {'status': ('exact', 'in'), } search_fields = ['=id', ] pagination_class = None Below is also the code I tried to override paginate_queryset def paginate_queryset(self, queryset, request, view=None): if 'no_page' in request.query_params: return None return super().paginate_queryset(queryset, request, view) -
How to get in Javascript specific Object of iteration done in a Django template
I have the next iteration in a Django template. This shows me a group of images and their title. {% for i in blogs %} <div class="content__blog"> <h4 class="content__blog__h4">{{i.title}}</h4> <img class="content__blog__img" src="{{i.image.url}}" onclick="clickImage()"> </div> {% endfor %} What i want to do by adding JavaScript is that when clicking on an Image it'll resize. But only the image clicked. How do i specify in the JS file which image i'm clicking on? -
global variable in Django views.py
I am new to Django. In views.py I want to use variable defined in one function in anothe function. But when even after defining a variable as global it returns error. views.py def index(request): data = {'Price':[100,200], 'Sale':[30,40]} global df df = pd.DataFrame(data) def corr(request): correlation = corr.df() print(correlation) Error: name 'df' is not defined