Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to append value to the ArrayField in Django with PostgreSQL?
I have created a model with the ArrayField in Django Model. I am using PostgreSQL for the database. I want to create new rows in the database or update the existing rows. But I can not insert or append data to the ArrayField. Model class AttendanceModel(BaseModel): """ Model to store employee's attendance data. """ user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='attendance_user') date = models.DateField() time = ArrayField(models.TimeField(), blank=True, null=True) class Meta: unique_together = [['user', 'date']] def __str__(self): return f'{self.user.username} - {self.date}' View attend, created = models.AttendanceModel.objects.get_or_create(user=fingerprint.user, date=attendance_date) attend.time = attend.time.append(attendance.timestamp.time()) attend.save() The time field does not being created or updated with the new value. How can I do this? -
TypeError: add() missing 1 required positional argument: 'resubscribe' in Django 3
Here i am using Django 3.0 and Python 3.7 I am getting 2 errors here: TypeError: add() missing 1 required positional argument: 'consent_to_track' TypeError: add() missing 1 required positional argument: 'resubscribe' Here is my code from models.py where the issue is def subscribe_to_signup_email_list(self): # campaign monitor subscriber = createsend.Subscriber({'api_key': settings.CAMPAIGN_MONITOR_API_KEY}, settings.CAMPAIGN_MONITOR_LIST_MCAM_ADMINS, self.email) try: email_returned = subscriber.add(settings.CAMPAIGN_MONITOR_LIST_MCAM_ADMINS, self.email, self.name, [], True) except Exception as e: ''' print type(e) print e.args print e ''' # it is not obvious what the error is subject, from_email, to = 'Welcome Email Error', 'noreply@mycontactandme.com', "notifications+errors@mycontactandme.com" client = self.client text_content = "Name: " + self.name + "\n" text_content += "Email: " + self.email + "\n" text_content += "Phone: " + client.phone + "\n" text_content += "Company: " + client.name + "\n" text_content += "Website: " + client.website + "\n" text_content += "Country: " + client.country + "\n" text_content += "\n\n" + traceback.format_exc() + "\n" msg = EmailMultiAlternatives(subject, text_content, from_email, [to], []) msg.send() return False return True Here is my error traceback for error 1 (i.e TypeError: add() missing 1 required positional argument: 'consent_to_track') Traceback (most recent call last): File "/home/harika/krishna test/dev-1.8/mcam/server/mcam/core/models.py", line 1005, in subscribe_to_signup_email_list email_returned = subscriber.add(settings.CAMPAIGN_MONITOR_LIST_MCAM_ADMINS, self.email, self.name, [], True) TypeError: add() missing 1 … -
Save custom Date and Time in created_at field Django
I want to save a custom date and time in created_at field. Currently my model has created_at = models.DateTimeField(auto_now_add=True) I want to give my own date and time which i will receive from user current time . How can i do this -
can't install django using pipenv/unable to create process using python "blah blah"
Newbie python learner here. Was following Mosh's guide (yt: /watch?v=rHux0gMZ3Eg&t=804s) but I got stuck in the pipenv part.. I tried a lot of workarounds/solutions but none of them worked (..ones I found so far), I just want to proceed on coding my first web app using Django. The dilemma taught me a lot about virtual environments and dependencies tho, but I've been stuck on this for 2 days now and I wanna move on. Actually, at first, I got to install Django but I was tracing back and redoing the processes to learn and fix the errors on VSCode but it got me a few steps back and I got stuck eventually. Out of frustration, I deleted a couple of files because I had to do reinstallation of Python for both "All users" and "Specific users" - and the paths messed up and so there were Python folder at C:\Programs Files and there were in C:...\Users, so I had to delete the other one. I also deleted a pipfile and pipfile.lock - idk if this was where the problem is but I couldn't generate any pipfile.lock anymore - but maybe it's just because I couldn't install Django. My setup: Windows … -
How to display M2M field in in editing Django?
I have M2M fiedl that i need to displa in edit form. It looks like this When i create new entry i just use {{ form.analog }} with this form "analog": SelectMultiple(attrs={ 'multiple': 'multiple', 'name': 'favorite_fruits', 'id': 'fruit_select', But i dont khow how to display this in edit form with already selected values -
Update Django model without using a Serializer
How do I better update a model without using the built in serializer from Django Rest Framework? I have a view here that updates the RecipeIngredient model. My serializer is defined inside my view and I do not want to make it responsible for hitting the database, only for serializing/deserializing the data. I have a services.py which handles all the database calls. So I send it the data it updates the model and saves it. This does not seem like a very good approach to me. Is there a better way to accomplish this? View class RecipeIngredientUpdateApi(APIView): class InputSerializer(serializers.Serializer): magnitude = serializers.FloatField(required=False) unit = serializers.CharField(max_length=255, required=False) def post(self, request, id): serializer = self.InputSerializer(data=request.data) serializer.is_valid(raise_exception=True) recipe_ingredient_update(id=id, **serializer.validated_data) return Response(serializer.data, status=status.HTTP_200_OK) Service.py This service is what I am trying to clean up. def recipe_ingredient_update(*, id, magnitude, unit): """Updates an existing RecipeIngredient""" recipe_ingredient = RecipeIngredient.objects.get(id=id) recipe_ingredient.magnitude = magnitude recipe_ingredient.unit = unit recipe_ingredient.full_clean() recipe_ingredient.save() return recipe_ingredient -
Django: Filter AbstractUser records using SQL, only show logged in user records
I have an AbstractUser. I want to restrict the records they're shown to their own (only show the records of the logged in user). I'd really like to do it with an SQL query as there are neighbouring tables to deal with. Any ideas? models.py class Teacher(AbstractUser): profile = models.ManyToManyField(Profile, through='TeacherProfile') unit = models.ManyToManyField(Unit, through='TeacherUnit') mobile = models.CharField(max_length=16) email = models.EmailField(max_length=100, unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username', 'first_name', 'last_name'] def __str__(self): return self.email -
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