Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using GCS for media storage on Railway.app
I'm deploying my Django app to Railway.app and am hosting media on GCS (I like the free tier). I've created the service account and received the .json of the credentials. On my local system for dev, I have the .json file in the directory and refer to it like this: GS_CREDENTIALS = service_account.Credentials.from_service_account_file(".gcs_credentials.json") No problems and files upload great. I'm not passing the credentials file through Github (for safety reasons) but now I'm stuck. Is there a way to save this JSON file as an environment variable in Railway.app? For all of my other variables, I'm using django-environ and everything is working great. I just can't find anything online about passing credentials in JSON form to a deployment on Railway. Thank you in advance. -
Where does Django check framework functions live?
The django framework allows you to write your own checks https://docs.djangoproject.com/en/4.2/topics/checks/ but it says nothing about where that code should live and how it is hooked into the check framework. Any ideas on how this is done? -
Django Follow / Unfollow button does not change
I am trying to create a generic social media platform with django. The follow button works functionally, but doesn't text from "follow". The follower and following counts get updated appropriately. You can follow and unfollow people from the button. I just need the text to change. Models.py: class Follow(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='following', related_query_name='follower') followed_user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='followers', related_query_name='followed') created_at = models.DateTimeField(auto_now_add=True) Views.py: @login_required def follow(request, username): user_to_follow = get_object_or_404(User, username=username) follow, created = Follow.objects.get_or_create(user=request.user, followed_user=user_to_follow) if not created: follow.delete() return redirect(request.META.get('HTTP_REFERER', 'home')) def unfollow(request, username): user_to_unfollow = get_object_or_404(User, username=username) try: follow = Follow.objects.get(user=request.user, followed_user=user_to_unfollow) follow.delete() except Follow.DoesNotExist: pass return redirect(request.META.get('HTTP_REFERER', 'home')) URLS.py: path('follow/<str:username>/', views.follow, name='follow'), path('unfollow/<str:username>/', views.unfollow, name='unfollow'), Profile.html: {% extends 'base.html' %} {% block content %} <div class="profile"> <h2>{{ user.username }}</h2> <p>Followers: {{ user.followers.count }}</p> <p>Following: {{ user.following.count }}</p> {% if request.user in user.followers.all %} <form method="post" action="{% url 'unfollow' user.username %}"> {% csrf_token %} <button type="submit">Unfollow</button> </form> {% else %} <form method="post" action="{% url 'follow' user.username %}"> {% csrf_token %} <button type="submit">Follow</button> </form> {% endif %} </div> {% endblock %} -
Erro: GET / HTTP/1.1" 404 2281 - Python / Django
Boa noite! Ao tentar executar no terminal: python manage.py runserver, o seguinte erro é apontado: "GET / HTTP/1.1" 404 2281, a aplicação não inicia no navegador, acusando que: Usando o URLconf definido em , Django tentou estes padrões de URL, nesta ordem: type_event.urls admin/ usuarios/ eventos/ O caminho vazio não correspondia a nenhum desses. Revisei toda a parte de urls do projeto, de app por app e não consegui identificar a causa da falha. Tentei ver pelos arquivos estáticos também, mas não identifiquei a divergência. -
NoReverseMatch at /addpost/
I recently finished my schooling on Django, and now im building a simple travel blog website that will serve as a project and a portfolio for my job search. My reverse match was working but all the sudden it throws this error NoReverseMatch at /addpost/ Reverse for 'article_detail' with arguments '('1', '4')' not found. 1 pattern(s) tried: ['article/(?P[0-9]+)\Z'] it looks like my posts in my model are automatically being assigned two IDs as their primary key but my code is only built to take a single PK so im not sure whats going on or how to fix it here? i read about 20 other stack overflow posts with similar questions but im still struggling to see what i need to do to fix this. below i posted my models.py, views.py and urls.py please let me know if you need to see anything else. the error appears to be at the bottom of my post model where redirect for adding a post is. Here is my model from django.db import models from django.contrib.auth.models import User from django.urls import reverse from datetime import datetime, date from ckeditor.fields import RichTextField class Post(models.Model): title = models.CharField(max_length=255) author = models.ForeignKey(User, on_delete=models.CASCADE) body = RichTextField(blank=True, … -
Integrate reCAPTCHA Enterprise with Android apps and Python as Backend
I want to Integrate reCAPTCHA Enterprise on Front-end (Android) and with Back-end Python on Login. I have implemented on Android and perfectly generating reCAPTCHA response. Problem I send reCAPTCHA generated response to Back-end (Django) in HTTP/POST API call to verify on Back-end. On Back-end I call 'https://www.google.com/recaptcha/api/siteverify' and binded the reCAPTCHA response with GOOGLE_RECAPTCHA_SECRET_KEY to verify the user generated reCAPCHA. But I get message [invalid-input-response] reCAPTCHA in response of 'https://www.google.com/recaptcha/api/siteverify' -
Countdown timer in Django
I need a solution for this issue. I want to make a countdown timer where the deadline is taken from database .. Here is my code to take the remaining time exam_model = modelUjian.objects.get(kodeujian=kodeujian) finish_time = datetime.combine(exam_model.date, exam_model.finishtime) current_time = datetime.now().replace(microsecond=0) time_left = finish_time - current_time context = {"time_left":time_left} return render(request,'mulaiujian.html', context) But i don't know how to show it in HTML. I try some method but it's not working .. nothing appear on countdown span below Here is my HTML <div class="card"> <div class="card-body"> <p>Waktu tersisa: <span id="countdown"></span></p> </div> </div> and this is my javascript .. <script> var countdown = { time_left }; // mengambil countdown dari context di views var x = setInterval(function() { var hours = Math.floor(countdown / 3600); var minutes = Math.floor((countdown % 3600) / 60); var seconds = Math.floor(countdown % 60); // menampilkan waktu dalam format hh:mm:ss document.getElementById("countdown").innerHTML = hours + ":" + minutes + ":" + seconds; if (countdown <= 0) { clearInterval(x); document.getElementById("countdown").innerHTML = "Waktu telah habis!"; } else { countdown--; } }, 1000); </script> -
Using list elements in a form in Django template
I have the following form in a Django template. The list prize is a list of numbers defined in my view.py. Specifically, prize is defined to be prize = [0]*total I want to have the elements of prize listed as the default values on user input fields. I have tried to do this with the following code. <form> {% for i in total %} <label for="match_{{ i }}">Enter the prize received for getting {{ i }} matches:</label> <input type="number" name="match_{{ i }}" id="match_{{ i }}" required value="{{ prize.i|default:'' }}"> <br> {% endfor %} </form> While I get no errors, I only get the empty forms with no default values. Any ideas? I have checked that the list prize is rendered correctly as I can print out their values on the webpage fine. -
Django: can I verify email using otp in Django?
I have a question about Django authentication that has been bothering me for days now. Is it possible for a user, before they create an account they pass through these steps? Enter only their email first I send OTP to their email They verify their email using the OTP I then ask for their username, password 1, password 2 Please, if anybody knows whether something like this is possible using the Django REST framework, I would really appreciate an answer. -
Change dockerized Django default app from git ignored .env
I need to modify the default flatpages app which is in django.contrib and tinymce in site-packages. Both in gitignored env directory installed from requirements.txt when Docker is starting. How it should be properly done? Dockerfile; I've tried to pull it out, change imports (a mess) but soon realized it does not make sense as Django is installed from the Docker image.. -
I don't understand how to display clothing sizes in an online store in the format .html on django
ㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤ how do I make a form that will add this size to the shopping cart when choosing a clothing size. In principle, I wrote all the code, but I don't understand how I can write code in .html to make it all work, I really ask you, I spent about 2 weeks on it views.py @require_POST def cart_add(request , product_id , size): cart = Cart(request) product = Product.objects.get(id=product_id) size_ = get_object_or_404(ProductSizes , id=size) form = CartAddProductForm(request.POST) if form.is_valid(): cd = form.cleaned_data cart.add(product=product , quantity=cd['quantity'] ,size_=size_, override_quantity=cd['override'] ) return redirect("post") def cart_remove(request, product_id): cart = Cart(request) product = get_object_or_404(Product, id=product_id) cart.remove(product) return redirect('cart:cart_detail') def cart_detail(request): cart = Cart(request) for item in cart: item['update_quantity_form'] = CartAddProductForm(initial={'quantitu':item['quantity'],'update':True}) return render(request, 'cart/detail.html', {'cart': cart}) urls.py app_name = 'cart' urlpatterns = [ path('',views.cart_detail,name='cart_detail'), path('add/<int:product_id>/',views.cart_add,name='cart_add'), path('remove/<int:product_id>/',views.cart_remove,name='cart_remove'), ] cart.py class Cart: def __init__(self, request): self.session = request.session cart = self.session.get(settings.CART_SESSION_ID) if not cart: cart = self.session[settings.CART_SESSION_ID] = {} self.cart = cart # add to cart def add(self, product, size_, quantity=1, override_quantity=False): size_id = str(size_.id) if size_id not in self.cart: if size_.price: self.cart[size_id] = {'quantity': 0, 'price': size_.price} elif size_.off_price: self.cart[size_id] = {'quantity': 0, 'price': size_.off_price} self.cart[size_id]['quantity'] += quantity self.save() self.save() def save(self): self.session.modified = True # remove … -
Migrations error: changes detected but nothing changed in my database
I'm trying to connect my django project with mongodb database, after migrations the changes detected but nothing happen in my database. I'm providing the models.py and setting.py files, if anyone can help me and thank you in advance. models.py from django.db import models # Create your models here. class Task(models.Model): title=models.CharField(max_length=50) description=models.TextField() deadline=models.DateField() done=models.BooleanField(default=False) class Meta: db_table= 'Coll' settings.py DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'Mydb', } } DEFAULT_AUTO_FIELD='django.db.models.AutoField' I already installed djongo, and this is my pip list Django 4.2 django-cors-headers 3.14.0 django-grappelli 3.0.5 django-mongodb-engine 0.6.0 django-suit 2.0a2 djangorestframework 3.14.0 djangotoolbox 1.8.0 djongo 1.3.6 grep 0.3.2 mongoengine 0.27.0 Pillow 9.5.0 pip 23.0.1 pipenv 2023.3.20 pymongo 3.12.1 pytz 2023.3 sqlparse 0.4.3 virtualenv 20.21.0 virtualenv-clone 0.5.7 -
How can I connect ready-made layout on Vue with Django?
I made a frontend part of project on Vue.JS 3 and after a time gets a conclusion that I wants to create backend part on Django. Frontend part already written, backend only in the initial stage - they are located in two different directories. How can I connect backend and frontend to realize data exchange? Please give me some advices how solve this problem. With the help of guides , it was not possible to understand the examples beacuse they have slightly different architecture. -
Problem importing a module in django v4.1.7, pydroid3 python v3.9.7
My urls.py and views.py files are in the same directory (my_app), after importing the views.py file from my urls.py file, whenever I try to start the development server I get a module import error: no module named views but when I compile and run the urls.py file I get an import error: attempted relative import with no parent package. This is the code from urls.py: from django.urls import path from . import views urlpatterns = [ path('', index, name='index') ] I tried modifying the import statement for views into: from views import index and that removed the compilation error but not the server error. -
Odd behavior concerning Django's admin page saving files
I have Django 4.1.7 website, served by apache2 on Ubuntu PC. in the .conf file of apache2: Alias /static /mnt/hdd/SIMSY/static/ and Django works as expected. All CSS, JS, Images are loaded just fine. But when adding new object using Django's built-in admin site, the site tries saving the images on /static in the root of Ubuntu (it caused Permission error, then I tried creating that folder in the root and it actually saved the image in that folder). How is Django trying to save in /static while apache2 tells it that /static is /mnt/hdd/SIMSY/static? I assume there is something can be changed in settings.py to solve that, what can be changed? Here is the part of settings.py that has anything to do with static: BASE_DIR = Path(__file__).resolve().parent.parent STATIC_URL = '/static/' STATICFILES_DIRS = [ BASE_DIR / "static", ] -
Django_Password_Expiry_not_working
setting.py PASSWORD_RESET_TIMEOUT = 120 views.py def login(request): if request.method == 'POST': uname = request.POST['uname'] pwd = request.POST['pwd'] user = authenticate(username=uname, password=pwd) if user is not None: if user.is_active: auth.login(request, user) return redirect('home') else: return render(request, 'login.html') models.py class RegisterUser(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) mobile = models.CharField(max_length=100) password_expiry = models.TimeField(auto_now_add=True) def __str__(self): return self.user.username Does anyone know how to set password expiry in django for 2 minutes -
django drf not listing all data in models
I am testing to overwrite the object with same "user" value after posting the data, the django model is like below: class TestModel(models.Model): customer = models.CharField(max_length=128, verbose_name="Customer Name", help_text="Customer Name") account = models.CharField(max_length=20, verbose_name="Account Id", help_text="Account Id") role = models.CharField(max_length=64, verbose_name="customer Role", help_text="IAM Role") user = models.CharField(max_length=20, verbose_name="User Name", help_text="User Name") post_time = models.CharField(max_length=16, verbose_name="Post Time", help_text="Post Time", null=True) Serializer class: """ TestModel Serializer """ class Meta: model = TestModel fields = '__all__'``` def create(self, validated_data): user = validated_data.get('user') try: testobj = TestModel.objects.get(user=user) for key, value in validated_data.items(): setattr(testobj, key, value) testobj.save() return testobj except TestModel.DoesNotExist: return super().create(validated_data) Viewset: class TestViewset(viewsets.ModelViewSet): lookup_field = 'user' permission_classes = (permissions.IsAuthenticated,) serializer_class = TestModelSerializer queryset = TestModel.objects.all() Every time after post, the database record updated as expected, but when accessing via get api and using the user as lookup_field, it always return the stale(the old record values). Appreciate for any help. Thanks. -
DRF custom url for viewset method
I have a rating viewset for product per user as : class RatingViewSet(viewsets.ModelViewSet): queryset = models.Rating.objects.all() serializer_class = serializers.RatingSerializer # @action(detail=False, methods=['get'], url_path=r'(?P<user>\d+)/(?P<pizza>\d+)/') @action(detail=False, methods=['get'], url_path=r'<int:user>/<int:pizza>') def get_user_pizza_rating(self, request, *args, **kwargs): how can I define the url to call this method drf custom url actions -
Django Queryset filtering against list of strings
Is there a way to combine the django queryset filters __in and __icontains. Ex: given a list of strings ['abc', 'def'], can I check if an object contains anything in that list. Model.objects.filter(field__icontains=value) combined with Model.objects.filter(field__in=value). -
Change IP-address of django server [closed]
I'm currently trying to program a server that makes a series of files available for download within a network. I use Django to run the server on different PCs. My problem with this is that when I use python manage.py runserver 0.0.0.0:8000 the clients don't know what the IP address of the server is. Is it possible to change the IP address of the server so that the same address is always used everywhere, no matter what network or PC? -
How to dynamically generate optimal zoom on folium/leaflet?
I am using leaflet and folium to map out locations. These locations can be filtered out and therefore requires something a bit dynamic. I want to achieve two things: center the user on the map between the different locations (that works); Now I also want to regulate the zoom level to capture all the locations on the screen - sometime this zoom might be at street level, sometimes it might be at a country level. I feel my problem can be solved by using fitBounds, which according to documentation automatically calculates the zoom to fit a rectangular area on the map. That sounds ideal and this post here seems to be giving an answer about a similar question: pre-determine optimal level of zoom in folium Slight problem, I just don't understand it. I am thinking I should be able to use the min and max longitude and latitude to generate the rectangular area leaflet documentation refers to. But how does that translate in the zoom levels provided by leaflet? def function(request): markers = Model.objects.filter(location_active=True) #Max latitude & longitude min_latitude = Model.objects.filter(location_active=True).aggregate(Min('latitude'))['latitude__min'] min_longitude = Model.objects.filter(location_active=True).aggregate(Min('longitude'))['longitude__min'] #Min latitude & longitude max_latitude = Model.objects.filter(location_active=True).aggregate(Max('latitude'))['latitude__max'] max_longitude = Model.objects.filter(location_active=True).aggregate(Max('longitude'))['longitude__max'] sum_latitude = 0 # sum latitude … -
How to avoid similiar queries in for loop
I have json and i parse and filter that json literally in my template and for some reason i have 10 similiar queries bcs of that loop I tried to call my Model outside loop all_sections = CleanSections.objects.all() but it didnt help views.py class ShowProjectBudgetList(ListView): template_name = 'customer/customer_home.html' context_object_name = 'json_data' def get_queryset(self): response = session.get(url, auth=UNICA_AUTH) queryset = [] all_sections = CleanSections.objects.all() for item in response_json: my_js = json.dumps(item) parsed_json = ReportProjectBudgetSerializer.parse_raw(my_js) for budget in parsed_json.BudgetData: budget.SectionGUID = CleanSections.objects.filter(GUID=budget.SectionGUID) budget.СompletedContract = budget.СompletedContract * 100 budget.СompletedEstimate = budget.СompletedEstimate * 100 queryset.append(budget) return queryset template.html {% for info in json_data %} <tr> {% for section in info.SectionGUID %} <td>{{ section }}</td> {% endfor %} <td>{{ info.BudgetContract|floatformat:"2g" }} ₽</td> <td>{{ info.DiffContractEstimate|floatformat:"2g" }} ₽</td> <td>{{ info.СompletedContract|floatformat:0 }}</td> <td>{{ info.BudgetEstimate|floatformat:"2g" }} ₽</td> <td>{{ info.DiffEstimateAct|floatformat:"2g" }} ₽</td> <td>{{ info.СompletedEstimate|floatformat:0 }}%</td> <td>{{ info.SumAct|floatformat:"2g" }} ₽</td> </tr> {% endfor %} -
django-ckeditor5 server error 500 with AWS S3 bucket
I am attempting to use AWS S3 bucket for storage with a Django site. I am using django-ckeditor5 for some text fields in some models. I am allowing image uploads in the ckeditor fields. This works with local storage. However, when I attempt to upload an image while using the S3 bucket for storage, I get the following error in the terminal: OSError: [Errno 30] Read-only file system: '//bucketname.s3.amazonaws.com' [12/Apr/2023 13:33:58] "POST /ckeditor5/image_upload/ HTTP/1.1" 500 118977 For testing I have made the bucket policy completely open with the following policy: { "Version": "2012-10-17", "Statement": [ { "Sid": "AddPerm", "Effect": "Allow", "Principal": "*", "Action": "s3:*", "Resource": "arn:aws:s3:::bucketname/*" } ] } The relevant section from the settings.py file is: #S3 Bucket config AWS_ACCESS_KEY_ID = 'Key ID here' AWS_SECRET_ACCESS_KEY = 'secret key here' AWS_STORAGE_BUCKET_NAME = 'bucketname' AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com' #AWS S3 Settings AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3StaticStorage' # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.1/howto/static-files/ AWS_LOCATION = 'static' STATICfILES_DIRs = [ str(BASE_DIR.joinpath('static')), ] STATIC_ROOT = BASE_DIR / "static" STATIC_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{AWS_LOCATION}/' STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', # other finders.. 'compressor.finders.CompressorFinder', ) MEDIA_URL = '//%s.s3.amazonaws.com/media/' % AWS_STORAGE_BUCKET_NAME MEDIA_ROOT = MEDIA_URL AWS_QUERYSTRING_AUTH = False # needed for ckeditor … -
Django DreamHost - Request exceeded the limit of 10 internal redirects due to probable configuration error
I have hosted Django project on DreamHost. Everything works perfectly when I visit the homepage, but when I try to access any other page, I receive the following error message: Example: www.example.com (Working) www.example.com/foo/ (Getting error) 'Request exceeded the limit of 10 internal redirects due to probable configuration error. Use 'LimitInternalRecursion' to increase the limit if necessary. Use 'LogLevel debug' to get a backtrace.' I have tried to solve this issue, but I have been unable to do so. Following is my .htaccess file in /home/username/example.com/public folder. RewriteEngine On RewriteCond %{HTTPS} !=on RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301,NE] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ /electiondata_private/$1 [L,QSA] AddHandler wsgi-script .wsgi And my passenger.wsgi file in /home/username/example.com import sys, os INTERP = "/home/analyzethevote/atv/electiondata-private/venv/bin/python3" #INTERP is present twice so that the new python interpreter #knows the actual executable path if sys.executable != INTERP: os.execl(INTERP, INTERP, *sys.argv) cwd = os.getcwd() sys.path.append(cwd) sys.path.append(cwd + '/electiondata-private') #You must add your project here sys.path.insert(0,cwd+'/venv/bin') sys.path.insert(0,cwd+'/venv/lib/python3.9.16/site-packages') os.environ['DJANGO_SETTINGS_MODULE'] = "electiondata_private.settings" from django.core.wsgi import get_wsgi_application application = get_wsgi_application() PS. I am using django 4. Any help would be appreciated. -
Django build Models with duplicating data is a correct way?
I'm new to Django. But have a doubt now regarding building Models within one Django app with certain relations. For example I have an accounts app with defined model User(AbstractUser) which works fine. I've created a new Django app records with a model Bill which suppose to handle a certain service records with following fields: year_due service_name cost To link User with a Bill I've created an additional model Payment which contains: user_id bill_id service_name year_due Is this example a good practice to define models or better to incapsulate such a fields within one class? I want to make it clear to see the relevant data. The main idea is to clearly see to which service_name a certain bill or payment belong. The raw example of my code I haven't yet migrate: class Bill(models.Model): service_name = models.CharField(max_length=30) fixed_cost = models.BooleanField(default=False) unit = models.CharField(max_length=5, null=True, blank=True) current_counter = models.DecimalField(max_digits=15, decimal_places=2, null=True, blank=True) consumption = models.DecimalField(max_digits=8, decimal_places=2, null=True, blank=True) cost_per_unit = models.DecimalField(max_digits=6, decimal_places=2, null=True, blank=True) payed_amount = models.DecimalField(max_digits=8, decimal_places=2) is_paid = models.BooleanField(default=False) class Payment(models.Model): bill_id = models.ForeignKey(Bill, on_delete=models.CASCADE) user_id = models.ForeignKey(User, on_delete=models.CASCADE) record_date = models.DateTimeField(auto_now_add=True) service_name = models.CharField(max_length=30) year_due = models.IntegerField() month_due = models.IntegerField() payed_amount = models.DecimalField(max_digits=8, decimal_places=2) Thank You in advance …