Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
Preventing certain values adding to Django model
I'm trying to put a restriction on my Django model. I have a user model and then a model which allows one user to "follow" another. I want to put a restriction so the user cannot follow themselves. It's not really working at all but I'm sort of stuck what to do. When I try to add a new object. It will let me alter an existing entry but if I try to create a new one I get the error: Follower: Follower object (None)>" needs to have a value for field "id" before this many-to-many relationship can be used. It's like I have to save it somehow before I check for the items but I'm not sure how to go about it. Models class User(AbstractUser): pass class Follower(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE, related_name="followers", unique=True) follows = models.ManyToManyField(User,blank=True,related_name="follows") # Prevent User from following themselves def save(self, *args, **kwargs): if self.follows.contains(self.user): return else: super().save(*args, **kwargs) I've tried variations of the if statement and I've tried using a for loop to go through the ManytoMany field but I can see the object doesn't exist yet -
Get n value with n parameter with Django Queryset
this is my first question. If my question is not clear, let me know :) So I learn Django (learning by doing) for 4 Months in my project. I have one table name material, which is the table contains material name and price. Here I will describe my table: id materialName price 1 Not Required 0 2 Material 1 123 3 Material 2 456 4 Material 3 900 I want to calculate the total material price by getting the price from the table. It looks ok if I only want to get 1 price only. But, I need to get 4 values of prices from what the user wants in input. Let's say the user chooses Material 3, Material 2, Not Required and Not Required. So there is 4 material price. Then, I use a queryset like this: x = rawmaterial.objects.filter(Q(materialName = 'Material 3') | Q(materialName = 'Material 2') | Q(materialName = 'Not Required') | Q(materialName = 'Not Required')).values_list('price',flat=True) but the result is (900, 456, 0) not like (900, 456, 0, 0). I have been trying with SQL query using OR, is there any possibility to get 4 values? Thank you :) -
XMLParser.__init__() takes 1 positional argument but 4 were given
I am getting this error while running the below command:- Python version=3.10.8 Django version=2.1 openpyxl=2.6.2 python manage.py runserver 127.0.0.1:8000 Error:- Exception ignored in thread started by: <function check_errors.<locals>.wrapper at 0x118793400> Traceback (most recent call last): File "/Users/chandanvarma/Desktop/project/retailer-backend/venv/lib/python3.10/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/Users/chandanvarma/Desktop/project/retailer-backend/venv/lib/python3.10/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/Users/chandanvarma/Desktop/project/retailer-backend/venv/lib/python3.10/site-packages/django/utils/autoreload.py", line 248, in raise_last_exception raise _exception[1] File "/Users/chandanvarma/Desktop/project/retailer-backend/venv/lib/python3.10/site-packages/django/core/management/__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "/Users/chandanvarma/Desktop/project/retailer-backend/venv/lib/python3.10/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/Users/chandanvarma/Desktop/project/retailer-backend/venv/lib/python3.10/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/chandanvarma/Desktop/project/retailer-backend/venv/lib/python3.10/site-packages/django/apps/registry.py", line 89, in populate app_config = AppConfig.create(entry) File "/Users/chandanvarma/Desktop/project/retailer-backend/venv/lib/python3.10/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/opt/homebrew/Cellar/python@3.10/3.10.8/Frameworks/Python.framework/Versions/3.10/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "/Users/chandanvarma/Desktop/project/retailer-backend/venv/lib/python3.10/site-packages/tablib/__init__.py", line 3, in <module> from tablib.core import ( File "/Users/chandanvarma/Desktop/project/retailer-backend/venv/lib/python3.10/site-packages/tablib/core.py", line 15, in <module> from tablib import formats File "/Users/chandanvarma/Desktop/project/retailer-backend/venv/lib/python3.10/site-packages/tablib/formats/__init__.py", line 12, in <module> from . import _xlsx as xlsx File "/Users/chandanvarma/Desktop/project/retailer-backend/venv/lib/python3.10/site-packages/tablib/formats/_xlsx.py", line 14, in <module> import openpyxl File "/Users/chandanvarma/Desktop/project/retailer-backend/venv/lib/python3.10/site-packages/openpyxl/__init__.py", line 6, in <module> from openpyxl.workbook import Workbook …