Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Use elasticsearch on a local folder
So basically I have a Python Django app that get lots of html pages. I store them locally like this (imagine a lot more) : I want to search by key word(s) in all the these index.html I understood that Elasticsearch is a really powerfull tool but I don't know if it can fits my needs. I searched on the internet but didn't find really accurate websites that could help me. -
name 'ValidationError' is not defined in django form
I'm trying to restrict a user if they enter an e-mail that already exists during registration. This is the error i get Exception Value: name 'ValidationError' is not defined User Form from django import forms from django.db import models from django.contrib.auth.forms import UserCreationForm, UserChangeForm from .models import CustomUser class CustomUserCreationForm(UserCreationForm): email = forms.EmailField() def clean(self): email = self.cleaned_data.get('email') if CustomUser.objects.filter(email=email).exists(): raise ValidationError("Email already exists") return self.cleaned_data -
Django - is token/JWT authentication safer if backend and frontend are on the same server?
I'm researching the best security approaches for a webapp that i want to build, where the backend should be separated from the frontend but they will both be on the same server. The frontend is a standalone VueJS application while the backend is a Django app that will communicate with Vue using JSON, but i think this still applies to other frameworks like react or angular. For authentication, i would use djoser and probably token based authentication or JWT. I made some research about this topic and found that there are some concerns on token based authentication, mostly related to token storage on the client side. My question is: when backend and frontend are on the same server, instead of being cross domain, do these security concerns still apply? Or is it a much safer approach? If i deploy the two apps on the same server, can i store the tokens on Vuex or any other local storage safely? What can i do, instead, on the Django side, to make the app as safe as possible? -
Calling two fetch Requests in Django with Javascript displays the result in the same div
I am really new to Javascript therefore be kind! There must be something wrong with the way I am structuring this. I have seen possible solutions, could involve async functions and I tried them but for some reason, I might not get the order straight, or simply I am missing the point. I am using a fetch request to source some data at first from the API that I made on my local server. And that works fine. I am able to source the names of the cryptocurrencies that I have coupled with a username in JSON format. After I have created the styling for the divs to display and inserted the data in, I call another fetch for another API this time external, to further source data and insert it in divs I have created previously, per each piece of data I sourced from my own API. For some reason, it ends up displaying the data that I am fetching from this external API all in the same div, instead of displaying them for each. I have tried a forEach function, I have tried (i=0;i<data.lenght;i++), I have tried to place it differently, I have tried creating global variables and … -
making context variable from one method accessible to other other methods (and views) in Django
i'm working on a dashboard project (django + charts.js) that currently looks like this: currently, all of the charts are based on all the data in the database (approx 1.5 mil lines). however, i'd like these charts to be responsive to the dates indicated in the start date/end date HTML widget - e.g. show payment methods, taxi orders by the hour/day of week according to the start/end dates indicated. my date_input method gets the start and end dates from the frontend, and queries my MySQL database according to the dates selected. these queries are then rendered to the context variable of date_input - however, i'd like the context variable in date_input to be available to all methods (each chart is rendered by a different method, based on the JsonResponse returned to different endpoints). i've tried making context available as a global variable by defining it outside date_input as queryset = date_input(request) - NameError: name 'request' is not defined. i've looked into context processors, but that seems to be an option only if i didn't have a request (e.g. start/end date input from the frontend). i'm rather confused and would appreciate some help. here's my views.py code: def date_input(request): if request.method … -
Set different password for Django admin users than for the public Django app
We have a Django app where we're using the default password/password reset functionality. Lots of our staff also login to Django admin using the same credentials. Is it possible to create separate passwords for these two areas (the public app and Django admin)? The advantage of doing this is I can set & enforce strong passwords for everyone in Django admin, and people aren't tempted to change them to something that's easier to log into the public app with. -
Django - Override save() method of auth_user model
I want store the username of the auth_user table into the first_name, if no first name is provided. Something like this: from django.contrib.auth.models import User class CustomUser(User): class Meta: proxy = True def save(self, *args, **kwargs): if not self.first_name: self.first_name = self.username super(CustomUser, self).save(*args, **kwargs) Thank you -
Requests-oauthlib access token reuse in Django App
I'm able to fetch an OAuth2 access token using Backend Application Flow for Requests-Oauthlib. The API documentation states "Re-use the access token until it expires. Then, get a new token". from oauthlib.oauth2 import BackendApplicationClient client = BackendApplicationClient(client_id=client_id) oauth = OAuth2Session(client=client) token = oauth.fetch_token(token_url='https://provider.com/oauth2/token', client_id=client_id, client_secret=client_secret) The Requests-Oauthlib documentation states that you can save the token, but has no further information on how to do this. The token has 'expires_in' and expires_at fields returned in addition to the access token. I'm going to this in a Django App, but I'm not sure where to store the access token as it's for the Application, not User. How can I retain the token to re-use until it expires? -
Django - Cannot combine a unique query with a non-unique query or pub_date field look up not available
Trying to filter queries by name & datetime. The query should fulfill both criteria, i tried using field lookup in single query using pub_date__date field lookup , it threw the error pub_date not available, then i tried using date field, but that didnt work either. dtt here is = datetime.datetime.now() orders = OrderItemss.objects.filter(customer=customer_object, pub_date__date= str(dtt.day)) orders = OrderItemss.objects.filter(customer=customer_object, date= str(dtt.date()) when i tried combining 2 queries using & , it throws the error 'Cannot combine a unique query with a non-unique query' code: orders = OrderItemss.objects.filter(customer=customer_object) & Customer.objects.datetimes('date', 'hour', order='DESC') -
Custom User Model in Django throws SettingsReference error when making migrations
thanks in advance. I'm trying to build a custom user model and profile model for use in a Django app. I'm just subclassing the built-in CustomUser in case I want to add authentication features in the future, and adding all of the non-authentication related user information in CustomUserProfile. Here's the code: from django.db import models from django.conf import settings from django.contrib.auth.models import AbstractUser from django.utils.translation import ugettext_lazy as _ from django.db.models.signals import post_save class CustomUser(AbstractUser): # ADD AUTH FUNCTIONALITY IN THE FUTURE HERE pass def __str__(self): return self.email class CustomUserProfile(models.Model): # relates profile to user user = models.OneToOneField(CustomUser, related_name="profile", on_delete=models.CASCADE) # the next date the payment is due payment_due_date = models.DateField(null=True) def save(self, *args, **kwargs): # custom save logic will go here super().save(*args, **kwargs) def __str__(self): return f"Profile of user: {self.user.email}" # post save hook that creates a user profile for new users def create_user_profile(sender, instance, created, **kwargs): if created: CustomUserProfile.objects.create(user=instance) post_save.connect(create_user_profile, sender=BaseUser) And in the settings.py file, I have included the user model and profile with: AUTH_USER_MODEL = 'accounts.CustomUser' AUTH_PROFILE_MODULE = 'accounts.CustomUserProfile' The error I'm getting occurs when I run manage.py makemigrations. Specifically, it's returning AttributeError: 'SettingsReference' object has no attribute '_meta'. Frankly I'm not sure where to begin … -
REDIRECT_FIELD_NAME from django.contrib.auth
In my class-based django view, I am using redirect_field_name = REDIRECT_FIELD_NAME. May I know where I am redirecting to, and also by default, what is the field name and how I can set it? Thank you def zulip_login_required( function: Optional[ViewFuncT]=None, redirect_field_name: str=REDIRECT_FIELD_NAME, login_url: str=settings.HOME_NOT_LOGGED_IN, ) -> Union[Callable[[ViewFuncT], ViewFuncT], ViewFuncT]: actual_decorator = lambda function: user_passes_test( logged_in_and_active, login_url=login_url, redirect_field_name=redirect_field_name, )( zulip_otp_required( redirect_field_name=redirect_field_name, login_url=login_url, )(add_logging_data(function)) ) if function: return actual_decorator(function) return actual_decorator # nocoverage # We don't use this without a function -
How to customise the representation of fields of a nested serializer?
I am having a nested serializer as:- serializers:- class DeviceConfigSerializer(serializers.ModelSerializer): config = serializers.JSONField() context = serializers.JSONField() class Meta: model = Config fields = ['backend', 'status', 'templates', 'context', 'config'] class DeviceDetailSerializer(serializers.ModelSerializer): config = DeviceConfigSerializer() class Meta(BaseMeta): model = Device fields = [ 'id', 'name', 'organization', 'mac_address', 'key', 'last_ip', 'management_ip', 'model', 'os', 'system', 'notes', 'config', ] def update(): ... ... ... Views:- class DeviceDetailView(RetrieveUpdateDestroyAPIView): serializer_class = DeviceDetailSerializer queryset = Device.objects.all() When I try to get the data with a get request, this is what I receive:- but the fields in the HTML Form section of browsable API doesn't represent the context and config field in JSON format, instead, this is what I receive:- What I expect is to have the same representation of the context and config fields for the HTML Form and the JSON response. -
How to set session key in djago channels
I have a chat app and i want to use session key to save chats in models for persistence,how can i do this import json from channels.generic.websocket import AsyncWebsocketConsumer class ChatRoomConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name # Join room group await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() ........ -
Need to apply a clear function or rest for the following code to rest the input field
I need to apply a clear function when I add the input frequency. Now when I add a number say 2, 2 fields are created and when I add 3, it's getting appended and showing 5 fields. I need the exact number of fields as given in the input. Please give any tips <div class="container"> <div class="row"> <div class="col-4"></div> <div class="col-4"> <form method="post" enctype="multipart/form-data" autocomplete="off"> {%csrf_token%} <div class="mb-3"> <label>{{medicineform.frequency.label}}</label> </div> <div class="mb-3"> {{medicineform.frequency}} </div> <br> <div id="dynamicCheck"> <input type="button" value="+" onclick="createNewElement();"/> </div> <br> <div id="newElementId">Your time here</div> <br> <div class="mb-3"> <button type="submit" class="btn btn-block btn-primary">Add a reminder</button> </div> </form> </div> <div class="col-4"></div> </div> </div> </div> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <script> $(function () { $("#medicine").autocomplete({ source: '{% url 'autocomplete' %}', minLength: 2 }); }); </script> <script type="text/JavaScript"> function createNewElement() { var inpObj = document.getElementById("id_frequency").value; // First create a DIV element. var i; for (i=1;i<=inpObj;i++) { var txtNewInputBox = document.createElement('div'); // Then add the content (a new input box) of the element txtNewInputBox.innerHTML = "<input type='time' name='reminder' id='newInputBox'>"; // Finally put it where it is supposed to appear. document.getElementById("newElementId").appendChild(txtNewInputBox); } } </script> {% endblock %} -
How speed up sending email in Django rest framework?
I have a backend server that allows users to track the price of products on an ecommerce site. Whenever the price drops down, I'll have to send an informing email to my users. I have been written an API that updates the price of products and at the same time, sending an email if the price has dropped. So, the are thousands of emails have to be sent in one API call. Currently, I'm using django.core.email to sending email to users but it takes so long each time sending an email (about 3s-4s for each. If it has 5 product's prices dropped, the time of the API call will be around 20s). Is there any way to make a lot of emails sent within the shortest amount of time in my case? -
Image url not displaying my uploaded images when django project loaded onto heroku site
My uploaded images are not loading when uploaded to heroku and I think its not related to static file issue. When i set debug = False they come fine and i know that when it is false django uses itself to host the static assests. So setting that and my images loads fine but that's not the case if i set Debug = True on heroku or on my local env. Can somebody help me solve this issue. template <img class="img-fluid" style="height:auto;" src="{{post.work_img.url}}" alt="Generic placeholder image"> model class WorkExp(models.Model): work_img = models.ImageField(upload_to="work_images/") app/urls.py urlpatterns = [ path("carrer/", WorkExpView, name="carrer_page"), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) project/urls.py urlpatterns = [ path("admin/", admin.site.urls), path("", include("blog.urls", namespace="blog")), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
Django Excel Custom Column and Rows format
I want to customized Columns and Rows in Excel output like the image below. It is possible to make the same output in django using openpyxl workbook? This is my regular export excel code: def summary_excel(request): car_queryset = Reg_Date.objects.all() response = HttpResponse( content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', ) response['Content-Disposition'] = 'attachment; filename=Reg.xlsx' workbook = Workbook() worksheet = workbook.active worksheet.title = 'Reg' columns = [ 'SUBJECT:', 'PERSONEL:', 'LOGOUT:' ............. ] row_num = 1 for col_num, column_title in enumerate(columns, 1): cell = worksheet.cell(row=row_num, column=col_num) cell.value = column_title for car in car_queryset: row_num += 1 row = [ car.subject, car.personel, car.time .................... ] for col_num, cell_value in enumerate(row, 1): cell = worksheet.cell(row=row_num, column=col_num) cell.value = cell_value workbook.save(response) return response -
To Fetch Data from scanned barcode number
I am new to Django,I am currently working on application that need barcode reading and fetch data from server.I am now able to get barcode from a scanned barcode. My question is: how can I get more information about a product from its barcode number in django (e.g. product price)? Can I do this from the barcode_scan library, or will I need something else? -
Django functional index migration (postgres), error: invalid input syntax for type integer: "none"
I'm trying to create a functional index based on a newly created field in Django 3.2 (see the prerelease notes for more info about functional indexing), but keep getting the following error when migrations are run (using postgres): psycopg2.errors.InvalidTextRepresentation: invalid input syntax for type integer: "none" This seems like it may be a bug in the Django prerelease, but I'm not sure. I'm not just dumping all my code in this post; the larger block of code below is actually an auto-generated migration by django. The first code block is my code, where I just include the relevant fields and the problematic functional index. This code creates a new field "registration_volume" and a functional index "raw_demand" which should equal registration_volume/capacity if [capacity is not null and capacity>0], capacity being another field of the model), in a model called "Section": capacity = models.IntegerField( default=0, help_text="The number of allowed registrations for this section, " "e.g. 220 for CIS-120-001 (2020A).", ) registration_volume = models.PositiveIntegerField( default=0, help_text="The number of active PCA registrations watching this section." ) class Meta: indexes = [ Index( Case( When( Q(capacity__isnull=False) & Q(capacity__gt=0), then=( Cast("registration_volume", models.DecimalField()) / Cast("capacity", models.DecimalField()) ), ), default=None, output_field=models.DecimalField(null=True, blank=True), ), name="raw_demand", ), ] The auto-generated … -
Get django-filters working on 2 level foreign key relations
I have 3 models a-->b-->c. I want to add django-filter on c so that it could filter using the attributes/values of a. I have tried using ModelChoiceFilter, but only got it working till model b. Is there any way we could filter through 2 levels of foreign key relations? -
2 Options for permission_required in Django View
I have to render a page that requires either of the 2 permissions. views.py class Dashboard(TemplateView, PermissionRequiredMixin): permission_required = "m.view_dashboard" // I want to add another option like "m.add_item" template_name = "dashboard.html" so permission is either of the two options, view and add. Is there any way I can implement this through permission_required? -
Django: AUTH_USER_MODEL refers to model '%s' that has not been installed
I am trying to deploy a Django app to Heroku. It works on my localhost but I get this error when deploying to heroku: File "./blog/models.py", line 6, in <module> 2021-03-24T23:31:05.696194+00:00 app[web.1]: User = get_user_model() 2021-03-24T23:31:05.696219+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/auth/__init__.py", line 162, in get_user_model 2021-03-24T23:31:05.696372+00:00 app[web.1]: "AUTH_USER_MODEL refers to model '%s' that has not been installed" % settings.AUTH_USER_MODEL 2021-03-24T23:31:05.696397+00:00 app[web.1]: django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'auth.User' that has not been installed I have tried setting AUTH_USER_MODEL = 'auth.User' in settings after doing from django.contrib.auth.models import User and: from django.contrib.auth import get_user_model User = get_user_model() but nothing works. settings.py import django from django.core.wsgi import get_wsgi_application from django.core.asgi import get_asgi_application # from django.contrib.auth.models import User #todo: this causes ImproperlyConfigured: SECRET_KEY MUST NOT BE EMPTY import os import django_heroku DJANGO_SETTINGS_MODULE = 'django_project.settings' SECRET_KEY = 'asdaf123$9pv98=e6p^gl(-eoj' #todo: test removing this in own deployment DEBUG = 'True' ALLOWED_HOSTS = ['*', 'localhost', '127.0.0.1'] INSTALLED_APPS = [ 'django.contrib.auth', 'blog.apps.BlogConfig', #allows Django to correctly search your templates for the 'blog' app 'users.apps.UsersConfig', 'chat', 'crispy_forms', 'channels', 'dal', 'dal_select2', 'django.contrib.admin', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'storages' ] # ~~~MESSAGES CONFIG~~~ WSGI_APPLICATION = 'django_project.wsgi.application' ASGI_APPLICATION = 'django_project.asgi.application' # older version of django: 'django_project.routing.application' # Channels redis config: CHANNEL_LAYERS = { 'default': { 'BACKEND': … -
Getting an error while using HyperlinkedModelSerializer in DRF
When i run the URL http://127.0.0.1:8000/api/leave/, I get this frustrating error: Could not resolve URL for hyperlinked relationship using view name "leaveapplication-detail". You may have failed to include the related model in your API, or incorrectly configured the lookup_field attribute on this field. I found some solutions over the internet but none of them worked for me. What is the best way to solve this error? Currently i got this if i use ModelSerializer but i want to generate URL instead of id { "id": 7, "date_start": "2021-03-20", "date_end": null, "time_start": "09:00:00", "time_end": "13:00:00", "remarks": "something", "status": null, "type": 1, "leave_type": "Test" }, I have a models directory rather than models.py file. Here is the directory: models/ ......__init __.py ...... leaveApplication.py Here is my model: from leave.models.leavetype import LeaveType from django.db import models from authentication.models import TimeStampedModel, User class LeaveApplication(TimeStampedModel): date_start = models.DateField(default=None) date_end = models.DateField(default=None, null=True) time_start = models.TimeField(auto_now=False, auto_now_add=False, null=True) time_end = models.TimeField(auto_now=False, auto_now_add=False, null=True) remarks = models.TextField(default=None, null=True) status = models.CharField(max_length=255, null=True) type = models.ForeignKey(LeaveType, related_name='leave_applications',default = None, on_delete=models.CASCADE) user = models.ForeignKey(User, related_name='leave_applications',default = None, on_delete=models.CASCADE) Here is my Serializer: class LeaveApplicationSerializer(serializers.HyperlinkedModelSerializer): date_start = serializers.DateField(required=True) date_end = serializers.DateField(default=None, required=False, allow_null = True) time_start = serializers.TimeField( required=False, allow_null … -
Is it safe to render python dictionary data in html template in django or shall I use json?
When I learned about JSON data I am confused. I am rendering data in html template. data = {'user': username, 'data': data} return render(request, 'index.html', data) Is this way safe to use or I need to send response as JSON? Can you also explain how can I use JSON data in html template? How can I use jhinja format like python with JSON {{json data here}}? -
TypeError at /api/updateproducts/59 unhashable type: 'collections.OrderedDict' in Django Rest Framework
I created update-product API where I have to update many to many fields. Product models have m2m relationships with the Category and Variants model. I am able to update Category model fields using instance.category.set(), but when I try the same thing with Variants, it generates the above error. I am sending the raw JSON data like this. My models: class Category(models.Model): name = models.CharField(max_length=100, unique=True) image = models.ImageField(null=True, blank=True) class Meta: verbose_name_plural = "Categories" class Variants(models.Model): product_id = models.CharField(max_length=70, default='OAXWRTZ_12C',blank=True) price = models.DecimalField(decimal_places=2, max_digits=20,default=500) size = models.CharField(max_length=50, choices=SIZE, default='not applicable',blank=True,null=True) color = models.CharField(max_length=70, default="not applicable",blank=True,null=True) variant_image = models.ImageField(upload_to="products/images", blank=True) quantity = models.IntegerField(default=10,blank=True,null=True) # available quantity of given product variant_availability = models.CharField(max_length=70, choices=AVAILABILITY, default='available') class Product(models.Model): merchant = models.ForeignKey(Seller,on_delete=models.CASCADE,blank=True,null=True) category = models.ManyToManyField(Category, blank=False) brand = models.ForeignKey(Brand, on_delete=models.CASCADE) collection = models.ForeignKey(Collection, on_delete=models.CASCADE) variants = models.ManyToManyField(Variants,related_name='products') My views: class ProductUpdateView(UpdateAPIView): permission_classes = [AllowAny] queryset = Product.objects.all() serializer_class = ProductUpdateSerializer My serializers: class ProductUpdateSerializer(serializers.ModelSerializer): variants = VariantSerializer(many=True) class Meta: model = Product fields = ['id','category','featured', 'top_rated','brand','collection', 'name','description', 'main_product_image','best_seller', 'rating','availability','warranty','services','variants'] def update(self, instance, validated_data): instance.featured = validated_data.get('featured',instance.featured) instance.top_rated = validated_data.get('top_rated', instance.top_rated) instance.brand = validated_data.get('brand', instance.brand) instance.collection = validated_data.get('collection',instance.collection) instance.name = validated_data.get('name', instance.name) instance.description = validated_data.get('description', instance.description) instance.save() #category_logic category_data = validated_data.pop('category') instance.category.set(category_data) instance.save() #variants_logic variants_data …