Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Building urls with django template system
So I need to build an url querying multiple objects. I tried to use the template system from django to build it with no success. I was wondering if there is any way of doing this in the template or if I should just write a view function. {% url 'service-ticket/new' as request %} {% with request|add:"?" as request %} {% endwith %} {% for entry in object.items.all %} {% with request|add:"spareparts="|add_string:entry.item.id|add:"&" as request %} {% endwith %} {% endfor %} <a class="btn-add float-right" href={{ request }} role="button"> THIS SHOW HAVE ALL </a> -
After refreshing angular application in browser: django response
I´m currently working on an application: Django backend and angular frontend. Everything works fine, but after refreshing one page in the browser I don´t get the angular response anymore. But what I get is a successful answer from my Django server (HTTPResponse: 200). My Django urls.py is as followed: from django.urls import path from quickstart import views # Wire up our API using automatic URL routing. # Additionally, we include login URLs for the browsable API. urlpatterns = [ path('images/', views.ImageList.as_view()), path('images/<str:id>/', views.Image.as_view()), path('images/<str:id>/explanations', views.Explanation.as_view()) ] My app-routing.modules.ts: const routes: Routes = [ {path: 'home', component: MainComponent}, {path: 'images', component: ImageComponent, children: [ { path:':id', component: ImageDetailComponent } ]}, {path: '', redirectTo: '/home', pathMatch: 'full'}, ]; @NgModule({ imports: [RouterModule.forRoot( routes )], exports: [RouterModule] }) export class AppRoutingModule { } Thanks for helping! -
Django Model isn't migrating even after i saved and added app to installedApps
from django.db import models from django.contrib.auth import get_user_model user = get_user_model # Create your models here. class Post(models.Model): title = models.CharField(max_length=200) text = models.TextField(max_length=100) author = models.ForeignKey( user, on_delete=models.CASCADE) created_date = models.DateTimeField() published_date = models.DateTimeField() PS C:\Users\hp\Desktop\djangomodels> cd I4G006918VEO PS C:\Users\hp\Desktop\djangomodels\I4G006918VEO> python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions Running migrations: No migrations to apply. -
Django Rest Framework: After defining permissions I'm not able to access user details of logged in user
I want the admin user to access every user detail (GET, POST) and the non-admin user to get access to its own detail only but I'm getting error while implementing this. As I've shared my views.py, permissions.py, and models.py for the same. I'm using Postman for API testing and this is working fine for admin user but for an individual user, it's not working. views.py class UserListCreateAPIView(generics.ListCreateAPIView): permission_classes = [IsStaffOrTargetUser] queryset = User.objects.all() serializer_class = UserSerializer class UserRetrtieveUpdateDestroyAPIView(generics.RetrieveUpdateDestroyAPIView): permission_classes = [IsStaffOrTargetUser] queryset = User.objects.all() serializer_class = UserSerializer permissions.py class IsStaffOrTargetUser(BasePermission): def has_permission(self, request, view): # allow user to list all users if logged in user is staff return request.user or request.user.is_staff def has_object_permission(self, request, view, obj): # allow logged in user to view own details, allows staff to view all records return request.user.is_staff or obj == request.user models.py class User(AbstractBaseUser): email = models.EmailField(verbose_name='Email',max_length=255,unique=True) name = models.CharField(max_length=200) contact_number= models.IntegerField() gender = models.IntegerField(choices=GENDER_CHOICES) address= models.CharField(max_length=100) state=models.CharField(max_length=100) city=models.CharField(max_length=100) country=models.CharField(max_length=100) pincode= models.IntegerField() dob = models.DateField(null= True) # is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name','contact_number','gender','address','state','city','country','pincode','dob'] def __str__(self): return self.email def has_perm(self, perm, obj=None): "Does the user have a … -
How do i increase the number of likes
How do i increase the number of likes in a answer models. I want when a user posted the answer, some user's in the application would be able to like it, like social media likes system, is anyone who can shows me how to increase the number of likes in my views and template ? I really don't know how to use count() function in the views and template, so this is my first time trying to add likes system in django application. class Answer(models.Model): user = models.ForeignKey(User, blank=False, null=False, on_delete=models.CASCADE) answer = RichTextField(blank=False, null=False) post = models.ForeignKey(Question, blank=False, null=False, on_delete=models.CASCADE) def __str__(self): return str(self.user) my like model: class Like(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Answer, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.user) my views: def viewQuestion(request, slug): question = get_object_or_404(Question, slug=slug) answers = Answer.objects.filter(post_id=question) context = {'question':question, 'answers':answers} return render(request, 'viewQuestion.html', context) my viewQuestion template: <div class="container"> {% for answer in answers %} <div class="row justify-content-center"> <div class="card my-2"> <div class="card-header"> Answer </div> <div class="card-body"> <h5 class="card-title">From: {{answer.user.username.upper}}</h5> <p class="card-text">{{answer.answer|safe}}</p> </div> </div> </div> {% endfor %} -
Django admin Resource Policy COEP ERR_BLOCKED_BY_RESPONSE
The static files of my Django admin site are on a S3 bucket (DigitalOcean Spaces actually) and in the Console I get a ERR_BLOCKED_BY_RESPONSE.NotSameOriginAfterDefaultedToSameOriginByCoep 200 In the network panel all the static files are considered 3rd party and blocked for this reason (not same origin) The response to any one of these files contains a not set cross-origin-resource-policy error which says: To use this resource from a different origin, the server needs to specify a cross-origin resource policy in the response headers. What I tried : Following the error message, I tried to set a response header on the ressources, something like Cross-Origin-Resource-Policy: cross-origin. But in a DigitalOcean Spaces I cannot set headers other than Content-Type, Cache-Control, Content-Encoding, Content-Disposition and custom x-amz-meta- headers. I tried to extend the Django admin/base.html template, duplicate a few link tags and manually set a crossorigin attribute to them. This way the resources are queried twice, one query is blocked as before and the other one is working. The only difference in the headers is that the Origin is set. Is there a way to tell Django to add a crossorigin attribute to all link and script and img tags of the Django admin templates … -
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 …