Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there a way to call a django model function from a template inside an javascript function?
I am trying to trigger my note.send function (from a method) whenever I call a javascript function. Here is my Javascript code. function send_mail(){ {{ note.send }} } I then call the function send_mail() whenever an specific action happens on the website, however the django template function is called each time I reload the website even if I don't call the javascript function at all. Please help -
Here, i want to achieve that I want to take my current site's URL (not using forms) and convert those into short urls and display it here
in this picture I have written what i wanted to achieve. I am trying to use hashlib, but i am not able to do the following. This is my views. def SaveURL(request): full_url = request.META['HTTP_HOST'] obj = create_short_url('full_url') url = full_url=full_url, obj=obj url.save() return render(request, 'link.html', {"full_url": obj.full_url, "short_url": request.get_host()+'/'+obj.short_url}) #generating short link def create_short_url(self, request, full_url): temp_url = md5(full_url.encode()).hexdigest()[:8] try: obj = self.objects.create(full_url=full_url, short_url=temp_url) except: obj = self.objects.create(full_url=full_url) return render(request, 'link.html', {"obj": obj}) This is my html template, its just not so clean , plz help. #this is my original url {{ request.scheme }}://{{ request.META.HTTP_HOST }}{{ request.path }} #IT DISPLAYS - http://127.0.0.1:8000/product/product_view/10001 But i have not achieved the soln. -
Error 400 when adding Google Analytics Script
I put a Google Analytics tag in the header of my website: <!-- Global site tag (gtag.js) - Google Analytics --> <script async src="https://www.googletagmanager.com/gtag/js?id=G-V51YR2QF7N"></script> <script> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'G-V51YR2QF7N'); </script> But even after reloading the website in my pythonanywhere integrated development environment, still no statistics appear. I ran this code locally and here are the errors: (dja_env) C:\Users\antoi\Documents\Programming\Projects\django3-personal-portfolio>python manage.py runserver Looks like no local file. You must be on production Looks like no local file. You must be on production Performing system checks... System check identified some issues: WARNINGS: blog.Blog: (models.W042) Auto-created primary key used when not defining a primary key type, by default 'django.db.models.AutoField'. HINT: Configure the DEFAULT_AUTO_FIELD setting or the BlogConfig.default_auto_field attribute to point to a subclass of AutoField, e.g. 'django.db.models.BigAutoField'. portfolio.Project: (models.W042) Auto-created primary key used when not defining a primary key type, by default 'django.db.models.AutoField'. HINT: Configure the DEFAULT_AUTO_FIELD setting or the PortfolioConfig.default_auto_field attribute to point to a subclass of AutoField, e.g. 'django.db.models.BigAutoField'. System check identified 2 issues (0 silenced). May 30, 2021 - 21:20:44 Django version 3.2.3, using settings 'personal_portfolio.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. [30/May/2021 21:22:47] "GET / HTTP/1.1" 400 143 … -
Set different logout time for different users in django?
Can anyone know how to set session timeout per user in Django? I'm building a system where I need to set a user timeout session, if a user is failed to perform any action till a timeout setting then he will be logout of the system. Is this possible in Django? -
Django Rest Framework Create New Data If Not Exist
I have been created a new user to user messaging app on Django. I want to if there is no User1i and User2ii created ever create new one and if it exist return the ID of this conversation. views.py class ConversatViewSet(viewsets.ModelViewSet): serializer_class = ConversatSerializer authentication_classes = (JSONWebTokenAuthentication,) permission_classes = (IsAuthenticated,) def get_queryset(self): queryset = Conversation.objects.all() return queryset models.py class Conversation(models.Model): User1i = models.ForeignKey(User, related_name='u1', on_delete=models.CASCADE) User2ii = models.ForeignKey(User, related_name='u2', on_delete=models.CASCADE) class Meta: unique_together = ('User1i', 'User2ii') JSON output [ { "id": 1, "User1i": 1, "User2ii": 2 }, { "id": 2, "User1i": 3, "User2ii": 1 }, { "id": 3, "User1i": 3, "User2ii": 2 } ] For example if "POST" to '1' as "User1i" and '2' as "User2ii" return the ID of conversation ("id": 1,) and if "POST" TO '4' as "User2i" and '2' as "User2ii" create a new conversation and return it's ID. -
supervisord/celery/python - "dynamic" environment variables - "global" versus "local" - DRY
Let's imagine I have the following /etc/supervisord.conf main file: [unix_http_server] file = /tmp/supervisor.sock [supervisord] <snip> environment = STATIC_VAR="foo", DYNAMIC_VAR="bar_%%s" [include] files = /etc/supervisord.d/worker1.conf /etc/supervisord.d/worker2.conf The worker1 and 2 files: [program:worker1] environment = WORKER_1_VAR_1"toto", WORKER_1_VAR_2="toto_too" [program:worker2] environment = WORKER_2_VAR_1"toto", WORKER_2_VAR_2="toto_too" (skipping the other file contents as they are not relevant) My supervisor version is 3.4.0 on Centos 7.9. This runs within a virtualenv on the back on Python 3.9.0 MAIN GOAL: Somewhere in the code run by one of the workers, something like this will occur (the "%%s" turned into "%s" will be replaced by a dynamic value): from django.conf import settings final_value = settings.DYNAMIC_VAR % ('replacement_string_of_some_kind') What happens is the above always results in an error upon supervisor startup: Error: Format string <snip> for 'supervisord.environment' is badly formatted: not enough arguments for format string HOWEVER, if I remove the supervisord.environment section from the main configuration file, and copy its contents to the individual worker files, startup occurs normally. For example: [program:worker1] environment = STATIC_VAR="foo", DYNAMIC_VAR="bar_%%s", WORKER_1_VAR_1"toto", WORKER_1_VAR_2="toto_too" Am I doing something wrong? Is there some kind of "double parsing" happening upon startup? Can this even be made to work. Asking because my list of "global env variables" is quite long, … -
Render dynamic value inside content django template
Please, I would like to render a varible in django template, kind of {{ user.name }} inside of a textfield from database, that I filled up on the django admin. like this how can I manage to achieve it please, thank you all, have a good day. -
Django Simple POST Class View Not Working
I am experimenting with Django class based views and for some reason this simple post view does not seem to be working. When looking at my terminal it gets stuck on the GET method / validation of the csrf token. It is either not being validated or not saving to the database and therefore not being redirected to the thank-you page. I am not sure how to solve this issue. It definitely is not being saved to the DB, but as far as I am aware everything is correct here. I also am using a class based form which is why I am simply just calling form.save() The code is as follows: class ReviewView(View): def get(self, request): form = ReviewForm() return render(request, 'reviews/review.html', { 'form': form }) def post(self, request): form = ReviewForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect('/thank-you') return render(request, 'reviews/review.html', { 'form': form }) Any help or ideas is greatly appreciated! -
Django Admin Custom User password not getting hashed+salted
I've created a custom user to use email instead of the username. This is the code that works models.py # Overriding the default users model from django.contrib.auth.base_user import BaseUserManager from django.utils.translation import ugettext_lazy as _ from django.db import models from django.contrib.auth.models import AbstractUser class CustomUserManager(BaseUserManager): """ Custom user model manager where email is the unique identifiers for authentication instead of usernames. """ def create_user(self, email, password, **extra_fields): """ Create and save a User with the given email and password. """ if not email: raise ValueError(_('The Email must be set')) email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() return user def create_superuser(self, email, password, **extra_fields): """ Create and save a SuperUser with the given email and password. """ extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) if extra_fields.get('is_staff') is not True: raise ValueError(_('Superuser must have is_staff=True.')) if extra_fields.get('is_superuser') is not True: raise ValueError(_('Superuser must have is_superuser=True.')) return self.create_user(email, password, **extra_fields) class CustomUser(AbstractUser): username = None email = models.EmailField(_('email address'), unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() def __str__(self): return self.email and registered it to the admin modal for a more flexible list. (admin.py) from django.contrib import admin from .models import CustomUser @admin.register(CustomUser) class CustomUserADM(admin.ModelAdmin): list_display = ("email", "is_staff", "is_active") … -
how to deal with __init__ in serializers.ModelSerializer?
I need to create a dynamic serializer and inside it I need to get the method (GET/PUT/..) and the pk value if the url look like this url/1/ or url/2/ where 1 and 2 are pks. class DynamicSerializer(QueryFieldsMixin, serializers.ModelSerializer): def __init__(self, * args, **kwargs): super(DynamicSerializer, self).__init__(*args, **kwargs) modelname = self.Meta.model.__name__.lower() method = '' is_owner = False pk = None user = self.user class Myser(DynamicSerializer): class Meta: model = models.Model fields = '__all__' Myser(Mode).data I think there is somthing like slef.list, self.delete, self.create in the views where it looks like this class ItemView(mixins.ListModelMixin, mixins.CreateModelMixin, generics.GenericAPIView): MyModel = None def get_object(self, pk,): try: return self.MyModel.objects.get(id=pk) except self.MyModel.DoesNotExist: raise status.HTTP_404_NOT_FOUND def get(self, request, pk, format=None): item = self.get_object(pk) serializer = self.serializer_class(item, many=False) return slef.item(request) #<= this -
Send message using Django Channels from outside Consumer class from new Process
I am building an REST Api in Django for training and predict some data. I have a websocket connection with the purpose of having bidirectional communication. For non-blocking server when someone wants to train a new model I decide to use a new Process from multiprocessing. All work good but i can't send back a message when training is over from that Process. This is my consumer.py class import json from asgiref.sync import sync_to_async from channels.generic.websocket import AsyncJsonWebsocketConsumer, AsyncWebsocketConsumer import time import asyncio from multiprocessing import Process from .train import train from threading import Thread from channels.layers import get_channel_layer class Consumer(AsyncJsonWebsocketConsumer): async def connect(self): await self.channel_layer.group_add("gossip", self.channel_name) await self.accept() async def disconnect(self, close_code): pass # Receive message from WebSocket async def receive(self, text_data): print(text_data) await self.send(text_data=json.dumps({ 'message': text_data })) data = "Works good" p = Process(target=train, args=(data,)) p.start() # Receive message from room group async def chat_message(self, event): message = event['message'] # Send message to WebSocket await self.send(text_data=json.dumps({ 'message': message })) async def sendMessageTrain(self): await self.send(text_data=json.dumps({ 'message': "Model success trained" })) async def notify(self, event): print("In notify method: Notify") print(event["content"]) await self.send(text_data=json.dumps({ 'message': event["content"] })) Channles layer settings: CHANNEL_LAYERS = { "default": { "BACKEND": "channels.layers.InMemoryChannelLayer" # "BACKEND": "channels_redis.core.RedisChannelLayer", # "CONFIG": … -
How to solve unsupported locale setting in pandas
Error at ... unsupported locale setting cats = ['Понедельник', 'Вторник', 'Среда', 'Четверг', 'Пятница', 'Суббота', 'Воскресенье'] cat_type = CategoricalDtype(categories=cats, ordered=True) locale.setlocale(locale.LC_ALL, 'rus_rus' if sys.platform == 'win32' else 'ru_RU.UTF-8') df['w_date_to'] = df['w_date_to'].dt.day_name(locale='Russian').astype(cat_type) My Ubuntu server local settings: *locale -a* C C.UTF-8 POSIX ... en_US.utf8 ... ru_RU.utf8 ru_UA.utf8 *locale* LANG=en_US.UTF-8 LANGUAGE=en_US:en ... LC_ALL=C Thanks in advance. -
How to manage Postgres Enum type in Django?
I had used django-mysql to manage MySQL enum type from Django. Recently I am using the Postgres database for my Django project. To manage the Postgres Enum, I could not able to find any library. There is a db_type() method in Django to manage custom type. But the problem is Postgres enum must be created first at database and after that, I can use it. Here is a code sample for Postgres enum. CREATE TYPE mood AS ENUM ('sad', 'ok', 'happy'); CREATE TABLE person ( name text, current_mood mood ); Is there present a library at all? If not, how could I be able to achieve the Postgres enum management from Django? -
I want to create work schedule for employees for crm system in django REST
**I could not find any helpful resource or any libs related to this.I have tried this library :https://github.com/rodrigoamaral/django-fullcalendar but it didnt help me ** -
What do I return if I override dispatch() method in Django?
So I am trying to write controller logic for my page search field. It suppose to search posts by title and display them. I am trying to implement a verification that the search field isn't empty and while at it I am also trying to let user know if there weren't posts to display. I am trying to do so via HttpResponses. The problem is I can't place'em in get_queryset method because it's supposed to return querysets not http responses, so I placed them in "view" part of CBV i.e. dispatch method and it works fine. But now I don't understand what to do to display the result when there's actually some posts found. I get Exception Value: The view blog.views.Search didn't return an HttpResponse object. It returned None instead. So what do I do to display posts when there are actually some to display? Thanks beforehand! My search field: <div class="email" align="right" style="margin: 100px 0 0 150px"> <h2 class="sidebar-title" align="center">Search Post</h2> <form action="{% url 'search' %}" method="get"> <input type="text" name="s" placeholder="Search Post"> <input type="submit" value="look up"> </form> </div> My view: class Search(ListView): """Searching Posts""" template_name = 'blog/posts_by_search.html' context_object_name = 'posts_found' paginate_by = 2 def dispatch(self, request, *args, **kwargs): """HttpResponse … -
Authentication fails during login testing
I am trying to test custom login (with pytest) but authentication fails returning None. Here is views.py from rest_framework.authtoken.views import ObtainAuthToken from my_auth.api.serializers import UserLoginSerializer class LoginAuthToken(ObtainAuthToken): serializer_class = UserLoginSerializer serializers.py from django.contrib.auth import authenticate from django.utils.translation import gettext_lazy as _ from rest_framework import serializers from rest_framework.authtoken.serializers import AuthTokenSerializer class UserLoginSerializer(AuthTokenSerializer): username = None email = serializers.EmailField( label=_("Email"), ) def validate(self, attrs): email = attrs.get('email') password = attrs.get('password') if email and password: user = authenticate(request=self.context.get('request'), email=email, password=password) # returns None if not user: msg = _('Unable to log in with provided credentials.') raise serializers.ValidationError(msg, code='authorization') # raises else: msg = _('Must include "email" and "password".') raise serializers.ValidationError(msg, code='authorization') attrs['user'] = user return attrs tests.py import pytest from django.urls import reverse from rest_framework import status from rest_framework.authtoken.models import Token from rest_framework.test import APIClient @pytest.fixture def test_user(): user = MyUser.objects.create( email='test@m.com', first_name='Firstname', last_name='Lastname' ) user.set_password('pass5678') return user @pytest.mark.django_db def test_login(test_user): client = APIClient() response = client.post( path=reverse('login'), data={ 'email': 'test@m.com', 'password': 'pass5678', }, format='json', ) assert(response.status_code == status.HTTP_200_OK) token = Token.objects.get(user=test_user) assert(token.key == response.data['token']) Terminal output: ========================================================================================================== test session starts ========================================================================================================== platform linux -- Python 3.8.5, pytest-6.2.4, py-1.10.0, pluggy-0.13.1 django: settings: news_project.settings (from ini) rootdir: /home/andrei/NEWS/news_project, configfile: pytest.ini plugins: lambda-1.2.4, Faker-8.4.0, common-subject-1.0.5, … -
Why is the Post model that I create in the admin panel not showing in the admin panel?
I do not understand why when I create a Post model in the admin panel, it is not displayed on my server in the admin panel enter image description here here is the code admin.py `from django.contrib import admin from .models import Post admin. site.register(Post)`, here is the code models.py `from django.db import models class Post(models.Model): title = models.CharField(max_length=200) author = models.ForeignKey( 'auth.User', on_delete=models.CASCADE, ) body = models.TextField() def __str__(self): return self.title` I will be glad to any of your advice and help -
TypeError at /ap1/checkbooks/ 'type' object is not iterable; return [auth() for auth in self.authentication_classes] TypeError: 'type' object is
I am getting django Error while using rest django concept. How to solve the below error of django i can't able to open the webpage in my browser. please let me know how to solve the issue.All the codes are below. Any help appreicatable . TIA Settings.py """ Django settings for pro1 project. Generated by 'django-admin startproject' using Django 3.2.3. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-_=f2k%yr6l&3sbcz#dpt5ec8t+7aw_i^2p*$$z0kt0iq!u0iag' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'ap1', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'pro1.urls' ''' REST_FRAMEWORK={ 'DEFAULT_PERMISSION_CLASSES':( 'rest_framework.permissions.IsAuthenticated', # for restriction ) }''' # for restriction access REST_FRAMEWORK={ 'DEFAULT_PERMISSION_CLASSES':( 'rest_framework.permissions.AllowAny', ), } TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['templates'], 'APP_DIRS': True, 'OPTIONS': { … -
Django Form to Model Before Save
I have a Django model called Family, and a Django form called FamilyForm. I save the form in a view as follows: if request.method == 'POST': form = FamilyForm(request.POST) if form.is_valid: form.save() messages.success(request, 'Successfully added the family') else: messages.error( request, 'There was a problem with adding the family') However, my problem is that I would first like to convert this form to a Family object before saving it as I would like to assign some missing properties. Any idea how to convert the form to a Model object so that I can make the changes before saving? -
Getting SMTPServerDisconnected Error when trying to send email in django
I am trying to send an email with gmail in Django but I am getting SMTPServerDisconnected error. I have tried everything from enabling lesssecuredapps to DisplayUnlockCaptcha but still getting the same error. Any help would be greatly appreciated! Here is the setting.py for email config Here is the send_mail in my views.py The error I've been getting -
The best way to extract a large zip file in the background regardless of the template changing (or other external issues occurring) in Django?
I want to upload a zip file that contains 1 GB or more image data. I have a function that renders a basic Django template that uploads the zip file in the server and then later extracts it using the zipfile module and stores these images. My only worry is that when the user suddenly moves around the site or a network error (or some other external issue) occurs, the function gets interrupted and the extraction, as well as the database storage progress, stops. In short, duplication occurs. If I try to re-run the function again, the 'already stored' images get stored again and later saved to the model. I am not sure how to proceed with the file extraction and storage once the python function gets interrupted. What should I do? This my code so far: def upload(path, id): try: with zipfile.ZipFile(path, mode='r', allowZip64=True) as file: document = Mymodel.objects.get(id=id) directory_to_extract = f"media/{document.path}" file.extractall(directory_to_extract) except zipfile.LargeZipFile: print("File size is too large.") return 0 #returns an error finally: file.close() os.remove(path) Note: The parameter 'path' is the temporary file path moved to the stored path in the directory. The parameter 'id' is the zip file id that gets stored in the model … -
Authentication & Authorization based on JWT Token in Django rest
I am just a newbie with Django, python. I try to build 1 simple API Collection include CRUD basic, and authentication, authorization. I have 1 simple Views like: @api_view(['GET']) @permission_classes([IsUser]) def get_test(request : Request): return JsonResponse({"message": "success"}, status = status.HTTP_200_OK) and IsUser is: class IsUser(IsAuthenticated): def has_permission(self, request : Request, view): token = request.query_params.get('token') if token: role = jwt.decode(token.split(" ").__getitem__(1), key="secret_key",algorithms="HS256").get('role') if role == 'User': return True else: return False return False My purpose wants to parse the JWT token and authorization based on that. I wonder don't know if my way is really correct? Can anyone give me some comments as well as documentation to better understand this issue? I don't use any other lib because I want to code by myself at first to understand the flow. Thanks for helping me. -
How to add Bar chart for my values in database using django
I have 4 columns in my database(userid,month,value1,value2).I need to add a bar graph to compare two values(value1 and value2) for the same month and retrieve it in a bar chart like shown below models.py from django.db import models from django.contrib.auth.models import User class graphinput(models.Model): user=models.ForeignKey(User,on_delete=models.CASCADE) Month = models.CharField(max_length=30) Value1 = models.IntegerField() Value2 = models.IntegerField() I need my graph to look like this like comparing two values(value1 and value2) for a same month.. -
Django translation resolution order
I have my base code strings written in Spanish. I want to use another lang as base lang, and sets it in LANGUAGE_CODE, for example, 'de'. I have de.po in locale. I set 'es' as user lang. I have es.po in locale with all empty msgstr values. translation.activate('es') In this case, Django loads the LANGUAGE_CODE value 'de' as default, and loads the 'de' msgstr values as user lang, not the base code strings. The django docs says: When an English variant is activated and English strings are missing, the fallback language will not be the LANGUAGE_CODE of the project, but the original strings. For example, an English user visiting a site with LANGUAGE_CODE set to Spanish and original strings written in Russian will see Russian text rather than Spanish. Maybe a bug? -
Django AJAX : submitting form to different url
Consider having a page url of (localhost:8000/tests). my form in the page submit the form data to url (localhost:8000/add/model) what I'm trying to do is to get the response and render the form template with success or fail message in same page (localhost:8000/tests). the submitting working fine but rendering the form back to the page (localhost:8000/tests) the response render to separate page on url (localhost:8000/add/model) and render form template only views.py: @login_required(login_url="/login/") def add_user(request): done = [] fail = [] context = {} crud = CRUDHandler() form = UserForm(request.POST or None) context['user_form'] = form if 'save' in request.POST: if form.is_valid(): new_user = crud.c_user( username = form.cleaned_data.get('username'), first_name = form.cleaned_data.get('first_name'), last_name = form.cleaned_data.get('last_name'), email = form.cleaned_data.get('email'), ) done.append("User | "+str(new_user.first_name)+" | added successfully!") #change to the right page else: fail.append("Somthing went wrong, new user can't be created!") #change to the right page context['done'] = done context['fail'] = fail return TemplateResponse(request,'components/forms/single_instance_form.html',context) Form_Handler.js $('#form').on('submit', function(event){ event.preventDefault(); var form_anchor = $(this).attr('id') console.log(form_anchor) submit_form(form_anchor); }); function submit_form(form_anchor) { $.ajax({ url : $(form_anchor).attr('action'), // the endpoint type : "POST", // http method // data sent with the post request data : { 'context': $(form_anchor).serialize(), 'csrfmiddlewaretoken': '{{ csrf_token }}', }, // handle a successful response success : …