Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I start a project to know more about google sign in and only add my app to my projects settings.py.Then i try to migrate, throws an error like
from django.utils import importlib ImportError: cannot import name 'importlib' from 'django.utils' -
Django auth views, problem at trying to change default reset email content?
Hello everyone i know there is a similar question to the one , as this thread shows How to customize django rest auth password reset email content/template. But unfurtunately even tho i followed the latest and the most upvoted answers i still didnt manage to succeed on changing the default email text and since that thread is based on older version i think it would be nice to have a patched up answer. So currently i am trying to access the default text by using the following serializer and trying to override the default one, from rest_auth.serializers import PasswordResetSerializer class CustomPasswordResetSerializer(PasswordResetSerializer): def get_email_options(self): return { 'subject_template_name': 'usuarios/password_reset_subject.txt', 'email_template_name': 'usuarios/password_reset_message.txt', 'extra_email_context': { 'pass_reset_obj': self.your_extra_reset_obj } } After that i created the templates and so on but i still get the default messages is worth noting i also followed brian ks old answer but that didnt work neither, would appreciate any help. -
Django - Pass int and None value to chart.js
I'm not really good in javascript, a language I always have difficulties to understand and work with. I'm working on a Django project where I need to pass a list to Chart.js to display a graph according to a specific Model. The problem I have is trying to pass a list to javascript from Django in order to display data if they are available or not. Let's say I have a python list from a Model attribute : [10, 20, None, 30, 40, None, 50] I need Chart.js to display data depending if they is a value for each axis point and nothing if they is None. When I try to pass the list with json.dump() and then in my template with {{ my_list|safe }} it display it like this : ['10', '20', 'None', '30', '40', 'None', '50'] Everything is diplayed as str when it should be either int or None/null value. How should I do if I need chart.js to have values as they are in backend ? Hoping my problem is clear enough, if not let me know and I'll try to better explain ! Thank you in advance for your precious help. -
Error Not Null Contriant Failed quiz_quiz.subject_id
I have this Table class Quiz(models.Model): quiz_title = models.CharField(max_length=300) num_questions = models.IntegerField(default=0) subject=models.ForeignKey(Subject,on_delete=models.CASCADE,blank=True,null=True) def __str__(self): return self.quiz_title And within this Table you can see I have subject foreign key Like when I create Quiz choose foreign key of subject in which subject I want to create Quiz class CreateQuizForm(forms.Form): quiz_name = forms.CharField(max_length=50, label="Quiz Name", widget=forms.TextInput(attrs={'class': 'quiz_name_box'})) num_questions = forms.IntegerField(label="Number of Questions", widget=forms.NumberInput(attrs={'class': 'num_questions_box'})) speed = forms.ModelChoiceField(queryset=Subject.objects.all()) def clean_name(self): data = self.cleaned_data['quiz_name'] # Check if quiz name is unique. if data == "Default_Name": raise ValidationError(_('Invalid name - Must be Unique')) # returns cleaned data return data this is My CreateQuizForm And when I choose Subject its showing Integrity Null contriantError -
spaces not getting printed in html
I have a django html template which has this form in it <form action="/image_info/" method="POST" id='image_form'> {% csrf_token %} <button class="imginfo" name='info_button' value={{x.desc}} type="submit">info</button> </form> The above form will POST the value to views.py whenever the submit button is pressed. but the problem is {{x.desc}} is a sentence and has blank spaces in it so only the first word is getting posted. I need the whole sentence. How should I do it. here x is a model and desc is its object. Thanks you. -
data send for covid tracker page /Django
I want the create a covid tracker page with Django.I created html frame with Bootstrap.I want get covid data and send to my page but I do not know how to do it. I get the data with request module but I don't know how to send to html.Can I write python code to the .html file? Note:I am sorry because my english is very poor therefore I got help from translate my html code: <div class="card-columns "> <div class="card bg-primary text-white"> <div class="card-body"> <p>Number of tests</p> </div> </div> <div class="card bg-danger"> <div class="card-body text-white"> <p>Cases</p> </div> </div> <div class="card bg-secondary"> <div class="card-body text-white"> <p>Deaths</p> </div> </div> <div class="card bg-warning"> <div class="card-body text-white"> <p>Lorem ipsum dolor sit amet consectetur.</p> </div> </div> <div class="card bg-success"> <div class="card-body text-white"> <p>Lorem ipsum dolor sit amet consectetur.</p> </div> </div> <div class="card bg-info"> <div class="card-body text-white"> <p>Lorem ipsum dolor sit amet consectetur.</p> </div> </div> </div> -
How to use Jinja with HTML carousel
I am working on my first Django project and I am trying to get Jinja code to properly align images on my index.html file. here is the code <!-- Start Banner Hero --> <div id="template-mo-zay-hero-carousel" class="carousel slide" data-bs-ride="carousel"> <ol class="carousel-indicators"> <li data-bs-target="#template-mo-zay-hero-carousel" data-bs-slide-to="0" class="active"></li> <li data-bs-target="#template-mo-zay-hero-carousel" data-bs-slide-to="1"></li> <li data-bs-target="#template-mo-zay-hero-carousel" data-bs-slide-to="2"></li> </ol> <div class="carousel-inner"> <div class="carousel-item active"> <div class="container"> <div class="row p-5"> {% for bnn in bnns %} <div class="mx-auto col-md-8 col-lg-6 order-lg-last"> <img class="img-fluid" src={{bnn.img.url}} alt=""> </div> <div class="col-lg-6 mb-0 d-flex align-items-center"> <div class="text-align-left align-self-center"> <h1 class="h1 text-success">{{bnn.title}}</h1> <h3 class="h2">{{bnn.subtitle}}</h3> <p>{{bnn.decs}} </p> </div> </div> </div> {% endfor %} </div> </div> <a class="carousel-control-prev text-decoration-none w-auto ps-3" href="#template-mo-zay-hero-carousel" role="button" data-bs-slide="prev"> <i class="fas fa-chevron-left"></i> </a> <a class="carousel-control-next text-decoration-none w-auto pe-3" href="#template-mo-zay-hero-carousel" role="button" data-bs-slide="next"> <i class="fas fa-chevron-right"></i> </a> </div> <!-- End Banner Hero --> I have tried the same format on other sections of the HTML page and they work fine. Here is an example: <!-- Start Categories of The Month --> <section class="container py-5"> <div class="row text-center pt-3"> <div class="col-lg-6 m-auto"> <h1 class="h1">Categories of The Month</h1> <p> Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </p> </div> </div> <div class="row"> {% for catg in … -
adding one serializer fields to another -django rest framework
my serializer.py file is as ... class RelativeSerializerSLC(serializers.ModelSerializer): full_name = serializers.CharField(source="user.full_name") rtl_full_name = serializers.CharField(source="user.rtl_full_name") gender = serializers.CharField(source="user.gender") phone = serializers.CharField(source="user.phone") email = serializers.CharField(source="user.email") avatar = serializers.CharField(source="user.avatar") date_of_birth = serializers.CharField(source="user.date_of_birth") class Meta: model = Relative fields = ("full_name", "rtl_full_name", "gender", "phone", "email", "avatar", "date_of_birth", "blood_group", "rel") read_only_fields = ["patient"] class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = "id", "full_name", "rtl_full_name", "gender", "phone", "email", "date_of_birth", "avatar" there i'm creating other serializer fields(userSerializer) and added to my RelativeSerializer. that seems uglyyy to me, i have no idea on. is there any better option like using one serializer fields for other. Thanks, new to DRF :) -
How to humanize measurement queries in Django
I have a distance query in Django and prints a distance with several decimal points. It displays distance in a measurement format as 1023.40258027906 m .I want to make this human readable. I tried using Decimal but this failed as it does not apply to Measurement objects. <style type="text/css"> ul{ list-style-type: circle; margin:0px; padding-left: 1em; } </style> <head> </head> <body><strong>Nearby Apartments</strong> {% if apartments %} <ul> {% for apartment in apartments %} <li> {{ apartment.apt_id }}: {{apartment.distance}} </li> {% endfor %} </ul> {% endif %} </div> </body> -
Django Channels group_send ~30s delay before sending
I'm trying to send two messages in succession from an AsyncJsonWebSocketConsumer to a group via group_send. My problem is that only one message to one client is delivered immediately, while the other messages are delivered roughly 30s later. If I only send one of the two messages, all messages are delivered immediately. I have set up a minimal example. The consumer sends back the message it received, but adds two timestamps server_received and server_sent when it receives and sends the message, respectively. class TestConsumer(AsyncJsonWebsocketConsumer): async def connect(self): await self.channel_layer.group_add('TESTGROUP', self.channel_name) await self.accept() async def receive_json(self, content): content['server_received'] = datetime.now().strftime('%H:%M:%S') await self.channel_layer.group_send('TESTGROUP', {'type': 'send_message', 'message': content}) # delayed only if sending two messages #await self.channel_layer.group_send('TESTGROUP', {'type': 'send_message', 'message': content}) async def send_message(self, event): await self.send_json({**event['message'], 'server_sent': datetime.now().strftime('%H:%M:%S')}) Here's some Javascript creating two connections and sending an initial message from the second websocket. (I know it's not super safe to do it this way, because we don't know in what state ws1 is, when sending, so we could drop a few messages, but doesn't matter for our purposes) function fmtDate(date) { return date.toLocaleTimeString('en-GB', {timeZone: 'UTC'}) } var ws1 = new WebSocket('ws://localhost:8000/test/') ws1.onmessage = (event) => { var msg = JSON.parse(event.data) const now … -
HTML displays duplicates of database entries
I'm having an issue with displaying my database entries in HTML. models.py: class Behandling(models.Model): title = models.CharField(max_length=100) description = models.CharField(max_length=200) time = models.IntegerField(default=60) price = models.IntegerField(default=995) views.py: def behandling(request): behandlingar = Behandling.objects.all() args = { 'behandlingar': behandlingar } return render(request, 'behandlingar.html', args) behandlingar.html <h2>{% for behandling in behandlingar %} {{ behandlingar.0.title }}</h2> <p>{{ behandlingar.0.description }}</p> {% endfor %} This is what displays in the html It seems like the title and description text repeats itself once for each item in the database. What could be wrong? -
Regarding Django error message TemplateDoesNotExist at /post/new
I'm learning djangou if anyone can help me when I want to create a new article I get this wrong. error TemplateDoesNotExist at /post/new/ blog/post_form.html Request Method: GET Request URL:http://127.0.0.1:8000/post/new/ Django Version: 3.1.7 Exception Type: TemplateDoesNotExist Exception Value: blog/post_form.html Exception Location: C:\Python39\lib\site-packages\django\template\loader.py, line 47, in select_template Python Executable: C:\Python39\python.exe Python Version: 3.9.2 Python Path: ['C:\\Users\\zakoo\\Desktop\\blogproject', 'C:\\Python39\\python39.zip', 'C:\\Python39\\DLLs', 'C:\\Python39\\lib', 'C:\\Python39', 'C:\\Python39\\lib\\site-packages'] this is sttings.py file sttings.py import os from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '*$=h-)vh383w^@02dus@xb73sdb78m%vpg=%8#vclb$mjw!y*b' # 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', #local apps 'blog', 'accounts.apps.AccountsConfig', #3rd party 'crispy_forms',#new ] 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 = 'blogproject.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'blogproject.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { … -
Only one like button for all the images of user
I am building a BlogApp and I am trying to implement a feature that User can upload multiple images in one Story AND i build a like button for every every story uploaded by different users. BUT when i access like button then , Like button is showing for all the images upload in one story BUT i am tying to show like button for one story of user AND another user posted story then show another like button for another story models.py class Story(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE,default='',null=True) file = models.ImageField(upload_to='posts',null=True) likes = models.ManyToManyField(User, related_name='story_like', blank=True) views.py def story_like(request, story_id): post = get_object_or_404(Story, pk=story_id) # Like if request.GET.get('submit') == 'like': if request.user in post.dislikes.all(): post.dislikes.remove(request.user) post.likes.add(request.user) return JsonResponse({'action': 'undislike_and_like'}) elif request.user in post.likes.all(): post.likes.remove(request.user) return JsonResponse({'action': 'unlike'}) else: post.likes.add(request.user) return JsonResponse({'action': 'like_only'}) template.html stories: [ // {% for story in trending %} Story.buildTimelineItem( '{{ story }}', '{{ user.profile.file.url }}', '{{ story.user }}', '{{story.id}}', timestamp(), [ [ '{{story.id }}-1', 'file', 3, '{{ story.file.url }}', '', ], ] ), // {% endfor %} ], }); </script> {% for story in trending %} <br> <br> <div class="card-footer"> <form method="GET" class="likeForm d-inline" action="{% url 'mains:story_like' story.id %}" data-pk="{{ story.id }}"> <span id="id_likes{{story.id}}"> {% if … -
how to make a 'GET' view that depends on another modal's primary Key
i have a Django Rest API with multiple items on it and i want to be able to show reviews for a given item, i already set up the reviews model and the reviews 'POST' view,the reviews show up just fine in the django admin page all i need now is to make a 'GET' view for the Reviews according to item's primary Key (i am using React on the front end but i don't think that's relevent) views.py @api_view(['GET', 'POST']) def item_detail(request,pk): try: item_detail = items.objects.get(pk=pk) except item_detail.DoesNotExist: return Response({'message': 'The Item does not exist'}, status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': item_serializer = itemsSerializer(item_detail) return Response(item_serializer.data) elif request.method == 'POST': permission_classes = (IsAuthenticated,) parser_classes = [MultiPartParser, FormParser] new_Review = None serializer = NewReviewSerializer(data=request.POST) if serializer.is_valid(): # Assign the current item to the Review new_Review = serializer.save(item=item_detail) # Save the Review to the database new_Review.save() return Response(serializer.data, status=status.HTTP_200_OK) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) @api_view(['GET']) def ReviewsView(request,pk): ?????? models.py class Review(models.Model): item = models.ForeignKey(items, related_name='Reviews', on_delete=models.CASCADE) name = models.CharField(max_length=100) email = models.EmailField() body = models.TextField() date = models.DateTimeField(auto_now_add=True) active = models.BooleanField(default=False) class Meta: ordering = ['date'] def __str__(self): return 'Review of ({}): {} by {}'.format(self.item, self.body, self.name) -
Django delete item use case : good practice?
Little general explanation. I'm pretty newbie in Django, I have a little knowledge, but nothing as experience. The code that I want ask about is working, but I have a question about good/bad practice. Does my approach is good or at least not bad? Little use case explanation. I have a site with the items. There is a functionality to add the items and now I want to add a possibility to delete the item. Use case : on the page of item user clicks on the button Delete, we will show a page with details about this item and the button "Confirm delete" at the bottom. If user click on the button I delete this item from database. So I create in urls.py path('item/delete/<int:id>/', views.delete_item, {}, 'delete_item'), I create in views.py def delete_item(request,id): if id : cur_item = get_object_or_404(Item, pk=id) else : raise Http404 if request.POST: try : post_item_id=int(request.POST["pk"]) except ValueError : messages.error(request,"Wrong id number") return render(request, 'myapp/item_delete_form.html', {'cur_item': cur_item}) if (request.POST["delete"] == "yes") and (post_item_id == id): Item.objects.filter(pk=id).delete() # Delete was successful, so redirect to another page redirect_url = reverse('items') return redirect(redirect_url) else: messages.error(request, "id number in form not the same as in URL") return render(request, 'myapp/item_delete_form.html', {'cur_item' … -
How to get parent model in child serializer without using depth?
I am new to django, i tried to practice django rest api implementation. models.py from django.db import models class Parentmodel(models.Model): ptid = models.IntegerField(primary_key=True) ptname = models.CharField(default="",max_length=50) def __str__(self): return self.ptname class Studentmodel(models.Model): stid = models.IntegerField(primary_key=True) stname = models.CharField(max_length=50) ptid=models.ForeignKey(Parentmodel,db_column='ptid', related_name="student", on_delete=models.CASCADE) def __str__(self): return self.stname class Marksmodel(models.Model): Marksid=models.IntegerField(primary_key=True) maths=models.IntegerField() physics=models.IntegerField() science=models.IntegerField() stid=models.ForeignKey(Studentmodel,db_column='stid', related_name="marks", on_delete=models.CASCADE) def __str__(self): return self.Marksid serializers.py from rest_framework import serializers from polls.models import Studentmodel, Marksmodel, Parentmodel class MarksSerializer(serializers.ModelSerializer): class Meta: model=Marksmodel fields="__all__" class StudentSerializer(serializers.ModelSerializer): marks=MarksSerializer(read_only=True,many=True) class Meta: model=Studentmodel fields="__all__" class ParentSerializer(serializers.ModelSerializer): student=StudentSerializer(read_only=True,many=True) class Meta: model=Parentmodel fields="__all__" views.py from rest_framework import viewsets from .serializers import StudentSerializer, MarksSerializer, ParentSerializer from .models import Studentmodel, Marksmodel, Parentmodel class Studentapi(viewsets.ModelViewSet): queryset = Studentmodel.objects.all() serializer_class = StudentSerializer class Marksapi(viewsets.ModelViewSet): queryset = Marksmodel.objects.all() serializer_class = MarksSerializer class Parentapi(viewsets.ModelViewSet): queryset = Parentmodel.objects.all() serializer_class = ParentSerializer Above code is working fine. I able to get the correct response if i call parent api. Parentapi Response : [ { "ptid": 1, "student": [ { "stid": 1, "marks": [ { "Marksid": 1, "maths": 100, "physics": 100, "science": 123, "stid": 1 } ], "stname": "Nainika", "ptid": 1 } ], "ptname": "Sabish" } ] Studentapi Response : [ { "stid": 1, "marks": [ { "Marksid": 1, "maths": 100, "physics": 100, … -
Celery no longer connecting to Redis through Heroku
I had my Redis server set up and deployed on Heroku and Celery was fully functional however now it does not want to connect. The host and port recently updated but I have switched this over to my code like I usually do to fix the issue but it still persists. [2021-04-22 09:01:46,999: ERROR/MainProcess] consumer: Cannot connect to redis://:host:port//: Error while reading from socket: (54, 'Connection reset by peer'). My celery is set up as follows and the credentials all match with those on Heroku - os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myapp.settings') app = Celery('myapp') app.conf.timezone = 'Europe/London' app.config_from_object('django.conf:settings') app.conf.update(BROKER_URL='redis://:password@host:port', CELERY_RESULT_BACKEND='redis://:password@host:port') In my settings I just have - CELERY_BROKER_URL = 'redis://:password@host:port' If I check heroku redis:credentials REDIS_URL I get - rediss://:password@host:port Is the difference between redis and rediss doing something here? I've also seen on the documentation the usual set up for Redis is - 'redis://:user:password@host:port' - but I haven't had to add a user in before and it has worked fine. There is also no named user when looking at the Redis credentials on Heroku. As I mentioned it was working perfectly fine until a week ago and nothing has changed other than Redis updating as it does periodically. -
Why is the 'r' before strings in python so important?
I am fairly new to the Django framework and for a couple of hours I was getting TemplateNotFound error returned when I tried to map my views.py to my templates directory. This issue was eventually solved just by inputting 'r' before my path to templates in os.path.join(BASE_DIR, 'templates') to become os.path.join(BASE_DIR, r'templates'). I really want to understand better what function it carries out on the string. what is the big idea? -
Filter Foreign Key in Django Graphene Filter using DjangoFilterConnectionField
I am finding a solution for filtering Foreign Key in Django Graphene Filter using DjangoFilterConnectionField. Here is my code: My models: class Team(models.Model): name = models.CharField(max_length=125, validators=[MinLengthValidator(1)]) creator = models.ForeignKey(User, related_name='team_creator', on_delete=models.CASCADE) My schema: class TeamType(DjangoObjectType): class Meta: model = Team filter_fields = ['creator', 'is_active', ] interfaces = (graphene.relay.Node, ) use_connection = True class Query(graphene.ObjectType): team = graphene.relay.Node.Field(TeamType, idname=graphene.Int()) teams = DjangoFilterConnectionField(TeamType) def resolve_teams(self, info, **kwargs): return Team.objects.all() When I exec query to list all teams which created by creator with id 1: query getTeamsCreatedByMe { teams(creator: "1") { edges { node { name } } } } It goes error: { "errors": [ { "message": "['{\"creator\": [{\"message\": \"Invalid ID specified.\", \"code\": \"\"}]}']", "locations": [ { "line": 2, "column": 3 } ], "path": [ "teams" ] } ], "data": { "teams": null } } Please help me with this code. Thanks in advance! -
Django JWT - Add Custom Field to User
I want to add a custom field to JWT User Model like biography and fetch with API. I couldn't handle with it, i'm so confused. I'm getting this error "django.core.exceptions.ImproperlyConfigured: Field name bio is not valid for model User." My models.py as below: from django.core.validators import MinValueValidator, MaxValueValidator from django.db import models from django.db.models.signals import post_save from rest_framework_jwt.serializers import User from tinymce.models import HTMLField class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=500, blank=True) Views.py from rest_framework import viewsets, status, permissions from rest_framework.response import Response from rest_framework.authentication import TokenAuthentication from rest_framework.views import APIView from rest_framework.permissions import IsAuthenticated, AllowAny from django.contrib.auth.models import User from rest_framework.decorators import action, api_view from .serializers import UserSerializer, UserSerializerWithToken @api_view(['GET']) def current_user(request): """ Determine the current user by their token, and return their data """ serializer = UserSerializer(request.user) return Response(serializer.data) class UserList(APIView): """ Create a new user. It's called 'UserList' because normally we'd have a get method here too, for retrieving a list of all User objects. """ permission_classes = (permissions.AllowAny,) def post(self, request, format=None): serializer = UserSerializerWithToken(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Serializers.py from rest_framework_jwt.serializers import User from .models import Content, Rating from rest_framework import serializers from rest_framework_jwt.settings import api_settings class UserSerializer(serializers.ModelSerializer): … -
how to make function call independent to Django server?
I have a python module which updates database infinitely for multiple connections. To start the work I have a button in UI to initiate the call using ajax and django views action is like below views.py def initiate_all(request): pool = Pool(4) pool.map_async(enableUpdate, [entity] for entity in range(3)) return HttpResponse() for three iterations it calls function and establishes three concurrent connections to update the data like below module.py def enableUpdate(e): while connection_is_alive(): connection to db update the values The above code works perfect where its doing multiprocessing to create 3 connection (in above example) and update database respectively. But if django server is stopped it destroys all objects which intern stops database update work as well. Requirement is ones the user clicks start button from UI, python update code should work even if the django server stops running. How to achieve this ? -
Joblib svm model giving KeyError when opening from nginx server but it works when loading from localhost
I am doing a classification problem i have almost completed my work and everything works perfectly on localhost by classifying with my external svm model but it does not works when i deploy on digital ocean nginx server it gives me keyerror 118 Error Image. Code for loading model filname = "new_bigger_category_classification_svm_model_v5.sav" model_cat = joblib.load(open(filname, 'rb')) Error on terminal: terminal error I am repeatedly getting error when i am trying to predict from online Ubuntu server in digital ocean but works perfectly on local server. Please help me to solve this problem. Thank you! -
How to pass modelform instance fields that are not intended for user input to template in Django
I'm using formsets to pass several modelforms with existing model instances to a template. I'd like to do something in the template for each form depending on the value of a model field (let's call it field_check) for that instance. Field_check is not intended for user input and a required field. If I include field_check into my form without rendering it, I can easily access its value. But then after submitting the form Django complains that field_check is required. What is the recommended way to access the value of field_check without including it as an input field or running into the required field problem? Models.py class MyModel(models.Model): field_check = models.CharField(max_length=50) user_input_field = models.CharField(max_length=50) some_type = models.CharField(max_length=50) Forms.py class MyModelForm(forms.ModelForm): class Meta: model = MyModel fields = [ 'user_input_field', 'field_check', #having this field here creates problems, since it's not intended for user input ] MyFormSet = forms.modelformset_factory(MyModel, form = MyModelForm, extra=0) Views.py def myview(request): this_type = 1 formset = MyFormSet(request.POST or None, queryset = MyModel.objects.filter(some_type = this_type)) if request.method == 'POST': if formset.is_valid(): formset.save() return render(request, 'some_other_template.html') context = {'formset':formset} return render(request, 'mytemplate.html', context) Template <form method="post"> {{ formset.management_form }} {% for form in formset %} {{form.id} # here is the … -
Applying CORS to Django static files
I'm trying to get one project to access resources of another project. I installed django-cors-headers and everything started working fine except for static files. I followed the answer here and while it does work, it's mentioned that this isn't advisable for production environments. Is there an alternative that I can do to serve static files without compromising my production environment? If it helps, I'm trying to access the static file (a .csv) with d3 via the following javascript code: d3.csv('https://127.0.0.1:8200/static/tracks/3CeCwYWvdfXbZLXFhBrbnf.csv') .get(function(data) { // Code here }); }); Accessing my production server yields the following: Access to XMLHttpRequest at 'http://example.com/static/tracks/3CeCwYWvdfXbZLXFhBrbnf.csv' from origin 'http://127.0.0.1:8000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Production server settings: CORS_ORIGIN_ALLOW_ALL = False CORS_ORIGIN_WHITELIST = [ 'https://example.com', 'http://localhost:8000', 'http://127.0.0.1:8000', 'http://127.0.0.1', ] CORS_ALLOWED_ORIGINS = CORS_ORIGIN_WHITELIST MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'sass_processor', 'corsheaders', ] -
How to use parent loop counter in the nested for-loop to access to a specific row in a json like data in django templates (.html file)
at the following code the interior for loop needs to access to a specific row of entries. In the other words the nested loop should be {% for entry in entries.(topic.id) %} the entries is a JSON like array as the following: entries = [ {'a', 'b', 'c'}, {'d'}, {'e', 'f', 'g', 'h', 'i'}, {'j','k'} . . . ] {% for topic in topics %} <li> <h5> {{topic.id}} - {{topic}} <ul> <small> {% with i=topic.id %} {{i}} {% for entry in entries.i %} <li>{{forloop.counter}} . {{entry}}</li> {% empty %} <li>No entries available!</li> {% endfor %} {% endwith %} </small> </ul> </h5> </li> {% empty %} <li> <h4 style="color: tomato;">There is no available topic(s)</h4> </li> {% endfor %}