Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django cast string to Integer
I'm trying to cast a value from my template to the views with this code: <form action="{% url 'view_passwordgenerator' %}"> <select name="length"> <option value="8">8</option> <option value="9">9</option> <option value="10">10</option> <option value="11">11</option> <option value="12" selected="selected">12</option> <option value="13">13</option> <option value="14">14</option> <option value="15">15</option> <option value="16">16</option> <option value="17">17</option> <option value="18">18</option> <option value="19">19</option> <option value="20">20</option> </select> Length <input type="submit" value="Generate Password" class="btn btn-primary"> </form>``` views def view_passwordgenerator(request): length = int(request.GET.get('length')) for i in range(length): ... return render(request, 'home/passwordgenerator.html') This error appears: TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType' im just looking for a way to get the int out of the template without this error, maybe there is another way to cast it. -
How to hide the Button in Django with help of JavaScript and CSS?
I have set a Boolean Model in the Django Admin panel with the Name of CouponButtonDisplay The Full Line is Like this CouponButtonDisplay = models.BooleanField(default=True) Now i want to hide a button when it is False The Code for Button is <div class="product-count"> <a href="#" class="round-black-btn" onclick="openCouponLinkDetails()" style="color: white !important;" id="getCouponBtnDetails" data-toggle="modal" data-target="#modalCouponDetails">Get Coupon</a> The Code Which I have written in javascript is let CouponButtonDisplay = {{Data.CouponButtonDisplay}}; function CouponButtonDisplay(){ CouponButtonDisplay = !counter; if(CouponButtonDisplay == true){ document.getElementById('getCouponBtnDetails').style.display = 'block'; } if(CouponButtonDisplay == false){ document.getElementById('getCouponBtnDetails').style.display = 'none'; } } This Code is not working anyone can help me as I am a complete newbie in Django -
Compress image in Django before saving to AWS s3 bucket
Can someone please help me how to compress large image before saving to aws s3 in Django ? I have tried thousands logic but nothing worked, when I override save method its saying , 'absolute path not supported' kind of thing, One method worked for me but when I click post , Its gives me error of Unique constrains like post.id, but it saves in the background when I comeback and refresh its shows up with the size reduced image, Can someone please help me how to do that properly with code . This is my post model: class Post(models.Model): postuuid = models.UUIDField(default=uuid.uuid4,unique=True,editable=False) user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE, null=True) title = models.CharField(max_length=150,blank=False) text = models.TextField(null=True,blank=False) image = models.ImageField(upload_to='post_images/',null=True,blank=True,default="") created_at = models.DateTimeField(auto_now_add=True, null=True) likes = models.ManyToManyField(User, blank=True, related_name="post_like") tag= models.CharField(max_length=150,blank=True) post_url=models.URLField(max_length=150,blank=True) video = models.FileField(upload_to='post_videos/',null=True,blank=True,default="") is_ad = models.BooleanField(default=False) # community = models.ForeignKey(communities,on_delete=models.CASCADE) def __str__(self): return self.title -
How to Implement Role Based Data Restriction In Django?
I'm a newbie to Django. I am working on an Application where data are to be shown to users based on their roles. Example User A Should only see the data created by A. Similarly User B should See only his data. Finally, there is a superuser who can see all data. What is the best way in Django to implement this?. Currently, I am trying with Django ORM Managers. -
Gitlab CI pipeline failure
My gitlab ci pipeline keeps failing. It seems am stuck here. Am actually still new to the CI thing so I don't know what am doing wrong. Any help will be appreciated Below is .gitlab-ci.yml file image: python:latest services: - postgres:latest variables: POSTGRES_DB: projectdb # This folder is cached between builds # http://docs.gitlab.com/ee/ci/yaml/README.html#cache cache: paths: - ~/.cache/pip/ before_script: - python -V build: stage: build script: - pip install -r requirements.txt - python manage.py migrate only: - EC-30 -
How to test Meta tags for Images in a Django Project on local host
I have a Django Project and I am trying to add Meta Tags for an Image and Test them in the Local Host before going for the public Website. In the base.html I have added the following: <meta property="og:title" name="description" content="{% block description %}{% endblock %}"> <meta property="og:type" content="website" > <meta property="og:image" content="{% block image %}{% endblock %}"> In the home.html I have add the following: {% block description %}{{ info.description }}{% endblock %} {% block image %}{{ info.avatar.url }}{% endblock %} My question is: How do I test it before going production because on the local host I can see the path of the {{ info.avatar.url }} on the top of the page. -
ModuleNotFoundError: No module named 'django.config' using celery and rabbitmq
I'm getting this error after running the following command: C:\Users\callu\project_name>celery -A project_name worker -l info I'm wondering if it has something to do with the fact that I've not created my django project in a virtual environment but I can't find anything on the issue. If it was due to it being outside a virtual environment I'm not sure how I'd get around it without restarting the project in one (is it easy to move to a venv in PyCharm?) I run my django server and my above celery command here: C:\Users\callu\project_name> I run start my RabbitMQ server in another location (not venv) but don't think that's the issue Full Traceback: Traceback (most recent call last): File "c:\users\callu\appdata\local\programs\python\python37-32\lib\site-packages\cached_property.py", line 70, in __get__ return obj_dict[name] KeyError: 'data' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "c:\users\callu\appdata\local\programs\python\python37-32\lib\runpy.py", line 193, in _run_module_as_main "__main__", mod_spec) File "c:\users\callu\appdata\local\programs\python\python37-32\lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "C:\Users\callu\AppData\Local\Programs\Python\Python37-32\Scripts\celery.exe\__main__.py", line 7, in <module> File "c:\users\callu\appdata\local\programs\python\python37-32\lib\site-packages\celery\__main__.py", line 15, in main sys.exit(_main()) File "c:\users\callu\appdata\local\programs\python\python37-32\lib\site-packages\celery\bin\celery.py", line 213, in main return celery(auto_envvar_prefix="CELERY") File "c:\users\callu\appdata\local\programs\python\python37-32\lib\site-packages\click\core.py", line 764, in __call__ return self.main(*args, **kwargs) File "c:\users\callu\appdata\local\programs\python\python37-32\lib\site-packages\click\core.py", line 717, in main rv = self.invoke(ctx) File "c:\users\callu\appdata\local\programs\python\python37-32\lib\site-packages\click\core.py", line 1135, in … -
Why is my date in python wrong after formating using timedelta?
I am using Django and have a problem with a date that I need to calculate. The Variable data > test should be 17:00 and not 15:00. Why does this happen as soon as I format the date? My timezone is Europe/Berlin. Changing the timezone has to effect to the time printing in test. It is always -2h def date(req): now = datetime.datetime.now() model = MyModel.objects.filter(date__gt=now).first() next = model.date future = datetime.timedelta(hours=float(model.future)) #model.future = 1.5 open = next-future date = next.strftime('%Y/%m/%d') data = { 'next': next, 'date': date, 'time': open, 'test': open.strftime('%Y/%m/%d %H:%M:%S') } What I get: next: 20. November 2021 18:30 date: 2021/11/20 time: 20. November 2021 17:00 test: 2021/11/20 15:00:00 -
"Could not derive file name from *" while uploading images in django
I am building a image upload modle in django and the upload_to function to name the path. But it is showing me this error from django.utils import timezone from django.contrib.auth import get_user_model # Create your models here. def user_directory_path(instance, filename): return 'images/{0}/'.format(filename) class Category(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Images(models.Model): User = get_user_model() category = models.ForeignKey(Category, on_delete=models.PROTECT, default=1) title = models.CharField(max_length=250) alt = models.TextField(null=True) image = models.ImageField( max_length=255,upload_to=user_directory_path, default='posts/default.jpg') slug = models.SlugField(max_length=250, unique_for_date='created') created = models.DateTimeField(default=timezone.now) author = models.ForeignKey( User, on_delete=models.PROTECT, related_name='author') ``` -
REST Django - use objectID right after creation
I have a Project model from wich I can create instances via POST method. I created a new model called UserProject wich contains a userID and a projectID. Now I want to add an UserProject object each time a Project is created with that POST view. The Project is being created, but the UserProject database keeps being empty, what am I missing? models.py: from django.db import models from django.contrib.auth.models import User # Create your models here. class Project(models.Model): id = models.AutoField(db_column = 'db_ID', primary_key = True) name = models.CharField(max_length=500, default = None) descriptor = models.CharField(max_length = 1000, null = True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: db_table = 'projects' def __str__(self): return self.name class Userproject(models.Model): id = models.AutoField(db_column = 'db_ID', primary_key = True) user = models.ManyToManyField(User) project = models.ManyToManyField('Project') created_at = models.DateTimeField(auto_now_add=True, null=True) updated_at = models.DateTimeField(auto_now=True, null = True) class Meta: db_table = 'UserProjects' def __str__(self): return self.id views.py : class ProjectView( APIView, ): def post(self, request): serializer = ProjectSerializer(data = request.data) if serializer.is_valid(): serializer.save() id = serializer.id user = request.user n = Userproject.objects.create(user = user, project = id) n.save() return Response({"status": "success", "data": serializer.data}, status = 200) else: return Response({"status": "error", "data": serializer.errors}, status = 400) serializers.py: … -
The static resource location of Django's static page is incorrect
When loading picture resources on the page, the following error is always prompted, and the picture resources cannot be loaded. WARNING 2021-10-19 23:05:11,608 basehttp 3161 140233184446208 "GET /dist/static/webpack/img/logo18.png HTTP/1.1" 404 7224 This is my setting: STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] there is always a strange "/dist" in the path. -
Django rest_framework forgot password
I'm newbie in Django I have a trouble with this: I've already make API for 'request-reset-email', 'password-reset' and 'password-reset-complete' Here are the code: file: urls.py from django.urls import path from .views import * from django.contrib.auth import views as auth_view from rest_framework_simplejwt.views import ( TokenObtainSlidingView, TokenRefreshSlidingView, ) urlpatterns=[ path('register/', RegisterView.as_view(), name="register"), path('login/', LoginAPIView.as_view(), name="login"), path('email-verify/', VerifyEmail.as_view(), name="email-verify"), path('token/refresh/', TokenRefreshSlidingView.as_view(), name='token_refresh'), path('request-reset-email/',RequestPasswordResetEmail.as_view(), name='request-reset-email'), path('password-reset/<uidb64>/<token>/',PasswordTokenCheckAPIView.as_view(),name='password-reset'), path('password-reset-complete/',SetNewPasswordAPIView.as_view(),name='password-reset-complete') ] file Views.py: from django.shortcuts import render from rest_framework import exceptions, generics, serializers from rest_framework.response import Response from rest_framework import status from .models import * from .serializers import * from rest_framework_simplejwt.tokens import RefreshToken from .utils import * from django.contrib.sites.shortcuts import get_current_site from django.urls import reverse import jwt from django.conf import settings from django.contrib.auth.tokens import PasswordResetTokenGenerator from django.utils.encoding import smart_str, force_str, smart_bytes, DjangoUnicodeDecodeError from django.utils.http import urlsafe_base64_decode, urlsafe_base64_encode # Create your views here. class RegisterView(generics.GenericAPIView): queryset = User.objects.all() serializer_class=RegisterSerializer def post(self, request): user = request.data serializer = self.serializer_class(data=user) serializer.is_valid(raise_exception=True) serializer.save() user_data = serializer.data user= User.objects.get(email=user_data['email']) token=RefreshToken.for_user(user).access_token current_site=get_current_site(request).domain realtivelink = reverse('email-verify') absurl='http://'+current_site+realtivelink+"?token="+ str(token) email_body='Hi '+ user.email+ ' Use link below to verify your email \n' + absurl data={'email_body':email_body,'to_email':user.email,'email_subject':'Verify your email'} Util.send_email(data) return Response(user_data,status= status.HTTP_201_CREATED) class VerifyEmail(generics.GenericAPIView): def get(self,request): token= request.GET.get('token') try: payload=jwt.decode(token,settings.SECRET_KEY,algorithms='HS256') user=User.objects.get(id=payload['user_id']) if not user.is_verified: user.is_verified=True user.save() return … -
obtaining individual model values python django
I have a database object that has several values that make it up. I can select the whole object by doing the following my_object = WholeValues.objects.all() The object has different parts such as "height, weight, arm_length, leg_length". each part is of type FloatField() in the django database model. How can I access these individually? for example just obtaining the weight value. -
Django template fragment caching not working the way it is supposed to
Referring to following documentation, I am trying this https://docs.djangoproject.com/en/dev/topics/cache/#template-fragment-caching {% cache 500 sidebar request.user.username %} {% if user.is_authenticated %} {{ user.first_name}} {% endif %} {% endcache %} The problem is my authenticated Name and picture is getting cached and seen by other users, and those of other users by some other user. Essentially anyone coming in hits the cache of previous chap visiting the web site. Apart from this no user access or any other security issue is not there. Can you advise why this is so and what is the solution to the problem. -
Bootstrap and Jinja - centering images
I'm using Bootstrap3 in my Django project and I would like to display images in row next to each other horizontally and I have: <div class="row"> {% for image in images %} {% if image.image %} <div class="col-lg-4 col-md-4 col-xs-4 thumb"> <img class="img-responsive" src="{{ image.image.url }}" /> </div> {% endif %} {% endfor %} </div> and it works. But images are displayed from left to right (for example, if there is only 1 image, it's pinned to the left and it doesn't look great). How can I center all images to always be centered independent on number of images? -
How do I clear path from history in Django?
I want to clear all path from history and redirect to new path. If is there any way to do this please provide suitable solutions. -
from an address get the altitude and longitude in django rest, I am new with this python
I am designing an api with django, I need to convert many directions to latitude and longitude, I don't know where to start I am something new in this -
Importing view is showing error from app in Django?
i am trying to create simple hello world page from django in pycharm and from urls.py file of my app "first_app" trying to import views. But when i type "from first_app import views" in urls.py, pycharm is underlining it as an error but my hello world page is still showing. Earlier it was giving some error. I am attaching screenshot of it. I have also mentioned first_app in installed_apps in settings.py file of the project. If any one knows about it please tell me what the issue is here. -
How do I change a parameter dynamically?
I have a simple e-commerce on Django. Can you show how to implement a dynamic price change depending on the number of items? For example: when adding to cart from 1 to 10 items the cost is 1, from 11 to 20 the cost is 0.9 and so on. Thank you very much! -
Django set relation between two models
I want to save my custom Model as Field in another Model as shown below. It's normal when I create and work with them during one session. But when I start a new session Django loads the Game model with player1 and player2 that have a null id. Here example of my code class Player(models.Model): name = models.CharField(max_length=40) class Game(models.Model): player1 = Player() player2 = Player() -
How to install python package from the project if requirememt.txt is not exist
How to install python package from the project if requirememt.txt is not exist like: In node.js we run npm install command and all npm package install. like that, I want a python package installed from the project. If any way to do that? -
Getting error when setting up HyperlinkedModelSerializer
I keep getting the error Could not resolve URL for hyperlinked relationship using view name "departments-api". You may have failed to include the related model in your API, or incorrectly configured the "lookup_field" attribute on this field. I am trying to link this but am not sure where I am going wrong here. I can get to the '/api/' page but can not click on either of the links to take me to the corresponding page. I believe I may need to change around my serializer hyperlinkedidentityfield or my api_root function but am not sure where to start. Models.py class Department(models.Model): name = models.CharField(max_length=300) def __str__(self): return self.name class Teacher(models.Model): name = models.CharField(max_length=300) # delete dept == delete teacher department = models.ForeignKey(Department, on_delete=models.CASCADE) tenure = models.BooleanField() def __str__(self): return f'{self.name} teaches {self.department}' def get_absolute_url(self): return reverse('teacher-detail', kwargs={'pk': self.pk}) serializers.py class TeacherSerializer(serializers.HyperlinkedModelSerializer): url = serializers.HyperlinkedIdentityField(view_name="teachers-api") class Meta: model = Teacher fields = '__all__' class DepartmentSerializer(serializers.HyperlinkedModelSerializer): url = serializers.HyperlinkedIdentityField( view_name="departments-api") class Meta: model = Department fields = ['url', 'name'] urls.py urlpatterns = [ path('api/', api_root), path('api/teachers/', TeacherAPIList.as_view(), name='teachers-api'), path('api/teachers/<int:pk>/', TeacherAPIDetail.as_view()), path('api/departments/', DepartmentAPIList.as_view(), name='departments-api'), path('api/users/', UserAPIList.as_view()), path('api/users/<int:pk>/', UserAPIDetail.as_view()), ] views.py @api_view(['GET']) def api_root(request, format=None): return Response({ 'teachers': reverse('teachers-api', request=request, format=format), 'departments': reverse('departments-api', request=request, … -
Group by query in Django ORM
I an having a confusion on how to write a django query to get my data. I have 2 tables 'ticket' and 'ticket_details'. Below is the schema for them. Ticket(id, name, type, user) TicketDetails(ticket_id, message, created_time) Note: Multiple message can be associated to one ticket id. And ticket_id is a foreign key to the Ticket table. I would like to fetch all the columns from both the table where only the latest message from the TicketDetails table should be picked for a particular ticket id. Thanks in advance -
REST Django - How to grab recently created Object
I use a post method to create an instance of the class called Project. When the Post method is done, I want to get the ID of the recently created Project-object. How would I do this? my model looks like this: models.py class Project(models.Model): id = models.AutoField(db_column = 'db_ID', primary_key = True) name = models.CharField(max_length=500, default = None) descriptor = models.CharField(max_length = 1000, null = True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: db_table = 'projects' def __str__(self): return self.name and my view is this: views.py: class ProjectView( APIView, ): def post(self, request): serializer = ProjectSerializer(data = request.data) if serializer.is_valid(): serializer.save() user = request.user return Response({"status": "success", "data": serializer.data}, status = 200) else: return Response({"status": "error", "data": serializer.errors}, status = 400) -
How does Django handle multiple CRUD actions on same table? (at same time)
I am curious about how Django handles multiple actions to be performed on same table at the same time. I'm using Postgresql with Django ORM. Does it have locking mechanism to handle such scenario? If yes then is it by default or any parameter must be added?