Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework Custom Throatting Not Working
I'm creating a custom throatting for an api I've developed using django rest framework, currently there are two subscription plans, each one with its own quota, so here, in throatting.py, I've created a custom class that fetches the user quota and overwrites it to the default setting: from rest_framework.throttling import UserRateThrottle def get_user_daily_limit(user): # Some calculations # return the daily quota for user, f.ex: 20 request class SubscriptionDailyRateThrottle(UserRateThrottle): scope = "subscription" def __init__(self): super().__init__() def allow_request(self, request, view): if request.user.is_staff: return True if request.user.is_authenticated: user_daily_limit = get_user_daily_limit(request.user) if user_daily_limit: self.duration = 86400 self.num_requests = user_daily_limit else: return True if self.rate is None: return True self.key = self.get_cache_key(request, view) if self.key is None: return True self.history = self.cache.get(self.key, []) self.now = self.timer() while self.history and self.history[-1] <= self.now - self.duration: self.history.pop() if len(self.history) >= self.num_requests: return self.throttle_failure() return self.throttle_success() And this is my settings.py: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', ], 'DEFAULT_THROTTLE_CLASSES': [ 'rest_framework.throttling.UserRateThrottle', 'app.throttling.SubscriptionDailyRateThrottle' ], 'DEFAULT_THROTTLE_RATES': { 'user': '5/second', 'subscription': '16/day' } } I checked the tutorial I was following and everithing seems to be fine but when I test it doing request I can't see neither the 5 seconds betweet requests nor the maximum of 16 request per day, … -
Run Django Custom Command locally?
Owing to not having a Credit Card, can't use heroku's task scheduler. https://devcenter.heroku.com/articles/scheduling-custom-django-management-commands This site talks about running the custom command locally via cli. Is it possible to automate this cli "script" so it runs every day? I know it's possible in normal python scripts but unsure about this one. All leads appreciated thanks a lot. -
Docker not recognising Dockerfile
I am running into a problem where docker isn't recognising my Dockerfile. -What I am trying to do: Make a docker upload of an existing heroku app. -The error that occurs:**** failed to solve with frontend dockerfile.v0: failed to read dockerfile: open /var/lib/docker/tmp/buildkit-mount649479195/Dockerfile: no such file or directory -What I have tried: Ensuring docker file is where my manage.py file is and ensuring it has the title Dockerfile. -My set up: I have a django project in a folder on on my desktop. The folder is called site1. In the folder is all the django files. Including my manage.py and Dockerfile I have created. My heroku app is called: tactilefire. My django app is called site1app. My docker file consists of: FROM python:3.8 ADD . /site1/ WORKDIR /site1 RUN apt-get update RUN apt-get install -y pandoc RUN apt-get install -y texlive-fonts-recommended RUN pip install --upgrade pip RUN pip install -r requirements.txt RUN python manage.py makemigrations && python manage.py migrate CMD gunicorn --bind 0.0.0.0:$PORT site1.wsgi so when I try build my docker i get the error. Any ideas? there must be something wrong with my set up? -
Can I make a Django mixin that adds context variables just before template render?
I have a Django application that uses a JSON API as its data source. Here's a simplified example of use in one of my views.py: class GroupsList(LoginRequiredMixin): def get(self, request, **kwargs): # Get file list and totals try: group_list = group_adapter.list() # makes an API call and ALSO populates a meta info class except APIAccessForbidden: return HttpResponseRedirect(reverse('logout')) return render(request, 'groups/index.html', { # can I make a mixin to add data here gained from the API call? 'group_list': group_list, }) This line: The group_adapter.list() call populates some meta information into another class, that's not related to the group_list itself. I'd like to pass that data to the template. Ordinarily I'd use a context_processor, but when the context processor is called, the API call hasn't been made yet. I could manually check the information and add it to the render() method, but then I'd need to do that in dozens of different views. Can I use a mixin here that adds this information to context AFTER the view code runs but BEFORE render passes information to the template? In other words is there a way to do this: class GroupsList(LoginRequiredMixin, RenderMetaInfoMixin): and then create a mixin something like this? class RenderMetaInfoMixin: def … -
Django reverse_lazy improperly configured
Under my once my user has signed up I would like to redirect them to the login page. However, reverse_lazy doesn't seem to be able to find my login path. views.py from django.shortcuts import render from django.urls import reverse_lazy from django.views.generic import CreateView from . import forms # Create your views here. class SignUpView(CreateView): form_class = forms.UserCreateForm template_name = 'accounts/signup.html' #Redirect login page once they have successfully signed up succes_url = reverse_lazy('login') urls.py from django.urls import path from django.contrib.auth import views as auth_views from . import views app_name = 'accounts' urlpatterns = [ path('login/', auth_views.LoginView.as_view(template_name='accounts/login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(template_name='accounts/logout.html'), name='logout'), path('signup/', views.SignUpView.as_view(template_name='accounts/signup.html'), name='signup'), ] -
I have set of regex patterns stored in database and i want to get loop in it and apply to re.search() using Django rest frameworks and return json
document = """teams and customers Microsoft cloud Background Check: this position wil be required to pass the microsoft cloud Background check upon""" dictionaries = Dictionary.objects.all() #retrive patterns from db for d in dictionaries: x = str(getattr(d, 'word')) result = re.search(x,document) # always have some error 'NoneType' object has no attribute context.append({'start': result.start(), 'end': result.end(), 'text': result.group(0), 'label': x}) return Response({'text': document, 'Annotations': context}) -
can you combine functions in views.py using django?
I have two functions in my views.py def example1(request) return render(request, 'example1.html') def example2(request) return render(request, 'example2.html') I am curious if there is a feature django supports that allows me to better group these functions without being redundant? -
Make boxes wider in django
I am currently doing a website and i'm using django all-auth for all the authentication. Anyways, It all works perfectly, but I'd like to know if there's any way to make the username and password boxes bigger using html. Here's the code I've used: <div class="p-t-31 p-b-9"> <div class="col-lg-40"> {{ form | crispy }} </div> </div> And the image of the template in case you need a reference: -
How do I initialize my admin Class from a "custom django-admin command"?
I have functions in my admin Class that I'd like to perform on a regular basis (every 10 minutes). I am trying to use the "custom django-admin commands" solution ( https://docs.djangoproject.com/en/3.1/howto/custom-management-commands/#howto-custom-management-commands ) and will use a cron job to run it. I do have the custom command working with test code, however I am running into a few issues: I'm not sure how to initialize the class (I get errors such as "missing 1 required positional argument"). If I skip instantiation I can call the functions explicitly, but then I run into these next two problems. I'm used to calling internal Admin class functions using "self.functionname()". But 'self' doesn't work when called from my custom management command. Many of my admin functions use the standard 'request' argument; however I don't have a 'request' from my custom management command. These code snippets are paraphrased from the originals. polls/management/commands/performTasks.py from django.core.management.base import BaseCommand, CommandError from polls.models import Question from polls.admin import QuestionAdmin class Command(BaseCommand): help = 'Starts the process.' def handle(self, *args, **options): QuestionAdmin.tasks(self, 'YES') # The following 2 lines I simply use to prove a successful query: myqueryset = Question.objects.filter(author="Tolkien") print(myqueryset) admin.py from django.contrib import admin from .models import Question from … -
How to pass arguments to a function in for loop Jinja DJANGo
How can I pass an argument to a function in for loop? I use Django and jinja and I want to somehow pass an argument to my function but I don't know whether it is possible, didn't find any pieces of information online {% for student in get_students%} <tr> <td>User.name</td> {% for colum in get_columns %} {% for grade in colum.get_grade_by_user(student.id) %} <=== like that <td>{{grade.value}}</td> {% endfor %} {% endfor %} </tr> {% endfor %} def get_grade_by_user(self, student): get_grade = Grade.objects.all().filter(date=self.id, user=student) return get_grade -
Wagtail - TypeError from get_context when attempting to view reports or page history
I'm running into the error get_context() missing 2 required positional arguments: 'value' and 'attrs' when attempting to view any report or open the history of any page from the Wagtail admin. Traceback (most recent call last): File "/var/task/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/var/task/django/core/handlers/base.py", line 145, in _get_response response = self.process_exception_by_middleware(e, request) File "/var/task/django/core/handlers/base.py", line 143, in _get_response response = response.render() File "/var/task/wagtail/admin/auth.py", line 187, in overridden_render return render() File "/var/task/django/template/response.py", line 105, in render self.content = self.rendered_content File "/var/task/django/template/response.py", line 83, in rendered_content return template.render(context, self._request) File "/var/task/django/template/backends/django.py", line 61, in render return self.template.render(context) File "/var/task/django/template/base.py", line 171, in render return self._render(context) File "/var/task/django/template/base.py", line 163, in _render return self.nodelist.render(context) File "/var/task/django/template/base.py", line 936, in render bit = node.render_annotated(context) File "/var/task/django/template/base.py", line 903, in render_annotated return self.render(context) File "/var/task/django/template/loader_tags.py", line 150, in render return compiled_parent._render(context) File "/var/task/django/template/base.py", line 163, in _render return self.nodelist.render(context) File "/var/task/django/template/base.py", line 936, in render bit = node.render_annotated(context) File "/var/task/django/template/base.py", line 903, in render_annotated return self.render(context) File "/var/task/django/template/loader_tags.py", line 150, in render return compiled_parent._render(context) File "/var/task/django/template/base.py", line 163, in _render return self.nodelist.render(context) File "/var/task/django/template/base.py", line 936, in render bit = node.render_annotated(context) File "/var/task/django/template/base.py", line 903, in render_annotated return self.render(context) File "/var/task/django/template/loader_tags.py", line … -
How can I start localizing a Web App that wasn't designed with localization in mind (how can I find localizable strings)?
I am working on a large web application. It has components in both Django and in Angular.js. Our team was recently asked to evaluate the effort it would require to localize the app in French Canadian. Unfortunately, this app is several years old, and it was not designed with localization in mind (e.g., hard-coded strings everywhere). I've done some research, and I've found several best-practices for designing new, localizable apps, but little on transitioning an existing app. Our primary task is to collect a list of all of the localizable strings. Is there any way to automate this process? I thought something like a regex to find all hardcoded strings in html files would be a good start, although it sounds like that may be the wrong path. Any help would be greatly appreciated! -
Having a problem with the generic template module in Django that won't allow me to run the live server
I am trying to learn Django by doing the app on their documentation page, but I have came across an error with the generic templates that I can't figure out at all. Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib/python3.8/threading.py", line 932, in _bootstrap_inner self.run() File "/usr/lib/python3.8/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/home/andrei/.local/lib/python3.8/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/home/andrei/.local/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "/home/andrei/.local/lib/python3.8/site-packages/django/core/management/base.py", line 392, in check all_issues = checks.run_checks( File "/home/andrei/.local/lib/python3.8/site-packages/django/core/checks/registry.py", line 70, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/home/andrei/.local/lib/python3.8/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/home/andrei/.local/lib/python3.8/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/home/andrei/.local/lib/python3.8/site-packages/django/urls/resolvers.py", line 408, in check for pattern in self.url_patterns: File "/home/andrei/.local/lib/python3.8/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/andrei/.local/lib/python3.8/site-packages/django/urls/resolvers.py", line 589, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/home/andrei/.local/lib/python3.8/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/andrei/.local/lib/python3.8/site-packages/django/urls/resolvers.py", line 582, in urlconf_module return import_module(self.urlconf_name) File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, … -
How to Combine Django 3.0 Dynamic PDF Template view along with a PDF File Dynamically
I am using Django 3.0 and in my two function the first one will generate the bill dynamically rendering an object into an HTML page and the other function will just response with a FileResponse. I am trying to combine trying to these two PDF's into one PDF in the view function. def MyPDF(request, id): bill = get_object_or_404(bill, id=id) response = HttpResponse(content_type="application/pdf") response['Content-Disposition'] = "inline; filename={name}.pdf".format(name=slugify(bill.title).upper()) html = render_to_string("PDFBill.html", {'object': bill, }) font_config = FontConfiguration() HTML(string=html).write_pdf(response, font_config=font_config) return response def BillAttachment(request, id ): object = get_object_or_404(bill, id=id) response = HttpResponse(content_type="application/pdf") response.content = object.file.read() response["Content-Disposition"] = "inline; filename={0}.pdf".format(object.title) return response -
Only allow calls to endpoint from frontend Django Rest Framework
I am new to Django Rest Framework. My API is used in 2 ways: I have a React frontend As a normal REST API returning JSON However, I don't want the endpoints called for my frontend to be able to be called in the normal REST API. Specifically, I want those endpoints to only be able to be reached when called from my frontend React app. How can I do this? Thanks! -
I am unable to import Static Files in Django website. Any on please explain what i am missing in code?
I am facing issue while loading static files in the project. I have created the folder named as static, added (JS,CSS and Image files to the folder). I have provided the path in settings.py file. Please any one explain me that what i am missing and where i have to do modifications. STATIC_URL = "/static/" STATICFILES_DIR = [os.path.join(BASE_DIR, "static")] LOGIN_URL = "account:login" LOGIN_REDIRECT_URL = "public:index" LOGOUT_REDIRECT_URL = "public:index" Installed Apps: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'website.apps.accounts',] -
How to remove specific fields from the django User Model?
From the Django User Model, I'd like to remove some fields such as 'first_name', 'last_name', 'email', 'date_joined'. I want no changes in the Auth system of the User Model, i.e. I still want authentication to be done using the username. I just want to remove some unrequired fields. Will I need to extend the AbstractBaseUser model for this, or can this be achieved just by extending the AbstractUser model? Or is there any other way also to do this ? Thanks in advance ! -
Queryset in django admin action is always empty
I wrote an action that is supposed update a field in every record selected by the user according to this document. The problem is that queryset is always empty and thus, no changes take place. def SendCommandAction(self, request, queryset): print(self._Command) commandStatus = { 'Command':self._Command, 'Fetched':False } print(queryset) #output from console: <QuerySet []> updated = queryset.update(Command_Status = commandStatus,) self.message_user(request, ngettext( '%d record was successfully updated.', '%d records were successfully updated.', updated, ) % updated, messages.SUCCESS) After I select records and hit "Go" button this message appeares: 0 records were successfully updated. -
What is the best way to handle multiple clients payment setups? [closed]
Which method is the most clever and professional when first setting up and then handling multiple clients payment services in web-applications? I'm thinking about something like a developer part of the service which doesn't give access to payments and such information. Stripe has a service for platforms and marketplaces but that doesn't seem to be what I'm looking for. I want to use Django as back-end. How should I proceed? Thanks! -
Django Need 2 values to unpack in for loop; got 1
I have looked for other answers but cannot get this one working. I have model "Sitting" with a field "user_answers" which stores a dictionary {"437": "1574", "319": "hi", "383": "1428", "424": "1528", "203": "785"} When I do {% for key, value in sitting %} <p> {{key}}--{{value}} </p> <p> {{question.id}}--{{answer.id}} </p> {% ifequal key question.id %} {% ifequal value answer.id %} <li class="list-group-item quiz-answers" > <span><label for="id_answers_0"><input type="radio" name="answers_{{question.id}}" value="{{answer.id}}" style="margin-right:10px;" id="{{answer.id}}" selected required> {{answer.content}} </label> </span></li> {% else %} <li class="list-group-item quiz-answers" > <span><label for="id_answers_0"><input type="radio" name="answers_{{question.id}}" value="{{answer.id}}" style="margin-right:10px;" id="{{answer.id}}" required> {{answer.content}} </label> </span></li> {% endifequal %} {% endifequal %} {% endfor %} I get the error Need 2 values to unpack in for loop; got 1. How can I compare the values so I can select the radio if the key and value matches the question and answer? -
Howto show a filterd list in admin ForeignKey combo box
i have 2 models like bellow. class Student(model.Models): SEX = ( ('MALE', 'MALE'), ('FEMALE', 'FEMALE'), ) name = models.CharField(max_length=25) sex = models.CharField(max_length=6, choices=SEX) class Netball (models.Model): position = models.CharField(max_length=25) student = models.ForeignKey(Student) in the admin Netball insert page under student combo-box i want only to display FEMALE student how can i do this. is their is any override method ? -
Django ValueError Can only compare identically-labeled Series objects
i am getting this error. one df dataframe is read from json API and second df2 is read from csv i want to compare one column of csv to API and then matched value to save into new csv. can anyone help me df2=pd.read_csv(file_path) r = requests.get('https://data.ct.gov/resource/6tja-6vdt.json') df = pd.DataFrame(r.json()) df['verified'] = np.where(df['salespersoncredential'] == df2['salespersoncredential'],'True', 'False') print(df) -
Django media image displays blank box
Hi I'm trying to display an uploaded user image in django but when I try to display it only a blank box appears. However when I click on the image it brings up a new page with the image. I don't know why it isn't displaying on the page. html {% load mptt_tags %} {% recursetree location %} <div class="card"> <div class="card-body"> <a class="btn btn-primary" type="button" href="/AddClimb/{{node.id}}">Add Climb</a> </div> </div> <a href="{{ node.img.url }}"><img source="{{node.img.url}}" width="500" height="400"></a> <div class="container"> <div class="row equal"> <div class="col-md-6 col-sm-6"> <div class="card-header bg-primary text-white text-center">{{ node.name }}</div> <div class="card" style="background-color: #eee;"> <p class="font-weight-bold">Image: <img source="{{node.img.url}}"></p> <p class="font-weight-bold">Description: <span class="font-weight-normal">{{node.description}}</span></p> <p class="font-weight-bold">Directions: <span class="font-weight-normal">{{node.directions}}</span></p> <p class="font-weight-bold">Elevation: <span class="font-weight-normal">{{node.elevation}}</span></p> <p class="font-weight-bold">Latitude: <span class="font-weight-normal">{{node.latitude}}</span></p> <p class="font-weight-bold">Longitude: <span class="font-weight-normal">{{node.longitude}}</span></p> <p class="font-weight-bold">Added By: <span class="font-weight-normal">{{node.author}}</span></p> <p class="font-weight-bold">Date Added: <span class="font-weight-normal">{{node.date}}</span></p> <a class="btn btn-primary float-center" type="button" href="/EditLocation/{{node.id}}/">Edit Location</a> </div> </div> {% endrecursetree %} settings.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'Choss_App/media') urls.py from django.conf.urls import url from django.contrib import admin from django.urls import include, path from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('Choss_App.urls')), ] # if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
How to retrieve files from Django FileSystemStorage uploaded in a multisteps form using formtools wizard
I am using Django 3.0 and python 3.8.2 to develop an ads website. To add a post, I used Django formtools wizard. It worked and everything goes nicely. I could save the multiform data. However, I could not retrieve the files from the FileSystemStorage so I can save them. Hence, any help to achieve this or suggestion is much appreciated. I want to retrieve uploaded files, save them to the data base and then delete them from the wizard (from the FileSystemStorage). Note: there is no error and everything is working except that the uploaded files are not saved to the data base even though they are available in the FileSystemStorage. Thus, I want to retrieve them to be able to save them to the data base. Here is the view class: class PostWizard(SessionWizardView): # The form wizard itself; will not be called directly by urls.py, # but rather wrapped in a function that provide the condition_dictionary _condition_dict = { # a dictionary with key=step, value=callable function that return True to show step and False to not "CommonForm": True, # callable function that says to always show this step "JobForm": select_second_step, # conditional callable for verifying whether to show step … -
In custom registration form, how to fetch data from phpmyadmin database in django
I have made custom registration form in django. To register users, I need user's country, state, city that I have to fetch from phpmyadmin database (in dependent dropdown menu). How to integrate user's country, state and city from phpmyadmin database to custom django form??