Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to add pdf file to django response
I have a model that contains a link to the file stored in AWS S3. class Documents(models.Model): """ uploaded documents""" author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) filedata = models.FileField(storage=PrivateMediaStorage()) filename = models.CharField(_('documents name'), max_length=64) created = models.DateTimeField(auto_now_add=True) filetype = models.ForeignKey(Doctype, on_delete=models.CASCADE, blank=True) url_link = models.URLField(default=None, blank=True, null=True) url_link is the field using pre-signed URLs from boto3 for to get access to privat S3 repo. I'm trying to make a function that receives the model's id, loads it by reference and passes it to response for further processing in the SPA. Based on the answers found on the stackoverflow, I wrote the following function def view_pdf(request, pk): pdf = get_object_or_404(Documents, pk=pk) response = requests.get(pdf.url_link) with open(response, 'rb') as pdf: response = HttpResponse(pdf.read(), mimetype='application/pdf') response['Content-Disposition'] = 'inline;filename=some_file.pdf' return response pdf.closed BUt got an error TypeError at /api/v1/files/pdf/90 expected str, bytes or os.PathLike object, not Response error traceback Internal Server Error: /api/v1/files/pdf/90 Traceback (most recent call last): File "/home/y700/Env/healthline/lib/python3.7/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/home/y700/Env/healthline/lib/python3.7/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/y700/Env/healthline/lib/python3.7/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/y700/projects/healthline/lifeline-backend/apps/files/views.py", line 68, in view_pdf with open(response, 'rb') as pdf: TypeError: expected str, bytes or os.PathLike object, … -
'AnonymousUser' object has no attribute 'profile'
Can someone help me? I've been going around and around with questions here on SO but can't get the answer. I'm getting 'AnonymousUser' object has no attribute 'profile' My views.py are: @login_required def profile(request): if user.is_authenticated: if request.method == 'POST': u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, f'Your account has been updated!') return redirect('profile') else: u_form = UserUpdateForm(instance=request.user) p_form = ProfileUpdateForm(instance=request.user.profile) context = { 'u_form': u_form, 'p_form': p_form } else: return redirect('/login/') return render(request, 'aml/profile.html', context) -
How to separate logic correctly into separate applications?
I implement simple django website, where I tried to separate different parts from website in different APPs, but I'm facing some problems: I have two django apps, right now (core - where are heaader, footer, index) and (objects - where I have objects which I want to list at index page): core/templates/header.html (header elements, login, logout etc) core/templates/index.html (html tags, blocks, etc..): <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> {% block 'head-title' %} {% endblock %} {% load static %} <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"> </script> <script src="{% static 'core/js/custom.js' %}"></script> </head> <body> {% include 'header.html' %} {% block 'body' %} {% endblock %} </body> </html> core/templates/home.html (homepage - here I want to list all Objects and implement filters for them): {% extends 'index.html' %} {% block 'body' %} {% endblock %} core/views.py: from django.shortcuts import render, redirect def show_home_page(request): return render(request, "home.html") Ok everything is perfect, but now I don't know how to add listing of elements: What I tried is to call Object model in show_home_page() function with Object.objects.all() and pass this list to home.html and for filters to call same function with parameters, for example def show_home_page(request, price_up, distance): But then I mess … -
Djanog/drf - delete method
I want to delete likes from my Likes table. for which I am making an axios call from the front end with axios({ method: "delete", url:http://127.0.0.1:8000/api/delete/, params: { companyid: xyz } }) It is supposed to delete a like that has company_id = xyz in it. The Url looks like this path('delete/', DeleteLikesView.as_view()), (/api/ is included in the project's urls.py. So taken care of...) and the DeleteLikesView - class DeleteLikesView(DestroyAPIView): queryset = Likes.objects.all() serializer_class = LikesSerializer def perform_destroy(self, request): print(self.kwargs['companyid']) companyid = self.kwargs['companyid'] instance = Likes.objects.get( company_id=companyid, user_id=request.user.id) instance.delete() I am either being stuck with errors 403 (csrf_token error. Although I tried using csrf_exempt, no luck) or 405 method not allowed(for which I refered this. the solution in this question puts me back with 403 error) Any help is appreciated. Thank! -
not able to traverse AJAX response
I am trying to send some data to save in database using AJAX request. How can I get all the values using some loop or anything. I've tried doing dataType and contentType as well. 'application/JSON' in both My Script in Template var values = { answer: [{'age': '21'},{'name': ['abc', 'xyz']}], user_id: 11 }; $.ajax({ type: 'post', url: 'respMap', data: values, success: function(result) { console.log("done"); }, error: function () { console.log("error"); } }); My Views def saveResponseMap(request): data = request.POST print(data) return HttpResponse(data) I expected a JSON but it "answer[0][name]" is coming as string in the response {'answer[0][age]': ['21'], 'answer[1][name][]': ['abc', 'xyz'], 'user_id': ['11']} -
MySQL: cannot save non-ascii characters in database
Whenever I try to save an address with non-ascii characters like: 721-1 Higashishiokōjichō, Shimogyō-ku, Kyoto, 600-8216, Japan Mysql fails with an error: OperationalError(1366, "Incorrect string value: '\\xC5\\x8Djich...' for column 'formatted_address' at row 1") What is the best practice to save foreign language characters in database? Should I just ignore these characters in code? Or find a way to store them in MySQL (how?) ? -
Cost calculations: suggestions for code improvements
I stumbled upon this piece of code to calculate costs based on country code and city(optional). There is also a condition that countries in Asia have separate pricing logic depending on both country and city and they are stored in a different table (for segregating regional price variances). For the rest, it's only dependent on country code. Let's assume we must have separate tables Asia & the rest. Please suggest some improvements in the below code. def get_cost_by_location(country_code: str, city=None) -> Optional[models.OperatorCost]: cost = None # check if the country is in Asia if models.OperatorCostAsia.objects.filter(country=country_code).exists(): cost = models.OperatorCostAsia.objects.filter(country=country_code, city__icontains=city).first() if cost is None: cost = models.OperatorCostAsia.objects.filter(country=country_code).first() else: cost = models.OperatorCost.objects.filter(country=country_code).first() return cost -
Django cannot login user after registration
The app has a basic registration form. I am trying to authenticate users after they fill it out. However, I'm unable to authenticate them. Am I going about this in the correct way? Here is the view: def registration(request): if request.method == "POST": form = CustomUserCreationForm(request.POST) if form.is_valid(): user = request.user password1 = form.cleaned_data['password1'] #this works try: validate_password(password1, user) except ValidationError as e: form.add_error('password1', e) return render(request, 'register.html', {'form': form}) profile = form.save(commit=False) profile.save() user = authenticate(username=form.cleaned_data['username'], password=form.cleaned_data['password1']) # this login not working, user is never authenticated login(request, user) return redirect('agree') else: raise ValidationError("Form is not valid. Try Again.") else: form = CustomUserCreationForm() return render(request, 'register.html', {'form': form}). Here is the forms.py. The model here is just the Django base user model. class CustomUserCreationForm(forms.ModelForm): username = forms.CharField(label='Username', widget=forms.TextInput(attrs={'class': "form-control"})) password1 = forms.CharField(label='Password', widget=forms.PasswordInput(attrs={'class': "form-control"})) password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput(attrs={'class': "form-control"})) class Meta: model = User fields = ['username'] def clean_password(self): password1 = self.cleaned_data.get('password1') password2 = self.cleaned_data.get('password2') if password1 and password2 and password1 != password2: raise forms.ValidationError("Passwords do not match") return password2 def save(self, commit=True): user = super(CustomUserCreationForm, self).save(commit=False) user.username = self.cleaned_data['username'] user.set_password(self.cleaned_data['password1']) if commit: user.save() return user User never gets registered and authenticated. -
Django channels JsonWebsocketConsumer self.send_json() error
i'm writing a consumer that sends a list of conversation and a profile object (contact) after sending the via self.send_json() this error shows up i really don't know what is going on wondering if you could help Error: Exception inside application: 'name' File "C:\Users\DELL\ENVS\async\lib\site-packages\channels\sessions.py", line 183, in __call__ return await self.inner(receive, self.send) File "C:\Users\DELL\ENVS\async\lib\site- packages\channels\middleware.py", line 41, in coroutine_call await inner_instance(receive, send) File "C:\Users\DELL\ENVS\async\lib\site-packages\channels\consumer.py", line 62, in __call__ await await_many_dispatch([receive], self.dispatch) File "C:\Users\DELL\ENVS\async\lib\site-packages\channels\utils.py", line 52, in await_many_dispatch await dispatch(result) File "C:\Users\DELL\ENVS\async\lib\site-packages\asgiref\sync.py", line 238, in __call__ return await asyncio.wait_for(future, timeout=None) File "C:\Users\DELL\AppData\Local\Programs\Python\Python37\lib \asyncio\tasks.py", line 4 14, in wait_for return await fut File "C:\Users\DELL\AppData\Local\Programs\Python\Python37\lib \concurrent\futures\thread.py", line 57, in run result = self.fn(*self.args, **self.kwargs) File "C:\Users\DELL\ENVS\async\lib\site-packages\channels\db.py", line 14, in thread_handler return super().thread_handler(loop, *args, **kwargs) File "C:\Users\DELL\ENVS\async\lib\site-packages\asgiref\sync.py", line 271, in thread_handler return func(*args, **kwargs) File "C:\Users\DELL\ENVS\async\lib\site-packages\channels\consumer.py", line 105, in dispatch handler(message) File "C:\Users\DELL\ENVS\async\lib\site- packages\channels\generic\websocket.py", line 60, in websocket_receive self.receive(text_data=message["text"]) File "C:\Users\DELL\ENVS\async\lib\site- packages\channels\generic\websocket.py", line 125, in receive self.receive_json(self.decode_json(text_data), **kwargs) File "E:\Personal Projects\Tolk\chat\consumers.py", line 41, in receive_json name = content['name'] 'name' Consumers.py: ```python class LoadConsumer(JsonWebsocketConsumer): def connect(self): if self.scope['user'].is_authenticated: self.accept() else: self.close() def receive_json(self, content, **kwargs): if content['command'] == "CHAT": name = content['name'] data = self.load_conversation_contact(name) else: data = {"success": False, "errors": "no such command"} self.send_json(data) … -
Django admin:i tried granting permission through the group but its not working,
I want to restrict what my custom users through the group permission, but its not working, they still have access to all functionalities I have added the has_add_permission,has_change_permission,has_delete_permission,has_view_permission,has_module_permission method to my custom user admin but it is still not restricting the access class CustomUserAdmin(UserAdmin): add_form = CustomUserCreationForm form = CustomUserChangeForm model = Account list_display = ('email','address', 'is_staff', 'is_active', 'is_superuser', 'is_admin') list_filter = ('email','address', 'is_staff', 'is_active','is_superuser', 'is_admin','groups') fieldsets = ( (None, {'fields': ('email','address', 'password')}), ('Permissions', {'fields': ('is_staff', 'is_active','is_superuser', 'is_admin','groups', 'user_permissions')}), ) add_fieldsets = ( (None, { 'classes': ('wide',), 'fields': ('email','address', 'password1', 'password2', 'is_staff', 'is_active','is_superuser', 'is_admin')} ), ) search_fields = ('email',) ordering = ('email',) enter code here def has_add_permission(self, request): return True def has_change_permission(self, request, obj=None): return True def has_delete_permission(self, request, obj=None): return True def has_view_permission(self, request, obj=None): return True def has_module_permission(self, request): return True admin.site.register(Account, CustomUserAdmin) I expect that when i put when i put a "can delete" permission on group, the users in that group should only be able to delete. but after doing that, they are still having permissions like the superuser. -
In a django model, provide a set of default set of fields but also allow users to add their own
Not the most descriptive title, I know, but my question is much better illustrated with an example. Let's say I'm making an application that will allow student drivers to log their driving time. They are required to log day time and night time, so I provide both fields by default. But let's say for the sake of argument that one curious teenager decides he wants to track the time he spends while driving in thunderstorms as well. And another one decides he wants to track how much time he spends driving in snow. What is the best way of making this possible using Django? This is a rough outline of how I'm thinking about this now. Assume this is in models.py: class Trip(models.Model): user = models.ForeignKey(User, on_delete = models.CASCADE) date = models.DateField() class DrivingTime(models.Model): trip = models.ForeignKey(Trip, on_delete=models.CASCADE) tag = models.ForeignKey(AcceptableTimeType, on_delete=models.CASCADE) hours = models.TimeField() class AcceptableTimeType(models.Model): name = models.CharField(max_length=50) # null/blank if visible for everyone # otherwise, should link to the user that wants this specific type of time tracked user = models.ForeignKey(User, on_delete=CASCADE, blank=True, null=True) I pre-set the list of default types of time (day/night in this example) in the Django admin and leave the User field blank. … -
Django-Template: Tap list item and make a detail page
So I have a bunch of list items, when I tap one I want to get the name and other info of that object. Right now I don't now how to parse data and need help :) As you can see I have a detail page, but my point there is to get the data at that specific index in the list view, so if I tap index one, I want the name of index one! Views: @login_required def studyplanPage(request): obj = Studyplan.objects.filter(canview__user=request.user) username = request.user context = { 'object': obj, 'MyName': username } return render(request, 'allStudyplans.html', context) @login_required def detailStudyplanPage(request): return render(request, 'detailStudyplan.html') Html List: {% for x in object %} <div class="col-lg-6"> <div class="card card-project"> <div class="card-body"> <div class="dropdown card-options"> <button class="btn-options" type="button" id="project-dropdown-button-1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <i class="material-icons">more_vert</i> </button> <div class="dropdown-menu dropdown-menu-right"> <a class="dropdown-item" href="#">Edit</a> <a class="dropdown-item" href="#">Share</a> </div> </div> <div class="card-title"> <a href="detail-studyplan"> <span style=" height: 100%; width: 100%; left: 0; top: 0; z-index: 1; "> <h5 data-filter-by="text">{{x.name}}</h5> <h6 style="font-size: 12px">Studierar inför {{x.parent_assignment}}</h6> </span> </a> </div> <ul class = "hor-list"> {% for student in x.students.all %} <li class = "list-item"> <div class="circle"> <span class="initials" , style="color: #ffffff"> {{ student|make_list|first|capfirst }} </span> </div> </li> {% endfor %} … -
Google Credentials Picker
I registered api google but the account picker did not appear on the site as in the picture how the account picker appears because i searched for a long time and i did not find any solution to the problem When I click on the account picker it takes me to the Google page and I want the account picker to be on the site This is done automatically without moving to the Google page This is the problem is Authenticated in the Google page is not Authenticated in the site page and also does not appear picker in the site page https://6.top4top.net/p_13407jtc21.png https://1.top4top.net/p_1340ergmc2.png -
Not return Queryset to show in template Django
def empFil(request): dep = request.POST.get('dep',None) site = request.POST.get('site',None) print(dep) print(site) fil = TB_employee.objects.filter(dep_id = dep, site_id = site).all().select_related('site_id','dep_id','pos_id','sec_id') print(fil) return render(request,'app/employee.html',{'fil':fil}) -
Want to get text from a DIV but getting "TypeError: 'str' object is not callable" error
I'm using Python 3.7, Django, and BeautifulSoup 4. I have the below bs = BeautifulSoup(html, features="lxml") reg = re.compile(r'u\/\[deleted\]') main_elt = bs.find("button", {"data-main-id": "vote"}) print(str(main_elt.parent)) vote_div = main_elt.parent.find('div') print(str(vote_div)) print("vote text:" + vote_div.text()) Despite the fact that the print(str(vote_div)) prints out <div class="outer2 inner4" style="color:#D7DADC">434</div> The line print("vote text:" + vote_div.text()) dies with a TypeError: 'str' object is not callable What's the right way to extract the text from a DIV object? -
How can i update one PostgreSQL database and sync changes/updates to another PostgreSQL database on another server
I have a django website with PostgreSQL database hosted on one server with a different company and a mirror of that django website is hosted on another server with another company which also have the same exact copy of the PostgreSQL database . How can i sync or update that in real time or interval -
how to fix "NameError: name 'context' is not defined"
I want to use ajax in comments and reply sections of my blog application. In function based view everything is working fine, but I want to do it class based view. ***My function based view*** def post_detail(request, pk): post = get_object_or_404(Post, pk=pk) comments = Comment.objects.filter(post=post, reply=None).order_by('-id') if request.method == 'POST': comment_form = CommentForm(request.POST or None) if comment_form.is_valid(): content = request.POST.get('content') reply_id = request.POST.get('comment_id') comment_qs = None if reply_id: comment_qs = Comment.objects.get(id=reply_id) comment = Comment.objects.create(post=post, user=request.user, content=content, reply=comment_qs) comment.save() else: comment_form = CommentForm() context = { 'title': 'blog', 'post': post, 'comments': comments, 'comment_form': comment_form, } if request.is_ajax(): html = render_to_string('blog/comments.html', context, request=request) return JsonResponse({'form': html}) return render(request, 'blog/post_detail.html', context) ***My class based view*** class PostDetailView(FormMixin, DetailView): model = Post form_class = CommentForm def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) post = get_object_or_404(Post, id=self.object.id) comments = Comment.objects.filter(post=post, reply=None).order_by('-id') context['title'] = 'Blog Detail' context['comments'] = comments context['comment_form'] = self.get_form() return context def post(self, request, *args, **kwargs): #if request.user.is_authenticated(): self.object = self.get_object() form = self.get_form() if form.is_valid(): content = request.POST.get('content') reply_id = request.POST.get('comment_id') comment_qs = None if reply_id: comment_qs = Comment.objects.get(id=reply_id) comment = Comment.objects.create(post=self.object, user=request.user, content=content, reply=comment_qs) comment.save() #return HttpResponseRedirect(self.object.get_absolute_url()) else: return self.form_invalid(form) if request.is_ajax(): html = render_to_string('blog/comments.html', context, request=request) return JsonResponse({'form': html}) def get_success_url(self): … -
I can't access objects from a many to many field
I cant access the objects of a many to many field on my template, whereas i can access the objects of other fields models.py class Cart(models.Model): ```timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) ```updated = models.DateTimeField(auto_now_add=False, auto_now=True) ```active = models.BooleanField(default=True) ```products = models.ManyToManyField(product) #views.py def carthome(request): cartproduct = Cart.objects.all() print(cartproduct) context = { 'cartproduct' : cartproduct, } return render(request, 'home/carthome.html', context) #in templates {% for abc in cartproduct%} {{ abc.product.name }} {% endfor %} Error AttributeError: 'Cart' object has no attribute 'product' -
Omited parameters in a url
In the book: 'The Django's book 2.0' the author talk about using 'catchers' in the url. According to him, you can omit some parameter in the url and define it in the views.py in order to prevent an error 404: urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^hours/(?P<hour>\d+)/$', views.date_in), views.py def date_in(request, hour='02'): #Default argument defined here hour=int(hour) #some extra code This doesn't work for me. I still get the error 404 because the argument after hours/ doesn't exist. -
How to represent multiple routes on Google Maps API with GPS Coordiates
I've looked at similar questions, and they all refer to Google Maps API DirectionsRenderer(). I have a set of GPS coordinates, and each set has a flight_id. Instead of Point A to Point B directions, I have every GPS coordinate I want to plot, connecting the lines from each distinct flight_id start and end points together with a provided timestamp. For example: [{ "flight_id": "2220", "first": { "lat": 41.9554, "lng": -87.888, "timestamp": "2019-07-15T22:32:50" }, "last": { "lat": 41.9554, "lng": -87.888, "timestamp": "2019-07-23T17:45:33" } }, { "flight_id": "2365", "first": { "lat": 41.9469, "lng": -87.8651, "timestamp": "2019-08-11T13:31:20" }, "last": { "lat": 36.844, "lng": -76.288, "timestamp": "2019-08-13T14:15:40" } }] I'm able to get one set of GPS coords first and last points to display on a map, but not multiple. What am I missing? -
PiCar Configuration Exception in thread django-main-thread
I tried to setup the (PiCar) from SunFounder and got following error: mjpg_streamer -i "/usr/local/lib/input_uvc.so" -o "/usr/local/lib/output_http.so -w /usr/local/www" & None Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib/python3.7/threading.py", line 917, in _bootstrap_inner self.run() File "/usr/lib/python3.7/threading.py", line 865, in run self._target(*self._args, **self._kwargs) File "/usr/local/lib/python3.7/dist-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python3.7/dist-packages/django/core/management/commands/runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "/usr/local/lib/python3.7/dist-packages/django/core/management/base.py", line 436, in check raise SystemCheckError(msg) django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: ?: (admin.E408) 'django.contrib.auth.middleware.AuthenticationMiddleware' must be in MIDDLEWARE in order to use the admin application. ?: (admin.E409) 'django.contrib.messages.middleware.MessageMiddleware' must be in MIDDLEWARE in order to use the admin application. ?: (admin.E410) 'django.contrib.sessions.middleware.SessionMiddleware' must be in MIDDLEWARE in order to use the admin application. System check identified 3 issues (0 silenced). I executed following command: ~/SunFounder_PiCar-V/remote_control $ sudo ./start Here the manual from the PiCar. The error occured on page 42. Maybe the pages 40 and 41 are relevant for this error. Sorry I am new to Python and Django. Maybe there is a person who can explain me this error. The OS is raspbian jessie. Thank you very much. -
Django annotate: sum of max of foreign objects
class CashEvent(models.Model): date = models.DateField() profit = models.FloatField() damage = models.FloatField() seller = models.ForeignKey(Seller) class Seller(models.Model): name = models.CharField() store = models.ForeignKey(Store) class Store(models.Model): name = models.CharField() country = models.ForeignKey(Country) From the models above, given that in ids I have a list of ids of Sellers, I need to annotate this list so that I have the sum of each highest damage of each single Seller in my list. Is this possible to do in annotate? ids = [4, 5, 6] Store.objects.filter( seller__cashevent__date__gte=date(2018, 1, 1), seller__id__in=ids ).annotate( sum_of_highest_damage_of_each_seller=? ) I have tried with Sum(Max('seller__cashevent__damage')) but you can't put an aggregation function inside of another. -
How to use pypy with Django along with postgresql backend?
Is there a way to install psycopg2 with pypy. I am trying to run Django with pypy and the main problem I am facing is psycopg2 library. pypy documentation says that I can install psycopg2cffi library instead, but I don't know how to tell Django postgresql backend to use psycopg2cffi instead of psycopg2. Is there any way I can do that? Is there a way to install psycopg2 with pypy. or more broadly, is there any advantage of using pypy than normal Cpython compiler with Django? I tried running various python programs using both Cpython and pypy and shockingly pypy was much faster. So, I thought using pypy can actually increase the throughput of APIs by reducing the time of each API, but I haven't found any documentation for the same? Any leads are welcome!! Thanks in advance. -
Automatically import custom files in Django
I have a Django project containing some files which are, obviously, not automatically discovered by Django. My workaround is to import them in urls.py so that Django can see them. This is how my urls.py looks like: from django.contrib import admin from django.urls import path from custom_file_1 import * # "unused" import from custom_file_2 import * # "unused" import urlpatterns = [ ... ] My IDE considers the commented imports unused, since they are not used, but they are vital so that Django can process those files. And the question: is there any nice way to let Django see those files? And how to do that? -
Django Cron job to update database Entry django python
I have search and found that it can be done using several ways . I am doing using django_cron like this from django_cron import CronJobBase, Schedule from FrontEnd.views import UpdateField class UpdateFiledJob(CronJobBase): RUN_EVERY_MINS = 2 MIN_NUM_FAILURES = 2 schedule = Schedule(run_every_mins=RUN_EVERY_MINS) code = def do(self): UpdateField() First this is what is code field for ? 2nd Can I run this my view function like this ? And in which folder I should keep my taskautomation.py file currently I put it with my manage.py file? my