Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
Foreign constraint failed on django model instance
I try to create a model instance upon an action. I can't get the process to a succes. I receive an error message, and I'm stuck. Here is the view @login_required(login_url='/login/') def return_book(request,pk): books = Books.objects.filter(school = request.user.school).get(id = pk) if books: Return.objects.create(borrowed_item_id=books.id,returner_id=request.user.school.id) return redirect("view_books") The models class Books(models.Model): school = models.ForeignKey(School, on_delete=models.CASCADE) reg_no = models.CharField(max_length=50) book_name = models.CharField(max_length=200) class Issue(models.Model): borrower_id = models.ForeignKey(Student,on_delete=models.CASCADE) book_id = models.ForeignKey(Books,on_delete=models.CASCADE) class Return(models.Model): return_date = models.DateField(default=datetime.date.today) borrowed_item = models.ForeignKey(Issue,on_delete=models.DO_NOTHING) returner = models.ForeignKey(CustomUser,on_delete=models.DO_NOTHING) And the traceback Traceback (most recent call last): File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "D:\Python\Django\test projects\library manage\lib_system\Library-System\libman\views.py", line 216, in return_book Return.objects.create(borrowed_item_id=pk,returner_id=request.user.school.id) File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\query.py", line 447, in create obj.save(force_insert=True, using=self.db) File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\base.py", line 753, in save self.save_base(using=using, force_insert=force_insert, File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\base.py", line 790, in save_base updated = self._save_table( File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\base.py", line 895, in _save_table results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw) File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\base.py", line 933, in _do_insert return manager._insert( File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, … -
django Select_related(): from another model has a ForginKey To the model that will execute Select_related
I have two model, one for Question and two for answer tow have a forginkey to one and one have a forginkey to users for this purpose I use a To be grouped together at the same endpoint I add the second to the first in serializer With this solution, Django accessed the database with the number of answers in the second form and I cannot use Select_related here the question is, how can I reduce database hits to the second model Models.py class Consultation(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) content = models.TextField() create_at = models.DateTimeField(auto_now_add=True) files = models.FileField(upload_to="media/files", null=True, blank=True, validators=[FileExtensionValidator(['pdf', 'jpg', 'png'])]) def __str__(self): return self.user.username class Meta: ordering = ['-create_at'] class ConsultaionAnswer(models.Model): consultation = models.ForeignKey( Consultation, on_delete=models.CASCADE, related_name='reply') answer = models.TextField(null=True, blank=True) def __str__(self): return self.consultation.content[:20] + "..." serializers.py class ConsultaionAnswerSerilaizers(serializers.ModelSerializer): class Meta: model = ConsultaionAnswer fields = ('answer',) class ConsultationSerilaizers(serializers.ModelSerializer): user = serializers.PrimaryKeyRelatedField( read_only=True, default=serializers.CurrentUserDefault() ) username = serializers.StringRelatedField( source='user.username', read_only=True, ) reply = ConsultaionAnswerSerilaizers(read_only=True, many=True) class Meta: model = Consultation fields = ( "id", "user", "content", 'create_at', 'files', 'username', "reply" ) views.py class ConsultationView(APIView): serializer_class = ConsultationSerilaizers def get(self, request, format=None): consultat = Consultation.objects.select_related().filter(user=request.user) serializer = self.serializer_class( consultat, many=True, context={'request': request}) return Response(serializer.data) django debug tool … -
how to add paypal and keep save data to user after buy
i want ask simple question : how to use / add paypal instead of razorpay in my app here is my simple app it's for checkout ( for buy digital products ) but it's use razorpay and i want to use paypal , does anyone can help me and edit my app to add paypal app link : https://gofile.io/d/x7Enng -
are there an equivalent of django mixin in node js?
So, I'm new to Node and I have a background with Django so there is a Mixins you can add to impose certain authorization on your models such as only login users can see this or only the owner of model can edited. Are there any equivalent for that in node or I should right them on my own? -
static filters rendering as strings in template
I am returning a valid HTML string that I'm rendering in a template, but specific {% ....%} is rendering as a literal, even after applying the safe filter. return "<button type='submit' value='Save'>Save<svg>{% load static %}<use xlink:href='{% static 'svg/icons.svg' %}#save'></use></svg></button>" I am rendering like this {{ html_string|safe }} {% load static %} and {% static 'svg/icons.svg' %} are rendering as literal strings, not processed by Django template engine. How can I render {% load static %} and {% static 'svg/icons.svg' %} properly if I'm building the string outside of the template? -
Django DTL for Frontend
I want to ask a question, that Django provides us with Django Template Language (DTL), when we write HTML and CSS code in the DTL does it considered as Frontend? As we are rendering HTML and CSS code in DTL just like we do in all other Frontend stack framework. Django Template Language (DTL) is just like Embedded JavaScript. Embedded JavaScript is considered as language for Frontend than why Django Template Language is not? I heard from someone he was saying that Django is only for server side code it has nothing to do with Frontend. Kindly help me out. -
E: Unable to locate package psql
I found a Django project and failed to get it running in Docker container in the following way: git clone https://github.com/hotdogee/django-blast.git $ cat requirements.txt in this files the below dependencies had to be updated: kombu==3.0.30 psycopg2==2.8.6 I have the following Dockerfile: FROM python:2 ENV PYTHONUNBUFFERED=1 WORKDIR /code COPY requirements.txt /code/ RUN pip install -r requirements.txt COPY . /code/ For docker-compose.yml I use: version: "3" services: db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres dbi5k: image: postgres volumes: - ./data/dbi5k:/var/lib/postgresql/data environment: - POSTGRES_DB=django_i5k - POSTGRES_USER=django - POSTGRES_PASSWORD=postgres web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db links: - db I had to change: $ vim i5k/settings_prod.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'db', 'PORT': '5432', } } and $ vim i5k/settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'django_i5k', 'USER': 'django', 'PASSWORD': 'postgres', 'HOST': 'dbi5k', 'PORT': '5432', } } Please below the logs after I ran docker-compose build docker-compose up # I had to wait for 2 minutes and do CTRL+C in order to give the database to start docker-compose up Attaching to djangoblast_dbik_1, djangoblast_db_1, djangoblast_web_1 dbik_1 | db_1 … -
Secure authentification with django graphql jwt reactjs
I did a website using frontend reactjs and back django, using graphQL to communicate with DB. I need to post data on a database (with a form accessible just when the user is logged in). For now I am able to connect it and get a token with jwt. but I did not succeed to post data on the database with graphQL with the token, and having a "unauthorized" page when token is not valid (unlogged). Can please you guide me to a good tutorial which can help me how to do that? I am searching and I am non founding anything useful... Thanks a lot in advance for your help ! -
Django unkown field
My django server is returning line 276, in new raise FieldError(message) django.core.exceptions.FieldError: Unknown field(s) (name) specified for Planet my forms.py file is from django import forms from .models import Planet class PlanetForm(forms.ModelForm): """a form to enter a new planet""" class Meta: """docstring for Meta""" model = Planet fields = ['text'] labels = {'text': ''} the function in views.py that would run the function in forms.py is as such def new_planet(request): """add a new planet""" if request.method != 'POST': # no data submitted; create a blank form form = PlanetForm() else: #post data submitted; process data form = PlanetForm(data=request.POST) if form.is_valid(): form.save() return redirect('HelloWorlds:planets') # display a blank or invalid form context = {'form': form} return render(request, 'HelloWorlds/new_planet.html', context) This is the way i know how to create forms on django. i have tried changing the forms.py as per the official documentations but that returned views.py, save() not defined on form from PlanetForm. Sorry if my technical terms are completely wrong -
Failure calculating Percentage of A django model
I intend to calculate 8 percent compound interest of the amount invested every ten days- something like a 10 days countdown and when the ten days countdown is over then another 10 days countdown should begin. The 10 days count will begin immediately the amount is deposited and the percent will be added to the balance only after ten days. The percentage countdown calculation should begin on request by the user or immediately after deposit. This questions is a question I have not been able to find solution to. I hope there is a solution now class Profile(models.Model): user = models.ForeignKey(UserModel, on_delete=models.CASCADE) balance = models.DecimalField(default=Decimal(0),max_digits=24,decimal_places=4) class Investment(FieldValidationMixin, models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) amount = models.DecimalField(max_digits=5, decimal_places=2, null=True, blank=True) fixed_price = models.DecimalField(max_digits=7, decimal_places=2, nulll=True, blank=True) percentageee = models.DecimalField(max_digits=3, decimal_places=0, nulll=True, blank=True) profile = models.ForeignKey(Profile, on_delete=models.CASCADE) added = models.DateTime() request_time = models.Daterime() def percentages_in_ten_days(self): return self.amount *0.08 I want to fetch the percentage of the user investment amount here Views.py def get_percentage(self, day=10): pef_of_amount = Investment.objects.filter([x for for x in get_percentage_ten_days]).annotate(day=Sum('x')) return get_percentage def percentile(self, days=10): percent=Investment.objects.filter(self.amount*self.percentage)/100 in days return percentile #get the percentage balance of the amount invested after ten days def get_current_balance(self,percentile): total_expenses = Profile.objects.all().aggregate(Sum('balance')).annonate(percentile) return get_current_balance