Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can i use from database models with MQTT in Django
Can anybody answer This Question ? I tried This: import django django.setup() But i got this exception: Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib/python3.10/threading.py", line 1009, in _bootstrap_inner self.run() File "/usr/lib/python3.10/threading.py", line 946, in run self._target(*self._args, **self._kwargs) File "/media/me/MAIN/Projects/Fulligence/fulligence-core/venv/lib/python3.10/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/media/me/MAIN/Projects/Fulligence/fulligence-core/venv/lib/python3.10/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "/media/me/MAIN/Projects/Fulligence/fulligence-core/venv/lib/python3.10/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception raise _exception[1] File "/media/me/MAIN/Projects/Fulligence/fulligence-core/venv/lib/python3.10/site-packages/django/core/management/__init__.py", line 398, in execute autoreload.check_errors(django.setup)() File "/media/me/MAIN/Projects/Fulligence/fulligence-core/venv/lib/python3.10/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/media/me/MAIN/Projects/Fulligence/fulligence-core/venv/lib/python3.10/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/media/me/MAIN/Projects/Fulligence/fulligence-core/venv/lib/python3.10/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/media/me/MAIN/Projects/Fulligence/fulligence-core/venv/lib/python3.10/site-packages/django/apps/config.py", line 228, in create import_module(entry) File "/usr/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "/media/me/MAIN/Projects/Fulligence/fulligence-core/billing/__init__.py", line 1, in <module> from .utils import client File "/media/me/MAIN/Projects/Fulligence/fulligence-core/billing/utils/__init__.py", line 1, in <module> from .mqtt import client File "/media/me/MAIN/Projects/Fulligence/fulligence-core/billing/utils/mqtt.py", line 2, in <module> django.setup() File "/media/me/MAIN/Projects/Fulligence/fulligence-core/venv/lib/python3.10/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/media/me/MAIN/Projects/Fulligence/fulligence-core/venv/lib/python3.10/site-packages/django/apps/registry.py", line 83, in populate … -
Soap implementation in Python:all parameter
We want to rewrite this request in Python: $client = new nusoap_client('https://appketaba.com/Webservice/index.php?wsdl', 'wsdl', $proxyhost, $proxyport, $proxyusername, $proxypassword); In php, the nusoap-client class accepts various variables, including these four parameters that we want to send look at this: class nusoap_client extends nusoap_base { var $username = ''; // Username for HTTP authentication var $password = ''; // Password for HTTP authentication var $authtype = ''; // Type of HTTP authentication var $certRequest = array(); // Certificate for HTTP SSL authentication var $requestHeaders = false; // SOAP headers in request (text) var $responseHeaders = ''; var $responseHeader = null; // SOAP Header from response (parsed) var $document = ''; var $endpoint; var $forceEndpoint = ''; // overrides WSDL endpoint var $proxyhost = ''; var $proxyport = ''; var $proxyusername = ''; var $proxypassword = ''; var $portName = ''; // port name to use in WSDL here's the problem: We have only 6 parameters in Python libraries like zeep class Client: _default_transport = Transport def __init__( self, wsdl, wsse=None, transport=None, service_name=None, port_name=None, plugins=None, settings=None, ): How to send these parameters :proxyhost, proxyport, proxyusername,proxypassword -
Are Django user registration form fields limited to 'username', 'password1', 'password2', 'email', 'first_name', and 'last_name'?
I started a tutorial (seems like ages ago now) in which I built a user registration form with just 'username', 'email', password1', and 'password2' fields. Then a profile form was created on a separate page -- but I didn't like the way CreateProfile page/form looked. So I wanted to be able to put the fields in the CreateProfile form into the user registration form. I still have not found an answer about how to do that. -
Django vs PyCharm, which one is better? [closed]
I'm learning Python for a while using PyCharm anh it's quite pleasant. But I found that PyCharm is not recommended so much. I want to know which one (Django vs PyCharm) is better (like for learning, creating my own project and furthermore for work...) Thank you so much! PS: I used to learn JAVA so I understand fundamental programming, OOP and data structures... -
Guild ID Exception
With the django-allauth module, I am wanting to throw an exception if the user is not in a particular guild. What I am hoping to do is pass in a ACCOUNT_GUILD_REQUIRED = True, or within the provider settings the option for GuilDID. I can then catch that in user.model.manager to check if they are in the guild or not. -
django.db.utils.DatabaseError when added objects = models.DjongoManager() to Djongo mongodb model
I am getting django.db.utils.DatabaseError when trying to migrate my migrations. The only think I remember changing to my models is adding objects = models.DjongoManager() to my StockInfo model. I don't know if that causes a new migration but I am getting a very long error: cchilders@cchilders-HP-ProBook-450-G3 ~/projects/stocks_backend (save_stocks_info_to_db)$ python3 manage.py makemigrations Migrations for 'dividends_info': dividends_info/migrations/0003_auto_20220814_1800.py - Alter field id on stockinfo Migrations for 'users': users/migrations/0002_auto_20220814_1800.py - Alter field id on userprofile cchilders@cchilders-HP-ProBook-450-G3 ~/projects/stocks_backend (save_stocks_info_to_db)$ python3 manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, dividends_info, sessions, users Running migrations: Not implemented alter command for SQL ALTER TABLE "dividends_info_stockinfo" ALTER COLUMN "id" TYPE int Applying dividends_info.0003_auto_20220814_1800...Traceback (most recent call last): File "/home/cchilders/.local/lib/python3.10/site-packages/djongo/cursor.py", line 51, in execute self.result = Query( File "/home/cchilders/.local/lib/python3.10/site-packages/djongo/sql2mongo/query.py", line 784, in __init__ self._query = self.parse() File "/home/cchilders/.local/lib/python3.10/site-packages/djongo/sql2mongo/query.py", line 876, in parse raise e File "/home/cchilders/.local/lib/python3.10/site-packages/djongo/sql2mongo/query.py", line 857, in parse return handler(self, statement) File "/home/cchilders/.local/lib/python3.10/site-packages/djongo/sql2mongo/query.py", line 889, in _alter query = AlterQuery(self.db, self.connection_properties, sm, self._params) File "/home/cchilders/.local/lib/python3.10/site-packages/djongo/sql2mongo/query.py", line 425, in __init__ super().__init__(*args) File "/home/cchilders/.local/lib/python3.10/site-packages/djongo/sql2mongo/query.py", line 84, in __init__ super().__init__(*args) File "/home/cchilders/.local/lib/python3.10/site-packages/djongo/sql2mongo/query.py", line 62, in __init__ self.parse() File "/home/cchilders/.local/lib/python3.10/site-packages/djongo/sql2mongo/query.py", line 441, in parse self._alter(statement) File "/home/cchilders/.local/lib/python3.10/site-packages/djongo/sql2mongo/query.py", line 500, in _alter raise SQLDecodeError(f'Unknown token: {tok}') djongo.exceptions.SQLDecodeError: Keyword: Unknown token: … -
How do I add a csrf token to a json fetch in js?
Every time I try to run the code, I get an error that a CSRF token is missing. I have tried adding the token in the html and then adding an event listener for the form but that did not work as I still got the error and the console linked it to the line where I fetched a url. Attempt: (the {{ form }} is a django form which contains a textarea) <div id="add-form"> <form action="" id="form-add"> {% csrf_token %} <h2>New Post</h2> {{ form }} <input type="submit" value="Post" /> </form> </div> // Javascript document.querySelector('#form-add').onsubmit = submit // submit is the function with the fetch command So instead I used babel to add the form into the html (this was not to fix the problem). I have tried to manually add a CSRF token to the react form but I still got the same error: Forbidden (CSRF token missing.): /post. I also tried to add it using a JQuery function I found here (django documentation) but it did not work probably because every time I added the CSRF token in the form I still got the error. So how do I add a csrf token to a fetch command in … -
Organize django apps inside
When creating the apps you do the following: python manage.py startapp app1, but this automatically creates the app inside the root folder of the project. /project1/ /app1/ /app2/ ... __init__.py manage.py settings.py urls.py how to create and save in a folder already created all the apps that are created in Django? for example: in this case I have a folder called "apps" inside it I will have all the apps that are created during the development time: /project/ apps/ app1/ app2/ ... __init__.py manage.py settings.py urls.py Anyone who can provide information would be appreciated in advance. -
How i can reformat this code to follow DRY principle
my views.py from rest_framework import generics from rest_framework.pagination import LimitOffsetPagination from rest_framework.filters import SearchFilter, OrderingFilter from django_filters.rest_framework import DjangoFilterBackend from rest_framework.permissions import IsAdminUser from .serializers import * from .permissions import IsAdminOrReadOnly from .filters import * class ProductsAPIList(generics.ListCreateAPIView): queryset = Products.objects.all() serializer_class = ProductsSerializer pagination_class = LimitOffsetPagination permission_classes = (IsAdminOrReadOnly,) filter_backends = (DjangoFilterBackend, SearchFilter, OrderingFilter) search_fields = ('title', 'category__name') filter_fields = ('category',) ordering_fields = ('price',) filterset_class = ProductsFilter class ProductsAPIUpdate(generics.RetrieveUpdateAPIView): queryset = Products.objects.all() serializer_class = ProductsSerializer permission_classes = (IsAdminOrReadOnly, ) class ProductsAPIRemove(generics.RetrieveDestroyAPIView): queryset = Products.objects.all() serializer_class = ProductsSerializer permission_classes = (IsAdminOrReadOnly, ) class StorageAPIList(generics.ListCreateAPIView): queryset = ProductsStorage.objects.all() serializer_class = ProductsStorageSerializer permission_classes = (IsAdminUser,) class StorageAPIUpdate(generics.RetrieveUpdateAPIView): queryset = ProductsStorage.objects.all() serializer_class = ProductsStorageSerializer permission_classes = (IsAdminUser,) class StorageAPIRemove(generics.RetrieveDestroyAPIView): queryset = ProductsStorage.objects.all() serializer_class = ProductsStorageSerializer permission_classes = (IsAdminUser,) class ProductSignAPIList(generics.ListCreateAPIView): queryset = ProductSign.objects.all() serializer_class = ProductSignSerializer permission_classes = (IsAdminUser,) class ProductSignAPIUpdate(generics.RetrieveUpdateAPIView): queryset = ProductSign serializer_class = ProductSignSerializer permission_classes = (IsAdminUser,) class ProductSignAPIRemove(generics.RetrieveDestroyAPIView): queryset = ProductsStorage.objects.all() serializer_class = ProductSignSerializer permission_classes = (IsAdminUser,) my urls.py from django.conf.urls.static import static from django.contrib import admin from django.urls import path, include from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView, TokenVerifyView from InternetShop import settings from InternetShopApp.views import * urlpatterns = [ path('admin/', admin.site.urls), path('api/v1/products/', ProductsAPIList.as_view()), path('api/v1/products/<int:pk>/', ProductsAPIUpdate.as_view()), path('api/v1/productsremove/<int:pk>/', ProductsAPIRemove.as_view()), path('api/v1/storage/', StorageAPIList.as_view()), path('api/v1/storage/<int:pk>/', … -
Wagtail / Django- images don't display in wagtail admin when published on a production server
I'm using Docker, PostgreSQL, Gunicorn and nginx. I've searched for the answer everywhere. All works fine on the development server. When I publish to the production server the images do not display in wagtail admin. Dockerfile.prod ########### # BUILDER # ########### # pull official base image FROM python:3.8.3-alpine as builder # set work directory WORKDIR /usr/src/wa-cms # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install Wagtail, Django and psycopg2 dependencies RUN apk update \ && apk add \ postgresql-dev \ gcc \ python3-dev \ musl-dev \ build-base \ jpeg-dev \ zlib-dev \ libwebp-dev \ openjpeg-dev # lint RUN pip install --upgrade pip --no-cache-dir RUN pip install flake8 COPY . . # install dependencies COPY ./requirements.txt . RUN pip wheel --no-cache-dir --no-deps --wheel-dir /usr/src/wa-cms/wheels -r requirements.txt ###################### # FINAL - PRODUCTION # ###################### # pull official base image FROM python:3.8.3-alpine # create directory for the app user RUN mkdir -p /home/app # create the app user RUN addgroup -S app && adduser -S app -G app # create the appropriate directories ENV HOME=/home/app ENV APP_HOME=/home/app/web RUN mkdir $APP_HOME RUN mkdir $APP_HOME/static RUN mkdir $APP_HOME/media WORKDIR $APP_HOME # install dependencies RUN apk update && apk add libpq \ postgresql-dev … -
How to show local time to the user in django?
I'm developing a Django app I have a model in which timestamps is added automatically. I want to show the time to the end users according to their local timezone. Here is my code: settings.py TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True model.py date_created = models.DateTimeField(auto_now_add=True, null=True) template {{object.date_created}} But it is showing UTC time I want this to detect user's current timezone and render date&time accordingly. -
Whole Javascript Not Working if 1 Array has Length of 0
Hi I am creating a bar chart, and having an issue with the JS in the chart. The JS is supposed to find the % of the total that each rating represents. For instance, A1 = 100 and total equals 1000, so a1 width should be 10%. The JS code works perfectly, except for when the array has no values in it, for instance when A2 has a length of 0. When this happens, it also makes all the values after it not work, even if they have arrays greater than a length of 0. I was wondering if anyone had an idea of what was going wrong thanks. <div class="statistics"> <h6>Rating Distribution</h6> <div class="bar-graph bar-graph-horizontal bar-graph-one"> <div class="bar-one"> <span class="rating">A1</span> <div class="bar" id="a1-rating" data-percentage=""></div> </div> <div class="bar-two"> <span class="rating">A2</span> <div class="bar" id="a2-rating" data-percentage=""></div> </div> <div class="bar-three"> <span class="rating">A3</span> <div class="bar" id="a3-rating" data-percentage=""></div> </div> <div class="bar-four"> <span class="rating">B1</span> <div class="bar" id="b1-rating" data-percentage=""></div> </div> </div> </div> <div class="hidden-rating-distribution-data"> {% for loans in a1_companies %} <div class="security-value-a1" hidden>{{loans.market_value}}</div> {% endfor %} {% for loans in a2_companies %} <div class="security-value-a2" hidden>{{loans.market_value}}</div> {% endfor %} {% for loans in a3_companies %} <div class="security-value-a3" hidden>{{loans.market_value}}</div> {% endfor %} {% for loans in b1_companies %} <div … -
How to keep the button clicked in javascript even after refreshing the page?
I am trying to build a single page app but like twitter for cs50 web project using Django I am using fetch API to get the all the posts on the site and use javascript to plug them in like this : document.querySelector('#all-posts-view').innerHTML = ''; fetch(`all_posts`,{ headers: new Headers({ 'secure': 'secure'}) }) .then(response => response.json()) .then(posts => { console.log(posts) posts.forEach(function(post) { let div = document.createElement("div"); div.setAttribute('id', 'post'); console.log(post.author) div.innerHTML = ` <a href='profile/${post.author}' id='profile-page' data-profile=${post.author_id} data-name=${post.author} > <P>${post.timestamp}</p> <h1 class="capitalize">${post.author}</h1></a> <h3>${post.post}</h3> <p>${post.likes}</p> <button onclick='style.color = "blue"'>Likes</button> {%if ${post.author} == 'zero'%} zzz{%endif%}` document.querySelector("#all-posts-view").append(div); }) }) and each div has a button to like the post , but when the user click on the button and the likes go up by one I do not know how can I show to that user that the like button was clicked because if the page is refreshed the function will just show normal posts and the user will not be able to tell if he actually liked the post or not When the button is clicked : After refreshing: After refreshing: So how can I keep the button clicked to that user ? do I need a global variable to represent the user? or … -
How can I prevent everyone from seeing admin user messages in django?
I'm attempting to set up a commenting system. The issue I have is that all users may see the admin messages. i thought i views from .models import Support, Comment from .forms import SupportForm, CommentForm @login_required def support_details(request, id): support = Support.objects.get(id=id) recent_support = Support.objects.all().order_by('-created_at') comments = Comment.objects.all() if request.method == 'POST': comment_form = CommentForm(request.POST) if comment_form.is_valid(): comment = comment_form.save(commit=False) comment.user = request.user comment.save() comment_form = CommentForm() messages.success(request, 'comment posted successfully') else: comment_form = CommentForm() context = { 'support': support, 'recent_support': recent_support, 'comments': comments, 'comment_form': comment_form } return render(request, 'support-detail.html', context) models from users.models import User from django.db import models class Support(models.Model): SERVICE_CHOICES = ( ("Crypto", "Crypto"), ("Transaction", "Transaction"), ("Others", "Others"), ) support_id = models.CharField(max_length=10, null=True, blank=True) user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) subject = models.CharField(max_length=30, null=True, blank=True) email = models.EmailField(null=True) related_service = models.CharField( max_length=100, choices=SERVICE_CHOICES, null=True) message = models.TextField(max_length=1000, null=True) is_close = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now=True, null=True) def __str__(self): return self.subject class Comment(models.Model): comment = models.TextField(max_length=1000, null=True) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user', null=True) support = models.ForeignKey(User, on_delete=models.CASCADE, related_name = 'comment', null=True, blank=True) created_at = models.DateTimeField(auto_now=True, null=True) def __str__(self): return self.comment template {% extends 'base2.html' %} {% load static %} {% load crispy_forms_tags %} {% load widget_tweaks %} {% block … -
I keep getting : Reverse for 'delete_entry' with arguments '('',)' not found. 1 pattern(s) tried: ['deleteentry/(?P<input_id>[^/]+)/\\Z']
I am a begginer and tried to look up solutions from other threads to no avail, Here is my views.py : @login_required(login_url='/login') def delete_entry(request, input_id): input=Diary.objects.get(pk=input_id) input.delete() return redirect('home') Here is my urls.py : urlpatterns = [ path('', views.welcome, name='welcome'), path('home', views.home, name='home'), path('MyEntries/', views.MyEntries, name='entries'), path('deleteentry/<input_id>/', views.delete_entry, name='delete_entry'), ] Here is my html code : <p>Hello, {{user.username}} !</p> {% for article in articles %} <p> {{ article.title}}<br> {{ article.description }} <br> {{ article.date }} <div class="card-footer text-muted"> </p> <a href="{% url 'delete_entry' input.id %}" class="delete">Delete</a> </div> {% endfor %} {% endblock %} -
Django Rest Framework, creating a one-to-many field relationship between users and another model
I am trying to create a simple model which holds a number as the primary key (week number) and then a list of users. Thus the model should be something like this, { id: 10, users: [ user1, user2, ... ] } I am pretty sure I should do this with a one-to-many field. Thus I created the following model, class Schema(models.Model): week = models.PositiveIntegerField(primary_key=True, unique=True, validators=[MinValueValidator(1), MaxValueValidator(53)], ) users = models.ForeignKey(MyUser, related_name="users", null=True, blank=True, on_delete=models.SET_NULL) class Meta: ordering = ('week',) What I want to happen is that if you do a POST request with an id and a list of users, then it simply creates the model. However if the id already exists, then it should simply clear the users, and add the newly given users instead. This is where I am stuck, I have tried the following (keeping comments in the code), class SchemaSerializer(serializers.ModelSerializer): # users = serializers.PrimaryKeyRelatedField(many = True, queryset = MyUser.objects.all()) # user_set = UserSerializer(many = True) class Meta: model = Schema fields = ('week', 'users') # def create(self, validated_data): # # users_data = validated_data.pop('users') # schema = Schema.objects.create(**validated_data) # # answer, created = Schema.objects.update_or_create( # # week=validated_data.get('week', 1), # # defaults={'users', validated_data.get('users', [])} # # … -
I can't place text and video in same grid in django with css
I have application which includes 3 videos(eventually it will include more). I have created a model in models.py and passed courses to template with context in my view. I want my title to be in border below the video but it makes some weird pose. I left some space under image for title. html <div class="next"> {% for course in courses %} {{ course.title }} <video src="/media/{{ course.videofile }}" controls=controls type="video" class="video">{{ course.title }}</video> {% endfor %} </div> css .next{ margin-top: 8em; display: grid; grid-template-columns: .1fr .1fr .1fr; gap: 1em; } .video{ max-width: 15em; border: 1px solid black; padding-bottom: 2em; } If I place for loop in another div it works better but titles are above videos. html <div class="next"> {% for course in courses %} <div class="div"> {{ course.title }} <video src="/media/{{ course.videofile }}" controls=controls type="video" class="video">{{ course.title }}</video> </div> {% endfor %} </div> (css is the same) -
CSRF_TOKEN Validation Failed in Django even it is included in form
Hi im new to Django and struggling with Django and csrf_token is getting 403 forbidden error even its included in the form template can some one explains me what's the issue here i have searched for answers but none worked for me when i inspect i can see the csrf token in the form Thanks In advance teplate.html {% extends "encyclopedia/layout.html" %} {% block title %} {{ title }} {% endblock %} {% block body %} <form action="{% url 'newPage'%}" method="post"> {% csrf_token %} {{form}} <br> <input type="submit" value="Save"> </form> {% endblock %} urls.py from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("<str:name>", views.title, name="title"), path("search/", views.search , name="search"), path("NewPage/", views.newpage, name="newPage") ] views.py def newpage(request): if request.method == 'POST': form = request.POST() print(form.is_valid()) if form.is_valid(): title = form.cleaned_data.get('title') content = form.cleaned_data.get('content') util.save_entry(title, f'# {title}\n\n{content}') return HttpResponseRedirect(reverse('encyclopedia:title')) else: form = newEntry() return render(request, "encyclopedia/newentry.html", { "form": form }) else: form = newEntry() return render(request, "encyclopedia/newentry.html", { "form": form }) -
Bootstrap modal dialog not displayed when click button or link in Django template
I am trying to get a button in a django view to display a model dialog to request delete confirmation of a list item. When I click the button I cannot get the modal dialog to display. Any ideas? Dialog (included from Django Template) <div id="confirmModal" class="modal fade" tabindex="-1" role="dialog" caller-id="" aria-labelledby="confirmModal" aria-hidden="true" > <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-body" id="modal-message"> Do you wish to proceed? </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button> <button type="button" class="btn btn-primary" data-dismiss="modal" id="confirmButtonModal">Confirm</button> </div> </div> </div> </div> <script type="text/javascript"> document.addEventListener('DOMContentLoaded', () => { var buttons = document.querySelectorAll("[data-target='#confirmModal']"); for (const button of buttons) { button.addEventListener("click", function(event) { // find the modal and add the caller-id as an attribute var modal = document.getElementById("confirmModal"); modal.setAttribute("caller-id", this.getAttribute("id")); // extract texts from calling element and replace the modals texts with it if ("message" in this.dataset) { document.getElementById("modal-message").innerHTML = this.dataset.message; }; if ("buttontext" in this.dataset) { document.getElementById("confirmButtonModal").innerHTML = this.dataset.buttontext; }; }) } document.getElementById("confirmButtonModal").onclick = () => { // when the Confirm Button in the modal is clicked var button_clicked = event.target var caller_id = button_clicked.closest("#confirmModal").getAttribute("caller-id"); var caller = document.getElementById(caller_id); // open the url that was specified for the caller window.location = caller.getAttribute("href"); }; }); </script> base.html <!DOCTYPE … -
Best framework to build a dev log website?
this is not be a technical question but my research on the internet has not answered my questions, so I would like to ask here. I have a few projects that I am working on that I would like to write about in a dev log fashion. Sort of like progress report. However, I would like for users to leave a like, or comment under a thread that I (and only I) post. However, I do not want to use WordPress, or anything like it, because I would like to build something from scratch. This is because I am interested as to how it all works, and it will be a good resume project. Is Django a good fit for this? Django has a cool admin panel built in that I can use to add content, I believe. What about Next.js? What are some suggestions? Thank you -
Assign database value to Django variable
Looking to do something like this is Django: $price = mysql_query("SELECT price FROM products WHERE product = '$product'"); $result = mysql_fetch_array($price); If $result['price'] == 1: do something My thought was something like below but seems to be way off: Item = Products.objects.get(product=pk) price = item.price status = item.status if price == 2: Do Something please note this is not being used to output to a template, as I already know how to do that. -
Calculate sum of model objects in django serializers
In my app, each user has his wallets in which he can save his daily expenses. How can I get sum of money for each instance of wallet with many expenses saved to it? I've tried serializers.SerializerMethodField() from django.db.models import Sum from django.db.models import Q class WalletInstanceSerializer(serializers.ModelSerializer): owner = serializers.ReadOnlyField(source='owner.id') entry = BudgetEntrySerializer(many=True, read_only=True) expense_sum = serializers.SerializerMethodField() class Meta: model = WalletInstance fields = '__all__' def get_expense_sum(self, obj): return WalletInstance.objects.filter(Q(id=obj.id)|Q(entry__entry_type='income')).aggregate(Sum('entry__amount'))['entry__amount__sum'] And this gives me data in the correct format but the sum is wrong, for example [ { "id": "d458196e-49f1-42db-8bc2-ee1dba438953", "owner": 1, "entry": [ { "id": 3, "owner": 1, "title": "dsfdsf", "amount": 7, "description": "sdfdsf", "entry_type": "income", "date_added": "2022-08-13", "entry_category": { "id": 2, "name": "Transport" } }, { "id": 4, "owner": 1, "title": "fesfvsdfgvbtdg", "amount": 12, "description": "efesf", "entry_type": "income", "date_added": "2022-08-13", "entry_category": { "id": 2, "name": "Transport" } } ], "viewable": [ "admin@gmail.com" ], "expense_sum": 83, "name": "dsdsds", "date_added": "2022-08-13" } ] Expense_sum is 83 but amount fields are 7 and 12 so that's equal to 19 How can i get the correct number? Models class BudgetEntry(models.Model): STATE= [ ('income','income'), ('expenses','expenses'), ] owner = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='owner_of_entry', on_delete=models.CASCADE) title = models.CharField(max_length=20) amount = models.IntegerField() description = models.CharField(max_length=60, null=True) entry_type = … -
Django Custom Login
I want a Loginpage which redirects User based on groups AND their username pk. Like Staff has a dashboard which they can see all the work from employees while employees are redirected to their own page based on their pk I made something with class based views and it works. But Staff are redirected to an empty page where they can click on a dashboard button which redirects them there. This dashboard button shows only if they are in a specific group restricted by a for loop in the template. And when employers try to go manually to that dashboard they see an empty page bc of the for loop for staff member but besides the horrible security I know that it must be somehow possible to do an if condition. But no matter where I look or what I try thats the only result I have. Does anybody has an idea ? template: {% for group in request.user.groups.all %} {% if group.name == 'Personalverwaltung' %} <li><a href="{% url 'Dashboard' %}">dashboard</a></li> {% endif %} {% endfor %} {% for group in request.user.groups.all %} {% if group.name == 'Personalverwaltung' %} html {% endif %} {% endfor %} View: class Einloggen(LoginView): template_name … -
SMTPServerDisconnected even though it was working properly a few days ago
I am using Django and I'm trying to send a verification email (with gmail) when the user registers, this was working fine some days ago, but then it suddenly stopped working. I have already created a new Google Application password and it is still not working. When the site tries to send the email it raises "SMTPServerDisconnected at /register/Connection unexpectedly closed". This are my settings for email. # EMAIL CONFIG DEFAULT_FROM_EMAIL = 'mymail@gmail.com' EMAIL_FROM_USER= 'mymail@gmail.com' EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'mymail@gmail.com' EMAIL_HOST_PASSWORD = 'password' EMAIL_USE_TLS = True EMAIL_PORT = 587 And this is my view: def send_action_email(user,request): current_site = get_current_site(request) email_subject = 'Activa tu cuenta' email_body = render_to_string('users/activate.html',{ 'user':user, 'domain':current_site, 'uid':urlsafe_base64_encode(force_bytes(user.pk)), 'token': generate_token.make_token(user) }) email = EmailMessage(subject=email_subject,body=email_body, from_email=settings.EMAIL_FROM_USER, to=[user.email] ) email.send() def activate_user(request,uidb64,token): try: uid=force_text(urlsafe_base64_decode(uidb64)) user= User.objects.get(pk=uid) except Exception as e: user=None if user and generate_token.check_token(user,token): user.email_is_verified=True user.save() messages.success(request, 'Se ha verificado tu email, ya puedes inciciar sesion!') return redirect('login') return render(request,'appName/activation_failed.html',{"user":user}) Might it be that google is not allowing me to login to the mail? -
Do I need to import class on it's own file?
Ok so, I have created 2 model classes for my Django Rest application and am trying to use foreign key to join both models. Here's my code: from django.db import models from . import Author class Article(models.Model): title = models.CharField(max_length=100) author = models.ForeignKey(Author, on_delete=models.CASCADE) date = models.DateTimeField(auto_now_add=True) class Author(models.Model): name = models.CharField(max_length=100) email = models.EmailField(max_length=100) The thing is, this line from . import Author is kind of annoying, and when I remove it Pylance puts a warning message in the Author parameter at the Article class ("Author" is not defined). My question is, do I really need to import the class in the same file it is being used?