Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to update a wagtail UserProfile avatar (or other fields) alongside other CustomUser fields into one django form
I'm using Django and Wagtail to build a webapp. This webapp will be used by a group of members in which some will have admin permissions and most will not. I created a custom user model like so: class User(AbstractUser): bio = models.TextField( verbose_name=_("bio"), blank=True, help_text=_("Write a bit about yourself"), ) phone = PhoneNumberField( verbose_name=_("phone number"), blank=True, ) street_address = models.CharField( verbose_name=_("street address"), max_length=150, blank=True, ) city = models.CharField( verbose_name=_("city"), max_length=50, blank=True, ) I would like to leverage some fields that are provided by wagtail.users.models.UserProfile (as seen in https://github.com/wagtail/wagtail/blob/main/wagtail/users/models.py), like the avatar field, preferred_language field, etc for my own use. I know I can access those fields in my templates using user.wagtail_userprofile.avatar etc. What I'm looking to achieve, is to have a UserUpdateView that can update my User model, including some fields from wagtail.users.models.UserProfile into the same form, but I dont see how to do this. Regards! -
How can I quickly upload JSON data as a Django Model
for my project i will need to have a large food database. I'm planning to use USDA API witch returns data as JSON. Now when I'll pass the url with restricions about what nutrients I want to have that will correspond to fields in my Django model I'll save the data to a JSON file. Now here's my question, how can I quickly pass all that data to create database table in Django? My model: class Fruit(models.Model): name = models.CharField(max_length=255) calories = models.DecimalField(decimal_places=2, max_digits=5,blank=False, null=False) ... API url https://api.nal.usda.gov/fdc/v1/food/1750339?nutrients=203&nutrients=204&nutrients=205&api_key=DEMO_KEY Returned data (not all) { "fdcId":1750339, "description":"Apples, red delicious, with skin, raw", "publicationDate":"10/30/2020", "foodNutrients":{ "type":"FoodNutrient", "nutrient":{ "id":1003, "number":"203", "name":"Protein", "rank":600, "unitName":"g" }, "foodNutrientDerivation":{ "id":49, "code":"NC", "description":"Calculated", "foodNutrientSource":{ "id":2, "code":"4", "description":"Calculated or imputed" } }, "id":21115516, "amount":0.18750000, "max":0.25000000, "min":0.12500000, "median":0.18750000, "nutrientAnalysisDetails":[ ] } } My JSON file { "name": '', "calories": '', "protein": '', ... } I'm working on a python script for fetching data and stripping all the unnecessary fields but in the meantime I would like to hear from you how can I quickly transform my JSON file into Django model and save it to database. Is there maybe a django library for doing this? Or some method in manage.py … -
failed to connect to server aws
I don't know why I failed migrate my database to aws , I am putting everything right but where is the problem I really don't know django.db.utils.OperationalError: connection to server at "hereendpoint", port 5432 failed: Connection timed out (0x0000274C/10060) Is the server running on that host and accepting TCP/IP connections?``` -
Simplest django setup
I want to use django for a very simple project, basically a local project to navigate directories, and I'm basically just using it for its template language and ORM. I was wondering if I could do it all in a one-file setup as follows: manage.py (includes everything except html) main.html This approach works for everything minus loading django.models, which I think assumes a settings file is already imported before calling it. Here is what I have so far: #!/usr/bin/env python import os, sys from django.core.management import execute_from_command_line from django.conf.urls import patterns, url ### Settings os.environ.setdefault("DJANGO_SETTINGS_MODULE", "manage") ROOT_URLCONF = 'manage' TEMPLATE_DIRS = '.' DEBUG = True DATABASES={'default':{'ENGINE':'django.db.backends.mysql','NAME':'bookmarks','USER':'root','PASSWORD':'','HOST':'','PORT':'',}} urlpatterns = patterns('', url(r'^$', 'manage.main', name='main'),) ### Views def main(request): from django.shortcuts import render return render(request, 'main.html', {'hello': "Hello"}) ### Models # from django.db import models <-- everything works except this line # class Tag(models.Model): # name = models.CharField(max_length=30, primary_key=True) if __name__ == "__main__": execute_from_command_line(sys.argv) The error message I get is: File ".../django/db/init.py", line 11, in if DEFAULT_DB_ALIAS not in settings.DATABASES: Is there a simple way to get everything in one file? -
Django cannot connect to MySQL RDS server
GOAL Connecting EC2 Django API to RDS Architecture AWS VPC has two subnets 1 private with the RDS instance 1 public with my two EC2 servers Main server: Hosts Django API connected to an internet gateway Bastion server: Only authenticated SSH connections allowed, used for admin purposes on RDS instance Background I have established a successful connection on MySQL Workbench. SSH connection to EC2 server, then a connection to a MySQL RDS host is established. I am able to perform all C.R.U.D with this connection. When I try and recreate this process manually on the command line, I can’t. I SSH to the EC2 server then try and connect to the RDS with SSH to MySQL at the same endpoint, user, port, and password but it fails. When I try and run my Django server on the remove EC2 it also fails. I have the user, endpoint and password saved as environment variables. When I launch the Django Server it says connection failed. This is frustrating since I am almost certain my AWS VPCs are configured correctly because I am able to connect via MySQL workbench, but when I try and connect manually or with Django, it does not work. … -
Annotate quering, pk
I have ask, How should i querying when i use pk with annotate? I need redirect to user profile when a guest click in link. Models class Posty(models.Model): title = models.CharField(max_length=250, blank=False, null=False, unique=True) sub_title = models.SlugField(max_length=250, blank=False, null=False, unique=True) content = models.TextField(max_length=250, blank=False, null=False) image = models.ImageField(default="avatar.png",upload_to="images", validators=[FileExtensionValidator(['png','jpg','jpeg'])]) author = models.ForeignKey(Profil, on_delete=models.CASCADE) updated = models.DateTimeField(auto_now=True) published = models.DateTimeField(auto_now_add=True) T_or_F = models.BooleanField(default=False) likes = models.ManyToManyField(Profil, related_name='liked') unlikes = models.ManyToManyField(Profil, related_name='unlikes') created_tags = models.ForeignKey('Tags', blank=True, null=True, related_name='tagi', on_delete=models.CASCADE) class CommentPost(models.Model): user = models.ForeignKey(Profil, on_delete=models.CASCADE) post = models.ForeignKey(Posty, on_delete=models.CASCADE, related_name="comments") content1 = models.TextField(max_length=250, blank=False, null=False) date_posted = models.DateTimeField(default=timezone.now) date_updated = models.DateTimeField(auto_now=True) def __str__(self): return str(self.content1) Views if tag == None: my_tag = Posty.objects.annotate( latest_comment = Subquery(CommentPost.objects.filter(post=OuterRef('id')).values('content1').order_by('-date_posted')[:1]), my_author=Subquery(CommentPost.objects.filter(post=OuterRef('id')).values('user__user__username').order_by('-date_posted')[:1]), ) I got a correct username, but i cant got a correct redirect -
Two (Almost) Identacle Veiw.py Functions Behaving Differently
So, I am developing a cart system for an e-commerce website using Django. There are two separate functions for handling adding and removing cart items. (No I can't consolidate them into one function without changing my database and template structure) The first function, 'update_cart' is working just fine. It properly updates the appropriate model. However, the second function 'remove_item' is triggered when the user clicks the 'remove' button in the item list, and the function does in fact execute and redirect properly. However, it fails to update the many-to-many, foreign key-identified model object associated with the item. It's so weird because I'm accessing the object the same way in both functions. The only difference is that in the first uses .add() and the second .remove(). Also, the template is supposed to load the product's id into the GET data but doesn't show it in the URL like with the other template that triggers the 'update_cart' function. But it does show the mycart/?id=86 when the cursor is hovering over the button. (this is a chrome feature). It's very confusing. Can you guys help me to see what I am overlooking? Thanks for your time. :) view.py functions: def update_cart(request): context={} if … -
Django shell get models object function does not work any ideas?
i have tried to look at the django documentation but cant find what i am looking for. I have a django models, and in this model i have defined som logic, the problem is that i cant get the value when i try fetching the recepie through django shell. I want to se if the def recepie_status is working. My model: class Recepie(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=60, null=False, blank=True, verbose_name='Recepie name') description = models.TextField(max_length=500, null=True, blank=True, verbose_name='Description') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) # slug = models.SlugField(max_length=255, verbose_name=_('Recepie Slug'), default=name) share = models.BooleanField(null=True, blank=True) def recepie_status(self): import datetime import date, timedelta, datetime status=(date.today()-timedelta(days=15)) if self.created_at > status: return "New" else: return "Old" i have done this in the django shell: >>> one = Recepie.objects.get(pk=1) >>> print (one.name) #this works >>> from datetime import timedelta, date, datetime >>> print (one.recepie_status()) throws this error in the django shell E:\Projekt\Fooders\fooders\recepies\models.py in recepie_status(self) 18 19 def recepie_status(self): 20 status=(date.today()-timedelta(days=15)) 21 if self.created_at > status: 22 return "New" ModuleNotFoundError: No module named 'date' -
Django Prevent that everyone can see /media Files
on my nginx server if people are using the /media path they can see a list of the whole folder with every file. How can I block that the people are seeing that, like with a 404 page. But I cant disable it in general because I refer to that path with images and stuff on other pages. So in conclusion I need to disable /media path for users but not for the server itself. I'm using django. Greetings and thanks for your help -
Adding 'graphene_django' in INSTALLED_APPS = [ 'graphene_django' ] of the settings.py file makes the django project to crush
Adding 'graphene_django' in INSTALLED_APPS = [ 'graphene_django' ] makes the django project makes the server to crush INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'graphene_django', "ingredients", ] Here is the error that appears from django.utils.encoding import force_text ImportError: cannot import name 'force_text' from 'django.utils.encoding' (/usr/local/lib/python3.9/site-packages/django/utils/encoding.py) -
How Can I Filter By Date Range Using Djangos Built in ListView?
I'm quite new to Django and everywhere I look seems to offer a solution that works for generic function based views, or really overcomplicates what i'm trying to do with a class based view. All I want to do is to filter out the results from a ListView to only include entries from a selected date range. For example I have a generic Class based view: class HomeView(ListView): model = Post template_name = 'home.html' that returns all of my blog posts and a very simple date selector on my home.html page: From date: <input type="date" name="fromdate"/> To Date: <input type="date" name="todate"/> <input type="submit" value="search"/> How can I take the input from the simple date range and alter my class based view to: IF a date range has been selected: only show posts from within that date range? Thank you in advance. I have checked and I can not see anywhere that has answered this on here that uses ListView or that doesn't overcomplicate the problem and become close to impossible to follow for a beginner Thank you -
unable to add model in custom context processor django
In my django project, I need to pass certain details from couple of models to all the views and realized that the best way to do this would be create a custom context processor file. the context processor works fine when passing harcoded values but throws django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. when trying to import model in the context processor file. project structure: accounts_engine | migrations | admin.py | apps.py | custom_processor.py | forms.py | models.py | tests.py | urls.py | views.py models.py class Role(models.Model): name = models.CharField(max_length=200) settings.py from accounts_engine import custom_processor TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'accounts_engine.custom_processor.general_details', ], }, }, ] accounts_engine/custom_processor.py def general_details(request): return {'some_key1': 'some_value1', 'some_key2': 'some_value2'} this works fine but fails when I import account_engine.models.py here -
i have Django suit problem in install as decumentation
i have a problem when installing django suit by site documentation as steps first:- WARNING: You are using pip version 20.2.3; however, version 21.3.1 is available. You should consider upgrading via the 'f:\web-devolopment\python\django\venv1\scripts\python.exe -m pip install --upgrade pip' command. second :- and I am adding the code in ENSTALLED_APP third:- when import the library like ( from suit.apps import DjangoSuitConfig ) I have wavy line under from suit.apps import DjangoSuitConfig so the problem in install the library not working who can fix it . thank you -
Django URL with parameter not working with include
I am trying to pass a parameter to a url before my include statement. I think my problem should be similar to this one, but I can't figure out why mine isn't working. I get the error NoReverseMatch at /womens/ Reverse for 'shampoo' with arguments '('womens',)' not found. 1 pattern(s) tried: ['(?P<gender>womens|mens)/items/shampoo/$'] *config.urls* urlpatterns = [ re_path(r'(?P<gender>womens|mens)/items/$, include('items.urls')), ... ] *items.urls* urlpatterns = [ path('shampoo', views.shampoo, name='shampoo'), path('soap', views.soap, name='soap'), ... ] {% url 'items:shampoo' gender='male' %} I expect to get male/items/shampoo, but it doesn't work. Despite this, I can still manually go to male/items/shampoo. -
how to filter many-to-many fields in django models
I have 3 models: User , Tag and Recipe. User model is so basic and it's not important. Here is the Tag model: class Tag(models.Model): name = models.CharField(max_length=255) user = models.ForeignKey(settings.AUTH_USER_MODEL , on_delete=CASCADE) And here is the Recipe model: class Recipe(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL , on_delete=CASCADE) title = models.CharField(max_length=255) tags = models.ManyToManyField('Tag',) I made endpoint for all of these models but there is one problem! When I try to create a Recipe object, all of Tag objects will be listed, But I want to list just the logged in user tags. Here is my Tag serializer: class TagSerializer(serializers.ModelSerializer): class Meta: model = models.Tag fields = ('id' , 'name') extra_kwargs = { 'id' : { 'read_only' : True, } } And here is my Tag viewset: class TagsView(RecipeAttrsView): queryset = models.Tag.objects.all() serializer_class = serializers.TagSerializer authentication_classes = (authentication.TokenAuthentication,) permission_classes = (permissions.IsAuthenticated,) def get_queryset(self): return self.queryset.filter(user=self.request.user) def perform_create(self, serializer): serializer.save(user=self.request.user) How can I filter tags, so that all listed tag objects belong to the logged in user? -
Calling a function from a function
I have some logic within a view that I want to have rendered on multiple templates. How do I call the logic view from within another view and pass the data back to the view to be rendered? This is a simple test I was doing. def table_view(request): today = now().date() project_data = get_data_view context = {'projects_data':project_data} return render(request, "pages/project_table.html", context=context) def get_data_view(request): project_list = Project.objects.all() context = {"project_list":project_list} return {'context':context} The table view just renders a table, but the data within the table I want from the get_data_view I know I can write the logic within the same view, but some of my views contain a lot of code and don't want to be repeating the same code to retrieve the same data. -
ERROR: django.template.exceptions.TemplateSyntaxError: Invalid block tag on line 47: 'else'. Did you forget to register or load this tag?
How to solve problem How to solve problem How to solve problem -
How can I supress this type error from Django create_user?
I'm getting the following type error from pylance: from django.contrib.auth.models import User, AbstractUser from django.contrib.auth import get_user_model get_user_model().objects.create_user(**user_data) # ^- Cannot access member "create_user" for type "BaseManager[Any]" # Member "create_user" is unknown Pylance reportGeneralTypeIssues # User.objects.create_user(**user_data) # same error # AbstractUser.objects.create_user(**user_data) # same error For some reason it thinks AbstractUser.objects has a broader type BaseManager[Any] instead of UserManager, even though AbstractUser defines objects = UserManager(). The code works without errors when tested. Does anyone know how I can supress or get rid of this sort of type error? -
Populate drop down from a database column without repetition - Django
am learning Django while building Hostel booking application. I want the drop down list found in index.html to be populated from a database column called "location". I would like to retrieve the second elements (the human-readable names) without repetitions. So far I have tried as shown in the codes below but I am getting repetitions whenever I have many hostels sharing the same location. I understand to obtain the list of distinct column names from the database is to use distinct() in conjunction with values(). But how do I use distinct() with get_FOO_display() at the same time to get distinct columns as well as the second elements of the tuples. Or is there another approach I should take? models.py HOST_LOCATION=[('KM', 'Kings Main Campus'), ('KT', 'Kings Town Campus'), ('KK', 'Kings Kitale Campus'), ('KE', 'Kings Eldoret Branch')] class Hostel(models.Model): name = models.CharField(max_length=100) slug = models.SlugField(null=False, unique=True, blank=True) location = models.CharField(max_length=50, choices=HOST_LOCATION, default=None, null=False) landlord = models.ForeignKey(User, on_delete=models.CASCADE, default=None) def __str__(self): return self.name Views.py def index(request): Host = Hostel.objects.all() return render(request, 'index.html', {'Host': Host}) Template <select class="custom-select" id="inputGroupSelect04"> <option selected disabled> SELECT A CAMPUS TO FIND HOSTEL</option> {% for entry in Host %} <option value="{{ entry.id }}">{{ entry.get_location_display }}</option> {% endfor %} </select> -
Django - Return months that posts by a user spans given time offset from UTC
I'm working on a social media app and I want user A to be able to get all the months that user B posted in user A's time zone. The front-end is in Javascript the most sensible thing would be for a user to send their time zone's offset from UTC (Can be done with new Date().getTimezoneOffset() in JS) as this is what time zone dates are saved in Django. So for example user A would ping a url that looks something like /<user B's username>/<year>/<user A's time zone offset from UTC>. Let's say user B is in PST and created a post at November 15 2021 12:00pm and December 31 2021 at 11:00pm. Then let's say user A who's in EST calls that url then it should return [November, January] (Or the equivalent numerical mapping), because December 31 at 11:00pm PST is January 1st at 2:00am EST. How can I return all months user B posted in user A's time zone, give user A's time zone offset from UTC? models.py class Post(models.Model): uuid = models.UUIDField(primary_key=True) created = models.DateTimeField('Created at', auto_now_add=True) updated_at = models.DateTimeField('Last updated at', auto_now=True, blank=True, null=True) creator = models.ForeignKey( User, on_delete=models.CASCADE, related_name="post_creator") body = models.CharField(max_length=POST_MAX_LEN, validators=[MinLengthValidator(POST_MIN_LEN)]) -
drf-spectacular: Add OpenApiResponse to a serializer-less function-based view
So, I'm documenting the following piece of code using drf-spectacular: from rest_framework import response from rest_framework.decorators import api_view, permission_classes from rest_framework.response import Response from rest_framework.permissions import AllowAny from rest_framework import status from drf_spectacular.utils import extend_schema, OpenApiParameter def passcode_generator: return 0 # placeholder @extend_schema( parameters=[ OpenApiParameter(name="callsign", required=True, type=str), ], description="Get an APRS-IS passcode for a given callsign", ) @api_view(["POST"]) @permission_classes([AllowAny]) def get_passcode(request): callsign = request.data.get("callsign", None) if callsign is None: raise Response( {"error": "Missing callsign"}, status=status.HTTP_400_BAD_REQUEST ) return Response({"passcode": passcode_generator(callsign)}) What I can't understand how to do is how to document the responses. Namely, there is OpenApiResponse in drf_spectacular.utils but the documentation is very slim. How can I document the responses of my API with this system? -
Can I use standard generic CreateView for model formset?
I am again stuck with model formset. I have following form: ArticleFormSet = modelformset_factory(Article, fields=('title', 'pub_date'), extra=3) and View for this model formset: class ArticleCreateView(CreateView): model = Article form_class = ArticleFormSet template_name = 'article_form_view.html' success_url = "/" Reading documentation here: https://docs.djangoproject.com/en/4.0/topics/forms/modelforms/#model-formsets I understand that, I can use ArticleFormSet instead of standard form for form_class attribute. So basically, what I am expecting is, this should display 3 forms for the same Article model and I should be able to create three articles at the same time. But I am getting "TypeError: init() got an unexpected keyword argument 'instance' ". So the question is, is this how it supposed to work? Or what would be the correct way of creating few articles at the same time? -
Django form - only show checkbox's with True values
This image shows how currently all 'tags' are displayed whether True or False. browser view of checkboxes I am trying to find a simple way to only display checkboxes for those 'tags' with a true value. Can I add an 'if' statement to this code in forms.py (e.g. within the widgets Meta, or in CheckboxSelectMultiple()) ? class ProjectForm(ModelForm): class Meta: model = Project fields = ['title', 'featured_image', 'description', 'demo_link', 'source_link', 'tags'] widgets = { 'tags': forms.CheckboxSelectMultiple(), } def __init__(self, *args, **kwargs): super(ProjectForm, self).__init__(*args, **kwargs) for name, field in self.fields.items(): field.widget.attrs.update({'class': 'input'}) The Project class (model) underlying the ProjectForm only stores the 'True' Tags on a many-to-many relationship. See image of sqlite showing only 'True' value Tags/Checkboxes are stored with each Project: view of sqlite database tables The ProjectForm (shown above) is used to create or update a single project and therefore only displays fields for that single project. Yet the widget containing the checkboxes is displaying the checkboxes used by all projects (not just the specific project being created/edited). HTML template Form is as follows: <form class="form" method="POST" enctype="multipart/form-data"> {% csrf_token %} {% for field in form %} <!-- Input:Text --> <div class="form__field"> <label for="formInput#text">{{field.label}}</label> {{field}} </div> {% endfor %} … -
Django. How to automatically select the desired user in the form
I recently started studying Django. I have a model that is associated with users. Need to fill in the "User" field automatically. I wanted to use request.user, but my attempts were unsuccessful. Can you tell me how to do it correctly? Sample from - https://i.stack.imgur.com/zcwLk.png models.py class Ticket(models.Model): ticket_id = models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID') ticket_title = models.CharField(max_length=100) ticket_date_open = models.DateTimeField(auto_now_add=True) ticket_status = models.BooleanField(default=False) ticket_reason = models.TextField() user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, verbose_name='User') forms.py class TicketForm(ModelForm): class Meta: model = Ticket fields = ('ticket_title', 'ticket_status', 'ticket_reason', 'user',) views.py class CreateTicket(CreateView): form_class = TicketForm template_name = 'support/new_t[enter image description here][1]icket.html' success_url = reverse_lazy('test') Form - https://i.stack.imgur.com/zcwLk.png -
Context Class for All Views Classes in Django
Is there a way to pass context or a variable to all Views Types Classes ? For example, I would like to set context for all views with: context = {'title': admin.site.site_title} I had to create one class for which type of Views Classes, like: class TitleView(View): context = {'title': admin.site.site_title} def __init__(self, **kwargs): kwargs = self.get_context_data(**kwargs) View.__init__(self, **kwargs) def get_context_data(self, *, object_list=None, **kwargs): self.context['title'] = kwargs['title'] = admin.site.site_title return kwargs class TitleCreateView(CreateView): context = {'title': admin.site.site_title} def get_context_data(self, *, object_list=None, **kwargs): self.context['title'] = kwargs['title'] = admin.site.site_title return CreateView.get_context_data(self, **kwargs) And descend from them the site views. Considering there are several different types of Views (View, FormView, CreateView, UpdateView, etc) and considering they are different (View class doensn't have get_context_data, for example), I would like a way to set context with less code and classes using Mixin or other centralized way for all Views.