Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I use a range slider with django-filter?
How to use a range slider (for example the jQuery one) with django-filter package? So now I'm using the RangeFilter which just displays to normal text fields for the range. So the search function is working perfectly fin but it's just not that fancy as a cool slider. class TentFilter(django_filters.FilterSet): width = django_filters.NumberFilter(label="Breite") length = django_filters.NumberFilter(label="Länge") number_of_People = RangeFilter(label="People range") class Meta: model = Tent fields = ['width', 'length', 'number_of_People', ] I really would appreciate help because this thing is stressing me out. -
QuerySet Optimisations in Django
I was just wondering, I have the following two pseudo-related queries: organisation = Organisation.objects.get(pk=org_id) employees = Employee.objects.filter(organisation=organisation).filter(is_active=True) Each Employee has a ForeignKey relationship with Organisation. I was wondering if there is anything I can leverage to do the above in one Query in the native Django ORM? Also, would: employees = Employee.objects.filter(organisation__id=organisation.id).filter(is_active=True) Be a quicker way to fetch employees? -
Filtering objects by timezone aware dates
Let's say I have TIME_ZONE variable in settings set to 'Europe/Prague' and also USE_TZ set to True. I also have some data stored in Example: id timestamp 1 2012-07-27T00:00:00+02:00 2 2018-03-11T02:00:00+01:00 3 2013-11-04T14:08:40+01:00 This is what I'm trying to achieve: Extract all dates from those data Filter those data date by date and perform some other action on them For extracting dates I use either Example.dates('timestamp', 'day') or Example.annotate(date=TruncDay('timestamp')).values('date'). Now here is the difference: for first object from example above (with timestamp=2012-07-27T00:00:00+02:00), date return by first approach is 2012-07-27, whereas for second approach it is 2012-07-26. I would like filter to be timezone aware, so I'm currently sticking with the first one. For filtering I am using Example.filter(timestamp__date=date). And there's a problem - it seems that __date filters by date in UTC. For date 2012-07-27 it returns empty QuerySet and for 2012-07-26 it returns first object. Is there any way to achieve filter by timezone aware date? -
dynamically condition form fields in django(Display fields based on previous fields value)
I am currently working on a django project .I have 2 fields namely has_conducted(Radio button[yes and no options]) and years(checkbox) fields.My main idea is that when I click yes in has_conducted the years field must be visible and if no is selected the years field must be disabled or hidden.Plzz do help me solve this .Thanks in advance models.py YES_NO = ( ('Y','Yes'), ('N','No') ) YR_REVISION = ( ('13-14','2013-2014'), ('14-15','2014-2015'), ('15-16','2015-2016'), ('16-17','2016-2017'), ('17-18','2017-2018'), ('18-19','2018-2019'), ('19-20','2019-2020'), ) class SurveyForm(models.Model): has_conducted = models.CharField(choices=YES_NO,max_length=20) year = MultiSelectField(choices=YR_REVISION,null=True,blank=True) forms.py YES_NO = ( ('Y','Yes'), ('N','No') ) class SurveyForm(forms.ModelForm): has_conducted =forms.ChoiceField(choices=YES_NO,widget=forms.RadioSelect()) class Meta: model = SurveyForm fields = '__all__' form.html <div class="container content"> <form method = "POST"> {% csrf_token %} {{ form|crispy }} <button class="btn-warning text-dark btn" type="submit">Submit</input> </form> </div> ````[enter image description here][1] [1]: https://i.stack.imgur.com/Ps8ea.png -
How to add tags name for makemessages, parse tag as xgettext
I'm creating translation for my site. Sometimes I need to add field in django.po when I use custom simple_tag. I expect to see following: {% my_not_standard_trans 'Value' %} I need to use makemessages for parse my custom tag like 'trans'. I tried use _noop, but it not works like {% some_tag _("Page not found") %} I have created custom makemessages command with string xgettext_options = makemessages.Command.xgettext_options + ['--keyword=_noop'] but it works for .py files only, if I add ['--keyword=custom_tag'] it not work also -
Setting up media file access on AWS S3
Im using boto3 and django-storage libraries for apload media files of my django project. storage_backends.py class PrivateMediaStorage(S3Boto3Storage): location = settings.AWS_STORAGE_LOCATION default_acl = 'private' file_overwrite = False custom_domain = False class PublicStaticStorage(S3Boto3Storage): location = settings.AWS_PUBLIC_STATIC_LOCATION settings.py AWS_STORAGE_LOCATION = 'media/private' AWS_PUBLIC_STATIC_LOCATION = 'static/' models.py class Documents(models.Model): """ uploaded documents""" author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) upload = models.FileField(storage=PrivateMediaStorage()) filename = models.CharField(_('documents name'), max_length=255, blank=True, null=True) datafile = models.FileField() created = models.DateTimeField(auto_now_add=True) type = models.ForeignKey(Doctype, on_delete=models.CASCADE, blank=True) File loading works well. But there is a point I don't understand, and the link to the file looks wrong (it contains static instead of media). Looks like https://myhost.s3.amazonaws.com/static/class-descriptions_1.csv And else about access. Now that I click on the link to the file, I get a message <Error> <Code>AccessDenied</Code> <Message>Access Denied</Message> <RequestId>4B8296F8F77491F5</RequestId> <HostId> CG96q+LGWcvsIK2YkuaE2wExL8/YTqH1PmjOSFGAqcgaKaTYnOet1QoItGJhW1Oj </HostId> </Error> This is normal for unregistered users, but how do I allow users registered in my Django project to see this file? -
How to return ManytoManyField to string?
I want to return the ManyToManyField as a string but it turned out to be none. This is the result "Cart id: 36,whitet-shirt,products.Variation.None" I got carts.models.py class CartItem(models.Model): cart = models.ForeignKey(Cart,null=True,blank=True,on_delete=models.DO_NOTHING) product = models.ForeignKey(Product_info,null=True,blank=True,on_delete=models.SET_NULL) variations = models.ManyToManyField(Variation,null=True,blank=True) quantity = models.IntegerField(default=1) linetotal = models.DecimalField(max_digits=100,default=10.99,decimal_places=2) timestamp = models.DateTimeField(auto_now_add=True,auto_now=False,null=True,blank=True) updated = models.DateTimeField(auto_now_add=False,auto_now=True,null=True,blank=True) def __str__(self): return "{},{},{}".format(self.cart,self.product,self.variations) products/models.py class Variation(models.Model): product = models.ForeignKey(Product_info,null=True,on_delete=models.SET_NULL) cat = models.CharField(max_length=120, choices=VAR_CATEGORIES, default='size') title = models.CharField(max_length=100) price = models.DecimalField(max_digits=5,decimal_places=2,null=True,blank=True) description = models.TextField(null=True,blank=True) active = models.BooleanField(default=True) objects = VariationManager() def __str__(self): return self.title -
Download link from ForeignKey model
I would like to create an attachment on every post of my blog. Then I've do this: class FileUpload(models.Model): name = models.Charfield(max_length=70) file = models.FileField() def __str__(self): return self.name def get_absolute_url(self): return reverse("single_file", kwargs={"pk": self.pk}) class BlogPost(models.Model): title = models.Charfield(max_length=70) . . . attachment = models.ForeignKey( FileUpload, on_delete=models.CASCADE, related_name="related_attachment", null=True, blank=True, ) Inside the template of a single post I've put this: {% if blogpost.attachment %} <hr> <div> <a class="btn btn-info" href="{{ attachment.get_absolute_url }}" rule="button"> Download </a> </div> {% endif %} But I see that the href is empty and I can't download the attachment. The if condition work fine because the button didn't appear if the post don't have the attachment. What is the right way to put a download link inside my download button? -
Django Admin multiple inline validation upon submit
I'm trying to validate 2 inlines upon submit. The validation is a qty cannot be 0 if both inlines are zero and will allow if 1 of the qtys is greater than 1. Any suggestions on how to capture both form values upon submit and flag a validation error based on the logic above? Code Flow class AInlineForm(forms.ModelForm): qty = forms.IntegerField(min_value=0) class Meta: model = A exclude = ['created'] def __init__(self, *args, **kwargs): super(AInlineForm, self).__init__(*args, **kwargs) self.fields['qty'].initial = 0 class BInlineForm(forms.ModelForm): qty = forms.IntegerField(min_value=0) class Meta: model = B exclude = ['created'] def __init__(self, *args, **kwargs): super(BInlineForm, self).__init__(*args, **kwargs) self.fields['qty'].initial = 0 class BInline(admin.TabularInline): model = B extra = 1 max_num = 1 form = BInlineForm class AInline(admin.TabularInline): model = A extra = 1 max_num = 1 form = AInlineForm class OrderAdmin(admin.ModelAdmin): inlines = [AInline, BInline] -
Data not showing on template
This is the first time I'll be implementing a Class Based View on a real project but the data is not showing on the template. <div class="container"> <h4 class="heading-decorated text-center mt-5">Our Volunteers</h4> {% for volunteer in volunteers %} <div class="row row-30 text-center mb-5"> <div class="col-sm-6 col-md-3"> <figure class="box-icon-image"><a href="#"><img class="rounded" src="{{volunteer.volunteer_image.url}}" alt="" width="126" height="102"/></a></figure> <p class="lead">{{volunteers.volunteer_name}}</p> </div> </div> {% endfor %} </div> views.py class VolunteerListView(ListView): model = Volunteers context_object_name = 'volunteer' template_name = 'add_my_language/home.html' models.py class Volunteers(models.Model): volunteer_image = models.ImageField(upload_to='media/volunteers') volunteer_name = models.CharField(max_length=255, blank=False) def __str__(self): return self.volunteer_name Did I miss anything? -
Django adds https:// in all my static files. This is after integrating S3
After integrating s3 and adding my static url all my static files add a http:// in the url <link rel="stylesheet" href="https://http://bucket_name.s3.amazonaws.com/static/css/styles.css"> STATIC_URL='https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) -
AJAX request to a Django server stays on stalled Chrome
I have a simple django server with the Django Rest API installed. My problem is that when I make a simple query using AJAX the query stays stalled by Chrome: If I make this request disabling Chrome's cache (with the dev tools options) it loads without any problem. Here is the ajax query I use: $.ajax({ type:"GET", dataType:"json", beforeSend: function(xhr){xhr.setRequestHeader('Authorization', 'Token '+global_api_token);}, url:url, error: function(result) { console.log(result) }, success: function(result){ console.log(result) } }); Does any know why this is happening? -
Django formset errorlist 'This field is required'
I am creating a formset with django which contains children information. I am using createview (CBV) for this. The form is displayed properly, it has functionality of adding children and removing children all working properly. But, when i click on submit, form_invalid is called instead of form_valid. To know this issue i printed form.errors and i saw following errors <ul class="errorlist"><li>deal_id<ul class="errorlist"><li>This field is required.</li></ul></li><li>child_name<ul class="errorlist"><li>This field is required.</li></ul></li><li>son_or_daugher<ul class="errorlist"><li>This field is required.</li></ul></li><li>child_age<ul class="errorlist"><li>This field is required.</li></ul></li><li>child_education<ul class="errorlist"><li>This field is required.</li></ul></li><li>child_occupation<ul class="errorlist"><li>This field is required.</li></ul></li></ul> Below is my code Template :- {% extends "forms_app/base.html" %} {% load static %} {% block title %}{% endblock %} {% block content %} <h2>Profile</h2> <hr> <div class="col-md-4"> <form action="" method="post">{% csrf_token %} <table class="table"> {{ childrens.management_form }} {% for form in childrens.forms %} {% if forloop.first %} <thead> <tr> {% for field in form.visible_fields %} <th>{{ field.label|capfirst }}</th> {% endfor %} </tr> </thead> {% endif %} <tr class="{% cycle row1 row2 %} formset_row"> {% for field in form.visible_fields %} <td> {# Include the hidden fields in the form #} {% if forloop.first %} {% for hidden in form.hidden_fields %} {{ hidden }} {% endfor %} {% endif %} {{ field.errors.as_ul }} {{ field }} … -
Get not all values but specific values of field in another model with one to one field
I have two models. 1. courses 2. First Year Here is course Model class Courses(models.Model): class Meta: verbose_name_plural = 'Courses' year_choices = [ ('----', '----'), ('First Year', 'First Year'), ('Second Year', 'Second Year'), ('Third Year', 'Third Year'), ('Fourth Year', 'Fourth Year'), ('Minor', 'Minor'), ] year = models.CharField(max_length=50,default='----',choices=year_choices) course_code = models.CharField(max_length=10, default='', validators=[MinLengthValidator(1)]) Here is FirstYear Model class FirstYear(models.Model): class Meta: verbose_name_plural = '1. First Year' course = models.OneToOneField(Courses, default='', on_delete=models.CASCADE) title = models.CharField(max_length=100,default='') def __str__(self): return '{}'.format(self.title).capitalize() I'm new to Django. When I run this code all of the course code is returning. But I don't need that. My question is I have to invoke the course_code field only if it is first year and not all year. Please help me here. Thank you. -
Django 2.2 set ModelChoiceField initial value without id/pk
I have a GET based search, passing a few search terms and paging info through the query string. I can grab the items from the query string without any issues, but passing them back to the template via the SearchForm to preserve the search is proving to be difficult. items/?search=foo&category=bar&page=1&pageSize=20 forms.py class SearchForm(forms.Form): search = forms.CharField(*) category = forms.ModelChoiceField(queryset=Items.objects.all(), *) *simplified for brevity In the view, I can retrieve all the values or their defaults from the query string, and I can even set the value for the search field, but the ModelChoiceField is the one I am struggling with. I can set an initial value, but not based on the select text... views.py class ItemList(View): template_name = 'items.html' def get(self, request): items = Item.objects.all() form = SearchForm() search = request.GET.get('search') category = request.GET.get('category') page = int(request.GET.get('page', 1)) pageSize = int(request.GET.get('pageSize', 20)) if category != None: #non working: #form.fields['category'].initial = category #working by setting a value form.fields['category'].initial = 1 items.filter(category__name=category) if search != None: form.initial['search'] = search items = items.filter(field__icontains=search) context = { 'form': form, 'items': items } return render(request, self.template_name, context) I tried various methods of trying to retrieve the value/id from the form.category field unsuccessfully. I would hate … -
How to publish django web to local server?
I am now using django to develop a web page but I found that I have no idea to publish it. As I am a really new to web programming, I don't even know what the key words I should search for, but I am asked to write a web program and no one in the company can help me with this. I know in my company, the company website is publish on the local server with only the html files. Therefore, if I want to publish the whole django project, how can I do it? or where can I have those information to look for? My main goal is to publish it to the intranet and also can interact with other pages that were not developed by django. For example, in the nav bar, there will be one link to the webpage that designed by django. Thank you. -
python manage.py runserver command not working [duplicate]
This question already has an answer here: Django runserver error, new installation, first time user of Django 2 answers python manage.py runserver not working and showing errors that are shown in image: enter image description here Kindly suggest a solution -
Django: How to conditionally define fields in a model mixin?
In my back-end (API) site, there are certain fields that are common to most models, but not all. I have been using mixins for those fields so that I can include them for the models they apply to, and omit them from the ones they don't. For example: class AddressPhoneModelMixin(models.Model): address = models.TextField( verbose_name=_('Address'), blank=True, null=True, ) country = models.ForeignKey( Country, on_delete=models.SET_NULL, verbose_name=_('Country'), blank=True, null=True, ) phone_number = PhoneNumberField( verbose_name=_('Phone'), blank=True, null=True, ) mobile_number = PhoneNumberField( verbose_name=_('Mobile Phone'), blank=True, null=True, ) fax_number = PhoneNumberField( verbose_name=_('Fax'), blank=True, null=True, ) class Meta: abstract = True But I have other such mixins, and when a model needs to include all fields, the model definition gets to be quite long: class Client(AddressPhoneModelMixin, DateFieldsModelMixin, models.Model): And I now have other "common" fields I want to add, so it's only going to get worse. I want to keep all these common fields in one place for DRY, but also in case anything changes about a field, I only have one place to make the changes. My idea is to have one mixin called CommonFieldsModelMixin, so that I will have only one mixin to include in the model definition. But for those models that don't need certain … -
Specify aws named profile S3Boto3Storage
I am using S3Boto3Storage for uploading django images to s3. I have multiple profiles in my local. Can I specify profile name with S3Boto3Storage ? -
What effective technique can I apply to use the get_initial method twice to solve the problem stated below?
I have created 3 models A,B, and C that are linked to each other using foreign key. Model "B" is linked to Model "A" using OneToOne relationship and Model "C" is also linked to Model "B" using "OneToOne" relationship. I then used then "get_initial()" method to set the initial id_field for the form of model "B" using the foreign key conection with model "A". I later repeated the same "get_intial()" to set the initial id field for the form of model "C" using its foreign key connection with B. This worked as projected. How ever upon deleting a record instance in Model "B" with its id=7 as obtained from an instance in model "A", and re-creating a new record in model "B" using that same id=7. When ever I call the get_initial() method form "C" with the id=7 from model "B", I recieve an error message "matching query does not exist." And when I, increment the called id by 1, I get the correct result of the query. I went further to delete 4 more records in model "B" and recreated them with their ids as passed by model "A". And realized when ever I called the get_initial() method to … -
Allow Blank FileField in Django
I have a model where one of the fields is a FileField. The file that should be attached here is not available at the time of creating the Order - so it should be allowed for the user to create an Order without attaching a file here. If you see the code below - I feel like I have setup the model properly to allow this field to be blank, but when I try to submit an Order, I get an error "The 'order_file' attribute has no file associated with it." So what am I missing? models.py class Orders(models.Model): ... order_file = models.FileField(upload_to='web_unit', default=None, null=True, blank=True) def __str__(self): return self.reference since I have default=None, null=True, blank=True I expected that this would work without uploading the file at time of creating the Order object. -
Type Error on uploading image files through django admin
I've created a personal website/blog with python django, and as an admin, I want to create instances of that blog based on the django model and display it to the html page accordingly. That model basically consists of a Title field, TextArea field, and Image field. My app is currently deployed on Heroku, and I'm serving images using AWS S3 Buckets. Locally, when I create a blog instance through the django admin it is successful, but on the deployed app on Heroku, I'm getting this error: expected string or bytes-like object and this is what appears in the console was loaded over a secure connection, but contains a form that targets an insecure endpoint 'http://dpaste.com/'. This endpoint should be made available over a secure connection. I'm unsure if the error has to do with the image field or the entire instance of the blog model. Any ideas on how to approach this? -
Django Many to Many query set relation has unexpected result
When running a filter against a many-to-many relation the result of the field contains unexpected results according to the filter. Note The is_current Foo and Bar will have at most one True for a group of Foo/Bar. Meaning Foo has several that are False ie. not current and same with Bar. I've tried 4 variations Normal filter: just listing out fields to filter Boolean value as True/1 on the filter Q filter prefetch_releated and Q filter # model.py class Bar(Model): is_current = BooleanField() text = CharField(max_length=32) class Foo(Model): is_current = BooleanField() name = CharField(max_length=32) bar = ManyToManyField(Bar) # views.py def index(request): # when viewing the bar objects from the filter result # it will contain bar objects that are both is_current = True & False return Foo.objects.filter(Q(is_current=1) & Q(bar__is_current=1)) The query output looks like this: SELECT app_foo.id, app_foo.is_current, app_foo.name FROM app_foo INNER JOIN app_foo_bar ON (app_app.id = app_foo_bar.bar_id) INNER JOIN app_bar ON (app_foo_bar.bar_id = app_bar.id) WHERE (app_foo.is_current = True AND app_bar.is_current = True) If I modify the query and run it in the dbshell I get what I expected. SELECT app_foo.id, app_foo.is_current, app_foo.name, app_bar.text FROM app_foo INNER JOIN app_foo_bar ON (app_app.id = app_foo_bar.bar_id) INNER JOIN app_bar ON (app_foo_bar.bar_id = app_bar.id) … -
How to bined a detailview field to a form field in django and save into database
I am building this simple system for online voting, where people can vote but will have to pay for their vote cast.My current challenge is how to bined a selected candidate on a page and allowing voters to enter number of votes they went to cast for that candidate on the same page I have tried using SingleObjectMixin but am having problem saving the form in database. And also how can i prepopulate the select candidate to a model field name Nominee model.py class Award(models.Model): STATUS_PUBLISHED = ( ('Closed', 'Closed'), ('Opened', 'Opened'), ) slug = models.SlugField(max_length=150) name = models.CharField(max_length=100) date = models.DateTimeField(auto_now_add=True) image = models.ImageField(upload_to='award_images') status = models.CharField(max_length=20, choices=STATUS_PUBLISHED, default='Closed') def __str__(self): return self.name class Category(models.Model): Award = models.ForeignKey(Award, on_delete=models.CASCADE) category = models.CharField(max_length=100,) slug = models.SlugField(max_length=150) date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.category class Nomination(models.Model): Fullname = models.CharField(max_length=120) Category = models.ForeignKey(Category, on_delete=models.CASCADE) votes = models.IntegerField(default=0) date = models.DateTimeField(auto_now_add=True) slug = models.SlugField(max_length=150) image = models.ImageField(upload_to='nominations_images') def __str__(self): return self.Fullname class VoteAmount(models.Model): Nominee = models.ForeignKey(Nomination, on_delete=models.CASCADE) votes_amount = models.IntegerField(default=0) def __str__(self): return self.votes_amount views.py from django.views.generic import ListView, DetailView, CreateView from .models import Award, Category, Nomination, VoteAmount from .forms import VoteAmountForm from django.urls import reverse from django.http import HttpResponseForbidden from django.views.generic import … -
Django REST Framework Deep Dive - Where is it determined that an enpoint needs an auth token
general django question for those who are more experienced than myself, I'm reading through the code posted for a tutorial on thinkster.io: https://github.com/howardderekl/conduit-django/tree/master/conduit/apps There's an endpoint pertaining to the User model authenticion/models.py that requires an Authorization header for it to return user information defined here in authentication/views.py: class UserRetrieveUpdateAPIView(RetrieveUpdateAPIView): permission_classes = (IsAuthenticated,) renderer_classes = (UserJSONRenderer,) serializer_class = UserSerializer def retrieve(self, request, *args, **kwargs): serializer = self.serializer_class(request.user) return Response(serializer.data, status=status.HTTP_200_OK) My question is how/where is it (supposed to be) determined that an endpoint requires this Authorization. My thought is that it is tied to the permission_classes variable stated in the UserRetrieveUpdateAPIVIiew class above. I dug into the package location where this was imported from (from rest_framework.permissions import IsAuthenticated), but that doesn't appear to contain anything pertaining to an HTTP header: class BasePermissionMetaclass(OperationHolderMixin, type): pass class BasePermission(metaclass=BasePermissionMetaclass): """ A base class from which all permission classes should inherit. """ def has_permission(self, request, view): """ Return `True` if permission is granted, `False` otherwise. """ return True def has_object_permission(self, request, view, obj): """ Return `True` if permission is granted, `False` otherwise. """ return True ... ... ... class IsAuthenticated(BasePermission): """ Allows access only to authenticated users. """ def has_permission(self, request, view): return bool(request.user and …