Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to render data selected choice on templates with bootstrap in DJANGO
Im Create Gender with field ('jenis_kelamin') in my models Male('Pria') and Female('Wanita'). But, when i post the data, data is not render. display on my template. DISPLAY ON MY TEMPLATE display on my Admin Page. DISPLAY ON MY ADMIN PAGE How to Fix That ? This is My : models.py class UserProfil(models.Model): JENIS_KELAMIN_CHOICE = ( ('Pria', 'Pria'), ('Wanita', 'Wanita' ), ) #Profil user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE,) gelar_depan = models.CharField(max_length=11, blank=True, default="") gelar_belakang = models.CharField(max_length=20, blank=True, default="") nik = models.CharField(max_length=11, blank=True, unique=True, default="") nidn = models.CharField(max_length=11, blank=True, unique=True, default="") email_alternatif = models.EmailField(_('email address'), blank=True, default="") jenis_kelamin = models.CharField(max_length=6, blank=True, default="", choices =JENIS_KELAMIN_CHOICE) tempat_lahir = models.CharField(max_length=30, blank=True, unique=True, default="") tanggal_lahir = models.DateField(null=True, blank=True) nomor_handphone = models.CharField(max_length=13, blank=True) alamat = models.CharField(max_length=255, blank=True, default="") forms.py class UserProfilUpdateForm(ModelForm): class Meta: model = UserProfil exclude = ['user'] widgets = { 'gelar_depan' : forms.TextInput({'class' : 'form-control form-control-user', 'id' : 'gelarDepan', 'placeholder' : 'Gelar Depan'}), 'gelar_belakang' : forms.TextInput({'class' : 'form-control form-control-user', 'id' : 'gelarBelakang', 'placeholder' : 'Gelar Belakang'}), 'nidn' : forms.TextInput({'class' : 'form-control form-control-user', 'id' : 'nidn', 'placeholder' : 'Nomor Induk Dosen Nasional'}), 'nik' : forms.TextInput({'class' : 'form-control form-control-user', 'id' : 'nik', 'placeholder' : 'Nomor Induk Karyawan'}), 'tempat_lahir' : forms.TextInput({'class' : 'form-control form-control-user', 'id' : 'gelarBelakang', 'placeholder' : … -
how to serve static files from EKS cluster for Django?
I am new to Kubernetes. By reading some blogs and documentation I have successfully created the EKS cluster. I am using ALB(layer 7 load balancing) for my Django app. For controlling the routes/paths I am using the ALB ingress controller. But I am unable to serve my static contents for Django admin. I know that I need a webserver(Nginx) to serve my static files. I'm not sure how to configure to serve static files. note: (I don't want to use whitenoise) -
Django access manytomany field from related_name in a view
I have what i think is a simple question but I am struggling to find out how it works. I get how related name works for foreign keys but with many to many fields it seems to break my brain. I have two 3 models at play here. A User, TeamMember and Team Model as seen below. User model is the built in django model. #TeamMember Model class TeamMember(models.Model): member = models.ForeignKey(User, on_delete=models.SET(get_default_team_member), verbose_name='Member Name', related_name="team_members") ... #Team Model class Team(models.Model): name = models.CharField(max_length=50) manager = models.ForeignKey(TeamMember, on_delete=models.SET_NULL, related_name="managers", null=True, blank=True) team_lead = models.ForeignKey(TeamMember, on_delete=models.SET_NULL, related_name="tls", null=True, blank=True) tps = models.ForeignKey(TeamMember, on_delete=models.SET_NULL, related_name="tps", null=True, blank=True) members = models.ManyToManyField(TeamMember, blank=True, related_name="members") ... Now in a view i want to access a specific users team. I thought i could do this by doing something like this: member = TeamMember.objects.get(pk=1) member_team = member.members.name However if I print member_name than it prints nothing. If I try to access any of the other fields on that model like member.members.team_lead.first_name it fails to find the team_lead field. I understand that this has a .all() attribute but i thought it was tied to the team object through the members field. So if that member matches the team … -
Django how access result from queryset in template from index
I have a queryset result in a template: {% for image in product.productimages_set.all %} <img src="{{ image.image_file.url }}"/> {% endfor %} How could I access a index of that object in a template, ie: <img src="{{ product.productimages_set.all.0 }}"/> -
Updating Django model with OneToOne field yields "Duplicate entry for id"
I have a PUT request that should update my Django model with a OneToOne field linking to another model. After running this successfully once, if I try it again, on serialize.save() I get a (1062), Duplicate entry '1 for key 'linked_model_id'. In my models.py: class ModelToUpdate linked_model = (LinkedModel, null=False, on_delete=models.deletion.CASCADE) other_stuff In my views.py: class ModelToUpdateView(arg): def put(self, request): linked_model = request.linked_model model_to_update = (linked_model.model_to_update if hasattr(linked_model, 'model_to_update') else ModelToUpdate(linked_model=request.linked_model) ) serializer = ModelToUpdateSerializer(model_to_update, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) In serializers.py: class ModelToUpdateSerializer(): class Meta: model = ModelToUpdate fields = ['all', 'my', 'fields', 'in', 'the', 'model'] This is the same format as other models in the app with OneToOneFields that are updating successfully. -
In Django, if my request returns a username, can I also get the user's first and last name?
I'm building a Django app for a law firm to let them assign incoming cases to the firm's lawyers. The lawyers are the users, so I used a list of the lawyers to make a dropdown of their usernames, so it's easy to select an active lawyer for the assignment. In some of the templates I create, it's not hard to show the full name of the assigned lawyer. I use "client.assignee.get_full_name", and it shows "John Attorney". But that's a piece of data that seems to ride along with the Client model. I can also get first and last names in my menu dropdowns by querying the list of attorneys through a context processor: def attorney_menu(request): return { 'attorneys': User.objects.filter(groups__name='attorney-staff') } The code to produce that is: <ul class="dropdown"> {% if attorneys %} {% for attorney in attorneys %} <li><a href="/by_attorney?username={{ attorney.username }}">{{ attorney.first_name }} {{ attorney.last_name }}</a></li> {% endfor %} {% endif %} </ul> All the above is working fine. However, in the admin, in the templates created by the default Django admin, my dropdowns can only show the username ("johnattorney" instead of "John Attorney"). Also in the attorney pages (the pages that show the attorney's individual assigned clients), … -
Django object_list from ListView with two models
I have two models, and need access property from both. models.py class Product(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) product_title = models.CharField(max_length=255, default='product_title') product_description = models.CharField(max_length=255, default='product_description') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) is_active = models.BooleanField(default=True) product_view = models.IntegerField(default=0) def __str__(self): return self.product_title def get_absolute_url(self): return reverse('product_change', kwargs={'pk': self.pk}) class ProductImages(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) image_type = models.CharField(max_length=33,default='image_type') image_file = models.ImageField( upload_to='images/', null=True, blank=True, default='magickhat-profile.jpg' ) ProductImages is a model to store multiple images. views.py class ProductListView(ListView): model = Product template_name = 'product_list.html' product_list.html ... {% for product in object_list %} <div class="product"> {% include 'label_perfil.html' %} {% include 'data_product.html' %} </div> {% endfor %} ... data_product.html {% block data-product %} <img src="{{ product.image_file }}"/> {% endblock %} All properties from Product model is available, but how ca access product.image_file data? That return empty... Django 3.2 -
Annotating on a distinct Django Queryset is no longer using the distinct queryset
I have a query and I am trying to annotate the count of each value for the field tail_tip. My original query filters on a related table so it is necessary to use distinct(). I'm not exactly sure how to describe but it appears when I annotate the distinct query the query is no longer distinct. Here are my queries I am playing with in my shell. // Without distinct() Ski.objects.filter(published=True, size__size__in=[178, 179, 180, 181, 182, 183, 184]).count() // 318 skis = Ski.objects.filter(published=True, size__size__in=[178, 179, 180, 181, 182, 183, 184]).distinct() skis.count() // 297 skis.values('tail_tip').order_by('tail_tip').annotate(count=Count('tail_tip')) // <QuerySet [{'tail_tip': 'flat', 'count': 99}, {'tail_tip': 'full_twin', 'count': 44}, {'tail_tip': 'partial_twin', 'count': 175}]> // total count = 318 Given that skis is already distinct() I don't know why when I annotate it the total count then equals the non-distinct query. -
Trying to import a webstie template throught Django and keep getting this error
Every time I try and run the template I get this error: Refused to apply style from '' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. Is there a place I can go to disable strict MIME checking? -
Django admin list filter dropdown with blank value
I am using django-admin-list-filter-dropdown for my app and I want to be able to filter out blank values in the dropdown as well. But currently, it's not doing it at the moment. How do I add the empty string/None values inside the list filter? -
Can Django fixtures be used for production?
I have a Django application that reads different CSV files and saves them to the same model/table in the DB. While fixtures are certainly used for setting up a test environment quickly, I used the fixture to configure the different CSV Schemata that is subsequently parsed by the Django application. So each of the data provider has their own distinct schema which is a different row in the CsvSchema table. During code review it came up that this is bad style because -- It leads to duplication of data. I found it useful to pass such configurations via a fixture and treated it like a configuration file. To further treat the fixture like a configuration file, I even put it inside the git repository, which is again somethong the reviewer agrees with. The reviewer also claimed that fixtures should be use only once in the lifetime of the application, while setting it up initially. To me, the fixtures are just a tool that Django provides us. I can play around with the schema details in my development machine, and then dump them into a fixture, effectively using it as configuration. Am I playing too hard and fast with the rules … -
Model instances without primary key value are unhashable with Djongo
I am getting the error Model instances without primary key value are unhashable when trying to remove a model instance from my admin panel. models.py from djongo import models import uuid PROPERTY_CLASSES = ( ("p1", "Video Property"), ("p2", "Page Property"), ("trait", "Context Trait"), ("custom", "Custom Property") ) EVENT_TYPES = ( ("video", "Video Event"), ("track", "Track Event"), ("page", "Page Event") ) class Device(models.Model): _id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=255) class Platform(models.Model): _id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=255) app_name_possibilities = models.TextField(blank=True) class EventPlatformDevice(models.Model): _id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = "" event_field = models.ForeignKey('Event', on_delete=models.CASCADE) applicable_apps = models.ManyToManyField('Platform', blank=True) applicable_devices = models.ManyToManyField('Device', blank=True) property_group = models.ManyToManyField('PropertyGroup', blank=True) custom_properties = models.ManyToManyField('Property', blank=True) class Event(models.Model): _id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=255, unique=True) event_type = models.CharField(max_length=20, choices=EVENT_TYPES) class PropertyGroup(models.Model): _id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=100) applicable_properties = models.ManyToManyField('Property') class Property(models.Model): _id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=255) property_class = models.CharField(max_length=20, choices=PROPERTY_CLASSES) format_example = models.TextField(blank=True) notes = models.TextField(blank=True) The issue lies with the EventPlatformDevice model I believe. The issue I think is when I create a new entry in the Admin panel and setup the relationships between EventPlatformDevice.applicable_apps it gets saved into the MongoDB using a _id:ObjectId("61c25d36cdca07c8a6101044") … -
App Engine running Django not logging on prod service
I am running Django application on Google App Engine standard env. I have two services running for dev and prod. both services plus my local machine are configured with Google Logging Client for logging. Recently, for some reason, the prod service stopped posting logs into StackDriver. But both my local and dev service are posting logs. here is my code: settings.py from google.cloud import logging if os.getenv('GAE_APPLICATION', None): client = logging.Client() else: # setup for my local logging. client = logging.Client.from_service_account_json('PATH TO JSON FILE') LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'formatters': { 'verbose': { 'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s' }, 'simple': { 'format': '%(levelname)s %(message)s' }, }, 'handlers': { 'stackdriver': { 'level': 'INFO', 'class': 'google.cloud.logging.handlers.CloudLoggingHandler', 'client': client }, 'console':{ 'level': 'INFO', 'class': 'logging.StreamHandler', 'formatter': 'simple' }, 'mail_admins': { 'level': 'CRITICAL', 'class': 'django.utils.log.AdminEmailHandler', "email_backend": "anymail.backends.mailgun.EmailBackend" } }, 'loggers': { 'django': { 'handlers': ['stackdriver'], 'propagate': True, 'level': 'INFO', }, 'django.request': { 'handlers': ['stackdriver', 'console', 'mail_admins'], 'level': 'INFO', 'propagate': True, }, } } urls.py def trigger_error(request): import logging logger = logging.getLogger('stackdriver') logger.error('test error') logger.critical('test critical') logger.warning('test warning') logger.info('test info') division_by_zero = 1 / 0 path('debug/', trigger_error), My questions are: Is there any limits or quotes for logging into a specific … -
ModelFormset save failing
I've created a web app that presents a set of questionnaires. I have different models for Question, Questionnaire, Answer and Response that acts as an intermediate table. I have created the modelFormset and rendered the form, but when I try to save I get a null value constraint, because I'm not passing in the question_id but I am at a loss of how I should be doing it. null value in column "question_id" violates not-null constraint Models.py class Questionnaire(models.Model): title = models.CharField(max_length=50, blank=False, unique=True) class Question(models.Model): questionnaire = models.ForeignKey(Questionnaire, on_delete=models.CASCADE) sequence = models.IntegerField() question = models.TextField() class Response(models.Model): project_name = models.ForeignKey(Project, on_delete=models.CASCADE) questionnaire = models.ForeignKey(Questionnaire, on_delete=models.CASCADE) user = models.CharField(max_length=50, blank=True) class Meta: constraints = [ models.UniqueConstraint(fields= ['project_name','questionnaire'], name='unique_response'), ] class Answer(models.Model): RAG_Choices = [ ('Green', 'Green'), ('Amber', 'Amber'), ('Red', 'Red') ] question = models.ForeignKey(Question, on_delete=models.CASCADE) answer = models.CharField(max_length=50, blank=True, choices=RAG_Choices) notes = models.TextField(blank=True) response = models.ForeignKey(Response, on_delete=models.CASCADE) class Meta: constraints = [ models.UniqueConstraint(fields=['question','response'], name='unique_answer'), ] view.py def get_questionnaire(request, project_id, questionnaire_id): # Get the Response object for the parameters response = Response.objects.get( project_name_id=project_id, questionnaire_id=questionnaire_id ) AnswerFormSet = modelformset_factory(Answer, form=AnswerForm, fields=('answer','notes',), extra=0) answer_queryset = Answer.objects.filter(response=response ).order_by('question__sequence' ).select_related('question') if request.method == 'POST': form = AnswerForm(request.POST) answers = form.save(commit=False) answers.project_name_id = response answers.save() return … -
How to get value from Django BigAutoField
Tyring to get a value out of django.db.models.fields.BigAutoField for reference. I can't seem to convert it to a int and if I convert to a str I just get (<django.db.models.fields.BigAutoField>,). I've tried to find some documentation but can't seem to see any way of getting a value out. -
I am trying to add an active class to my nav bar items on my website when clicked
I want to add the active class to the navbar item that I click on, on my website. In my JS code, it tells the program what class to look under ("nav-item"). Then it tells my program to remove the active class from the current active class, and then add the active class to the class that was clicked. I'm assuming the logic is correct but I most likely missed syntax. I am new to HTML and JS so any help would be greatly appreciated. HTML Code: <ul class="navbar-nav"> <li class="nav-item"><a class="nav-link js-scroll-trigger active" href="#about">About</a></li> <li class="nav-item"><a class="nav-link js-scroll-trigger" href="#education">Education</a></li> <li class="nav-item"><a class="nav-link js-scroll-trigger" href="#experience">Experience</a></li> <li class="nav-item"><a class="nav-link js-scroll-trigger" href="#skills">Skills</a></li> </ul> JS code: $('.nav-item').on('click', '.nav-link js-scroll-trigger', function () { $('.nav-link js-scroll-trigger active').removeClass('active'); $(this).addClass('active'); }); -
Convert pandas.core.series.Series data from nan to None Django
I have a pandas.core.series.Series class When the field is empty I get 'nan' as a value and like that it stores in database. I want to convert that empty value to 'None' so I can manipulate with None value What I tried is here import numpy as np data.replace(np.nan, None, regex=True) But this isn't working. Can someone help me please? -
Adding {% csrf_token %} to javascript insertion
All, I have a popup that is inserted via javascript when a button is clicked: function loadTypeManagement(existingDocTypes) { const typeManagementModalDiv = '<div class="modal fade" id="typeManagementModalDiv" >' + '<div class="modal-dialog" style="max-width: none;">' + '<div class="modal-content feedback_popup" style="height:100%; margin-top: 0vh;">' + '<form class="feedback_form" autocomplete="off" action="/" method="post" id="taskitem_form">' + '<h1 id="djangoInsert">Type Management</h1><br>' + '<hr>' + '<div class="autocomplete container justify-content-center">' + '<h3 style="margin-bottom: .5vw;">Add a Document Type</h3>' + '<hr style="width: 50% ;margin: auto; margin-bottom: .5vh;">' + '<div class="row">' + '<div class="col-3"></div>' + '<label class="col-6 admin_input_desc ">Document Type:</label>' + '<div class="col-3"></div>' + '</div>' + '<div class="row">' + '<div class="col-3"></div>' + '<input class=" text-center col-6 admin_input " id="addDoctypeId" type="text" name="addDocTypeName" placeholder="Document Type">' + '<div class="col-3"></div>' + '<div class="d-inline p-2 text-white ">' + '<p class="col-sm-4 admin_input_desc d-inline">Can this new type be an Authentication Source?</p>' + '<label class="">No</label>' + ' <input type="radio" id="date_newToOld" name="choice" value="date_newToOld" checked/>' + '<label class="float-right " style="margin-left: 1.25vw;">Yes</label>' + ' <input class="float-left" type="radio" id="date_newToOld" name="choice" value="date_newToOld" />' + '</div>' + '</div>' + '<input class="submit_button" name="submit" type="submit" value="Add Document Type">' + '</div>' + '</form>' + '<form class="feedback_form" autocomplete="on" action="/action_page.php">' + '<hr>' + '<div class="autocomplete container justify-content-center">' + '<h3 style="margin-bottom: .5vw;">Remove a Document Type</h3>' + '<hr style="width: 50% ;margin: auto; margin-bottom: .5vh;">' + '<div class="row">' + … -
Django-autocomplete-light - "No results found" in browser on startup - after doing one search in admin - results are found in browser again
I have a peculiar problem with Django-autocomplete-light. When I go to my browser and try searching for something I get "no results found" - but when I go to the admin panel and add a model, the results pop up as they should. When I have done this one time, I can go back to the browser and then the results show up as they should. I'm suspecting some caching issue, but not sure how to debug this. Maybe someone can take a look if there is something wrong with my set-up. models.py class DogBreeds(models.Model): name = models.CharField(max_length=150) def __str__(self): return self.name class Advertisement(SoftDeleteModel, TimeStampedModel): breed = models.ForeignKey(DogBreeds, on_delete=models.CASCADE, null=True, verbose_name='Hundras') views.py class BreedAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): if not self.request.user.is_authenticated: return DogBreeds.objects.none() qs = DogBreeds.objects.all() if self.q: qs = qs.filter(name__icontains=self.q) return qs Form template {% extends '_base.html' %} {% load static %} {% block content %} <form method="post" enctype="multipart/form-data" id="adForm" data-municipalities-url="{% url 'ajax_load_municipalities' %}" data-areas-url="{% url 'ajax_load_areas' %}" novalidate> {% csrf_token %} <table> {{ form.as_p }} </table> <button type="submit">Publish</button> </form> </body> {% endblock content %} {% block footer %} {% comment %} Imports for managing Django Autocomplete Light in form {% endcomment %} <script type="text/javascript" src="{% static 'admin/js/vendor/jquery/jquery.js' %}"></script> <link rel="stylesheet" … -
Django rest_framework MVC structure
I'm currently working on a Django project, using the rest_framework. The project is built around API endpoints the client-side will use to send/retrieve data about features such as users, players, playerInventory etc etc. My question is, I'm struggling to structure this project and I'm not sure if i should be destructuring the data my front-side receives. The data I'm working with looks like API ENDPOINT Returns a single player inventory [GET] { "elementId": 1, "elements": [1, 2, 3 ,4] } API ENDPOINT Update a single player inventory [POST] from -> { "elementId": 1, "elements": [1, 2, 3 ,4] } (example) to -> { "elementId": 1, "elements": [3, 3, 3 ,1] } I'd like to be able to use a front-end 'model' concenpt that takes the data from my API fetches and constructs them for me so i can use that data in a better manor. Could someone give me a detailed Django project file structure and some Javascript model code design patterns possible? here's my models.py: class User(models.Model): userId = models.AutoField(primary_key=True) username = models.CharField(max_length=16) email = models.EmailField(max_length=30) isMember = models.BooleanField(default=False) class meta: db_table = 'app_users' app_label = "app" managed = True def __str__(self): return str(self.userId) class Player(models.Model): playerId = models.ForeignKey(User, … -
Django Admin upload image with foreign key
I have a model Product with a User and ProductImages as foreign key. models.py class User(AbstractBaseUser): ... class ProductImages(models.Model): image_type = models.CharField(max_length=33,default='image_type') image_file = models.ImageField( upload_to='images/', null=True, blank=True, default='magickhat-profile.jpg' ) class Product(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) productimages = models.ForeignKey(ProductImages, on_delete=models.CASCADE) product_title = models.CharField(max_length=255, default='product_title') product_description = models.CharField(max_length=255, default='product_description') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) is_active = models.BooleanField(default=True) product_view = models.IntegerField(default=0) def __str__(self): return self.product_title def get_absolute_url(self): return reverse('product_change', kwargs={'pk': self.pk}) forms.py class ProductForm(ModelForm): productimages = forms.ImageField() CHOICES_STATUS = (('Pronto', 'Pronto'),('Em obras', 'Em obras'),('Lançamento', 'Lançamento'),) product_status = forms.ChoiceField(choices=CHOICES_STATUS) product_title = forms.CharField() product_description = forms.CharField() class Meta: model = Product fields = '__all__' admin.py class AdminProductModel(admin.ModelAdmin): def get_queryset(self, request): qs = super().get_queryset(request) return qs.filter(user_id=request.user) kadmin.register(User, UserAdmin) kadmin.register(Product, AdminProductModel) But in the admin Product model the field for image is redering as select field no ImageField My purpose is add a upload image field on django model administration. If i use ImageField direct on Product model the field is redering ok, but i need a external table to store that image becouse is a multimage upload, so i need a foreing key. How is the right way to that purpose. I see other questions about that, but the majority is old versions, and … -
How do I set up a nested URL pattern for /category/subcategory/post in Django?
I've looked through several answers and I cannot seem to figure out how to do this. My best guess is this has something to do with all of these answers are specific to writing function based views. The problem: I have a portal where I want the URL structure to be: /portal/engagement/engagement_name/finding/finding_name So I've tried several things and this is the closest I can get: urlpatterns = [ path('', login_required(CustomerDashboard.as_view()), name='portal_dashboard'), path('engagement/add', login_required(EngagementCreateView.as_view()), name='engagement_create'), path('engagement/<slug:slug>/', login_required(EngagementDetailView.as_view()), name='engagement_detail'), path('engagement/<slug:slug>/edit', login_required(EngagementUpdateView.as_view()), name='engagement_update'), path('engagement/<slug:slug>/finding/add', login_required(FindingCreateView.as_view()), name='finding_create'), path('finding/<slug:slug>', login_required(FindingDetailView.as_view()), name='finding_detail'), path('finding/<slug:slug>/edit', login_required(FindingUpdateView.as_view()), name='finding_update'), ] If I try to do something like engagement/<slug:slug>/finding/<slug:slug>/ it just errors. I've tried to follow some answers like choosing the slug field (i.e. slug:engagement_slug``` but none of it works. I'm using class based views. My models are: Company Engagement (FK to Company) Finding (FK to Engagement) I'm not sure what other code I can provide to help. I've read some other options on overriding the get_object method and passing the slug as a **kwarg. I'm just not sure what is the "right" way to do this. -
Django Update AbstractUser
IntegrityError at / NOT NULL constraint failed: pages_profile.username Request Method: POST Request URL: http://127.0.0.1:8000/ Django Version: 3.2.9 Exception Type: IntegrityError Exception Value: NOT NULL constraint failed: pages_profile.username How do I update an abstractuser that's already signed in? from django.shortcuts import redirect, render from .forms import UserProfileForm from .models import Profile def index(request): context = {} if request.method == "POST": print(request.POST) form = UserProfileForm(request.POST, request.FILES) if form.is_valid(): img = form.cleaned_data.get("avatar") obj, created = Profile.objects.update_or_create( username=form.cleaned_data.get('username'), defaults={'avatar': img}, ) obj.save() print(obj) return redirect(request, "home.html", obj) else: form = UserProfileForm() context['form']= form return render(request, "home.html", context) -
Django - Given time zone, month and year get all post created on that date in that time zone
So I have this Post model. I want to be able to retrieve all posts that were created in a month, year under a certain time zone. model.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) So for example if a user creates 10 posts in November, 2 in December of 2021 in PST. Then I have a view that takes month, year and time_zone and let's say the url looks something like /post/<int:month>/<int:year>/<str:time_zone> and the user pings /post/11/2021/PST then it should return the 10 posts from November. How do I return all posts from a month and year in a time zone given time zone, month and year? Setup: Django 3.2.9 Postgresql -
Django pluralize person as people
trying to output the correct plural value in Django template when count is more than 1. <p>{{ review.markers.helpful.count }} person{{ reviews.markers.helpful.count|length|pluralize }} found this helpful</p> still returns 1 persons or 2 persons instead of 1 person and 2 people any help to fix this in the template?