Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Crop multiple images In HTML form using Javascript
I am working on a project in Django , the functionality requires to add 4 images on a single html form for POST submission to the server. Now the images needs to be cropped individually ,for each selection. And should be able to submit it. I am able to do it for single image but cant do it for each image , a solution is JS will be highly helpful. -
Downloading a file from Django template on click doesn't work
I tried multiple ways to download a file on click from a Django template, but the download just won't start. Here's my view where I get the file path: def success(request): model_file_path = request.session.get('model_file_path') if request.method == 'POST': return render(request, "success.html", {'filepath': model_file_path}) else: return render(request, "success.html", {'filepath': model_file_path}) And here is what I tried in the success template with no success: <a href='{{filepath}}' download>download</a> <a href='{{ MEDIA_URL }}{{filepath}}' download={{filepath}}>download</a> <a href='{{filepath}}' download={{filepath}}>download</a> It just won't trigger a download, although the path is correct. -
Updating Database via GET request to Generic views in Django
I've got this Generic view that would list records from my DB for GET request to localhost:8000 However, I also want to UPDATE those records upon GET. For instance, GET localhost:8000 would return a list like so: [ { "user": 1, "address": "sdfgasgasdfg", "balance": "123.00000000" }, { "user": 1, "address": "sdfgasgasdfg25", "balance": "123.00000000" } ] Upon GET, I would like to also make an API to https://www.blockchain.com/api/blockchain_api to get the latest BTC balance and update the balance values for those addresses in my DB. Not quite sure how to do so with generic views view class WalletListCreateAPIView(generics.ListCreateAPIView): queryset = Wallet.objects.all() serializer_class = WalletSerializer model class Wallet(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) address = models.CharField(max_length=34) balance = models.DecimalField(max_digits=16, decimal_places=8) slug = models.SlugField(max_length=34, blank=True, null=True) def __str__(self): return self.address def save(self, *args, **kwargs): self.slug = slugify(self.address) super().save(*args, **kwargs) -
Generate data when button/link is clicked Django
I'm very new to Django and web apps. I have an HTML page that allows users to search database for player names. An HTML table is returned. Each entry is a player's performance in relation to a game they played. Each game has 10 players associated with it search_db.html <h1>Search Results for: {{searched}}</h1> <table> {% for player in match %} <tr> <td> <a href=search_player_db/{{player.match_id}}>{{player.match_id}}</a> </td> <td>{{ player.name}}</td> <td>{{ player.role}}</td> <td>{{ player.win_or_loss}}</td> </tr> {% endfor %} </table> {{IM TRYING TO GENERATE DATA HERE}} The match id is a link that brings the user to a page with additional details related to the match match_details.html {%block stats%} <body> <h1>Winning team</h1> {%for player in winners %} <li> {{player.name}} {{player.role}} </li> {%endfor%} <h1>Losing team</h1> {%for player in losers %} <li> {{player.name}} {{player.role}} </li> {%endfor%} </body> {%endblock%} Instead of being redirected to a new page when clicking the link, I'd like to load the content from match_details into the page below the table on search_db.html through the button/link in search_db.html views.py def search_playerdb(request): if request.method == "POST": searched = request.POST['searched'] players = PlayerInfo.objects.filter(player_name__contains=searched) context={ 'searched': searched, 'players': players} return render(request, 'searchdb.html', context) else: return render(request, 'searchdb.html', {}) def display_match(request, matchid): match = PlayerInfo.objects.filter(match_id=matchid) winners = … -
Serving static folder not from nginx but from uwsgi
I am using nginx - uwsgi setting. I want to serve the static folder from uwsgi not nginx. So I didn't set any static settings on nginx nginx setting server { listen 80; server_name dockerhost; charset utf-8; location / { proxy_pass http://127.0.0.1:8011/; include /etc/nginx/uwsgi_params; proxy_set_header X-Real-IP $remote_addr; proxy_set_header Host $host; proxy_pass_header X-XSRF-TOKEN; } } uwsgi start command uwsgi --http :8011 --processes 4 --threads 1 --module myapp.wsgi --logto /tmp/mylog.log and my django settings is here below. settins.py STATIC_URL = '/static/' STATIC_ROOT = "/usr/src/app/static" STATICFILES_DIRS = ( os.path.join(BASE_DIR,'frontend/dist'), ) urls.py urlpatterns += [ path('sp/', SeparateView.as_view()) ] if settings.DEBUG: urlpatterns += [ re_path(r'^static/(?P<path>.*)$', views.serve), ] When DEBUG=True, it works, static files are served,but DEBUG=False {% static %} in template doesn't work for it, the file under static directories are 404 error. I have done manage.py collectstatic and confirmed that there are files under /usr/src/app/static Where should I check ? -
How to prevent the trigger of django signals based Field value of Model?
I have a model with a boolean field. Based on the value of this boolean field I want to trigger a post_save signal in django. How can I implement it? Thanks in advance -
Django App on Azure App Service. How to upload files and view the uploaded files
I had created a Django app in which user can upload files and view it in dashboard. Its working fine in local system but when I deployed it in Azure App Service the file is uploading but can't view the file in dashboard. Its shows no file but i can see the file has uploaded in the directory mentioned and the url is correctly pointing to the file uploaded. -
way to implement Django case insensitive for login without using get_by_natural_key?
Need to make user login case insensitive without overiding the function get_by_natural_key, any way to achieve that with __iexact? Overiding any internal functions cant be done ,also note that we users are added from django admin so I just want to make the use login case insensitive -
"nie mo" after python3 manage.py startserver
I'm trying to start local server by using python django, and pycharm returns "nie mo" after python3 manage.py runserver command. Any idea what's the problem? -
Getting 'ModelBase' object is not iterable
I'm creating the following view to get the list of fruits and I got this type error message. I don't know what I missed here: TypeError: 'ModelBase' object is not iterable views.py class FruitsList(APIView): # To list fruits def get(self, request): fruits = Fruit.objects.all() serializer = FruitSerializer(Fruit, many = True) return Response(serializer.data) serializers.py: class FruitSerializer(serializers.ModelSerializer): class Meta: model = Fruit fields = [ 'id', 'name', 'customers', ] models.py: class Fruit(models.Model): """represents customer fruits""" name = models.CharField(max_length = 100) customers = models.ManyToManyField(Customer) def __str__(self): return self.name Your help is much appreciated! -
convert dropdown to text box when other option is selected
I have a dropdown which displays choices right now it works as just dropdown but when i select the option Other which is a choice when selected it should become textbox. models.py class MyModel(models.Model): task_name = models.CharField(blank=true, choices=somechoiceClass, default='') <div class="col-md-4"> <div class="form-group label-static" :class="{'has-error': errors.task_name && errors.task_name.length > 0}"> <label class="typo__label control-label">Task Name&nbsp;<span class="req">*</span></label> <multiselect v-model="form.task_name" :options="taskNameChoices" :multiple="false" :close-on-select="true" :clear-on-select="true" :preserve-search="true" placeholder="Select" label="text" track-by="id" :hide-selected="false" :show-labels="false"> </multiselect> <span class="help-block" v-show="errors.task_name" v-text="errors.task_name && errors.task_name[0]" v-cloak></span> </div> </div> <script> taskNameChoices: instanceData.case && instanceData.case.task_names || [], this.taskNameChoices = selectedOption.task_names; </script> -
''QuerySet' object has no attribute 'enter_the_destination_account_number'
Can anyone tell me what's wrong with my code? I am trying to use filter but its showing ''QuerySet' object has no attribute 'enter_the_destination_account_number'. I tried get() but it shows, get() returned more than one MoneyTransfer -- it returned 14!. here's some snap of code. Thanks in advance models.py class Status (models.Model): user_name = models.CharField(max_length=150, default=None) account_number = models.IntegerField() balance = models.IntegerField() phone_number= models.CharField(max_length=20, default=0) class MoneyTransfer(models.Model): enter_your_user_name = models.CharField(max_length = 150, default = None) enter_the_destination_account_number = models.IntegerField() enter_the_destination_phone_number=models.CharField(max_length=20, default=None) enter_the_amount_to_be_transferred_in_INR = models.IntegerField() views.py def TransferMoney(request): if request.method == "POST": form = forms.MoneyTransferForm(request.POST) if form.is_valid(): form.save() curr_user = models.MoneyTransfer.objects.filter(enter_your_user_name=request.user) dest_user_acc_num = curr_user.enter_the_destination_account_number #dest_phone number add korte hobe dest_phone_num= curr_user.enter_the_destination_phone_number temp = curr_user # NOTE: Delete this instance once money transfer is done dest_user = models.Status.objects.get(account_number=dest_user_acc_num) # FIELD 1 dest_phn= models.Status.objects.get(phone_number= dest_phone_num) transfer_amount = curr_user.enter_the_amount_to_be_transferred_in_INR # FIELD 2 curr_user = models.Status.objects.get(user_name=request.user) # FIELD 3 # Now transfer the money! curr_user.balance = curr_user.balance - transfer_amount #dest_phn.balance = dest_phn.balance + transfer_amount dest_user.balance = dest_user.balance + transfer_amount # Save the changes before redirecting curr_user.save() dest_user.save() temp.delete() # NOTE: Now deleting the instance for future money transactions return redirect(index) else: form = forms.MoneyTransferForm() return render(request, "epayapp/Transfer_money.html", {"form": form}) -
How to print query of Django ORM
I am using Django ORM query with Extra params. when I try to print the SQL query relevant to that ORM Query,i am getting the below Error message. ORM Query: Record = SAMPLE_TABLE.objects.extra(where=["REPLACE(Message,' ','') "+whereCaseSensitive+" like %s "+query],params=[duplicateCheckMessage]).filter(~Q(iStatus=2),~Q(iAppStatus=2),iEntityID=entityId,iTemplateType=1).first() Message - FieldName , whereCaseSensitive - '', query - ( FIND_IN_SET("test",Testfield)) I am trying to fetch the sql query related to this using print(Record.query) when i run this i am getting Exception as 'NoneType' object has no attribute 'query' Can any one help on this ? -
I am learning Django very hardly [closed]
I am stuck in Django Templates views (parameter) request: Any "request" is not accessedPylance No quick fixes available -
Using d Django Abstract Base User model to enable Profile tab
Using Django Abstract Base User model, How do I make the Profile tab show when a user is logged in. Should I create a model/form for Profile, This is the image of the html file. The backend for signup and login works perfectly fine but when a user signs up or logs in, the nav bar doesn't change at all. Please help {% extends 'base.html' %} {% block title %}Profile{% endblock %} {% block content %} <h1>Hello World</h1> {% if user.is_authenticated %} <a href="{% url 'profile' %}" type="button" class="btn btn-primary">Profile</a> <a href="{% url 'logout' %}" type="button" class="btn btn-primary">Logout</a> {% else %} <a href="{% url 'signup' %}" type="button" class="btn btn-primary">Sign Up</a> <a href="{% url 'login' %}" type="button" class="btn btn-primary">Log In</a> {% endif %} {% endblock %} -
Redirection from the link itself
I have auto logged-in URL for external service but it's one link open on the home page but I want to redirect the user to another page. Is there any way to open the logged-in link at first to save the credentials and then redirect the user to the desired page? -
Getting error on installing a python package regarding mysqlclient
I am currently working on a new project. Trying to install the requirements using pip but getting this error. Using python version 3.6.9 This is the error message I am getting. Collecting en-core-web-sm@ https://github.com/explosion/spacy-models/releases/download/en_core_web_sm-3.4.0/en_core_web_sm-3.4.0-py3-none-any.whl Downloading https://github.com/explosion/spacy-models/releases/download/en_core_web_sm-3.4.0/en_core_web_sm-3.4.0-py3-none-any.whl (12.8 MB) |████████████████████████████████| 12.8 MB 5.9 MB/s ERROR: mysqlclient-1.4.6-cp36-cp36m-win_amd64.whl is not a supported wheel on this platform. Any help would be highly appreciated and thank you in advance to anyone who looks into this. -
Point is not stored in database
I have a location based geodjango project. I got latitude and longitude from user and tried creating a point latitude = float(request.POST.get('latitude')) longitude = float(request.POST.get('longitude')) form.point = Point((latitude, longitude)) but data is not stored into the database, what is the real issue? -
django.core.exceptions.SynchronousOnlyOperation
Upgraded python from 3.6 to 3.8. Getting this error when I tried to connect to Django Admin. Is this because of version change? django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async. Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/usr/local/lib/python3.8/site-packages/django/core/handlers/base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.8/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/usr/local/lib/python3.8/site-packages/django/contrib/admin/sites.py", line 410, in login return LoginView.as_view(**defaults)(request) File "/usr/local/lib/python3.8/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "/usr/local/lib/python3.8/site-packages/django/utils/decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "/usr/local/lib/python3.8/site-packages/django/views/decorators/debug.py", line 89, in sensitive_post_parameters_wrapper return view(request, *args, **kwargs) File "/usr/local/lib/python3.8/site-packages/django/utils/decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "/usr/local/lib/python3.8/site-packages/django/utils/decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "/usr/local/lib/python3.8/site-packages/django/utils/decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "/usr/local/lib/python3.8/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/usr/local/lib/python3.8/site-packages/django/contrib/auth/views.py", line 63, in dispatch return super().dispatch(request, *args, **kwargs) File "/usr/local/lib/python3.8/site-packages/django/views/generic/base.py", line 98, in dispatch return handler(request, *args, **kwargs) File "/usr/local/lib/python3.8/site-packages/django/views/generic/edit.py", line 141, in post if form.is_valid(): File "/usr/local/lib/python3.8/site-packages/django/forms/forms.py", line 177, in is_valid return self.is_bound and not self.errors File "/usr/local/lib/python3.8/site-packages/django/forms/forms.py", line 172, in errors self.full_clean() File "/usr/local/lib/python3.8/site-packages/django/forms/forms.py", line … -
pip install PyDictionary : python setup.py egg_info did not run successfully. │ exit code: 1 [27 lines of output]
PS D:\projects\english-dictionary-with-django> pip install PyDictionary Collecting PyDictionary Using cached PyDictionary-2.0.1-py3-none-any.whl (6.1 kB) Requirement already satisfied: bs4 in c:\users\benard.byakatonda\appdata\local\programs\python\python310\lib\site-packages (from PyDictionary) (0.0.1) Requirement already satisfied: requests in c:\users\benard.byakatonda\appdata\local\programs\python\python310\lib\site-packages (from PyDictionary) (2.28.0) Collecting goslate Using cached goslate-1.5.4.tar.gz (14 kB) Preparing metadata (setup.py) ... done Collecting click Using cached click-8.1.3-py3-none-any.whl (96 kB) Requirement already satisfied: beautifulsoup4 in c:\users\benard.byakatonda\appdata\local\programs\python\python310\lib\site-packages (from bs4->PyDictionary) (4.11.1) Requirement already satisfied: colorama in c:\users\benard.byakatonda\appdata\local\programs\python\python310\lib\site-packages (from click->PyDictionary) (0.4.5) Collecting futures Using cached futures-3.0.5.tar.gz (25 kB) Preparing metadata (setup.py) ... error error: subprocess-exited-with-error × python setup.py egg_info did not run successfully. │ exit code: 1 ╰─> [27 lines of output] Traceback (most recent call last): File "", line 2, in File "", line 14, in File "C:\Users\benard.byakatonda\AppData\Local\Programs\Python\Python310\lib\site-packages\setuptools_init_.py", line 189, in monkey.patch_all() File "C:\Users\benard.byakatonda\AppData\Local\Programs\Python\Python310\lib\site-packages\setuptools\monkey.py", line 99, in patch_all patch_for_msvc_specialized_compiler() File "C:\Users\benard.byakatonda\AppData\Local\Programs\Python\Python310\lib\site-packages\setuptools\monkey.py", line 169, in patch_for_msvc_specialized_compiler patch_func(*msvc14('get_vc_env')) File "C:\Users\benard.byakatonda\AppData\Local\Programs\Python\Python310\lib\site-packages\setuptools\monkey.py", line 149, in patch_params mod = import_module(mod_name) File "C:\Users\benard.byakatonda\AppData\Local\Programs\Python\Python310\lib\importlib_init.py", line 126, in import_module return bootstrap.gcd_import(name[level:], package, level) File "C:\Users\benard.byakatonda\AppData\Local\Programs\Python\Python310\lib\site-packages\setuptools_distutils_msvccompiler.py", line 20, in import unittest.mock File "C:\Users\benard.byakatonda\AppData\Local\Programs\Python\Python310\lib\unittest\mock.py", line 26, in import asyncio File "C:\Users\benard.byakatonda\AppData\Local\Programs\Python\Python310\lib\asyncio_init.py", line 8, in from .base_events import * File "C:\Users\benard.byakatonda\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 18, in import concurrent.futures File "C:\Users\benard.byakatonda\AppData\Local\Temp\pip-install-zhu28thw\futures_997bcda2ca314b4a8559d52198da1259\concurrent\futures_init.py", line 8, in from concurrent.futures._base import (FIRST_COMPLETED, File "C:\Users\benard.byakatonda\AppData\Local\Temp\pip-install-zhu28thw\futures_997bcda2ca314b4a8559d52198da1259\concurrent\futures_base.py", line 357 raise type(self._exception), self._exception, self._traceback ^ … -
Django Loop Through Objects After Bulk .update()
This code runs on cron. So I want to update the status of the objects immediately so that these objects don't get picked up again if a second cron starts before the current one finishes (which will eventually start to happen with my app.) # Grab all pending emails. emails = delivery_que.objects.filter(status='PENDING') emails.update(status='SENDING') # Loop through the pending emails. for email in emails: The current code doesn't work, as I seem to no longer have access to the objects after I .update() them. This is the workaround I implemented: # Grab all pending emails. emails = delivery_que.objects.filter(status='PENDING') emails.update(status='SENDING') emails = delivery_que.objects.filter(status='SENDING') # Loop through the pending emails. for email in emails: Is there another better solution I'm missing? I'd prefer not to query the database again to reselect the objects that I should already have access to from the first query. -
Django - filtering related objects
I have a puzzle. These are my models: class StatusGroup(models.Model): name = models.TextField() def __str__(self): return self.name class StatusDetail(models.Model): action = models.CharField(choices=[("CORRECT", "CORRECT"), ("INCORRECT", "INCORRECT")], max_length=64) status_group = models.ForeignKey(to=StatusGroup, on_delete=models.CASCADE, related_name="status_details") def __str__(self): return f"Detail: {self.action}" serializers: class StatusDetailSerializer(serializers.ModelSerializer): class Meta: model= models.StatusDetail fields = "__all__" class StatusGroupSerializer(serializers.ModelSerializer): status_details = StatusDetailSerializer(many=True) class Meta: model = models.StatusGroup fields = [ "pk", "status_details", "name" ] And a view: class Status(viewsets.ModelViewSet): queryset = models.StatusGroup.objects.all() serializer_class = serializers.StatusGroupSerializer authentication_classes = [] permission_classes = [permissions.AllowAny] filter_backends = (DjangoFilterBackend,) filterset_fields = ['status_details__action'] When I hit localhost:8000/api/status?status_details__action=INCORRECT I get: [ { "pk": 2, "status_details": [ { "id": 3, "action": "CORRECT", "status_group": 2 }, { "id": 4, "action": "INCORRECT", "status_group": 2 } ], "name": "Mixed" } ] Whereas I would like to have: [ { "pk": 2, "status_details": [ { "id": 4, "action": "INCORRECT", "status_group": 2 } ], "name": "Mixed" } ] How do I force Django to filter the related objects? I can get the result I want in SQL console, but Django adds, all the related objects that belong to the StatusGroup. I have a misconception, but I don't know what that is. -
How to implement Django case insensitive for login without overriding the function get_by_natural_key
I want to make user login case insensitive without overiding the function get_by_natural_key , is there is any way to achieve that with __iexact ? I dont want to overide any internal functions,also note that we add users from django admin so i just want to make the use login case insensitive -
search functionality in Django ORM
if there is two type of data in table :'ABC-DE' and 'ABCDE' if someone search with space and underscore or hyphen so how to search for it without the regular expression -
Deploying Django application using openlitespeed and Gunicorn
Can I deploy a django application using gunicorn and openlitespeed ? Gunicorn can be used with LiteSpeed as mentioned here. But I am not getting any resource for openlitespeed.