Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Access to stye.css denied - Django Static files - Nginx - I can't make my project read staticfiles (style.css)
I don't know what it could be anymore, I've already given permissions to the files, directories, reviewed the nginx config, the files in sites-available/enabled , I've already cleared the cache through django-shell , I've restarted the instance. I simply don't know. Here is the output of nginx: sudo tail -f /var/log/nginx/error.log 2024/03/28 02:27:01 [error] 2952#2952: *12 open() "/home/ubuntu/learning-app/learning-log/learningLog/staticfiles/learningLogApp/css/estilo.css" failed (13: Permission denied), client: 179.214.112.55, server: django.xxx.dev, request: "GET /static/learningLogApp/css/estilo.css HTTP/1.1", host: "django.xxx.dev", referrer: "https://django.xxx.dev/assuntos/" nginx.config: user www-data; worker_processes auto; pid /run/nginx.pid; include /etc/nginx/modules-enabled/*.conf; events { worker_connections 768; # multi_accept on; } http { sendfile on; tcp_nopush on; types_hash_max_size 2048; include /etc/nginx/mime.types; default_type application/octet-stream; ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3; # Dropping SSLv3, ref: POODLE ssl_prefer_server_ciphers on; access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; gzip on; include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*; } sites-available server { listen 80; listen 443 ssl; server_name django.xxx.dev; ssl_certificate /etc/letsencrypt/live/django.xxx.dev/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/django.xxx.dev/privkey.pem; location / { proxy_pass http://localhost:8000; include /etc/nginx/proxy_params; } location /static/ { alias /home/ubuntu/learning-app/learning-log/learningLog/staticfiles; } # Redirecionamento de HTTP para HTTPS if ($scheme = http) { return 301 https://$server_name$request_uri; } } settings.py DEBUG = False ... STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') what have I tried sudo chmod -R a+r /home/ubuntu/learning-app/learning-log/learningLog/staticfiles sudo find /home/ubuntu/learning-app/learning-log/learningLog/staticfiles -type d -exec chmod a+x {} … -
Writing a Django signal to log user activities in a model
These are my models in the models.py file. class User(AbstractUser): date_of_birth = models.DateField(blank=True, null=True) bio = models.TextField(blank=True, null=True) job = models.CharField(max_length=250, blank=True, null=True) photo = models.ImageField(upload_to='account_images/',blank=True, null=True) phone = models.CharField(max_length=11, blank=True, null=True) followings = models.ManyToManyField('self', through='Contact', related_name='followers', symmetrical=False) def get_absolute_url(self): return reverse('social:user_detail', args=[self.username]) class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user_posts') description = models.TextField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) tags = TaggableManager(blank=True) likes = models.ManyToManyField(User, related_name='liked_post', blank=True) saved_by = models.ManyToManyField(User, related_name='saved_post', blank=True) total_likes = models.PositiveIntegerField(default=0) class Meta: ordering = ['-created'] indexes = [ models.Index(fields=['-created']) ] def __str__(self): return self.author.username def get_absolute_url(self): return reverse('social:post_detail', args=[self.id]) class UserActivity(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user_activity') post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='post_activity', blank=True, null=True) action = models.CharField(max_length=50) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return f"{self.user} {self.action} {self.post.author}' post" I want to write a signal in which when a user likes a post, an object of the UserActivity model is created, and the value of the user field is set to the user who liked it. The post field should be set to the post that the user liked. And the action field should be set to 'likes'. @receiver(post_save, sender=Post.likes.through) def create_like_activity(sender, instance, **kwargs): if instance.likes.exists(): UserActivity.objects.create( user=instance.likes.last(), post=instance.author, action='likes' ) I tried to achieve this through this … -
Django urls works locally, but deployed to heroku all but one work
I am creating a React/Django website for my final project. I have apps, such as posts, profiles, etc., that work perfectly both locally and when deployed to Heroku. However, one of the apps, "base," works without issue locally but breaks when pushed to Heroku. I suspect it's a serializers/views issue, but I'm not entirely sure. How can I fix this issue? "base" app that won't work on Heroku Views: Screenshot URLs: Screenshot Serializers: Screenshot Any help is appreciated. I'm still learning, and this could very well be a simple typo for all I know, but I cannot seem to solve it. I've tried changing the URLs in every way I could think of, to no avail. I've also attempted changing the serializers and views, but I can't seem to solve it. -
Error creating auth token for newly registered user in Django Rest Framework
I'm working on a Django project where I'm trying to create an auth token for a newly registered user using Django Rest Framework. However, when running the register function, I run into the following error: ValueError: Cannot assign "<User: Test>": "Token.user" must be a "User" instance. Here is the register function where the error occurs: @api_view(['POST']) def register(request): serializer = UserSerializer(data=request.data) if serializer.is_valid(): serializer.save() user = User.objects.get(username=request.data['username']) user.hash_password(request.data['password']) user.save() token = Token.objects.create(user=user) # This is where the error occurs return Response({ 'token': token.key, 'User': serializer.data }, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) How can I fix this error and successfully create the authentication token for the newly registered user? I have tried to register a new user using the register function in my Django Rest Framework view. I was expecting the user to register successfully (register in the database) and for an auth token to be generated associated with that user. -
Django site working for all pages except for a few
I'm using a combo of python and django in order to load a site. A HTML home file is also present in the templates folder. I coded all parts of my site the way I normally do, which has worked for every single instance except for this one. The only app in my site is called "news". Here's the error I recieved after in my terminal after clicking the link python manage.py runserver gave me. Internal Server Error: / Traceback (most recent call last): File "C:\Users\Mahsa\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Mahsa\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "K:\Desktop 2.0\Python 6\irna_project\news\views.py", line 6, in home return render(request, "news/home.html", {"news", all_news}) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Mahsa\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\shortcuts.py", line 24, in render content = loader.render_to_string(template_name, context, request, using=using) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Mahsa\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\template\loader.py", line 62, in render_to_string return template.render(context, request) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Mahsa\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\template\backends\django.py", line 57, in render context = make_context( ^^^^^^^^^^^^^ File "C:\Users\Mahsa\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\template\context.py", line 286, in make_context raise TypeError( TypeError: context must be a dict rather than set. [28/Mar/2024 02:45:00] "GET / HTTP/1.1" 500 78799 Not Found: /favicon.ico [28/Mar/2024 02:45:00] "GET /favicon.ico HTTP/1.1" 404 2334 For more info, here are the main files: settings.py: """ Django settings for … -
What is a good throttling rate limit for drf views to secure endpoints
I have two drf class based views endpoints one for login and one for password reset I want to use throttling to prevent bruteforce related attacks to these two endpoints I found a lot of questions discussing the implementation and the throttling classes but none were talking about what is a good rate limit to protect the endpoints So what are the actual numbers to use? per second or per minute or per hour , what is the actual rate that a user shouldn't pass otherwise it's considered illegal TLDR: What is the number of requests to allow in a period of time to make sure a login api endpoint can't be bruteforced -
fix django login bug
I'm working on a django project, after I finished the code of registration and login feature (serializers and viewsets) I tested theses features, so when the registration feature seems working like a charm, the login feature bug,so when I try login with a registered user credetials I get this error message "detail": "No active account found with the given credentials" I used django rest framework for the logic and rest framewok JWT for token authentication HOw can I fix the bug? I reviewed all the logic of authentication and permission , I axpect to fix the bug so I can login safely -
How to get an object for editing transfer to a form?
I don't know how to get my announcement to insert into the form for editing my model: class Announcement(models.Model): category = models.CharField(choices=professions, blank=False) title = models.CharField(max_length=40, blank=False) slug = models.SlugField(max_length=250, unique_for_date='publish', ) price = models.IntegerField(default=None, null=True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='announcement_work') publish = models.DateTimeField(auto_now_add=True) description = models.TextField(max_length=500, blank=False) company = models.CharField(max_length=30, blank=False) experience = models.CharField(choices=Experience, blank=False) address = models.CharField(max_length=30, blank=False) city = models.CharField(max_length=30, blank=False) country = models.CharField(max_length=30, blank=False) Favorites = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='Favorites', blank=True) class Meta: ordering = ['-id'] indexes = [ models.Index(fields=['-id']) ] def __str__(self): return self.title def get_absolute_url(self): return reverse('account:announcement_detail', args=[self.publish.year, self.publish.month, self.publish.day, self.slug]) tags = TaggableManager() my form class AnnouncementForm(forms.ModelForm): class Meta: model = Announcement fields = ['category', 'title', 'price', 'country', 'city', 'description', 'experience', 'company', 'address', 'tags'] i try write views and url, but see error: django.urls.exceptions.NoReverseMatch: Reverse for 'announcement_edit' with no arguments not found. 1 pattern(s) tried: ['account/(?P<announcement_id>[0-9]+)/edit/\Z'] [26/Mar/2024 22:21:09] "GET /account/2024/3/21/employer-and-user/ HTTP/1.1" 500 154441 django.urls.exceptions.NoReverseMatch: Reverse for 'announcement_edit' with no arguments not found. 1 pattern(s) tried: ['account/(?P[0-9]+)/(?P[0-9]+)/(?P[0-9]+) /(?P[-a-zA-Z0-9_]+)/edit/\Z'] i try transmit data to url : '{% url 'account:announcement_edit' year month day slug %}' i try use include i don't understand how get edit form and i have another one question: how to make favorites announcement without … -
Проблема з порядком urls django
Вітаю! Потрібно ваша допомога. Виникла проблема з url, структура наступна: головний файл проєкта urls.py urlpatterns = [ path('admin/', admin.site.urls), path('ckeditor/', include('ckeditor_uploader.urls')), path('', include('shop.urls')), path('', include('informations.urls')), ] shop urls urlpatterns = [ path('', views.index, name="index"), path('contact', views.Contact, name="contact"), path('<str:category_slug>/', views.TireListByCategory, name='category_list'), path('pdf/<int:id>/', views.render_pdf_detail_view, name='test-pdf-view'), path('pdf/category/<str:category_slug>/', views.render_pdf_category_view, name='category_pdf_list'), path('brand/<str:slug>/', views.BrandDetail, name='brand_detail'), path('<str:category_slug>/<str:slug>/', views.TireDetail, name='tire_detail'), path('brands/<str:brand_slug>/<str:slug>/', views.BrandModelDetail, name='brand_model_detail'), ] informations.urls urlpatterns = [ path('blog/', views.page_info_blog, name='page_info_blog'), path('<str:category_info_slug>/', views.category_info_detail, name='category_info_detail'), path('<str:category_info_slug>/<str:page_info_slug>/', views.page_info_detail, name='page_info_detail') ] Перший include('shop.urls') працює добре Другий, помилка 404 Також при заміні місцями, працює тільки перший по списку, другий - помилка 404 Будь ласка, підкажіть про рівні urls. М Міняю місцями, то працю тільки перший по списку. Другий видає помилку 404 -
Python & Django web app - auto emails not sending
I had a web app developed but found the automated emails are not sending. I found the .py file for sending the email, but cannot find another file calling this. filetree showing .py file Is there a standard file to place a call to the send_due_email.py file? If I find that there is nothing calling this file to run, where should the code be placed? I want the emails sent once a week - maybe every sunday -
How to exclude instances with empty querysets in prefetch_related?
I have two models - Project and Contract. They have one-to-many relationship. class Contract(models.Model): project = models.ForeignKey(Project) I get a qs of Project instances with relevant Contract instance(s). projects = Project.objects.filter(active=True).prefetch_related( Prefetch('contract_set', queryset=Contract.objects.filter(**filters), to_attr='contracts') ) But now I need to get Project instances with exact Contract instance by putting Contract guid to filters. filters: Dict = { 'guid': some_guid, } But I receive all Project instances where only one has not empty contracts attr and others Project instances have empty contracts attr. I found such issues: How to exclude rows with empty prefetch_related field Filter prefetch_related empty in django but they do not help me. I tried such options: a) using OuterRef and Exist: projects = Project.objects.filter(**filters_projects).annotate( has_contracts=Exists( Contract.objects.filter(project_id=OuterRef('pk'), **filters_contracts) ) ) projects = projects.filter(has_contracts=True) b) using annotate: projects = ( Project.objects.filter(**filters_projects) .annotate(num_contracts=Count('contract')) .exclude(num_contracts=0) .prefetch_related( Prefetch('contract_set', queryset=Contract.objects.filter(**filters_contracts), to_attr='contracts') ) ) They do not work for me... How can I implement the required functionality? -
Django application hosted in vagrant not available at localhost
I have the Vagrant configuration that used to work some time ago, but now the application is not available at localhost after starting in virtual machine. Vagrant file content: # -*- mode: ruby -*- # vi: set ft=ruby : ENV["LC_ALL"] = "en_US.UTF-8" ENV["VAGRANT_DETECTED_OS"] = ENV["VAGRANT_DETECTED_OS"].to_s + " cygwin" Vagrant.configure("2") do |config| config.vm.box = "generic/rocky8" config.vm.network "forwarded_port", guest: 8080, host: 1234 config.vm.synced_folder ".", "/vagrant", type: "rsync", rsync__auto: true config.vm.provider "virtualbox" do |vb| vb.memory = "1024" end if Vagrant.has_plugin?("vagrant-vbguest") config.vbguest.auto_update = false config.vbguest.no_remote = true end end Django application is started using following command python manage.py runserver 0.0.0.0:8080 When running curl http://0.0.0.0:8080 in the Vagrant machine it returns expected result and Django logs "GET / HTTP/1.1" 200 20766, while in the host machine: curl http://127.0.0.1:1234 curl: (56) Recv failure: Connection was reset Also, web browsers fail to connect returning either ERR_CONNECTION_RESET or ERR_INVALID_HTTP_RESPONSE. Additional thing I checked: vagrant port The forwarded ports for the machine are listed below. Please note that these values may differ from values configured in the Vagrantfile if the provider supports automatic port collision detection and resolution. 22 (guest) => 2222 (host) 8080 (guest) => 1234 (host) I am on Windows 11 and tried a lot of different … -
How can I let a task run all the time on a linux v-server?
I would like to develop a web game. It is based on a database (MySQL) and is intended to run on a Linux server. My question is: Can I write a Python program that I store on the server and that runs nonstop and performs actions on the data in the database? And then run a website on the same server that can then access the data in the database and also carry out actions on it? Later I would also like to create this website as an Android or iOS app. So far I've mainly read up on Django to develop the web game. But it doesn't seem to be 100% suitable for developing the web game with. So which tool would be best suited to develop the game with? -
Dictionary with unknown depth in Python Django
i have following data: [ {'I. Intangible Assets': ['1. Concessions, Licenses']}, {'II. Tangible Assets': [ '1. Land, Buildings and Similar Rights', '2. Machinery and Equipment', {'3. Other Facilities, Operating and Business Equipment': ['Cars', 'Trucks']} ]}, {'III. Financial Assets': ['1. Equity Interests in Affiliated Companies']} ] sourcecode: {% for group in structure %} {% for parent, elements in group.items %} <hr> <b>{{ parent }}</b><br> {% for child in elements %} {{ child }} <br> {% endfor %} {% endfor %} {% endfor %} The code works up to the second level without any problems. However, if there is a third level, this is only displayed as a dictionary. Therefore, the output is "{'3. Other Facilities, Operating and Business Equipment': ['Cars', 'Trucks']}" Iterating over them with for key, val in child do not work. Any ideas? -
django formset management_form null value for id_form-TOTAL_FORMS
I have a form with an inlineformset_factory. When the button to add more forms is clicked I receive the error Uncaught TypeError: totalForms is null $addFormset http://localhost:8000/static/js/site-js.js:21 line 21 of site-js.js totalForms.setAttribute('value', '${formsetNum + 1}'); // Increment the Number of Total Forms in the Management Form Data I see that client_formset.management_form creates the following 4 hidden input fields in my form. <input type="hidden" name="client_set-TOTAL_FORMS" value="1" id="id_client_set-TOTAL_FORMS"> <input type="hidden" name="client_set-INITIAL_FORMS" value="0" id="id_client_set-INITIAL_FORMS"> <input type="hidden" name="client_set-MIN_NUM_FORMS" value="0" id="id_client_set-MIN_NUM_FORMS"> <input type="hidden" name="client_set-MAX_NUM_FORMS" value="1000" id="id_client_set-MAX_NUM_FORMS"> when I log totalForms I receive a null value instead of the value for id_client_set-TOTAL_FORMS. index.html {% load static %} <!DOCTYPE html> <html> <body> {% block body_content %} <form method="post" id="form"> {% csrf_token %} {{ construction_form }} {% if client_formset %} <h3>Clients</h3> {{ client_formset.non_form_errors }} {{ client_formset.management_form }} {% for form in client_formset %} <div class="formset-container {{ client_formset.prefix }}"> <div class="first-name">{{ form.first_name.label }}: {{ form.first_name }}</div> <div class="last-name">{{ form.last_name.label }}: {{ form.last_name }}</div> {% if client_formset.can_delete %} <div class="delete">{{ form.DELETE }} {{ form.DELETE.label }}</div> {% endif %} </div> {% endfor %} {% endif %} <button id="add-formset" type="button">Add Another</button> <input type="submit" value="Save"> </form> {% endblock %} <script type="text/javascript" src="{% static 'js/site-js.js' %}"></script> </body> </html> site-js.js let formsetContainer = document.querySelectorAll('.formset-container'), form … -
How to get data from a form and paste them into template?
I'm trying to make search functionality in my project. There is a form where a person can enter a title of an article and redirect to the page of this article if it exists. But it always gives me "None". It gives me this line in the terminal if I for example enter 'CSS': "GET /search?csrfmiddlewaretoken=yzuY5iPKEJGJgFZE7D9GKoRhSxE2EsUVmVcvJvTuCG6Q2sEBHtiuzUJx2ZPu4fwb&title=CSS HTTP/1.1" 200 1264. What to do? Util.py: import re from django.core.files.base import ContentFile from django.core.files.storage import default_storage def list_entries(): """ Returns a list of all names of encyclopedia entries. """ _, filenames = default_storage.listdir("entries") return list(sorted(re.sub(r"\.md$", "", filename) for filename in filenames if filename.endswith(".md"))) def save_entry(title, content): """ Saves an encyclopedia entry, given its title and Markdown content. If an existing entry with the same title already exists, it is replaced. """ filename = f"entries/{title}.md" if default_storage.exists(filename): default_storage.delete(filename) default_storage.save(filename, ContentFile(content)) def get_entry(title): """ Retrieves an encyclopedia entry by its title. If no such entry exists, the function returns None. """ try: f = default_storage.open(f"entries/{title}.md") return f.read().decode("utf-8") except FileNotFoundError: return None Views.py: from django.shortcuts import render, redirect from django import forms from . import util from django.http import HttpResponseRedirect def index(request): return render(request, "encyclopedia/index.html", { "entries": util.list_entries() }) def entry(request, title): return render(request, "encyclopedia/details.html", { … -
Can't display page content in Django
There is an application posts. There is a model: class Post(models.Model): text = models.TextField() pub_date = models.DateTimeField("date published", auto_now_add=True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="posts") group = models.ForeignKey(Group, on_delete=models.SET_NULL, related_name="posts", blank=True, null=True) def __str__(self): # выводим текст поста return self.text There is a urls: path('posts/<str:username>/<int:post_id>/', views.post_view, name='post'), There is a views: @login_required def post_edit(request, username, post_id): post = get_object_or_404(Post, pk=post_id, author__username=username) print(post.text) if request.user != post.author: return redirect('post', username=username, post_id=post_id) form = PostForm(request.POST or None, instance=post) if form.is_valid(): form.save() return redirect('post', username=username, post_id=post_id) return render(request, 'post_new.html', {'form': form, 'post': post}) When checking here in Views everything is displayed correctly: print(post.text). However, nothing works on the HTML page? There is a HTML: <main role="main" class="container"> <div class="row"> <div class="col-md-12"> <div class="card mb-3 mt-1 shadow-sm"> <div class="card-body"> <p class="card-text"> <a href="{% url 'profile' user.username %}"> <strong class="d-block text-gray-dark">@{{ post.author.username }}</strong> </a> {{ post.text }} </p> <div class="d-flex justify-content-between align-items-center"> <div class="btn-group"> <p>Author: {{ post.author.get_full_name }}</p> <p>ID: {{ post.author.username }}</p> </div> <small class="text-muted">{{ post.pub_date }}</small> </div> </div> </div> </div> </div> </main> What is the problem. Nothing works here? post.pub_date, post.author.get_full_name... Why does this work in context: {% for post in posts %} .... {{post.text}} ... Works through {{ posts.0.author.username }}. But it doesn't work: … -
Connecting CSS in Django project
Please tell me what the error is. After running the python manage.py collectstatic files were generated, the js scripts work, but the css file is not connected. base.html <!doctype html> {% load static %} <html lang="en"> <head> .... <!--Custome CSS--> <link rel="stylesheet" href="{% static 'static/css/style.css' %}"> <title>{% block title %} {% endblock %}</title> </head> Folder: enter image description here settings.py STATIC_URL = 'static/' STATIC_ROOT = BASE_DIR / STATIC_URL I tried adding the code from the documentation: from django.conf import settings from django.conf.urls.static import static urlpatterns = [ # ... the rest of your URLconf goes here ... ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) -
Python & Django web app how to delete database values without affecting reports
I had a web app developed that is a simple crm used to create estimates, service reports and invoices. It includes a module for tracking inventory. I found if I deleted an item from inventory that the estimates, service reports and invoices that include this item will fail to load and cause an error. Is there a way to work around this? I am guessing it is referencing the id of the inventory item and then cannot find the details. How can I delete inventory items without affecting existing reports? The datbase file where the inventory is stored is named db.sqlite3 -
Payfort - (00073) Invalid request format
I hope everyone is doing well. I'm trying to set up payfort in Django, but I keep encountering this strange error. I believe I'm following all the necessary steps, but whenever I attempt to send a request after tokenization, I receive the following error. {'response_code': '00073', 'response_message': 'Invalid request format', 'status': '00'} Tokenization Code: def initiate_tokenization(request): current_timestamp = str(int(time.time())) requestParams = { 'service_command': 'TOKENIZATION', 'merchant_identifier': settings.MERCHANT_IDENTIFIER, 'merchant_reference': current_timestamp, 'language': settings.LANGUAGE, 'access_code': settings.ACCESS_CODE, 'return_url': 'http://localhost:8000/callback', } signature = calculate(requestParams, settings.SHA_REQUEST_PHRASE) requestParams['signature'] = signature redirectUrl = 'https://sbcheckout.payfort.com/FortAPI/paymentPage' response = "<html>\n<head>\n<title>Standard Merchant Page Sample</title>\n</head>\n<body>\n" response += "<h1 style='text-align:center'>Standard Merchant Page iFrame Sample</h1>\n" response += "<center><iframe style='width: 100vw; height: 500px; border:6px dotted green' name='myframe' src=''></iframe></center>\n" response += "<form action='" + redirectUrl + "' method='post' id='' target='myframe'>\n" for key, value in requestParams.items(): response += "\t<input type='hidden' name='" + html.escape(key) + "' value='" + html.escape(value) + "'>\n" response += "\t<input value='Show Payment Form' type='submit' id='form1'>\n" response += "</form>\n</body>\n</html>" resp = HttpResponse(response) resp['X-Frame-Options'] = 'ALLOWALL' return resp Purchase Code: import requests import time import hashlib def calculate(unsorted_dict, sha_phrase, sha_method=hashlib.sha256): sorted_keys = sorted(unsorted_dict, key=lambda x: x.lower()) sorted_dict = {k: unsorted_dict[k] for k in sorted_keys} result = "".join(f"{k}={v}" for k, v in sorted_dict.items()) result_string = f"{sha_phrase}{result}{sha_phrase}" signature = sha_method(result_string.encode()).hexdigest() … -
Show user location in django admin
There was a task to implement a map in the admin interface in Django. I have a model that stores data about users GPS. class Geoposition(BaseModel): created_by = models.ForeignKey("User", on_delete=models.CASCADE, verbose_name=_("User")) task = models.ForeignKey("Task", on_delete=models.SET_NULL, verbose_name=_("Task"), null=True, blank=True) longitude = models.CharField(max_length=20, default="", verbose_name=_("Longitude")) latitude = models.CharField(max_length=20, default="", verbose_name=_("Latitude")) battery_level = models.CharField(max_length=20, default="", verbose_name=_("Battery Level")) speed = models.CharField(max_length=20, default="", verbose_name=_("Speed")) Here I refer to the "Task" model by Foreign Key. In Django admin in Task model I have Inlines class TaskTransitInline(admin.TabularInline): model = Geoposition I need that when you click on Inline inside the Task model, a map displaying the user’s tracking will open Maybe someone has encountered this problem and can help me I looked at several libraries, but I have no idea which one might be useful to me -
Wagtail 6/ Django: TypeError: 'tuple' object is not callable creating a ListBlock with custom StructBlocks
I want to create a ListBlock with custom StructBlocks. I use the following code: card_group.py # Other custom blocks will be added in the future CARD_BLOCKS = [ ("text_block", TextBlock()) ] class CardGroup(blocks.StructBlock): cards = blocks.ListBlock( blocks.StructBlock(CARD_BLOCKS) ) class Meta: template = "blocks/card_group.html" label = _("Card group") I Get the following error: TypeError: 'tuple' object is not callable. I also use the same setup on different parts in the project for example in the homepage models.py. The only difference is that i have the list in parentheses like this: COMMON_BLOCKS = ( ("text_block", TextBlock()), ("button", Button()), ("button_group", ButtonGroup()) ("card_group", CardGroup()) ) HEADER_BLOCKS = () + COMMON_BLOCKS HOMEPAGE_BLOCKS = () + COMMON_BLOCKS That works for these lists but when i want to use this aproach for the CARD_BLOCKS i get the following error: ValueError: too many values to unpack (expected 2) But it works on the other blocks, i am clearly missing something. The usage in the models.py: header_content = StreamField( HEADER_BLOCKS, verbose_name=_("Header Content"), blank=True, null=True, ) content = StreamField(HOMEPAGE_BLOCKS, verbose_name=_("Content"), null=True, blank=True) I use wagtail 6 I want to create a ListBlock with custom StructBlocks. I use the following code: card_group.py # Other custom blocks will be added in the … -
ERROR 403 in Django even after configuring the django-cors-headers package
Is the django-cors-headers exclusive to the DRF? If not, why am I getting an error 403 if I am not using DRF in my project? I already configured the django-cors-header package. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'api', 'corsheaders', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ALLOWED_ORIGINS = [ 'http://localhost:8000', ] -
Missing email key in fields for UserCreationForm in Django
I am having an issue with the UserCreationForm in Django, namely, I receive an error related to the email field, which is my USERNAME_FIELD, not being found in self.fields I subclass the UserCreationForm as such class UserCreationForm(UserCreationForm, CheckUserEmailExtension): """ A UserCreationForm with optional password inputs. """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields["password1"].required = False self.fields["password2"].required = False # If one field gets autocompleted but not the other, our 'neither # password or both password' validation will be triggered. self.fields["password1"].widget.attrs["autocomplete"] = "off" self.fields["password2"].widget.attrs["autocomplete"] = "off" class Meta: model = User fields = ( 'first_name', 'last_name', 'email', 'is_pi', 'password1', 'password2', ) And the error occurs at authtools/forms.py, line 95, in __init__ self.fields[User.USERNAME_FIELD].validators.append(validate_uniqueness_of_username_field) due to email not being in self.fields in fact, if I check the local variables, I see only is_pi;password1;password2 in self.fields Local Vars __class__ <class 'authtools.forms.UserCreationForm'> args () kwargs {'initial': {'_changelist_filters': 'q=patt'}} self <UserForm bound=False, valid=Unknown, fields=(is_pi;password1;password2)> validate_uniqueness_of_username_field <function UserCreationForm.__init__.<locals>.validate_uniqueness_of_username_field at 0x7f255fb58540> Yet, when ModelForm is called, email is there form = ModelForm(initial=initial) Local Vars ModelForm <class 'django.forms.widgets.UserForm'> add True extra_context {'auto_populated_fields': (), 'username_help_text': ''} fieldsets ((None, {'description': "Enter the new user's name and email address and click Save. " 'The user will be emailed a link allowing him/her … -
"My weather site should show images based on weather. How to fix?" [closed]
I'm developing a weather website. How can I make it display images based on the weather data? For example, if it's sunny, I want it to show a sunny weather image. Currently, it doesn't display the images correctly. How can I fix this?" "I attempted to integrate image display based on weather data into my weather website, expecting it to show relevant images such as sunny weather pictures. However, the expected images aren't being displayed as intended. What could be the issue?"