Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I have problem reset password in django . My error is 'availabe Apps' key error
Firstly I call 'from django.contrib.auth import views as auth_views'. After that I have set the 'path('reset_password/',auth_views.PasswordResetView.as_view(),name='reset_password'),' url. When i run the url the key error raised. Request Method: GET Request URL: http://127.0.0.1:8000/user/reset_password/ Django Version: 3.1 Exception Type: KeyError Exception Value: 'available_apps' Exception Location: C:\Users\Syed Mithu\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\context.py, line 83, in getitem Python Executable: C:\Users\Syed Mithu\AppData\Local\Programs\Python\Python38\python.exe Python Version: 3.8.3 Python Path: ['F:\12.05.2021\Project\Music_E-com', 'C:\Users\Syed ' 'Mithu\AppData\Local\Programs\Python\Python38\python38.zip', 'C:\Users\Syed Mithu\AppData\Local\Programs\Python\Python38\DLLs', 'C:\Users\Syed Mithu\AppData\Local\Programs\Python\Python38\lib', 'C:\Users\Syed Mithu\AppData\Local\Programs\Python\Python38', 'C:\Users\Syed ' 'Mithu\AppData\Local\Programs\Python\Python38\lib\site-packages', 'C:\Users\Syed ' 'Mithu\AppData\Local\Programs\Python\Python38\lib\site-packages\win32', 'C:\Users\Syed ' 'Mithu\AppData\Local\Programs\Python\Python38\lib\site-packages\win32\lib', 'C:\Users\Syed ' 'Mithu\AppData\Local\Programs\Python\Python38\lib\site-packages\Pythonwin'] Server time: Thu, 20 May 2021 06:51:41 +0000 -
How to check if an object corresponding to a foreign key exists or not?
I need help to evaluate weather i am doing it right or not, the scenario is an 3rd party application is sending an webhook request after a successful payment but the problem is that sometimes this application may send the same notification more than once.so it is recommended to ensure that implementation of the webhook is idempotent.so steps that i am implementing for this are if signature is correct (assume it is corect),Find orders record in the database using orderId in the request params. Please note: orderId in request params is payment_gateway_order_identifier in orders table. if txStatus = 'SUCCESS' AND haven't already processed COLLECTION payment for this same order, Create payments record. 201 response with nothing in the response body. else 201 response with nothing in the response body. else 422 response with {message: "Signature is incorrect"} in response body views.py @api_view(['POST']) def cashfree_request(request): if request.method == 'POST': data=request.POST.dict() payment_gateway_order_identifier= data['orderId'] amount = data['orderAmount'] transaction_status = data['txStatus'] signature = data['signature'] if(computedsignature==signature): #assume it to be true order=Orders.objects.get( payment_gateway_order_identifier=payment_gateway_order_identifier) if transaction_status=='SUCCESS': try: payment= Payments.objects.get(orders=order) return Response({"Payment":"Done"},status=status.HTTP_200_OK) except (Payments.DoesNotExist): payment = Payments(orders=order,amount=amount,datetime=datetime) payment.save() return Response(status=status.HTTP_200_OK) else: return Response(status=status.HTTP_422_UNPROCESSABLE_ENTITY) models.py class Orders(models.Model): id= models.AutoField(primary_key=True) amount = models.DecimalField(max_digits=19, decimal_places=4) payment_gateway_order_identifier = models.UUIDField( primary_key=False,default=uuid.uuid4,editable=False,unique=True) sussessfull … -
Why js can't be loaded but css can be normally loaded
I put jquery-ui.min.js and jquery-ui.min.css in same folder. in HTML: However, jquery-ui.min.js can't be loaded but css is OK even I change the name of jquery-ui.min.js or change folder but all fails Why css is OK but js fails??? How can I solve it? -
comment serialize in Django rest api
I want my comment serializer response to be like this - [ { "id": 50, "comment": "50Reply1", "timestamp": "2021-05-20 00:26:41", "user": { "hnid": "d0a04c7b-6399-44db-ba7c-4ef39ae7e59c", "username": "Sunasuns #GD6GXAJ4", "profile_img": "/media/Bay-Morning-Sea-Clouds-Beach-House-Wallpaper-1162x768.jpg", "full_name": "Suna suns" }, "reply_comment": { "id": 51, "comment": "50Reply2", "timestamp": "2021-05-20 00:26:46", "user": { "hnid": "d0a04c7b-6399-44db-ba7c-4ef39ae7e59c", "username": "Sunasuns #GD6GXAJ4", "profile_img": "/media/Bay-Morning-Sea-Clouds-Beach-House-Wallpaper-1162x768.jpg", "full_name": "Suna suns" }, "reply_comment": 50 }, { "id": 52, "comment": "50Reply3", "timestamp": "2021-05-20 00:26:51", "user": { "hnid": "d0a04c7b-6399-44db-ba7c-4ef39ae7e59c", "username": "Sunasuns #GD6GXAJ4", "profile_img": "/media/Bay-Morning-Sea-Clouds-Beach-House-Wallpaper-1162x768.jpg", "full_name": "Suna suns" }, "reply_comment": 50 }, }] But instead I am getting something like this - [ { "id": 52, "comment": "50Reply2", "timestamp": "2021-05-20 00:26:46", "user": { "hnid": "d0a04c7b-6399-44db-ba7c-4ef39ae7e59c", "username": "Sunasuns #GD6GXAJ4", "profile_img": "/media/Bay-Morning-Sea-Clouds-Beach-House-Wallpaper-1162x768.jpg", "full_name": "Suna suns" }, "reply_comment": 50 }, { "id": 51, "comment": "50Reply1", "timestamp": "2021-05-20 00:26:41", "user": { "hnid": "d0a04c7b-6399-44db-ba7c-4ef39ae7e59c", "username": "Sunasuns #GD6GXAJ4", "profile_img": "/media/Bay-Morning-Sea-Clouds-Beach-House-Wallpaper-1162x768.jpg", "full_name": "Suna suns" }, "reply_comment": 50 }, { "id": 50, "comment": "Reply3", "timestamp": "2021-05-20 00:24:51", "user": { "hnid": "d0a04c7b-6399-44db-ba7c-4ef39ae7e59c", "username": "Sunasuns #GD6GXAJ4", "profile_img": "/media/Bay-Morning-Sea-Clouds-Beach-House-Wallpaper-1162x768.jpg", "full_name": "Suna suns" }, "reply_comment": null },] Here is my model.py class Comment(models.Model): post = models.ForeignKey(Posts, related_name='comments', on_delete=models.CASCADE) user = models.ForeignKey(HNUsers, related_name='comments', on_delete=models.CASCADE) comment = models.TextField("Comment", blank=True, null=True) timestamp = models.DateTimeField("Timestamp", blank=True, null=True, auto_now_add=True) reply_comment = models.ForeignKey('self', related_name='replies', on_delete=models.CASCADE, blank=True, null=True) class … -
How to dynamically add an If Else statement in Python?
Currently I had developed a script that will read incoming/latest email and filter the email based on certain criteria such as email subject and text. When user select subject or text, they are able to choose which condition they want to filter the email (Equals, Does not contain etc). My Problem I have a demo website that will let user to add different conditions to filter the email. But now my script can only handle one condition and execute at one time . How can I make my script to detect there are multiple condition and filter the email based on the multiple rules ? Im using Django to do my website My previous script: After user click on OK, the script in view.py will directly be executed and it will parse the email based on the current condition only What I trying to achieve: I had modify my html template and it will continuously letting user to add few conditions rather than just execute one condition only. Example: When user choose the parameter etc and click OK and new row will be store and the script will parse the email based on how many rules that user want to … -
django - Dynamic upload path including month and year not working
I want to upload file with dynamic path i.e. YEAR/MONTH//FILES To achieve this i am using below code def user_directory_path(instance, filename): return '%Y/%B/{0}/files/{1}'.format(instance.retailer.retailer_id, filename) class FileUpload(models.Model): file = models.FileField(upload_to=user_directory_path) car = models.ForeignKey(CarMaster, on_delete=models.CASCADE, default=None) class CarMaster(models.Model): user = models.ForeignKey(User,default=None,on_delete=models.CASCADE) car_id = models.PositiveIntegerField(unique=True) car_name = models.CharField(max_length=1000) Folder structure getting created is as below media\%Y\%B\100000\files Here %Y and %B should be replaced by Year and Month name which is not happening. Is there a way we can achieve this. -
IDW(Inverse Distance Weighted) Interpolation in openlayers 6.4.3
I have a django3.1 web application with map using ol6 in which I want to show IDW. I have generated an idw image using python & added to map as an image layer but it does not overlay in accurate point positions. So I am looking for a method or technique for overlaying idw as a vector/raster/anything which is correct using ol 6. -
Django urls Datatype
For passing datetime in django urls which datatype to use in place of datettime as datetime isn't working ('deletetask/datetime:id',deletetask,name="deletetask") -
AWS S3 static file access works on local but not production
I have setup a AWS S3 bucket for both my static and media files but it currently only works on local host but not when I try on gunicorn or when I deploy to Heroku. When I take a look at the network information on local host I can see the network is attempting to access the files from "https://mybucketname.s3.amazonaws.com/static/image.png". However, when I try this on gunicorn or heroku it is attempting to serve the files from "https://none.s3.amazonaws.com/static/image.png". I am unsure why it is using 'none' instead of 'mybucketname' and my settings are below. settings.py from pathlib import Path import os import django_heroku BASE_DIR = Path(__file__).resolve().parent.parent ALLOWED_HOSTS = ['xxxx.herokuapp.com', '127.0.0.1',] INSTALLED_APPS = [ xxx, 'storages', ] MIDDLEWARE = [ xxx, 'whitenoise.middleware.WhiteNoiseMiddleware', ] AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME') AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_S3_FILE_OVERWRITE = False AWS_S3_REGION_NAME = "us-east-1" AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_LOCATION = 'static' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] STATIC_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' DEFAULT_FILE_STORAGE = 'src.storage_backends.MediaStorage' # Configure Django App for Heroku. django_heroku.settings(locals(), staticfiles=False) If it's relevant my AWS s3 settings are set for '*' allowed hosts, public access is enabled for everything and my IAM account … -
Performance - SPRING VS DJANGO VS ASP.NET MVC
I want to build a personal Web Project which involves huge databases. Thus I want to have the best Performance from the framework. So which Framework is the best for the purpose. I have tried Django but I need an insight because Java and C# have Data Types which can help reduce the memory . NOTE : I know all 3 languages. OVERALL REVIEW of all the 3 will be appreciated. Also what is the difference between Spring and Spring - Boot and Spring - MVC -
This site can't be reached [closed]
This is my first project of django. I have tried to make very simple website.I tried to run this site on chrome and its showing the error Error This site can't be reached. 127.0.0.1 refused to connect Urls.py from django.contrib import admin from django.urls import path from. import views urlpatterns = [path('admin/', admin.site.urls),path('',views.index,name='index'),path('about',views.about,name='about')] views.py from django.http import HttpResponse def index(request): return HttpResponse("Hello") def about(request): return HttpReponse("About Hello") -
IllegalArgumentException: Shell is not a LinearRing
How can I can I resolve this error please? IllegalArgumentException: Shell is not a LinearRing edges_gdf.to_crs(crs=degree_crs, inplace=True) # Initialize the map tiles_layer = None if road_network.simple else 'OpenStreetMap' m = folium.Map(max_zoom=19, prefer_canvas=True, tiles=tiles_layer) # Add the representation of the edges. edges_gdf.drop(columns=['lanes', 'road_type', 'default_lanes', 'width'], axis=1, inplace=True) layer = folium.GeoJson( edges_gdf, smooth_factor=1, name='Roads' ).add_to(m) -
How to createview django manytomany models
been trying to save my recipe-ingredients and ingredient-measure to my recipe db. i tried a model like this: class IngredientList(models.Model): unit = [ ('lb', 'pound'), ('oz', 'ounce'), ('tsp', 'teaspoon'), ('tbsp', 'tablespoon'), ('G', 'gallon'), ('ml', 'mililitre'), ('l', 'litre'), ('g', 'gram'), ('kg', 'kilogram'), ] name = models.CharField(max_length=100) image = models.ImageField(default='img.jpg') #recipes = models.ManyToManyField('Recipe', through='RecipeList') protein = models.FloatField() fat = models.FloatField() carb = models.FloatField() units = models.CharField(max_length=10, choices=unit) def __str__(self): return self.name return self.ingredient.name class Recipe(models.Model): name = models.CharField(max_length=100) ingredients = models.ManyToManyField( 'IngredientList', through='RecipeList') instructions = models.TextField(max_length=3000) serving_size = models.IntegerField() image = models.ImageField(default='recipe.jpg') duration = models.IntegerField(blank=True, default=0) def __str__(self): return self.name def get_absolute_url(self): return reverse('recipe-detail', kwargs={'pk': self.pk}) class RecipeList(models.Model): recipe = models.ForeignKey(RecipeList, on_delete=models.CASCADE) ingredients = models.ForeignKey(IngredientList, on_delete=models.CASCADE) measurement = models.FloatField() def __str__(self): return self.recipe.name Found this form on a stackoverflow answer: class RecipeForm(forms.Form): name = forms.CharField() ingredient = forms.ModelMultipleChoiceField(IngredientList.objects.all()) instructions = forms.CharField() count = forms.IntegerField() serving = forms.IntegerField() and this CreateView as well: class RecipeCreateView(FormView): template_name = "recipe/shoppinglist_form.html" form_class = RecipeForm def form_valid(self, form): name = form.cleaned_data['name'] ingredient = form.cleaned_data['ingredient'] instructions = form.cleaned_data['instructions'] serving = form.cleaned_data['serving'] recipe = RecipeList(name=name) recipe.save() ingredient_list = IngredientList.objects.filter(pk__in=ingredient) for i in ingredient_list: recipe.ingredients.add(i) return render(request, 'recipe/recipe.html') When I submit, yes I do get the ingredients and the name … -
django access images in one to one field
i have created some models for a blog post with multiple images i am stuck on how to access the images from the blogpost any help would be appreciated models.py: from django.db import models # Create your models here. class ImageAlbum(models.Model): def default(self): return self.images.filter(default=True).first() def thumbnails(self): return self.images.filter(width__lt=100, length_lt=100) class Image(models.Model): title = models.CharField(max_length=255) image = models.ImageField() default = models.BooleanField(default=False) width = models.FloatField(default=100) length = models.FloatField(default=100) album = models.ForeignKey(ImageAlbum, related_name='images', on_delete=models.CASCADE) def get_image_url(self): if self.image.url: return self.image.url return self.image class BlogPost(models.Model): title = models.CharField(max_length=255) author = models.CharField(max_length=255) album = models.OneToOneField(ImageAlbum, related_name='model', on_delete=models.CASCADE) view.py: from django.db.models import fields from django.shortcuts import render from django.views.generic.list import ListView from .models import BlogPost # Create your views here. def main(request): return render(request, "main/main.html") class BlogList(ListView): template_name = "main/item.html" model = BlogPost fields = "__all__" context_object_name = "blogs" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) search_area = self.request.GET.get("search") or '' if search_area: context["blogs"] = context["blogs"].filter(name__icontains=search_area) return context i try to access the image using blog.album.image but nothing works. thank you -
How to avoid datetime.date name in list in django
Meanwhile creating sales report I faced issue. Django date field data appended to a list. So I got result attached below. So I want only date(2021,5,20) but given datetime.date name. So how to avoid datetime.date in a list. -
Can you combine Django Simple JWT with Oauth2 Azure?
I am using the simple JWT Django authentication module in a Django Rest APP. I need to implement Oauth2 Azure login protocol. As my frontend(react.js) is already configured with access and refresh token generated by the simple JWT, could I use the simple JWT to generate access and refresh tokens and some oauth2 module for the authentication? This is my code: settings.py INSTALLED_APPS = [ 'rest_framework_simplejwt.token_blacklist', 'authentication', ] REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ), } SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=30), 'REFRESH_TOKEN_LIFETIME': timedelta(minutes=15), 'ROTATE_REFRESH_TOKENS': True, 'BLACKLIST_AFTER_ROTATION': True, 'ALGORITHM': 'HS256', 'SIGNING_KEY': SECRET_KEY, 'VERIFYING_KEY': None, 'AUTH_HEADER_TYPES': ('JWT',), 'USER_ID_FIELD': 'id', 'USER_ID_CLAIM': 'user_id', 'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',), 'TOKEN_TYPE_CLAIM': 'token_type', } The authentication app has the routes to get token refresh and obtain. I could not find yet, but is there any module to create refresh and access tokens using oauth2? -
Add extra field which allows user to choose the type of extra field
I am creating a multi-tenant project. In which I need allow user to add extra attributes to models he needed. for example: In user creation he might want to add birth_date or is_physically_challenged So the user must be able to choose the field type he wants to ass Another example would be in payroll User might wants to add PF or EPF or any other schemes depending on country So user has to choose type field he wants to add Please help me out. Thanks in advance -
Django EmailMessage Subject
How can i change the title of the email that received of the user? mail = EmailMessage('Subject', email_template, [Email], [settings.EMAIL_HOST_USER, Email]) mail.attach_file('static/pdf/UCC-ENROLLMENT-PROCEDURE-2021-.pdf') mail.send(fail_silently=False) -
How to generate a uniquie ID containing 5 digits in Django
I am currently creating a website using Django, I have gotten the Admin Form to work however I want it so when I create an Owner Django generates a random ID containing a specific amount of numbers and for that ID to be displayed next to the Owners Firtsname and Last name. Below is the models.py used in the django: class Owner(models.Model): First_Name = models.CharField(max_length=100) Last_Name = models.CharField(max_length=100) email = models.CharField(max_length=100) phone = models.IntegerField() street_address = models.CharField(max_length=30) Suburb = models.CharField(max_length=30) postcode = models.IntegerField() owner_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) def __str__(self): return self.First_Name +" "+ self.Last_Name class Pet_Description(models.Model): description_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) species = models.CharField(max_length=50) pet_name = models.CharField(max_length=50) weight_in_kg = models.IntegerField() height_in_cm = models.IntegerField() gender = models.CharField(max_length=10) age = models.IntegerField() owner_id = models.ForeignKey(Owner, on_delete=models.CASCADE) overweight = models.CharField(max_length=50) healthy = models.CharField(max_length=50) indoor_or_outdoor = models.CharField(max_length=50) def __str__(self): return self.pet_name class Booking(models.Model): booking_ID = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) date = models.DateField() time = models.TimeField() owner_id = models.ForeignKey(Owner, on_delete=CASCADE) def __unicode__(self): return self.booking_ID class Payment(models.Model): payment_ID = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) payment_type = models.CharField(max_length=50) booking_ID = models.ForeignKey(Booking, on_delete=CASCADE) def __unicode__(self): return self.payment_ID class Pet_Illness(models.Model): pet_ID = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) owner_id = models.ForeignKey(Owner, on_delete=CASCADE) type_of_illness = models.CharField(max_length=50) description_of_illness = models.CharField(max_length=200) def __str__(self): return self.type_of_illness + ": " … -
Django cannot get file from Network File Sharing folder
i am trying to access files from two different locations(static folder inside the app and a mounted shared folder). Using os.path.isfile("/mnt/nfs_client/static/image.png") i can check that it's available. settings.py from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent DEBUG = True INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'channels', ] STATIC_URL = '/static/' # Define a list of directories (STATICFILES_DIRS) in your settings file where Django will also look for static files. STATICFILES_DIRS = [ BASE_DIR / 'static', '/mnt/nfs_client/static/',] when the file is available i make a dict and send to front-end to be displayed. views.py name_dict = {'name': "image-name", "icon": "/mnt/nfs_client/static/image.png", "meta": {"type": "image", 'description':"image-desc"}} But i get the following: Not Found: /mnt/nfs_client/static/image.png HTTP GET /mnt/nfs_client/static/image.png 404 [0.01, 127.0.0.1:38048] Ubuntu-18.04 Django-3.1.2 Python-3.6.9 -
how to show the content written in tinyMCE on html page
I am using Django Web frame-work The text written in TinyMCE, when i try to access it ...it shows me the content but with weird errors Below is the example image: But when i post the content it looks like this: -
Django: Simple solution to prepend $ to form field
I would like to prepend a $ to an input field for a few of my forms. I don't want the $ sent to the backend as part of the input value. I have found a few stack overflow questions that suggest things like the updates below: self.fields['buy_price'].localize = True self.fields['buy_price'].widget.is_localized = True self.fields['buy_price'].prefix = '$' But none of these are working for me. I also would prefer to avoid adding 50+ lines of code, such as recommended in this S.O. Answer: How to represent Django money field with currency symbol in list template and plain decimal for edits? Does anyone have a simple way to do this? -
Loading a .html file in django url
I have a file which I have to load directly through the web browser but it would still run inside of my django app. What I have done so far is url(r"^file_name.html", views.regular_person, name='regular_person') But when I do this it shows the page could not be found. error 404 Please how can i get that to work. Thanks -
Is there any way to use django adminsite in DRF
Currently,I am using Django Rest Framework to develop an API for a project. As we know, Django has default administration but i am wondering how can i convert into DRF or should i write from scratch and later integrate with react? Seeking better suggestion and some resources cause i am very much new to Django and DRF as well. Thanks in Advance -
How to Use Django Rest Framework to Call API with Javascript Files
I've done a few projects in Django before but I've never done one using the Django Rest framework, and it's my first time using an API. I'm trying to learn how to use it, and the class I'm taking makes it mandatory to create the project in Django, and use Javascript as the front end. 2 Questions: I'd like to call the API within the Javascript code. Can this be done using the Django Rest framework? I'm also having trouble figuring out how to show my html file with this url setup. Any help is appreciated. Currently when I go to http://127.0.0.1:8000/ I just get the API Root page. So far most tutorials I see, are just for calling the API in a Django view. They don't talk about how to use Javascript files to call the API also with the Django Rest Framework, and show the html file to the user. If you can point me to documentation or explain a bit more I'd really appreciate it! views.py - currently the home view is not showing or doing anything, but I want this to show to the user. class LocationViewSet(viewsets.ModelViewSet): queryset = Location.objects.all() serializer_class = LocationSerializer() def home(request): return …