Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django upgraded from 1.10.x to 2.2.x. Now passwords are not working
Is this a known issue? Is there a way to circumvent this without changing passwords or asking users to reset the password? I am using the Django-admin default app for the same. Please do ask what other information do you need to help me debug this. FYI, I also upgrade from python 2.7.x to python 3.6.x for the same. -
pgAdmin does not open in AWS EC2
I am trying to deploy Django based website on AWS EC2. I have successfully created an instance and install my python libraries there. I am using Postgres here. For that, I have installed Postgres along with pgAdmin, but for some reason, it does not open. It just displayed that it's starting up the server but it does not open at all. I am new to it so I do not know much about it. Can someone please help or guide me why it does not open up? -
How to create a form that make user is_active = False?
In my Django project, there are several types of users. User types are lead, manager, analyst. The Leads should change every user's is_active attribute. I created a form and view for that. I have a users page and every user is listing here with a for loop. What I want is lead can block a user with is_active = False method. But my form is does not work because I think I cannot reach the user. How can I solve it? views.py @user_passes_test(is_lead) def users(request): current_user = request.user userP = UserProfile.objects.get_or_create(username=current_user) user_list = UserProfile.objects.filter(company=userP[0].company).order_by('-first_name') form = makeInactive(request.POST or None, instance=user_list.all) if form.is_valid(): if form.isUserActive: ????.is_active = False form.save() context = { 'user_list': user_list, 'form': form } return render(request, 'user_list.html', context) forms.py class makeInactive(forms.ModelForm): isUserActive = forms.BooleanField(label='', widget=forms.CheckboxInput( attrs={'onclick': 'this.form.submit();'}), required=False) class Meta: model = UserProfile fields = ('isUserActive',) models.py class UserProfile(AbstractUser): company = models.ForeignKey(CompanyProfile, on_delete=models.CASCADE, null=True, unique=False) user_id = models.UUIDField(default=uuid.uuid4(), editable=False, unique=True) username = models.CharField(max_length=500, unique=True) first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) password = models.CharField(max_length=250) email = models.EmailField(max_length=254) rank = models.ForeignKey(Rank, on_delete=models.CASCADE, null=True, unique=False) image = models.ImageField(upload_to='profile_image', blank=True, null= True, default='profile.png') isUserActive = models.BooleanField(default=True) -
Restricting access to subdomains based on user in Django
I am setting up a multitenancy django app. I have already decided that a single shared schema is the best solution for me. I can currently segregate the data by using subdomains e.g. tenant1.mydomain.com/list will only show the data for tenant1. What is the best method to restrict access to the subdomain? I have thought about doing this via middleware. The user model would have a ManyToMany relationship to a Tenants model. The middleware would then check that the user in the request had permission to access the requested subdomain. I think this would be secure, but would involve a database query for every request. Is this an inefficient way to achieve this, or is there a better approach to use in general? -
get the duplicated records in Django queryset
I want to get the duplicated of ticket field in table FollowUp (Django) followups = FollowUp.objects.values('ticket').annotate(ticket_count=Count('ticket')).filter(ticket_count__gt=1) print(followups) but I get empty Queryset although I have duplicated records: <QuerySet []> when printing FollowUp.objects.values('ticket').annotate(ticket_count=Count('ticket')) I get: <QuerySet [{'ticket': 57, 'ticket_count': 1}, {'ticket': 58, 'ticket_count': 1}, {'ticket': 59, 'ticket_count': 1}, {'ticket': 59, 'ticket_count': 1}, {'ticket': 59, 'ticket_count': 1}, {'ticket': 59, 'ticket_count': 1}, {'ticket': 60, 'ticket_count': 1}, {'ticket': 60, 'ticket_count': 1}, {'ticket': 61, 'ticket_count': 1}, {'ticket': 61, 'ticket_count': 1}, {'ticket': 61, 'ticket_count': 1}, {'ticket': 62, 'ticket_count': 1}]> I expect to get: <QuerySet [{'ticket': 57, 'ticket_count': 1}, {'ticket': 58, 'ticket_count': 1}, {'ticket': 59, 'ticket_count': 4}, {'ticket': 60, 'ticket_count': 2}, {'ticket': 61, 'ticket_count': 3}, {'ticket': 62, 'ticket_count': 1}]> -
django error, "The QuerySet value for an exact lookup must be limited to one result using slicing"
I am having an error when i create an object with data from a csv file, the error is: "The QuerySet value for an exact lookup must be limited to one result using slicing." it seems to come from the get_or_create line. i have tried to slice all the querysets in the function but this has not fixed the problem. and i already know all the model fields exist and are correct with my models.py contracts = Contract.objects.filter(contract_id=row[2]) if not contracts: continue new_contract = contracts.first() logger.info(new_contract.contract_id) _, created = Job.objects.get_or_create(contract=new_contract, order_type = str(row[3])[:0], description_of_works = str(row[4]), added_on = date_time_obj, date_raised = date_time_obj, draughtsman = base_user.objects.filter(first_name__icontains=issuer_str[0:4]), status = job_status, #IDFK comment = str(row[8]), design_required = design_req, designer = str(row[10])).first() i have checked other questions of the same topic and they didnt have any solutions. Any help is appreciated. -
Message says Order is created, but there is no order object in the backend (django admin) in django rest framework
I created an order create API, it was working fine. Now I had to add another field in the Order model because of the business need. The field is billing details and it is a foreign key to a new model BillingDetails. Now, I had to create an Order object by creating an object of BillingDetails and then an Order object at the same time using Nested serialization. Now, when I call http://127.0.0.1:8000/api/addorderitem/1 passing product id, in everycall is says "Order is created & Item added to your cart". It should be "Quantity is added", on the 2nd, 3rd etc time. Also, for first time it says, Order is created but there is no order object when I checked in django admin. My models: class OrderItem(models.Model) : user = models.ForeignKey(User,on_delete=models.CASCADE, blank=True) ordered = models.BooleanField(default=False) item = models.ForeignKey(Product, on_delete=models.CASCADE,blank=True, null=True) quantity = models.IntegerField(default=1) def __str__(self): return f"{self.quantity} items of {self.item} of {self.user.email}" class Order(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True) items = models.ManyToManyField(OrderItem,blank=True, null=True) start_date = models.DateTimeField(auto_now_add=True) ordered_date = models.DateTimeField() ordered = models.BooleanField(default=False) billing_details = models.ForeignKey('BillingDetails',on_delete=models.CASCADE,null=True,related_name="order") def __str__(self): return self.user.email class BillingDetails(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True) first_name = models.CharField(max_length=50,blank=True,null=True) last_name = models.CharField(max_length=50, blank=True, null=True) email = models.EmailField(blank=True, null=True) phone = models.CharField(max_length=50,blank=True,null=True) … -
Django rest framework + simple JWT - permission classes always enabled
I'm using simple JWT for authentication in my rest API. In my function based views, I use @permission_classes([IsAuthenticated]) to define that the JWT token is required to access that view. However, I have some views that are not supposed to require the authentication token, therefore I didn't insert the @permission_classes([IsAuthenticated]), but when I test the view it still requires the token. Here's an example: @api_view(['POST']) def userCreate(request): serializer = UserSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(status=201) return Response(serializer.errors, status=400) When I try to access this view the server replies with a 401 and says: { "detail": "Authorization header must contain two space-delimited values", "code": "bad_authorization_header" } In my settings.py file I set: ... REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.authentication.JWTAuthentication', ], 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 10 } -
Celery task to delete old revisions
I am using django-reversion (1.9.3) which specifies a management command to delete old revisions. However I'm not familiar with django-admin and it seems the command isn't even registered as runnable and I've no idea how to do it. Besides, that's not the point, I like to keep all my tasks as celery tasks. I don't want to run a django-admin command. But the low-level API docs are not very helpful. I am not sure if I am supposed to delete the Version objects or the Revision objects to perform the cleanup. I assume I want the whole Version gone. Also, filtering them by date is completely undocumented. All I want is something like: d = datetime.datetime.now() - datetime.timedelta(days=180) reversion.get_before_date(my_model, d).delete() How can I filter old versions/revisions and delete them in a celery task? -
Python verify in two dictionaries and send mail when are equal
Dict_one = {1: [], 2: [], 3: [], 4: [], 5: [], 6: [], 7: [], 8: [], 9: [], 10: [], 11: [], 12: [], 13: [], 14: [], 15: [], 16: [], 17: ['Stefanescu-Delavrancea Barbu', 'Creanga Ion', 'Barbu Ion'], 18: [], 19: [], 20: ['MIHALACHE CRISTINA'], 21: [], 22: []} Dict_two = {1: [], 2: [], 3: [], 4: [], 5: [], 6: [], 7: [], 8: [], 9: [], 10: [], 11: [], 12: [], 13: [], 14: [], 15: [], 16: [], 17: ['user@example.com'], 18: [], 19: [], 20: ['user2@example.com'], 21: [], 22: []} I have that two dictionaries, I want to verify when keys are equal like in iterate or something to send a mail to address from dict_2 with names from dict_1 I have to mention that I am pretty new in python and I am sorry if it is a stupid question. Thanks in advance -
Is there a better way to write this code so DRY can be maintained?
I have 2 models Tour to save Tour TourImage to save images related to Tour class Tour(models.Model): name = models.CharField(max_length=50) class TourImage(models.Model): tour = models.ForeignKey(Tour, on_delete=models.CASCADE) image = models.FileField(upload_to='images/') In my views.py file I have the following code to save the Tour and the tour images class CreateTourView(CreateView): model = Tour template_name = "create_tour.html" fields = "__all__" def form_valid(self, form): tour = form.save() for image in self.request.FILES.getlist("extra_images"): TourImage.objects.create(tour=tour, image=image) return super().form_valid(form) The HTML form looks like this <form action="" method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form | crispy }} <input type="file" name="extra_images" multiple /> <input type="submit" value="Save" /> </form> This works fine, the images are saved the Database. But I also want to add option to edit Tour and add extra images, so the UpdateView code is as follows class TourUpdateView(UpdateView): model = Tour template_name = "update_tour.html" fields = "__all__" def form_valid(self, form): tour = form.save() for image in self.request.FILES.getlist("extra_images"): TourImage.objects.create(tour=tour, image=image) return super().form_valid(form) The .form_valid() method is same for both CreateView and UpdateView. Is there a better way to code this so as to avoid repetitive code? -
How to structure a quiz in django using ModelChoiceField?
I am building an app using Django that will have a hard-coded quiz with 4 choices that users will fill out periodically. I am having trouble implementing this so that the user can fill out the form on one page and the instance is saved with relation to the user and current date. Could anybody help with how to go about this? models.py ANSWER_CHOICES = ( (1, 'Never'), (2, 'Almost Never'), (3, 'Sometimes'), (4, 'Fairly Often'), (5, 'Very Often'), ) class Answer(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='answer', null=True) answer = models.CharField(max_length=200, null=True) def __str__(self): return self.answer class Quiz(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='quiz', null=True) question = models.CharField(max_length=200) answer = models.ForeignKey(Answer, on_delete=models.CASCADE, related_name='quiz_answer', null=True) pub_date = models.DateTimeField(auto_now=True) def __str__(self): return self.question views.py def test(request): user = request.user questions = Quiz.objects.all() if request.method == 'POST': form = Form(request.POST) if form.is_valid(): test = Quiz( answer=form.cleaned_data["answer"], user=user ) test.save() return redirect('app:dashboard') else: form = Form() context = { 'form':form, } return render(request, 'members/test.html', context) forms.py class Form(ModelForm): answer = forms.ModelChoiceField(widget=forms.RadioSelect, queryset=(Answer.objects.all())) class Meta: model = Quiz fields = ['answer'] test.html <form method="POST"> {% csrf_token %} <div class="card-body"> {{ form|crispy }} </div> <!-- /.card-body --> <div class="card-footer"> <button type="submit" class="btn btn-primary">Submit</button> </div> </form> -
Running server-side with Gunicorn and Django
Can an application running React as client side and Django with Gunicorn as server side run on Android phones/tablets/Snapdragon HDK? -
how does Django restores sessions after closing browser
I am working on a Django project and I am not clear how sessions are actually working. I've set SESSION_EXPIRE_AT_BROWSER_CLOSE = False in my settings.py. So that the session doesn't expire when the user closes the browser (Though it's the default behaviour of Django). I know that Django stores session data in the django_session table. But I don't know how Django is able to restore sessions in my browser even after closing the browser or internet or PC. Does Django save the browser's information in django_session in some encrypted way, so that every time I open my browser, it checks for my browser's information and starts the session accordingly? I am not using cookies in my Django code. Any help would be appreciated. -
how to structure our django model
I am doing online shopping project in django. I split my project into Admin app, moderator app, shop app. There are two types of product- one inserted by moderator and other by registered shops. do i need to create separate product models for both app, If I try to give one common product table inside admin app, there will be issue with foreign key. So how I will create product model, separate(one in moderator app and in shop app) or common (in admin app) same issue with order models and stock models. -
Django not creating user profile on user creation despite using signals
I am trying to make the user profile to be created automatically as i am creating the user. I used django signals to do this and imported it in the apps.py file but it still didn't work can you please show me what i did wrong. Thank you. models.py from django.db import models from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' signals.py from django.db.models.signal import post_save from django.contrib.auth.models import User from django.dispatch import receiver from .models import Profile @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_profile(sender, instance, **kwargs): instance.profile.save() apps.py from django.apps import AppConfig class UsersConfig(AppConfig): name = 'users' def ready(self): import users.signals in shell('NewUser2' was created with the registration form, 'Destiny' was given a profile using the admin) >>> from django.contrib.auth.models import User >>> user = User.objects.filter(username='NewUser2').first() >>> user <User: NewUser2> >>> user.profile Traceback (most recent call last): django.contrib.auth.models.User.profile.RelatedObjectDoesNotExist: User has no profile. >>> user.profile.image.url Traceback (most recent call last): django.contrib.auth.models.User.profile.RelatedObjectDoesNotExist: User has no profile. >>> user_created_in_admin = User.objects.filter(username='Destiny').first() >>> user_created_in_admin.profile.image.url '/media/default.jpg' -
django-allauth custom signup form throws an error in admin page while adding a new user. 'CustomUserForm' object has no attribute 'instance'
Trying to add a new user to the "general_user" group. since I am utilising custom user model and django-allauth I created custom registration form, inheriting allauth SignupForm. it works fine in the web page, but not in the admin page. every time trying to click +add Customuser, it shows below error. what should I check for this? forms.py from django import forms from django.contrib.auth.forms import UserCreationForm, UserChangeForm from django.contrib.auth import authenticate, get_user_model from allauth.account.forms import SignupForm from django.contrib.auth.models import Group class RegistrationForm(SignupForm): email = forms.EmailField( max_length=60, help_text='Required, Enter avalid Email address.' ) class Meta: model = get_user_model() fields = ['email', 'username', 'password1', 'password2'] def custom_signup(self, request, user): custom_form = self #use local signup() if hasattr(custom_form, 'signup') and callable(custom_form.signup): custom_form.signup(request, user) def signup(self, request, user): general_user_group = Group.objects.get(name='general_user') user.groups.add(general_user_group) user.save() return user admin.py from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django.contrib.auth import get_user_model from .forms import CustomUserChangeForm, RegistrationForm CustomUser = get_user_model() class CustomUserAdmin(UserAdmin): form = CustomUserChangeForm add_form = RegistrationForm model = CustomUser list_display = ('email', 'username', 'is_staff',) list_filter = ('is_staff', 'is_active',) search_fields = ('email', 'username',) ordering = ('email',) readonly_fields = ('date_joined', 'last_login') fieldsets = ( (None, {'fields': ('email', 'password',)}), ('Personal info', {'fields': ('username', )}), ('Permissions', { 'fields': ('is_active', 'is_staff', … -
Django does't send email on the remote server
I am trying to send an email when a user fills out a form on my site. Everything works on my local server, letters are sent. On a remote timeweb.com server with the same settings, letters are not sent and I am got them. Tried DEBUG = False and True I tried different mail services: gmail, mail, yandex, timeweb mail. In gmail included "Unreliable applications that have access to the account". And here I included https://accounts.google.com/DisplayUnlockCaptcha Nothing helps. Who knows, please tell me where to dig. -
How to validate different data in the same serializer in DRF
This is my current setup I want to be able to create new contributor entities as well as relate the old entities using the same data all when sending the parent Campaign data. I cannot use create method in serializers as I want all my logic to be reusable since I'll have multiple different ways of creating the same thing models.py class BaseModel(models.Model): created_at = models.DateTimeField( editable=False, auto_now_add=True, verbose_name=_("Created At") ) updated_at = models.DateTimeField( editable=False, auto_now=True, verbose_name=_("Updated At") ) class Meta: abstract = True class Contributor(BaseModel): name = models.CharField(max_length=128) class Contact(BaseModel): name = models.CharField(max_length=128) phone_number = models.CharField(max_length=128, blank=True, null=True) class Campaign(BaseModel): title = models.CharField(max_length=128) contributors = models.ManyToManyField(Contributor, through="CampaignContributor") class CampaignContributor(models.Model): campaign = models.ForeignKey(Campaign, on_delete=models.CASCADE) contributor = models.ForeignKey(Contributor, on_delete=models.CASCADE) tags = ArrayField( models.CharField(max_length=255, blank=True, null=True), null=True ) serializers.py class ContactSerializer(serializers.ModelSerializer): class Meta: model = Contact fields = "__all__" depth = 1 class ContributorSerializer(serializers.ModelSerializer): contacts = ContactSerializer(many=True) class Meta: model = Contributor fields = "__all__" depth = 1 class CampaignContributorSerializer(serializers.ModelSerializer): contributor = ContributorSerializer() class Meta: model = CampaignContributor fields = "__all__" class CampaignSerializer(serializers.ModelSerializer) contributors = CampaignContributorSerializer( many=True, extra_excludes=["campaign"], source="campaigncontributor_set" ) class Meta: model = Campaign fields = "__all__" depth = 1 views.py class CampaignViewSet(viewsets.ModelViewSet): lookup_url_kwarg = "id" queryset = Campaign.objects.all() serializer_class = … -
The view users.views.edit_profile didn't return an HttpResponse object. It returned None instead. It returned None instead
views.edit_profile does not return Fields Error but instead return webpage error. In views.registration - it does return fields error but in views.edit_profile instead of fields error it return a webpage error. how does it happen when the two have a similar codes? the below image is the error from views.register after submitted. views.register field error and this is the error from views.edit_profile. It cause an error because the mobile phone is invalid. The error should be the same from views.register. views.edit_profile field error models.py CustomUser model: Where I set the validations and made a table. class CustomUser(AbstractBaseUser, PermissionsMixin): username = models.CharField( _('Username'), max_length=150, unique=True, help_text=_('Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.'), validators=[UnicodeUsernameValidator()], error_messages={ 'unique': _("A user with that username already exists."), }, ) email = models.EmailField(_('Email Address'), unique=True) palotype = models.CharField(_('Type'), max_length=150, choices=TYPE_CHOICES, default='Palon-on') suffix = models.CharField(_('Suffix'), max_length=150, blank=True) first_name = models.CharField(_('First Name'), validators=[AlphaSpaces()], max_length=150, blank=False) middle_name = models.CharField(_('Middle Name'), validators=[AlphaSpaces()], max_length=150, blank=True) last_name = models.CharField(_('Last Name'), validators=[AlphaSpaces()], max_length=150, blank=False) birth_date = models.CharField(_('Birth Date'), validators=[BirthdateRegex()], max_length=10, blank=False) region = models.CharField(_('Region'), validators=[AlphaSpaces()], max_length=150, blank=False) city = models.CharField(_('City'), validators=[AlphaSpaces()], max_length=150, blank=False) barangay = models.CharField(_('Barangay'), max_length=150, blank=False) unitno = models.CharField(_('Unit / Apartment No.'), max_length=150, blank=True) floorno = models.CharField(_('Floor'), max_length=150, blank=True) … -
How to correctly write a function for template tags
I have a model: class Perm(models.Model): user_perm = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, related_name='user_perm') choices_perm = models.CharField(max_length=150, choices=permissions_choice, null=True,) class Meta: unique_together = ['user_perm', 'choices_perm'] I wrote a decorator that checks if the user has permission. if not, it redirects it. def user_permissions_handler(need_permissions_constant): def get_view(view): def get_params(request): user_permissions = Perm.objects.filter(user_perm=request.user)\ .values_list('choices_perm', flat=True) if user_is_need_permissions(user_permissions, need_permissions_constant): return view(request) else: return redirect('permissions:error_permissions') return get_params return get_view def user_is_need_permissions(user_permissions, need_permissions_constant): if need_permissions_constant in user_permissions: return True return False This is a table of permissions: edit_user = 'edit_user' view_all = 'view_all' create_user = 'create_user' delete_user = 'delete_user' add_user = 'add_user' permissions_choice = [ (edit_user, 'Can edit user '), (view_all, 'Can view all'), (create_user, 'Can create user'), (delete_user, 'Can delete user'), (add_user, 'Can add user'),] Now I need to write a template tag to check the permissions in templates (for example hang it in front of buttons, if there is permission the button is visible, if not hidden) Here is what I managed to write, but it does not work. please help me to understand from django import template from django.shortcuts import get_object_or_404 from ..models import Perm register = template.Library() @register.filter(name='has_perm') def has_perm(user, need_permissions_constant, request): user_permissions = Perm.objects.filter(user_perm=request.user) \ .values_list('choices_perm', flat=True) if need_permissions_constant in user_permissions: return … -
Django - How to change the `INNER JOIN` to `LEFT JOIN`?
Scenario: Showing all voucher that a user can apply. I have 2 tables Voucher (with all information of a voucher) and VoucherCustomer (listing number of vouchers that a user has used) A validation voucher that can show to user on the application should be Within use-able duration Do not exceed number of times used within a day Do not exceed number of times used per user Do not exceed number of times used for a voucher Must active Here is my model: class Voucher(models.Model): code = models.ForeignKey('VoucherCustomer', related_name= 'voucher_code', on_delete = models.CASCADE) (1) start_at = models.DateTimeField() (2) end_at = models.DateTimeField() (3) usage_limit_per_customer = models.BigIntegerField() (4) times_used = models.BigIntegerField() (5) usage_limit_daily = models.BigIntegerField() (6) times_used_daily = models.BigIntegerField() (7) is_global = models.BooleanField(blank=True, null=True) (8) is_active = models.BooleanField() (9) class VoucherCustomer(models.Model): voucher_code = models.CharField(max_length = 255, primary_key=True) (1) customer_id = models.IntegerField() (2) times_used = models.BigIntegerField(blank=True, null=True) (3) created_at = models.DateTimeField(blank=True, null=True) (4) updated_at = models.DateTimeField(blank=True, null=True) (5) Here is the sample data: +++++++ Voucher ++++++++ (1) (2) (3) (4) (5) (6) (7) (8) (9) TEST01 | 2020-11-30 17:00:00 | 2021-03-01 16:59:59 | 100 | 1124 | 5000 | 6 | true | true +++++++ VoucherCustomer ++++++++ (1) (2) (3) (4) (5) TEST01 10878 … -
Django QuerySet, drop data when value is null
I would like to ask how I can drop data from the QuerySet when the value of the attribute is null. Models.py: class RnDProject(models.Model): name = models.CharField(max_length=100) class Yhrtaskgrp(models.Model): employee_name = models.CharField(max_length=100) employee_id = models.CharField(max_length=10) hours_worked = models.FloatField() assigned_RnD = models.ForeignKey(RnDProject, on_delete=models.SET_NULL) views.py: class RndView(APIView): def get(self, request): qs = Yhrtaskgrp.objects.values('employee_name', 'employee_id').annotate(rnd_hours=Sum('hours_worked', filter=Q(assigned_RnD_id__isnull=False)), all_hours=Sum('hours_worked')) return Response(qs) Object from the qs can look like this when the ForeingKey is null: { "employee_id": "123456", "employee_name": "John Doe", "rnd_hours": null, "all_hours": 20 } I would like to drop all objects with rnd_hours == null from the QuerySet. Is there anyway how django can drop these objects? -
Django - Field attributes in widget context
As I am using some more exotic css framework I would like to change the behaviour of the text input (provide it with label etc. by default). I have overridden the template in django/forms/widgets/input.html Unfortunately the widget context is missing the field, so I cannot use field properties like help_text, label, etc in my template. Therefore I would need to override the TextInput widget. My two options are now: Setting my own widget class for every single field in my Form / Modelform classes Using My custom ModelForm which iterates all the fields in __init__ and replaces the widget. Is there any better way to override django's default text_input widget? Does is there any other way to get field.errors and field.label into the widget (Or is there a reason why there is no label in the widget context)? -
The admin page in django doesnt load the css even though i changed the static file dir
I have mentioned the following in settings.py file : STATIC_URL = '/static/' STATIC_ROOT = [os.path.join(BASE_DIR,'static'),] In my base file, I have mentioned the following : Performance Tool {% load static %} <link rel="stylesheet" type="text/css" href="{% static '/css/style.css' %}"/> <link rel="stylesheet" type="text/css" href="{% static '/css/bootstrap.min.css' %}"/> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <link rel="stylesheet" href="/static/assets/css/icon-filters.css" type="text/css"> <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" /> <link rel="shortcut icon" href="/static/assets/img/favicon.ico"> <!-- <link rel="stylesheet" href="/static/assets/css/skeleton.css" type="text/css"> --> <link rel="stylesheet" href="/static/assets/css/home.css?u=1612766733.2943635" type="text/css"> <link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous"> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.0/css/all.css" integrity="sha384-lZN37f5QGtY3VHgisS14W3ExzMWZxybE1SJSEsQp9S+oqd12jhcu+A56Ebc1zFSJ" crossorigin="anonymous"> <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" /> My index and base pages load well with css