Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
When I activate the form, it gives an error in my app " 'str' object is not callable"
**I would be grateful if my friends could help me ** When I activate the form, it gives an error in my app The form inside the HTML file is not called ** view : def student_register(request, id): form = RegisterlesonForm() students = Profile.objects.get(pk=id) if request.method == "POST": form = RegisterlesonForm(request.POST) if form.is_valid(): fs = form.save(commit=False) fs.student = students fs.member_add = request.user.id register = Registerleson.objects.filter( student=id, leson=request.POST['leson']).count() if register > 0: messages.add_message(request, messages.WARNING, 'error') return redirect('register_lessone', id) else: fs.save() return redirect('member_index') context = { 'form': form, 'students': students, } return render(request, 'member/register_lesson.html', context) code forms : class RegisterlesonForm(forms.ModelForm): class Meta: model = Registerleson fields = ['leson', 'book', 'discount'] widgets = { 'leson': forms.Select(attrs={'class': 'form-control'}), 'discount': forms.NumberInput(attrs={'class': 'form-control'}), 'book': forms.Select(attrs={'class': 'form-control'}), } html code <form method="post" autocomplete="off"> {% csrf_token %} {{ form }} <div class="modal-footer"> <button type="submit" class="btn btn-primary">ثبت</button> </div> </form> -
Error 'tuple index out of range' in Django
A bit time ago I've used a regular unit tests (not django test) and now I've got some saved tests data in my project. I can open them pages in admin panel, but when trying to delete those receive error 'tuple index out of range'. How can I solve this problem? For clear case: url /admin/quest_manager/quest/15/change/ is working, url /admin/quest_manager/quest/15/delete/ raise error named above. Before and now i've never use position arguments in view, serializer and models. I use PostgreSQL for data bases, if it important. Unnecessary data in base disturb project and i want delete this elements without full clearing table in db. Thank you for help! -
why show this error on ubuntu server [ WARN:0@11.723] global net_impl.cpp:174 setUpNet DNN module was not built with CUDA backend; switching to CPU
I build Image upscale resolution project using python Django on local using EDSR model dnn_supperres they run properly and trained the image resolution correctly but ubuntu server not support dnn_superres EDSR model didn't run properly.. it show this issue [ WARN:0@11.723] global net_impl.cpp:174 setUpNet DNN module was not built with CUDA backend; switching to CPU (https://i.stack.imgur.com/Cm0es.png) I try these are steps in upscale resolution and used EDSR model dnn_superres on local and used EDSR model they trained on this proper way [ WARN:0@8.023] global net_impl.cpp:174 cv::dnn::dnn4_v20221220::Net::Impl::setUpNet DNN module was not built with CUDA backend; switching to CPU But, I try this steps on ubuntu server it not working proper way its show this issues [ WARN:0@11.723] global net_impl.cpp:174 setUpNet DNN module was not built with CUDA backend; switching to CPU So please provide and solve my question soon as possible -
How to create seperate login system for user and service provider in django
I have this fully functional user auth system User model: class User(AbstractUser): first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) email = models.CharField(max_length=255, unique=True) password = models.CharField(max_length=255) username = models.CharField(max_length=255, unique=True) date_joined = models.DateTimeField(default=timezone.now) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name','last_name'] User login view .I'm using JWT tokens stored in cookies. @api_view(['POST']) def LoginView(request): email = request.data['email'] password = request.data['password'] user = User.objects.filter(email=email).first() if user is None: raise AuthenticationFailed('User not found!') if not user.check_password(password): raise AuthenticationFailed('Incorrect password!') payload = { 'id': user.id, 'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=60), 'iat': datetime.datetime.utcnow() } token = jwt.encode(payload, 'secret', algorithm='HS256') response = Response() response.data = { 'jwt': token } return response In my React front-end i use react-auth-kit to check if the user if logged-in, to be able to access UserProfile.jsx component which is private as shown bellow. const PrivateRoute = ({ Component }) => { const isAuthenticated = useIsAuthenticated(); const auth = isAuthenticated(); return auth ? <Component /> : <Navigate to="/login" />; }; <Router> <NavBar /> <Routes> <Route path="/" element={<Home />} /> <Route path="/login" element={<Login />} /> <Route path="/signup" element={<Signup />} /> <Route path="/profile" element={<PrivateRoute Component={UserProfile} />} /> <Footer /> </Router> The Login.jsx component has a simple axios request to get data from backend. axios .post( "/api/login", { … -
request.query_params parsed incorrectly
Django request.query_params returns an incorrectly formatted QueryDict. For example, if the query parameters read: example_param=[{"id":"f8","example_action":"kill"}] request.query_params returns: <QueryDict: {'example_param': ['[{"id":"f8", "example_action": "kill"}]']}> Noting example_param was parsed as a list containing a string, which is not correct. How do I return request.query_params as valid json?