Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django filter objects foreign key from another table
Two tables: post and rating. rating contains column - post (FK) that is post table's primary ID. I'm trying to filter table rating by columns user and ratingtype to get post (FK) value that I could use to filter post table by. Post.objects.filter(pk__in=Rating.objects.get(post=post).filter(Rating.objects.filter(user = self.request.user, ratingtype='like'))) -
getting queryset based on attributes from manytomanyfield in referenced object
I have the following models: class ModelOne(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) class ModelTwo(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) is_visible = models.BooleanField(default=False) modelones = models.ManyToManyField(ModelOne, blank=True) In a view, I want to get a queryset of ModelOnes based on attributes of ModelTwo. For instance, how might I get a queryset of ModelOnes that have a ModelTwo with is_visible set to True referencing them? To provide an example: one_one = ModelOne.objects.create() one_two = ModelOne.objects.create() two_one = ModelTwo.objects.create() two_two = ModelTwo.objects.create(is_visible=True) two_three = ModelTwo.objects.create() two_two.modelones.add(one_one) two_two.save() two_three.modelones.add(one_two) two_three.save() queryset = [????] queryset would only contain one_one because two_two has a reference to one_one and also has is_visible True. -
Django: NOT NULL constraint failed: wishlist_wish.user_id
I have a wishlist app with a custom user model. I added the user as the foreign key to each wishlist item. However, I am only able to add the foreign key by specifying a default user, even after deleting the existing db files and running makemigrations and migrate. The default user is associated with the wishlist item regardless of which user is logged in, and if I don't include a default user I get the "NOT NULL constraint failed: wishlist_wish.user_id" error. How can I update the code so that the wishlist item is associated with the logged-in user creating the item? A related question is whether I need to include a user id in my custom user model? I tried doing this as well and ran into the same problem. Thanks in advance. Wish Model: class Wish(models.Model): name = models.TextField() user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default=1) def __str__(self): return self.name Wish View: def add_wish(request): user = request.user wishes = Wish.objects.filter(user=request.user) if request.method == 'POST': form = WishForm(request.POST) if form.is_valid(): form.save() return redirect('home') else: form = WishForm() context = {'form' : form, 'wishes' : wishes} return render(request, 'wishlist/add_wish.html', context) Wish Form: class WishForm(ModelForm): class Meta: model = Wish fields = ('name', … -
(gcloud.app.deploy) Error Response: [9] Cloud build 3913ab4b-4a10-4205-8d84-a0a809bfab00 status: FAILURE
CLI ERROR when deploying strong text -
How can I fix my Django model to store multiple lists of strings inputted by the user. Which can then be retrieved in the future as an object?
I'm trying to make this simple app that retrieves a list of string(s) entered by the user, which is then stored in an object. The idea is for users to create a list of movies for each of their favorite genres. A "user-created-dictionary" sort of speak... Like so in Python: UserMovies = { Scary : ['A','B','C'], Funny : ['D'], Sad : ['E','F], Thriller : ['G','H','I','J'] } Using the example above, the ideal Model.py would store user created dictionary keys, followed by storing values for keys, in a list. I'm trying to replicate the same in my Django model, but I'm not sure how to create a many-to-many relationship that stores data in a list. Here is the syntax I'm trying to follow from django.db import models, UserModel class Genres(models.Model): user = model.UserModel(UserModel.username) genres = models.CharField(max_length=1000) class Movies(models.Model): genres = models.ForeignKey(genres, on_delete=models.CASCADE) title = models.TextChoices(max_length=1000, choices = IMDBmoviesTuple) What I'm striving for is being able to store the genres for each user, including the movies within the genres. All of this being a CRUD app. Given the info, what would be the best way to structure the model? currently struggling with this one. -
Django is only extending the base.html template in 1 html file
I run into an extremely annoying problem that no one has nearly a solution for. I've lost hours on it and unfortunately I can't get it working. This is the problem: I am trying to extend a base.html file into 2 different html files. For some reason it is possible to extend it in home.html but not in pakbon.html. Below you can see my folder structure (It also doesn't work if I put the files into the same folder): Below you can see my urls.py: urlpatterns = [ path("", views.home, name="home"), path("pakbon/", views.pakbon, name="pakbon") ] Below you can see my views.py: def index(request): return render(request, "main/base.html", {}) @login_required def home(request): return render(request, "main/home.html", {}) def pakbon(request): return render(request, "pakbonsysteem/pakbon.html", {}) My base.html: <html lang="en"> <head> --- Some HTML </head> <body data-background-color="{{info.mode}}"> --- Some HTML {% endfor %} {% if user.is_authenticated %} {% block content %} {% endblock %} {% else %} <meta http-equiv="refresh" content="0; url=/login"> {% endif %} </body> </html> My home.html: {% extends 'main/base.html' %} {% block content %} --- Some HTML {% endblock %} My pakbon.html: {% extends 'main/base.html' %} {% block content %} --- Some HTML code {% endblock %} Image from home.html: Image from pakbon.html: They … -
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!