Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Invalid command 'PassengerAppRoot', perhaps misspelled or defined by a module not included in the server configuration -django
I hosted a django website few week ago, it was working well and suddenly i got this error on my website. I am getting this error on my webpage And in webserver error log i am getting: Invalid command 'PassengerAppRoot', perhaps misspelled or defined by a module not included in the server configuration .htaccess file: DO NOT REMOVE. CLOUDLINUX PASSENGER CONFIGURATION BEGIN PassengerAppRoot "/home/plantsof/plantsofnepal" PassengerBaseURI "/" PassengerPython "/home/plantsof/virtualenv/plantsofnepal/3.8/bin/python" PassengerAppLogFile "/home/plantsof/plantsofnepal/logs/passenger.log" DO NOT REMOVE. CLOUDLINUX PASSENGER CONFIGURATION END I tried to remove this configuration and pass in .htaccess. I couldn't figure out why this error happened suddenly. -
How to search inside an uploaded document?
I'm trying to find a way to search inside the uploaded files. If a user uploads a pdf, CSV, word, etc... to the system, the user should be able to search inside the uploaded file with the keywords. Is there a way for that or a library? or maybe should I save the file as a text inside a model and search from that? I will appreciate all kind of reccommendation. -
Django Ninja API framework Pydantic schema for User model ommits fields
Project running Django with Ninja API framework. To serialize native Django's User model I use following Pydantic schema: class UserBase(Schema): """Base user schema for GET method.""" id: int username = str first_name = str last_name = str email = str But, this approach gives me response: { "id": 1 } Where are the rest of fields? Thought this approach gives me a full data response: class UserModel(ModelSchema): class Config: model = User model_fields = ["id", "username", "first_name", "last_name", "email"] Response from ModelSchema: { "id": 1, "username": "aaaa", "first_name": "first", "last_name": "last", "email": "a@aa.aa" } -
Can not import pyarrow, DLL load failed while importing lib
I have been trying to get polars working but pyarrow keeps giving me error with or without polars package, pyarrow==10.0.0 is installed and django version is Django==3.0.5, I can import it in python shell but when I import it within my django app, it throws me this error whenever and wherever it is imported: File "xxx.py", line 1870, in xxx print(pl.read_sql(query, ALCHEMY_SQL)) File "C:\Users\duoqu\miniconda3\envs\test-env\lib\site-packages\polars\io.py", line 1107, in read_sql tbl = cx.read_sql( File "C:\Users\duoqu\miniconda3\envs\test-env\lib\site-packages\connectorx\__init__.py", line 253, in read_sql import pyarrow File "C:\Users\duoqu\miniconda3\envs\test-env\lib\site-packages\pyarrow\__init__.py", line 65, in <module> import pyarrow.lib as _lib ImportError: DLL load failed while importing lib: The specified procedure could not be found. Or like this: File "xxx.py", line 59, in <module> import pyarrow File "C:\Users\duoqu\miniconda3\envs\test-env\lib\site-packages\pyarrow\__init__.py", line 65, in <module> import pyarrow.lib as _lib ImportError: DLL load failed while importing lib: The specified procedure could not be found. Importing the module from shell within anaconda environment but just plain python shell: Python 3.8.15 (default, Nov 4 2022, 15:16:59) [MSC v.1916 64 bit (AMD64)] :: Anaconda, Inc. on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import pyarrow >>> pyarrow.lib <module 'pyarrow.lib' from 'C:\\Users\\duoqu\\miniconda3\\envs\\test-env\\lib\\site-packages\\pyarrow\\lib.cp38-win_amd64.pyd'> >>> Also it is recognized by pylance: What could be the problem? I am … -
Error resolution django.core.exceptions.ImproperlyConfigured:
Ran into this error when trying makemigrations: django.core.exceptions.ImproperlyConfigured: DEFAULT_AUTO_FIELD refers to the module 'django.db.dashboard_models.BigAutoField' that could not be imported. the code in all train apps is identical, only the name changes: from django.apps import AppConfig class ToolsConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'tools' Maybe someone can tell me how to fix it, I will be grateful -
execute a code after return/response has been sent in django
I have gone through the answer at Execute code in Django after response has been sent to the client but I am having difficulty in sending html request. The web page is not loading. It is just only showing the string of the url i am requesting e.g. url/template.html This is what I have done and it keeps on sending a json response instead of an html class ResponseAfter(Response): def __init__(self, data, then_callback, **kwargs): super().__init__(data, **kwargs) self.then_callback = then_callback def close(self): super().close() self.then_callback() def followingFunction(): #this is the function that would be executed afterward page_result= return ResponseAfter((request,'index.html'), followingFunction, content_type ="text/html") Please how can I get the function to send the report update I have seen my mistake. I added render to the return statement and it worked fine. -
Issue with django crontabs there not working
hello guys i trying to use django_crontab on my django project and there not working does anyone know something about this im using Linux centos 8. I want to schedule a task to add some data to my database. Can someone help me The steps that i have take is: pip install django-crontab add to the installed apps build my cron function ` from django.core.management.base import BaseCommand from backups.models import Backups from devices.models import Devices from datetime import datetime from jnpr.junos import Device from jnpr.junos.exception import ConnectError from lxml import etree from django.http import HttpResponse from django.core.files import File class Command(BaseCommand): def handle(self, *args, **kwargs): devices = Devices.objects.all() for x in devices: devid = Devices.objects.get(pk=x.id) ip = x.ip_address username = x.username password = x.password print(devid, ip, username, password) dev1 = Device(host= ip ,user= username, passwd= password) try: dev1.open() stype = "sucsess" dataset = dev1.rpc.get_config(options={'format':'set'}) datatext = dev1.rpc.get_config(options={'format':'text'}) result = (etree.tostring(dataset, encoding='unicode')) file_name = f'{ip}_{datetime.now().date()}.txt' print(file_name) with open("media/"f'{file_name}','w') as f: f.write(etree.tostring(dataset, encoding='unicode')) f.write(etree.tostring(datatext, encoding='unicode')) backup = Backups(device_id=devid, host=ip, savetype=stype, time=datetime.now(), backuptext=file_name) print(backup) backup.save() except ConnectError as err: print ("Cannot connect to device: {0}".format(err)) print("----- Faild ----------") stype = ("Cannot connect to device: {0}".format(err)) backup = Backups(device_id=devid, host=ip, savetype=stype, time=datetime.now()) backup.save() ` … -
Django REST Framework - How to get current user in serializer
I have TransactionSerializer: class TransactionSerializer(serializers.ModelSerializer): user = UserHider(read_only=True) category_choices = tuple(UserCategories.objects.filter(user=**???**).values_list('category_name', flat=True)) category = serializers.ChoiceField(choices=category_choices) def create(self, validated_data): user = self.context['request'].user payment_amount = self.validated_data['payment_amount'] category = self.validated_data['category'] organization = self.validated_data['organization'] description = self.validated_data['description'] return Transaction.objects.create(user=user, payment_amount=payment_amount, category=category, organization=organization, description=description) class Meta: model = Transaction fields = ('user', 'payment_amount', 'date', 'time', 'category', 'organization', 'description') This totally does the job, however I need that instead of "???" the current user was substituted, or rather his ID, but I don't quite understand what basic ModelSerializer method I can use so as not to damage anything, but at the same time get the current user as a variable in order to substitute it later in the filtering place (in this case, categories are filtered if I put some specific user ID which is already registered, then on the DRF form, when creating an object, I get a drop-down list with categories specific only to my user)? I have already tried to do this through the get_user() method, and also tried to create a variable inherited from another serializer, which defines just the user ID, but I received various kinds of errors. -
Is it possible in Django?? If yes how?
I want another model to check if boolean == True then take the value and add to mine. Assuming I have 2 models class Balance (models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) Amount = models.FloatField(max_length=30) class Deposit (models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) Deposit_Amount = models.FloatField(max_length=30) Approved = models.BooleanField(default=False) Have tried it in my views but it seems views.py only trigger when an action is push from the user. def Deposits(request): if request.method == 'POST': Input_Amount = request.POST['Input_Amount'] user = request.user available = Balance.objects.get(user=request.user) Deposit_Request = Deposit.objects.create(Deposit_Amount=Input_Amount, user=user) Deposit_Request.save messages.warning(request, 'Request sent, please wait for confirmation') if Deposit_Request.Approved == True: sum = available.Amount + float(Input_Amount) New_balance = Balance.objects.update(Amount=sum, user=user) else: return redirect('deposit') else: return render(request, 'deposit.html') It always return and else statement because the default is False when that action was taken. Am a newbies on django -
django getting all objects from select
i also need the field (commentGroupDesc) from the foreign keys objects. models.py class commentGroup (models.Model): commentGroup = models.CharField(_("commentGroup"), primary_key=True, max_length=255) commentGroupDesc = models.CharField(_("commentGroupDesc"),null=True, blank=True, max_length=255) def __str__(self): return str(self.commentGroup) class Meta: ordering = ['commentGroup'] class Comment (models.Model): commentID = models.AutoField(_("commentID"),primary_key=True) commentUser = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) commentGroup = models.ForeignKey(commentGroup, on_delete=models.CASCADE, null=True) commentCI = models.ForeignKey(Servicenow, on_delete=models.CASCADE, null=True) commentText = RichTextField(_("commentText"), null=True, blank=True) commentTableUpdated = models.CharField(_("commentTableUpdated"), null=True, blank=True, max_length=25) def __str__(self): return str(self.commentGroup) class Meta: ordering = ['commentGroup'] views.py comment = Comment.objects.get(pk=commentID) here i get the commentGroup fine but i also need commentGroupDesc to put into my form its probably very simple, but i have tried several options. thanks -
Can AI (artificial intelligence) have consciousness [closed]
What do you think about artificial intelligence? Is it possible that artificial intelligence will be able to reach human levels in the near future, for example, in this decade? -
count the number of posts
I have created a website and want to count user generated posts. I tried to do it as follows: models.py class Blog(models.Model): user = models.ForeignKey( User, related_name='user_blogs', on_delete=models.CASCADE ) category = models.ForeignKey( Category, related_name='category_blogs', on_delete=models.CASCADE ) title = models.CharField( max_length=250 ) slug = models.SlugField(null=True, blank=True) banner = models.ImageField(upload_to='blog_banners') description = RichTextField() created_date = models.DateField(auto_now_add=True) def __str__(self) -> str: return self.title def save(self, *args, **kwargs): updating = self.pk is not None if updating: self.slug = generate_unique_slug(self, self.title, update=True) super().save(*args, **kwargs) else: self.slug = generate_unique_slug(self, self.title) super().save(*args, **kwargs) templates <span>Posts: <strong>{{account.user_blogs.count}}</strong></span> but it doesn't work what is the problem? should I rewrite the code at all? -
Make option tag set something in the url - Django
I'll dive straight to the point so to not waist any of your time... I'm trying to achieve this... <form class="header__search" method="GET" action=""> <input name="q" placeholder="Browse Topics" /> </form> i.e. set something in the url that I will fetch later but I want to do it using a dropdown menu that uses option tags <form action="" method="GET"> {% csrf_token %} <div class="units-div"> <label for="units">Units:</label> <select name="units" id="units-selection"> <option value="metric">Metric</option> <option value="imperial">Imperial</option> </select> </div> <div class="language-div"> <label for="language">Language:</label> <select name="language" id="language-selection"> <option value="english">English</option> <option value="italian">Italian</option> </option> </select> </div> </form> Any idea how I can achieve that? -
Spotipy can't access user's info using SpotifyOAuth (authorization flow error)
I'm trying to do an API using spotify, and spotipy (I use django rest framework for this). I followed the documentation and when I use SpotifyClientCredentials It works just fine but I can't access user's information (in my exemple I try to get the username). To do this, spotipy tells me to use SpotifyOAuth But then things get worse, I have a "test" endpoint and when I connect my account, postman opens TONS of tabs https://accounts.spotify.com/authorize?client_id=....&response_type=code&redirect_uri=... Here is my code : @api_view(['GET']) @permission_classes([permissions.IsAuthenticated]) def test(request): if request.method == 'GET': urn = 'spotify:artist:3jOstUTkEu2JkjvRdBA5Gu' sp = spotipy.Spotify(auth_manager=SpotifyOAuth(client_id=envi.SECRET_ID, client_secret=envi.SECRET_PASS, redirect_uri=envi.SPOTIPY_REDIRECT_URI)) artist = sp.artist(urn) print(artist) user = sp.current_user() print(user) return JsonResponse(test, safe=False) It's just the code from the documentation, but I don't know where to look. -
Adding ordering on serializer (Django)
I have an issue for which I'm not sure if I am getting the right path to the soluction, hope you guys could help me out. I have added an extra field to my serializer, called distance (distance is equal the distance in miles between 2 different locations) I am looking to return the Business Object order my this new field, would it be possible? or am I taking the wrong path for this soluction? Down here you have my Serializer and ModelViewSet Serializer class BusinessesSerializer(serializers.ModelSerializer): distance = serializers.SerializerMethodField('get_location') class Meta: model= Businesses fields = ('id', 'address_first_line', 'address_second_line', 'city', 'region', 'post_code', 'phone_number', 'logo', 'join_date', 'distance') def get_location(self, business): ip_info = requests.get('https://api64.ipify.org?format=json').json() ip_address = ip_info["ip"] response = requests.get(f'http://api.ipstack.com/{ip_address}?access_key=8eba29fcae0bbc63c1e93b8c370e4bcf').json() latitude = response.get("latitude") longitude = response.get("longitude") first = (float(latitude), float(longitude)) second = (business.lat, business.long) distance = great_circle(first, second).miles return distance ModelViewSet class BusinessesViewSet(ModelViewSet): serializer_class = BusinessesSerializer queryset = Businesses.objects.all() -
In Django how can I get result from two tables in a single queryset without having relationship?
I have two models like this : class A(models.Model): is_available = models.BooleanField() date = models.DateTimeField(auto_now_add=True) # Some Other Fields class B(models.Model): is_available = models.BooleanField() date = models.DateTimeField(auto_now_add=True) # Some Other Fields I want to get the records from both models in a single list of dictionaries based on available or not and filter by date in descending order. How can I do it? -
Values join two tables without prefetch_related in Django with Postgress
I have one table "table1" I have other table "table2" "Table2" has a foreing key with "table1" I need to get "table1" values, with all register joined in "table2" in Django Table1.objects.filter().values("id","table2__id") My question is simple. Should I use select_prefetch mandatorily? Table1.objects.prefetch_related('table2').filter().values("id","table2__id") I'm suspecting that a lot of prefetch_related in one query are consuming a lot of memory, because is so slow. Thanks -
How to compute on the fly + download a file - React / Django?
I am working on an app which uses React and Django. I need a functionality whereby a user on the app can click a button and download a csv file on their machine. Importantly, the file is not already available anywhere, it needs to be generated on the fly when the user requests it (by clicking on the download button). I am thinking of implementing this flow: When the user clicks on the button, an API call is made which tells the backend to generate the csv file and store it in an s3 bucket the backend then sends a response to the frontend which contains the URL that the frontend can access to download the file from the s3 bucket the file gets downloaded Would this be a good approach? If not, what is the best practice for doing this? -
Filter model without using distinct method
I have a model with a list of products. Each product has an ID, price, brand, etc. I want return all the objects of the model where brand name is distinct. I am currently using django's built-in SQLite, so it does not support something like products = Product.objects.all().distinct('brand') Is there another way of returning all the objects where the brand name is distinct? -
Why is model._meta.get_fields() returning unexpected relationship column names, and can this be prevented?
Imagine I have some models as below: class User(AbstractUser): pass class Medium(models.Model): researcher = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True, related_name="medium_researcher") old_medium_name = models.CharField(max_length=20, null=True, blank=True) class Uptake(models.Model): material_quality = models.CharField(max_length=20, null=True, blank=True) medium = models.ForeignKey(Medium, on_delete=models.CASCADE, blank=True, null=True, related_name="uptake_medium") Now I have a function to return all column names to generate some overview in my HTML as such: from database.models import Medium MODEL_HEADERS=[f.name for f in Medium._meta.get_fields()] MODEL_HEADERS ['uptake_medium', 'id', 'researcher', 'old_medium_name'] Why does this return uptake_medium? As this is a ForeignKey relation set within the Uptake model, it should only be present within the Uptake model right? When I review the admin models this column does not show up, neither in the db.sqlite3 model when checking Uptake, so it seems to be sort of hidden, and only show up when requested with _meta. The relationship seems to be correct... This is causing a lot of problems with my code, and it would be great if only the 'non-meta' columns only could be returned. How should I approach? -
Is there any way to get name of request path in Django
I wanted to get django re_path's name parameter value from request or in any way. I have a url pattern like that, re_path(r'^user/query/page/list$', views.UserListView.as_view(), name="user_list") When request comes with user/query/page/list, I want to match it with name or directly get name of the path that described in re_path. I checked all request data and didn't reach it. -
I want to create a temporary url for login in my django project, how would I go about doing that?
My friend is teaching me coding via a project and I wanted to see if I could go a bit beyond what he is currently asking. I'd like to have a code to create a temporary url to give out for my site to create a profile. I basically want it to jump to a "create profile page", allow them to create the profile, and then redirect back to the home page. Keep in mind, I'm relatively new to this, so any and all excess explanation is more than welcome! I read some things about model.tempurl might be what I'm looking for, but I couldn't figure out where the temp url gets spit out. -
filter queryset for multiple models in Django
I'm implementing a search feature where I'm matching keys from the description. and also matching media if description and media type of ['mp4','mkv','mov','avi'] match so the condition is satisfied. So I have tried many methods but didn't find an efficient way. to make it possible without for loop. I want to use those together. description and media type ['mp4','mkv','mov','avi'] postinlang_queryset = PostInLanguages.objects.filter(description__contains=search_name) media_type_query_set = LanguageMedia.objects.filter(content_type__contains ['mp4','mkv','mov','avi']) -
Django UserCreationForm and Bootstrap Forms Layouts
I am trying to extend the UserCreationForm using a Bootstrap layout style for the field username. After the input tag in the registration form, I would like to add a div element like an example that I have readapted from the Bootstrap page: i.e. suggesting the user to enter the same username as the company domain. Let's focus to the bare minimum. The form readapted from Bootstrap is: <form class="row gy-2 gx-3 align-items-center method="POST" action="{% url 'register' %} "> <div class="col-auto"> <div class="input-group"> <input type="text" name="username" class="form-control" placeholder="your.username" id="id_username"> <div class="input-group-text">@company.domain.com</div> </div> </div> <div class="col-auto"> <button type="submit" class="btn btn-primary">Submit</button> </div> </form> Which produces the following: For the moment, I am using only {{form.as_p}} in my html template file: <form class="row gy-2 gx-3 align-items-center method="POST" action="{% url 'register' %} "> {{form.as_p}} <div class="col-auto"> <button type="submit" class="btn btn-primary">Submit</button> </div> </form> And I don't know how to add the <div class="input-group-text">@company.domain.com</div> part embedded in a <div class="input-group">...</div> block. My actual forms.py is a bit more complex, but readapted for this minimum example it contains the widget attributes as follows: class SignupForm(UserCreationForm): username = forms.CharField(label="", widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'your.username'})) class Meta: model = User fields = ( 'username', ) Without additional libraries, is there … -
Why do i keep encountering this error when i try to migrate on django app
return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: no such table: theblog_categories i expected to migrate succesfully