Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to update File field django
how to update a file field using the object model? my current code: impressao = Impressao.objects.get(id=id) My current condition: (it is getting inside the if condition, but it doesn't save the data) if request.FILES.get("uri_arquivo"): #uri file impressao.arquivo = request.FILES.get("uri_arquivo") impressao.save() model class Impressao(models.Model): comentario = models.CharField('comentario', max_length=255, blank=True, null=True) arquivo = models.FileField(name='uri_arquivo', max_length=400) qtd_copias = models.SmallIntegerField("qtd_copias") visualizado_em = models.DateTimeField("visualizado_em", blank=True, null=True) prazo_entrega = models.DateTimeField("prazo_entrega", blank=True, null=True) colorida = models.BooleanField("colorida", default=False) cliente = models.ForeignKey(Usuario, name="cliente", on_delete=models.CASCADE, null=True) imprimida = models.BooleanField("is_imprimida", blank=True, default=False) tipo = models.ForeignKey(TipoImpressao, on_delete=models.SET_NULL, null=True, name="tipo") -
Nginx (on docker)return 403 Forbiden when trying to get static files
I'm trying to render static and media files using Nginx but i'm always getting 403 forbidden. Some are ssaying that I need to set a USER in nginx.conf file but how ? Need your help. Dockerfile FROM nginx:1.19.0-alpine RUN rm /etc/nginx/conf.d/default.conf COPY ./nginx/nginx.conf /etc/nginx/conf.d my nginx.conf file upstream zandu { server gunicorn:8000; } server { listen 80; server_name localhost; root /app/nginx; location / { proxy_pass http://zandu; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /static/ { alias /etc/nginx/staticfiles/; } location /media/ { alias /etc/nginx/media/; } } -
Custom field not showing in Admin page
I created a cutom user model for my project. And the extra fileds I created is not showing in the Admin page. I just see the standard fields and none of the extra made. I can't fins anything online about what i'm missing. My model for customuser: from django.contrib.auth.models import AbstractUser from django.db import models class CustomUser(AbstractUser): email = models.EmailField(blank=False, null=False) firstname = models.CharField(max_length=25, blank=True, null=True) surname = models.CharField(max_length=45, blank=True, null=True) mobilephone = models.IntegerField(blank=True, null=True) def __str__(self): return self.email My admin.py from django.contrib import admin from django.contrib.auth import get_user_model from django.contrib.auth.admin import UserAdmin from .forms import CustomUserCreationForm, CustomUserChangeForm from .models import CustomUser class CustomUserAdmin(UserAdmin): add_form = CustomUserCreationForm form = CustomUserChangeForm model = CustomUser list_display = ["surname", "firstname", "email", "mobilephone"] admin.site.register(CustomUser, CustomUserAdmin) Also, the field 'First name' and 'Last name' is not the same field as my custom user model. -
Multi step form category specified fields in vue js
I have built multi step form by using vue js. When user type is "business" we have to prompt multi step form in that we have 3 steps They are. first step form:- This form contains only one fields Category field. If user enters first form field then user can able to open category specified fields. second step form:- This form contains category specified fields. If user entered for example IT in first form in second form it has salary, job type,..etc. third step form:- Price package form for business user. If logged in user type is "Consumer" we need prompt like this multi step form. we have 3 steps again her, Those are. First step form:- In this we have category field. If user enters category then user clclick on next button we prompt next form. Second step form:- In this second form it prompts We asks a question like weather he want to continue as consumer or business in this form we have two radio button if user selects consumer we need prompt category specified fields again in third form. else if user selects business we need to prompt signuup form to update user to business in thrid … -
DigitalOcean spaces with django
I have a Learning Management System frontend written in React Js and backend written in django. Users can upload PDF files and image files from the frontend. PDF files are lessons and image files going to be user profile pictures, Subject pictures and course pictures I've configured Digitalocean spaces with the current setup. All the static files, images and pdf files are saving in the object storage. But I need to save pdf files and static files inside the object stiarage and Images inside backend servers. How can I configure django settings file to achieve that task AWS_ACCESS_KEY_ID = 'KEY_ID' AWS_SECRET_ACCESS_KEY = 'ACCESS_KEY' AWS_STORAGE_BUCKET_NAME = 'elearn-storage' AWS_S3_ENDPOINT_URL = 'https://fra1.digitaloceanspaces.com' AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_LOCATION = 'storage' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static/'), ] STATIC_URL = 'https://%s/%s/' % (AWS_S3_ENDPOINT_URL, AWS_LOCATION) STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' DEFAULT_FILE_STORAGE ='storages.backends.s3boto3.S3Boto3Storage' This is my current configuration. What chages I need to make? -
Python Django website not showing on Ubuntu like on Windows
I run into a problem without understanding where it could come from. I have the same website in Django 3.0.8 under environment which works on one side on a PC with windows 10: preview on Windows On the other side, on an old PC with Xubuntu 20.04: preview on Xubuntu Everything is the same: code, files, environments, version of python (3.8). However, the Xubuntu version doesn't perform well as you can see. Do you have any idea what could be blocking? I have the impression that Bootstrap and FontAwesomeIcon are not working correctly. -
DJango admin read_only fields
Below is my admin.py file: # readonly_fields=['product_images'] def product_images(self, obj): return mark_safe( f''' <img class='product' src="{obj.product_image.url}"> <img class='product' src="{obj.product_back_image.url}"> <img class='product' src="{obj.product_pack_image.url}"> <img class='product' src="{obj.product_detailed_image.url}"> ''' ) def get_form(self, request, obj=None, **kwargs): # Proper kwargs are form, fields, exclude, formfield_callback if obj: # obj is not None, so this is a change page kwargs['exclude'] = ['product_image', 'product_back_image', 'product_pack_image', 'product_detailed_image'] # self.readonly_fields=['product_images'] else: # obj is None, so this is an add page kwargs['exclude'] = ['product_image_link', 'product_back_image_link', 'product_pack_image_link', 'product_detailed_image_link'] return super(ProductAdmin, self).get_form(request, obj, **kwargs) The problem is with the first line, if I uncomment it I get an error as below: Is there any work around for the same? -
Nuxt auth with cookies with DRF
I'm trying to implement authentication on my frontend (which is written in NuxtJS) using cookies as opposed to local storage. I'm using the nuxt-auth package, with the following configuration:- auth: { strategies: { cookie: { token: { required: false, type: false, }, user: { property: false, }, endpoints: { login: { url: '/auth/token/login/', }, user: { url: '/auth/users/me/', method: 'get', }, logout: { url: '/auth/token/logout', }, }, }, local: false, }, } My backend is django with rest framework and djoser with the following config:- DJOSER = { 'CREATE_SESSION_ON_LOGIN': True } REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.SessionAuthentication' ), } When I call the auth login method in my frontend, like this:- this.$auth.loginWith('cookie', { data: this.login, }) it all works as expected. The frontend calls /auth/token/login. The backend authenticates the user and sets the cookie in the browser. The frontend calls /auth/users/me which returns the user data and the frontend sets loggedIn to true. But when the user tries to logout in the frontend, the POST request fails because the CSRF token is not set. HTTP 403: CSRF Failed: CSRF token missing or incorrect. I've tried all sorts of other ways to set this stuff up and none of them seem … -
How to set '%' mark in as_sql query (custom Lookup) in Django?
I try to select phone numbers from DB ignoring (, ) , - symbols and allowing to search by substring I have a custom lookup from django.db.models import Lookup from django.db.models import Field class ContainsPhoneNo(Lookup): lookup_name = 'contains_phone_no' def as_sql(self, compiler, connection): lhs, lhs_params = self.process_lhs(compiler, connection) rhs, rhs_params = self.process_rhs(compiler, connection) print(lhs_params, rhs_params) params = lhs_params + rhs_params return "REPLACE(REPLACE(REPLACE(%s, '(', ''), ')', ''), '-', '') ILIKE %s" % ( lhs, rhs), params Field.register_lookup(ContainsPhoneNo) So right now, for example, if I filter by 2345, I can get (23)-45, 2-3-45, etc numbers. But I want to get also 123456. So my query should be "REPLACE(REPLACE(REPLACE(%s, '(', ''), ')', ''), '-', '') ILIKE %%s%" But I don't know how to set % symbols before and after second %s. Django don't allow to set % as is inside query string (I also tried '%'+str(rhs)+'%' way). So how can I do that? -
Django - Add custom field in django admin get_queryset method with multiple levels of prefetch_related
I have the following models. There are Stops in Cities. There are Connections between Stops. MODEL.PY class City(models.Model): pass class Stop(models.Model): city = models.ForeignKey(City, related_name='stops') class Connection(models.Model): origin = models.ForeignKey(Stop, related_name='origin_connections') destination = models.ForeignKey(Stop, related_name='destination_connections') In Django Admin view of City, I want to have clickable custom field showing the number of Connections with links to those Connections. I need the prefetch_related to prevent repetitive queries. Prefetch_related decreased the loading duration from 20 seconds to 1 seconds. ADMIN.PY class CityAdmin(TranslationAdmin): list_display = ["get_connection_count"] def get_queryset(self, request): queryset = super().get_queryset(request) queryset = queryset.prefetch_related('stops__origin_connections', 'stops__destination_connections') return queryset def get_connection_count(self, obj): """ City has 'stops' that, in turn, have 'origin_connections' and 'destination_connections'. Connection count for the city will be the count of connections that either start (origin) or end (destination) in 'stops' """ connections = [] for stop in obj.stops.all(): connections.extend(stop.origin_connections.all()) connections.extend(stop.destination_connections.all()) connections = list(set(connections)) # to drop duplicates connection_count = len(connections) url = reverse("admin:loc_connection_changelist") if connection_count: connections_id_str = ','.join(str(x.id) for x in connections) return format_html('<a href="{}?id__in={}">{} Connections </a>', url, connections_id_str, connection_count) else: return format_html('<a href="{}?id__in=-1">{} Connections </a>', url, connection_count) get_connection_count.short_description = "Connection count" I want to move the loop part from custom field to get_queryset() function. In other words I want to … -
Apostrophe showing as ' in html template
I have a template in django that is pulling in a question title into the title tag. <title>{{question.title}}</title> I find though that is the question contains an Apostrophe the resulting html file shows it as &#x27. e.g. If the title is: 'It won't work' the resulting html source looks like <title>It won&#x27;t work</title> Is this an issue? or will google etc see the title as it was meant to be and present it normally in search results? note: the title is pulled from a question model stored in a postgres db -
How Can I Publish My Flask Script Into Web
I made A Website With Flask And IDK How To Compile It And Publish Can You Help Me? -
django run server is not working from crontab script
I m writing my cronjob as below: */5 * * * * /bin/bash /root/gitsync.sh and content of gitsync.sh is as below: #!/bin/bash cd /root/devices-web git checkout main git pull echo "log1" >> /root/log.txt pip install -r requirements.txt python manage.py runserver 0.0.0.0:8000 Script is getting called every 5 minutes, but services are not running. -
"Unicode error "when trying to connect to microsoft SQL server 19
I am trying to use the Microsoft SQL server as my database of django project but when I am trying to connect it it give me a SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 9-10: truncated \uXXXX escape . The issue is with 'USER': 'INDIANLEO\user',. Here is the database connection DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'ENR', 'HOST': 'INDIANLEO', 'USER': 'INDIANLEO\user', 'PASSWORD': '', 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server', } } } -
Django REST Framework - Return error if not allowed to view object not working?
I'm creating a custom Django Rest Framework permission for one of my view, I only want Admins and the owner of the object to be able to view and edit the object, for everyone else return an exception error. But I can't get my custom permission to return an error if the request.user is not an Admin or the owner of the object. Currently I have in my view.py class ItemQuery(generics.RetrieveUpdateDestroyAPIView): queryset = Item.objects.all() serializer_class = ItemSerializer permission_classes = [IsOwnerOrReadOnly] lookup_field = 'name' and my permissions.py from rest_framework.views import exception_handler class IsOwnerOrReadOnly(permissions.basePermission): def has_object_permission(self, request, view, obj): if request.method in permissions.SAFE_METHODS: return True if obj.id.user = request.user or request.user.is_admin == True: return True else: return False response = exception-handler(self, request) response.status_code = 404 return response -
How can I use multiple inheritance to compose Django forms?
I have lots of forms which contain the same non-model field. For the sake of this example, let's call the field author. This is not a field of any model, just a field that I want to appear in each form. Here is a working example of my current code: from django import forms from . import models class BlogForm(forms.Form): author = forms.CharField() class Meta: model = models.Blog fields = ["author"] class BookForm(forms.Form): author = forms.CharField() class Meta: model = models.Book fields = ["author"] So, naturally, I thought I could use Python inheritance and create a reusable "mixin" class that contains this field. However, it seems that this is not possible. For some reason, I can't get the following to work: from django import forms from . import models class AuthorMixin: author = forms.CharField() class BookForm(AuthorMixin, forms.Form): class Meta: model = models.Book fields = ["author"] This is the error I'm getting: django.core.exceptions.FieldError: Unknown field(s) (description) specified for Book How can I use multiple inheritance to compose Django forms? -
Django: Add formset to a form
I am trying to add a formset to a forms in order to be able to add lines to a bill. I`ve start using a generic view as I found this tutorial for working with formset: https://dev.to/zxenia/django-inline-formsets-with-class-based-views-and-crispy-forms-14o6 I kept encountering some errors when trying to load the form. The current error is: init() takes 1 positional argument but 2 were given, Many Thanks views.py @login_required(login_url="/login/") class BillCreate(CreateView): model = Bill template_name = 'accounting/bills/create_bill.html' form_class = BillForm success_url = None def get_context_data(self, **kwargs): data = super(BillCreate, self).get_context_data(**kwargs) if self.request.POST: data['lines'] = BillLineFormSet(self.request.POST) else: data['lines'] = BillLineFormSet() return data def form_valid(self, form): context = self.get_context_data() lines = context['lines'] with transaction.atomic(): form.instance.created_by = self.request.user self.object = form.save() if lines.is_valid(): lines.instance = self.object lines.save() return super(BillCreate, self).form_valid(form) def get_success_url(self): return reverse_lazy('accounting:bill_detail', kwargs={'pk': self.object.pk}) models.py class Bill(models.Model): vendor = models.CharField(max_length=250, null=True, blank=True) bill_title = models.CharField(max_length=250, null=True, blank=True) reference = models.CharField(max_length=250, null=True, blank=True) class BillLine(models.Model): bill = models.ForeignKey(Bill,related_name="has_lines",on_delete=models.CASCADE, blank=True, null=True, unique=False) bill_item = models.CharField(max_length=100, verbose_name="Line") description = models.TextField(blank=True, null=True) forms.py class BillForm(forms.ModelForm): class Meta: model = Bill fields = ['bill_title','vendor','reference'] def __init__(self, *args, **kwargs): super(BillForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_tag = True self.helper.form_class = 'form-horizontal' self.helper.label_class = 'col-md-3 create-label' self.helper.field_class = 'col-md-9' self.helper.layout = Layout( … -
, i having problem with Listmodelmixin. when i call self.list(request). it only returns only first object.. i am pasting my code here
below is my class code with get method. problem is if i do not specify pk only one value is coming . its not returning complete list. and if i add pk it works fine for every record. pls guide. class UserGenericAPIView(generics.GenericAPIView, mixins.ListModelMixin, mixins.RetrieveModelMixin, mixins.CreateModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin): authentication_classes = [JWTAuthentication] permission_classes = [IsAuthenticated ] queryset = User.objects.all() serializer_class = UserSerializer def get(self, request, pk=None): if pk: return Response({ 'data': self.retrieve(request, pk).data }) return self.list(request).data -
Can this Django queryset loop be optemize?
I need to replace an index value in a pandas data-frame, my solution involves looping through the queryset and replacing the values 1 by 1 before converting into a list for pandas. The issue is that this method takes almost 3 times as long, below is my loop for i in list(report_queryset): Merchant = Posranges.objects.using('DATABASE').filter(posgroupid=i['posgroupid']) i['posgroupid'] = Merchant[0].description # value replacement with description field from posranges database updated_list.append(i) is there a way that this can be optimized? or have I completely missed a better way altogether? -
JSONDecodeError at / .. Expecting value: line 1 column 1 (char 0) [closed]
I'm working on a payment gateway project. so I converted a string into JSON and then create a payment URL. but this error occurs. traceback: Traceback (most recent call last): File "C:\Users\user\Desktop\Django Web App\Len-den\venv\lib\site- packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\user\Desktop\Django Web App\Len-den\venv\lib\site- packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\user\Desktop\Django Web App\Len-den\venv\lib\site- packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\user\Desktop\Django Web App\Len-den\len_den\users\views.py", line 101, in product_rashid print(r.json()) File "C:\Users\user\Desktop\Django Web App\Len-den\venv\lib\site- packages\requests\models.py", line 900, in json return complexjson.loads(self.text, **kwargs) File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\json\__init__.py", line 357, in loads return _default_decoder.decode(s) File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\json\decoder.py", line 337, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\json\decoder.py", line 355, in raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) I think an error occurs here. def payment(request): jsonObj={ "name": "name" } json_string = json.dumps(jsonObj) print(json_string) url = "https://url.something" headers = {'Content-type': 'application/json', 'Accept': 'application/json'} r = requests.post(url, data=json_string, headers=headers) print(r.json()) j = r.json()['status'] k = r.json()['data'] if j == "200": payment_id = k['payment_id'] redirect_url = k['redirect_url'] payment_link = str(redirect_url) + "?" + str(payment_id) print(payment_link) context = { 'payment_link': payment_link, } return render(request, 'users_dashboard/payment.html', context) return render(request, 'users_dashboard/product_rashid.html') -
How to track download link in django?
I followed these method to track how much downloaded the file was. But total_downloads always remains same(it's 0). How to increment total_downloads field by 1 after every download? My models.py: from django.db import models class FilesAdmin(models.Model): id_no = models.IntegerField() name = models.CharField(max_length=20) loc = models.CharField(max_length=20) adminupload = models.FileField(upload_to='media') total_downloads = models.IntegerField(default=0) def __str__(self): return self.name views.py. In this program, I want to increment the number of downloads. But it's 0 in admin site. from django.shortcuts import render from django.http import HttpResponse import os from .models import FilesAdmin def index(request): context = {'file': FilesAdmin.objects.all()} return render(request,'libooki/index.html',context) def download(request,path): file_path = os.path.join(settings.MEDIA_ROOT,path) if os.path.exists(file_path): with open(file_path,'rb') as fh: response = HttpResponse(fh.read(),content_type="application/adminupload") response['Content-Disposition']='inline;filename'+os.path.basename(file_path) FilesAdmin.total_downloads+=1 FilesAdmin.total_download.save() return response urls.py from django.contrib import admin from django.urls import include,path from django.conf import settings from django.conf.urls.static import static from libooki import views #here's libooki is my app name from django.conf.urls import url from django.views.static import serve urlpatterns = [ path('', views.index,name='index'), path('admin/', admin.site.urls), url(r'^download/(?P<path>.*)$',serve,{'document_root': settings.MEDIA_ROOT}), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) index.html where to people can download the file <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>hello</title> </head> <body> {% for post in file%} <h2>{{post.name}}</h2> <a href="{{post.adminupload.url}}" download="{{post.adminupload.url}}">Download</a> {% endfor %} </body> … -
Django - robot.txt - sitemaps - dynamic video service
I have been developing a dynamic video service. The couple of example links regarding the service are as following ( there are thousands of video links in the service ) : https://supereye.co.uk/watch/?v=QByCOKlmao5 or https://supereye.co.uk/watch/?v=4pZ3APUR4hx I have done the following changes in settings.py: SITEMAP_MAPPING = 'mysite.urls.sitemaps' SITEMAP_INDEX_URL = 'sitemap-video-' SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') ROBOTS_CACHE_TIMEOUT = 60*60*24 INSTALLED_APPS += [ 'django.contrib.sitemaps', 'django.contrib.sites', 'robots', 'sitemap_generate', 'corsheaders', and in urls.py from django.contrib.sitemaps.views import sitemap from mysite.sitemaps import VideoSitemap sitemaps = { 'static': VideoSitemap } urlpatterns = [ path('admin/', admin.site.urls), path(r'^robots.txt$', include('robots.urls')), path('sitemap.xml', sitemap, {'sitemaps': sitemaps}, name='sitemap-index'), path('sitemap-<section>.xml', sitemap, {'sitemaps': sitemaps}, name='django.contrib.sitemaps.views.sitemap'), What shall I add into django models of robots admin url and sitemaps ? How can I correctly implement/integrate robot.txt and sitemaps for each using the following packages : django-sitemap-generate django-robots -
Django - Generic OneToOneField to enable select_related() functionality
I have the following models: class A(Model): ... class B(Model): ... class C(Model): ... class Generic(Model): genericable_id = PositiveIntegerField() genericable_type = CharField() # One of A, B, C ... For which the data look like this: Table A: id, other fields 1, ... 2, ... Table B: id, other fields 1, ... 2, ... Table C: id, other fields 1, ... 2, ... Table D: id, genericable_id, genericable_type, other fields 1, 1, 'A', ... 2, 2, 'A', ... 3, 1, 'B', ... 4, 2, 'B', ... 5, 1, 'C', ... 6, 2, 'C', ... To retrieve Generic object from A/B/C's class perspective, I do something like the following: Example for class A @property def genericable(self): return Generic.objects.get(genericable_id=self.id, genericable_type='A') It turns out I query for that generic object quite a lot from all these classes, and it slows down my application, as there's no way to prefetch that object using select_related() given current implementation (cached_property helps a bit, but having an ability to do that through select_related would be much better. I was wondering whether it is possible to somehow define that relationship in Django so I can do for example: qs = A.objects.select_related().all() # all generic objects for A retrieved … -
form registers as valid but does not update
This is a very weird phenomenon. Why is it that even though the form is valid, the values are not updated? It works if i do it in django admin though. I am not even receiving any errors. The form is just valid but its not being updated. Its as if they took the old values to update... html: <form action="{% url 'account:displayinfo' request.user.id %}" method="POST" enctype="multipart/form-data">{% csrf_token %} {{ form.as_p }} <div class="d-flex justify-content-center"> <button type="submit" class="btn btn-primary btn-sm col-lg-5">Update</button> </div> </form> views.py def display_information_view(request, *args, **kwargs): user_id = kwargs.get("user_id") account = Account.objects.get(pk=user_id) context = {} displayinfo = AccountDisplayInfo.objects.get(account=account) if request.method == "POST": form = DisplayInformationForm(request.POST, request.FILES, instance=request.user) if form.is_valid(): info = form.save(commit=False) info.account = request.user info.save() messages.success(request, 'Your profile display information have been updated', extra_tags='editdisplayinfo') return redirect("account:view", user_id=account.pk) else: form = DisplayInformationForm(request.POST, instance=request.user, initial={ "instagram": displayinfo.instagram, } ) context['form'] = form else: form = DisplayInformationForm( initial={ "instagram": displayinfo.instagram, } ) context['form'] = form return render(request, "account/displayinfo.html", context) forms.py class DisplayInformationForm(forms.ModelForm): class Meta: model = AccountDisplayInfo fields = ('instagram',) models.py class Account(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) class AccountDisplayInfo(models.Model): account = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) instagram = models.CharField(max_length=50, unique=True, blank=True, null=True) #instagram -
Python threading lifecycle
I am developing a Django project where after discarding the use of celery for its complexity, I have implemented python threading directly through the Thread class. The purpose is very simple tasks that do not need a control if they have been carried out, such as sending push messages to devices (with a very low load, in the order of about 20 messages per hour). However I have been looking for multiple information about the Thread life cycle in python and I can come up with a conclusion about it. Is it necessary to manually close each Thread launched or does the process end when the run function completes? Not being necessary to control the correct execution of the operation, what advantages does the use of celery have over this option with the purpose and workload mentioned?