Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there any alternative for Oracle regexp_substr in Django ORM?
As I have seen there is a method for matching regex patterns in Django. But can we extract matching patterns from data in Django ORM? -
access to heroku side to update a file included in venv?
I'm making a blog using Django. Just finished coding and tested offline, everything is fine, and also was able to deploy using Heroku. But the problem is, when I do heroku run , it returns this error: cannot import name 'url' from 'django.conf.urls' (/app/.heroku/python/lib/python3.8/site-packages/django/conf/urls/init.py) I had the same issue before so had to update a file in venv: venv/Lib/site-packages/django/conf/init.py from from django.conf.urls import url to from django.urls import re_path as url . Now it works fine offline thanks to the solution to this problem: ImportError: cannot import name 'url' from 'django.conf.urls' after upgrading to Django 4.0 I think I could do the same on the Heroku side, but not sure how to access to /app/.heroku/python/lib/python3.8/site-packages/django/conf/urls/init.py and update it. Any help would be appreciated. -
Django Graphene when filtering on nested value, don't show parent record if no data is returned
I have a GraphQL query that will return purchase orders and the products that go with those purchase orders. I have set up two filters, the first being on the username that is associated with a purchase order, and another filter on the product name for products for the purchase orders. If a user were to search for a particular product, I would like to only return orders that contain that product. At the moment, it still returns all purchase orders, but removes the product data that doesn't match the search criteria. The database structure is a table that contains the purchase orders called purchase_orders and a purchase order products tables called purchase_orders_products that has a FK called order_id to the purchase order id field. For example, in the response below, if purchaseOrdersProductsOrderId.edges is empty, I don't need to return the order data for ThisIsUsername. Schema # region Integration Purchase Orders class PurchasesProducts(DjangoObjectType): id = graphene.ID(source='pk', required=True) class Meta: model = purchase_orders_products interfaces = (relay.Node,) filter_fields = {'product_name': ['icontains']} class Purchases(DjangoObjectType): id = graphene.ID(source='pk', required=True) class Meta: model = purchase_orders interfaces = (relay.Node,) filter_fields = {'date': ['gt', 'lt', 'isnull'], 'username': ['icontains'],} connection_class = ArtsyConnection class PurchasesQuery(ObjectType): purchases = ArtsyConnectionField(Purchases) date_filter_list … -
No module named 'fusioncharts'
I am trying to plot fusion chart in django after adding fusioncharts,I am getting an error. from fusioncharts import FusionCharts FusionCharts ModuleNotFoundError: -
How to get the current url into django model
I'm very new onto Django world and I want to get the current URL from the save instruction and I don't have an idea of how to do that. -
How to convert timezone to datetime and ISO 8601 format in python?
How to convert a timezone string like 2022-06-23T05:00:00.006417+00:00Z to datetime and ISO 8601 format? -
how automatically filter multiple condition in Django
i have a user model like this : class User: first_name = models.CharField(max_length=64) last_name = models.CharField(max_length=64) phone = models.CharField(max_length=11) city = models.CharField(max_length=11) province = models.CharField(max_length=11) i need doing search on my model and i have data like city=x,province:y . but i don't want use them manually in filter. can Serializer do this automatically? -
Django User Authentication via another API (DRF)
I need to build a frontend django application that will need to authenticate users via the other internal API built using DRF/Djoser (backend API). The backend API (DRF) allows Session and Token Authentication at the moment. It is built using Django REST Framework/Djoser auth package and has all the common auth endpoints like login, logout, token, etc. My task is to build a frontend app that will authenticate users via the backend API and let the users to do common CRUD operations (I guess by calling the endpoints on the backend API). I am not clear about how to handle the auth - via Django views or via AJAX calls to the backend API endpoints. Does it need to be SessionAuth or TokenAuth? The more I research this topic, the more I get confused :) Any help/direction is much appreciated. -
How to inherit Generic Filtering in extra action
I want to inherit Generic Filtering include (filterset_fields, search_fields, ordering_fields in extra action sold. So how to do it, and any way better for this case ? Thank any advice for me ! class ApartmentViewset(viewsets.ModelViewSet): queryset = Apartment.objects.all().order_by('-timestamp') serializer_class = ApartmentSerializer # Set permission for only user owner apartment can edit it. permission_classes = [ permissions.IsAuthenticatedOrReadOnly, IsOwnerApartmentOrReadOnly] # Add search by address, filter by district and ordering by price filter_backends = [filters.SearchFilter, DjangoFilterBackend, filters.OrderingFilter] filterset_fields = ['district'] search_fields = ['address', 'seller'] ordering_fields = ( 'price', ) # fill current username when create new apartment def perform_create(self, serializer): serializer.save(seller=self.request.user) @action(detail=False) def sold(self, request): queryset = self.queryset.filter(issold=True) serialize = self.serializer_class(queryset, many=True) return Response(serialize.data) -
In Django application (sqllite3)Primary key of a table is not to resetting its unique id
I created a Product table that has items that I deleted in order to clear data and add new items, however, when I add new items the primary key which is a unique id in the below image is not starting from 0 but continuing from the previous unique id that I deleted. I am using Django ORM - sqllite3. I found a similar question was asked in this stackoverflow question which is not helpful to me in my case of Django application. How can I reset the primary key to 0 so that It always starts from'0'? -
How to get length of array field present in PostgreSQL using Python Django Models
This is my Django model: class UserVpaUpiId(models.Model): user_id = models.IntegerField(db_index=True, unique=True) vpa_upi_id = models.TextField(null=False, blank=True) created_on = models.DateTimeField(auto_now_add=True, null=False) updated_on = models.DateTimeField(auto_now=True, null=False) I want to delete an entry with a particular user_id, which I am able to do successfully using: UserVpaUpiId.objects.filter(user_id=user_id).delete() But, before that, I want to display the number of UPIs, which are stored in vpa_upi_id in the format: ["acbd.pq@icici", "9987654431@apl", "9876543210@apl"] How can I achieve that? -
Javascript wont executed in my html Django code
I have a very basic HTML code that i include in my Django project, however the Javascript wont load somehow in my project, the button seems do nothing, where i want to start my guidetour js. The code is attached below {% load static %} <html> <head> <title>Tourguide Demo</title> <link rel="stylesheet" href="{% static 'css/base.css' %}"> <link rel="stylesheet" href="{% static 'js/script.js' %}"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"/> <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/LikaloLLC/tourguide.js@0.2.0/tourguide.css"/> <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/LikaloLLC/tourguide.js@0.2.0/tourguide.min.js"/> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js"/> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"/> <link rel="stylesheet" href="https://code.jquery.com/jquery-3.3.1.slim.min.js"/> </head> <body> <h1 style="text-align:center;"> Tour Guide Demo.</h1> <div class="container"> <div class="py-5 text-center"> <h2>Checkout form</h2> <p class="lead">Below is an example usage of Tour Guide content based approach. Click [Start tour] button below to start the guided tour:</p> <p> <button class="btn btn-success btn-lg btn-block" id="tourbutton"> Start tour </button> </p> </div> <div class="row"> <div class="col-md-4 order-md-2 mb-4"> <h4 class="d-flex justify-content-between align-items-center mb-3"> <span class="text-muted">Your cart</span> <span class="badge badge-secondary badge-pill">3</span> </h4> <ul class="list-group mb-3" data-tour="step: 1; title: Your cart; content: Example cart description text displays cart description"> <li class="list-group-item d-flex justify-content-between lh-condensed"> <div> <h6 class="my-0">Product name</h6> <small class="text-muted">Brief description</small> </div> <span class="text-muted">$12</span> </li> <li class="list-group-item d-flex justify-content-between lh-condensed"> <div> <h6 class="my-0">Second product</h6> <small class="text-muted">Brief description</small> </div> <span class="text-muted">$8</span> </li> <li class="list-group-item d-flex … -
Is there any Javascript or React-Native equivalent syntax of this python code?
all. I'm trying to post to my django REST server and following is python-version of how I post. with open(some_image, 'rb') as f: response = requests.post( url, files={ 'image': f, }, data={ 'longitude': SETTINGS[1]['long'], 'latitude': SETTINGS[1]['lat'], 'user_id': SETTINGS[1]['user_id'], }) I tried to do the same thing in react native ( javascript ), but it gives me errors. Following is my react native code: upload = async () => { let files = { 'image' : test // test is a base64 image file } let data = { 'longitude' : location["longitude"], 'latitude' : location["latitude"], 'user_id' : "test_id", } postUrl = "someurl"; axios.post(postUrl, files = files, data = data ).then( response => console.log(response) ).catch(function (error) { console.log(error.response); console.log(error); }); } The error status is 415 and it says "Unsupported media type "application/json" in request. -
Django Rest Framework: Got a `TypeError` when calling `*.objects.create()` when setting logged in User as owner of team
I am trying to set the logged in user as the owner of the team the user creates. However I get the following error: Got a TypeError when calling Team.objects.create(). This may be because you have a writable field on the serializer class that is not a valid argument to Team.objects.create() In models.py: class Team(models.Model): name = models.CharField(max_length=100) owner = models.OneToOneField( to=get_user_model(), on_delete=models.CASCADE, editable=False, ) budget = models.PositiveBigIntegerField(default=5000000) country = MultiSelectField(choices=COUNTRY_CHOICES) value = models.PositiveBigIntegerField(default=0) In serializers.py: class TeamSerializer(ModelSerializer): owner = UserSerializer(read_only=True) class Meta: model = Team fields = '__all__' read_only_fields = ['owner', 'budget', 'value'] In views.py class TeamCreateView(CreateAPIView): queryset = Team.objects.all() permission_classes = [IsAuthenticated] authentication_classes = [SessionAuthentication, BasicAuthentication] serializer_class = TeamSerializer def perform_create(self, serializer): serializer.save(owner=self.request.user) In urls.py path('team/', TeamCreateView.as_view(), name='create_team'), Please ignore the bad indentation. I am not sure why the error is throwing or what I have done differently. Already checked some other questions such as: Django Rest Framework - "Got a `TypeError` when calling `Note.objects.create()'" Django Rest Framework nested objects create with request.user I wonder if it's because I am using OneToOneField instead of ForeignKey because as far as I am aware, ForeignKey should not used when unique=True -
Can I seed a join table in Django not using fixtures?
I'm trying to seed a many-to-many join table in Django. To seed the rest of my database, I've been using fixtures. That process requires a model. But if I create a model and then a fixture for the join table, I'll end up with two tables in the database -- the one based on my model/fixture and the one django automatically creates. Is there a way to seed this Django-created join table? -
In Django REST framework's filtering, What "purchaser__username=username" mean
I'm studying to using Django Rest framework in my Project, but I'm confuse with this code serializer_class = PurchaseSerializer def get_queryset(self): """ Optionally restricts the returned purchases to a given user, by filtering against a `username` query parameter in the URL. """ queryset = Purchase.objects.all() username = self.request.query_params.get('username') if username is not None: queryset = queryset.filter(purchaser__username=username) return queryset What does purchaser__username=username mean in this code ? It quite confusing me for time now. -
Querying an API, and displaying it's results from from form input - Django
I am not sure if I am going about this correctly, but I am not getting any errors it just reloads the page without displaying anything. The issue could be with me trying to format the api string and input the users input there? I also tried returning the variable as an HttpResponse, still made no difference. Sorry just getting back into python, and just starting with Django. Correct code should go something like this: 1.User inputs their name into the form 2. Page then displays the usersid. Code: views.py: from urllib import response from django.shortcuts import render from django.http import HttpResponse import requests from .forms import SearchUser import json # Create your views here. def home(response): # data = requests.get( # 'https://americas.api.riotgames.com/riot/account/v1/accounts/by-riot-id/ReallyBlue/NA1?api_key=RGAPI-6c5d9a2c-3341-4b0c-a0a5-7eafe46e54cf') # userid = data.json()['puuid'] return render(response, "main/home.html", { 'form': SearchUser(), # include reference to your form 'userid': search, # 'mmr':NA, }) def search(response): if response.method == "POST": form = SearchUser(response.POST) if form.is_valid(): n = form.cleaned_data["name"] user = n(name=n) user.save() data = requests.get( "https://americas.api.riotgames.com/riot/account/v1/accounts/by-riot-id/f'{user}'/NA1?api_key=RGAPI-6c5d9a2c-3341-4b0c-a0a5-7eafe46e54cf") userid = data.json()['puuid'] return HttpResponse(userid) else: form = SearchUser() return render(response, "main/home.html", {"userid": userid}) forms.py: from django import forms class SearchUser(forms.Form): name = forms.CharField(label="Name", max_length=200) urls.py: from django.urls import path from . import views … -
Django filter model objects related to another model
I am trying to create a query set that matches a model objects, here's what i tried: a = Product.objects.first() # Select first product as a test b = a.compareproducts_set.all() # Filter only related product "a" in the query Now i only have first product "a" and it's filtered related query set "b", how to iterate the rest products along with their filtered query set from second model? So i can have two lists i can zip and loop them in template -
how to remove html elements after 30 min django
hello iam trying to make breaking news bar in my website , i used for that html ,css and django framework as follows : this is my html code : <div class="bereaking"> <div class="breaking_news"> <div class="news-ticker-title">عاجل</div> <div class="news"> <marquee direction="right" onmouseover="this.stop();" onmouseout="this.start();" class="marquee"> {% for breaking in breakings %} <a class="marquee-child" href=""><span>{{breaking.breaking_news}}</span></a> {% endfor %} </marquee> </div> </div> </div> this is my model.py: class breaking(models.Model): breaking_news = models.TextField(max_length=5000 , blank=True) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.id) i want to make timing for each news so iwant to add this bar when i add news from control panel and remove the bar after 30 min of the time how can i make that ? -
Is there a way to write a pytest test case to test the current api url?
I am attempting to set up a new GraphQL API for the first time, and am attempting to write a pytest test suite to cover the process. I am using Django 4.0. I want to set up a test that, when run, will look at the current server address (localhost or not), send a request to the GraphQL url at that address, and assert the result. I currently receive the following error "FAILED api/tests/test_api.py::test_get_all_notifications - requests.exceptions.ConnectionError: HTTPConnectionPool(host='localhost', port=2448): Max retries exceeded with url: /graphql ..." Here is what I have so far: import requests import json from main.tests.fixtures import * def get_current_server_url(): # TODO: <---- THIS IS WHAT SHOULD CHANGE BASED ON CURRENT SERVER return "http://localhost:2448/graphql" def make_graphql_request(query: str) -> dict: url = get_current_server_url() request = requests.post(url, json={'query': query}) return json.loads(request.text) def test_get_all_notifications(db, notification) -> None: """Confirms that the GraphQL API returns a valid notification ID when requested.""" all_notifications_query = """{ allNotifications { id } }""" data = make_graphql_request(query=all_notifications_query)['data'] assert len(data['allNotifications']) == 1 There are several dependant fixtures being used in my notification fixture, but the notification fixture itself is as follows: @pytest.fixture() def notification(db, user__user_in_group__group, default_config) -> None: """Stages a new notification in the database.""" (sending_user, receiving_user, group) = … -
getting elements with a queryset based on a left join in django
I have two models: class A(models.Model): field1 = models.CharField(max_length=100) field2 = models.CharField(max_length=100) class B(models.Model): a_field = models.ForeignKey(null=True,blank=True,related_name='a',on_delete=models.SET_NULL) field2 = models.CharField(max_length=100) I want to get all of elements of model A which are not related to B. Here is the query I wrote but it doesn't work: B.objects.select_related("a_field").filter(a_field__isnull=True) How can I solve this problem? -
HTTPSConnectionPool - Caused by SSLError(SSLError(1, '[SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:1131)
Consuming an API which was by http and passed to https returns the error: HTTPSConnectionPool(host='ip', port=por): Max retries exceeded with url: /b1s/v1/Deposits (Caused by SSLError(SSLError(1, '[SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:1131)'))) in the code I already tried adding this way: session = requests.Session() session.verify = False session.trust_env = False verify=ssl.CERT_NONE I also tried to install urllib3 Requirement already satisfied: urllib3==1.23 -
Can't join two tables on a foreign key field using django ORM?
class weapons(models.Model): weapon = models.CharField(max_length=11) country = models.IntegerField() flags = models.IntegerField(default=0) title = models.CharField(max_length=1000) class compare(models.Model): weapon = models.CharField(max_length=11) user_id = models.IntegerField() flags = models.IntegerField(default=0) WeaponNode = models.ForeignKey(weapons, on_delete=models.PROTECT) When I run this function: compare.objects.filter(user_id=1).values_list('weapon', 'WeaponNode__title') I expect this query raw: SELECT apps_compare.weapon, apps_weapons.title FROM apps_compare INNER JOIN apps_weapons ON (apps_compare.weapon = apps_weapons.weapon) WHERE apps_compare.user_id = 1 Result should be: But it returns this instead: SELECT "apps_compare"."weapon", "apps_weapons"."title" FROM "apps_compare" INNER JOIN "apps_weapons" ON ("apps_compare"."WeaponNode_id" = "apps_weapons"."id") WHERE "apps_compare"."user_id" = 1 apps_weapons.title returns null: In other examples I saw, they only used id with JOIN ON but I want to use a weapon value instead of id. How can I do accomplish with ORM? If it's not possible with ORM, then what are the other ways? -
Retrieving data from Mongodb and show it on front-end using django
I have a mongodb database named as world, which has two collection from before city, languages. I want to show the data of my collection on the web, how can i do it. currently i know to create collection in models.py and migrate it. like; first we have to edit databases[] in setting.py DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'world', } } in models.py i creted a class and migrated it using python manage.py migrate class Destination(models.Model): name= models.CharField(max_length=100) img=models.ImageField(upload_to='pics') desc=models.TextField() and i'm able to retrieve data from Destination by using below code in views.py from django.shortcuts import render from .models import Destination def index(request): dests=Destination.objects.all() return render(request,'index.html',{'dests':dests}) My question is my collection/class is already available in the database ( city, language) and i'm not creating it contrary to Destination which was defined by me. then how to show data of city collection of world database on the front-end. kindly looking for help. -
'Account' object has no attribute 'orderproduct' The downlad and preview is not shwoing
I want a situation, when the user purchases the product, and orderproduct created, he can download the image.. This is the product Model class Product(models.Model): # user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) # managers = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name="product_manager") seller = models.ForeignKey(SellerAccount, on_delete=models.CASCADE) media = models.ImageField(blank=True, null=True, upload_to=download_media_location, storage = FileSystemStorage(location=(protected_uploads_loc))) title = models.CharField(max_length=250) slug = models.SlugField(blank=True, unique=True) description = models.TextField() price = models.DecimalField(decimal_places=2, max_digits=100, default=15.99) sale_active = models.BooleanField(default=False) sales_price = models.DecimalField(decimal_places=2, max_digits=100, default=9.99, null=True, blank=True) image_size = models.CharField(max_length=20, null=True) # date_taken = models.DateTimeField(auto_now_add=True, auto_now=False) location = models.CharField(max_length=150, null=True) This is the orderproduct model class OrderProduct(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE) payment = models.ForeignKey(Payment, on_delete=models.SET_NULL, blank=True, null=True) user = models.ForeignKey(Account, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) # download = models.ManyToManyField(Product, related_name="download_product") ordered = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.user.username This is the product download views class ProductDownloadView(MultiSlugMixin, DetailView): model = Product def get(self, request, *args, **kwargs): obj = self.get_object() # if obj in request.user.myproducts.products.all(): if obj in request.user.orderproduct.product_set.all(): filepath = Path.joinpath(settings.PROTECTED_UPLOADS, obj.media.path) print(filepath) guessed_type = guess_type(filepath)[0] wrapper = FileWrapper(open(filepath, "rb")) mimetype = "application/force-download" if guessed_type: mimetype = guessed_type response = HttpResponse(wrapper, content_type=mimetype) if not request.GET.get("preview"): response["Content-Disposition"] = "attachment; file=%s"%(obj.media.name) response['X-SendFile'] = str(obj.media.name) return response else: raise Http404 This is the html …