Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
disable ordering by default for django_tables2 Tables
I use django_tables2 to render my tables. For one table, I only want to see the most recent 5 entries. Therefore, I need to order my queryset before passing it to the table object: qset = myObject.objects.order_by('-start_time').all()[:5] table = MyTableClass(qset, template='path/to/template.html') This yields the following error message: AssertionError: Cannot reorder a query once a slice has been taken. I could set orderable=False for every django_tables.Column, but since MyTableClass inherits from another table class, I would like to avoid this. Thanks in advance -
Daphne in Docker file
I have my docker file configuration for my django project, I am trying to set up daphne server for my project in the Docker file, I do not want to have the daphne command in the compose file.But when I add the following command to the Dockerfile I get an error of no app specified. CMD daphne -b 0.0.0.0 -p 8080 <app>.asgi:channel_layer How do I correctly configure this? -
Adding extra content to Class Based View and filtering it
I've built a for-loop in my HTML template and its nearly working. The issue I'm having is its listing Matches that are apart of a different tour. I think the way to fix this is adding a filter to the view that basically says "only pull in the matches to do with this tour" which is what I've tried to do below in the Match.objects.filter() but it isnt working and I'm not sure why. class CricketCalendar(generic.ListView): template_name="monthly_view/cricket-monthly-view.html" context_object_name='cricket_monthly_view' queryset = CricketMonthlyView.objects.all() def get_context_data(self, **kwargs): context = super(CricketCalendar, self).get_context_data(**kwargs) context['Tour'] = Tour.objects.all() context['Match'] = Match.objects.filter(tour=self.request.Tour) return context I have also tried the following and neither worked: self.kwargs['pk'] self.kwargs['Tour'] -
Django Admin conditional display inlines based on models property
I've got marketplace models with fields: class VacationEvent(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) process_fba = models.BooleanField(default=True) @property def has_amazon_fba_vacation(self): return hasattr(self, 'amazon_fba_vacation') And in admin.py: class FBAInline(admin.StackedInline): model = AmazonFBAVacation can_delete = False verbose_name_plural = 'amazon fba vacation' fk_name = 'event' I need to display conditionally FBAInline class when creating\updating VacationEventAdmin. list_filter shows true\false values of "process_fba" field, so if it is true - FBAInline should be displayed: @admin.register(VacationEvent) class VacationEventAdmin(admin.ModelAdmin): inlines = [] list_display = ('id', 'user', 'holiday_name', 'start_date', 'end_date', 'process_fba', 'process_fbm', 'process_walmart', 'process_ebay') list_filter = ['process_fba', 'process_fbm', 'process_walmart', 'process_ebay', 'status',] search_fields = ['holiday_name', 'user__username'] # if VacationEvent.process_fba and VacationEvent.has_amazon_fba_vacation: # inlines.append(FBAInline) # try: # getattr(VacationEvent, 'process_fba') # except AttributeError: # print "doesn't" # else: # inlines.append(FBAInline) I tried getting attr but don't understant how to compare field values for admin. Thanks for any help. -
Django ignore method for ALLOWED_HOSTS and django-cors-headers
In my app, I defined ALLOWED_HOSTS and CORS_ORIGIN_WHITELIST, but I have some methods which I want to be ignored from ALLOWED_HOSTS and CORS_ORIGIN_WHITELIST, in other words I want to access those methods from from everywhere. Is there a way to achieve this? -
Make autocomplete on text Input field using django-autocomplete-light 3.2.10
I have integrate django-autocomplete-light 3.2.10 successfully and it is working fine the issue is with its UI In template it renders with <select> <option> html, after clicking on it a span get attached to it with input text field inside. In form i am using ModelSelect2 as widget. widget=autocomplete.ModelSelect2(url='discovery:city-autocomplete') TextWidget is not supported in latest version 3.2.10 I just want the input text field directly visible to user. is there any possible way to achieve it with same library. May be i can create my own CustomTextWidget, or use some javascript to customize its UI -
Django + CMS: filer failing to upload
I am using django-cms==3.4.4 with django-filer==1.2.8, which has been working perfectly until now. When attempting to upload new images/files using the bootstrap3 image plugin, I am shown 'upload successful' but get an error 500: "POST /en/admin/filer/clipboard/operations/upload/2/?qqfile=test.jpeg HTTP/1.1" 500 102 This has been working previously. Recent changes to settings.py have included modifying MEDIA_ROOT and STATIC_ROOT, however, reversing these changes does not resolve the issue. I have seen on questions with similar problems that installing Pillow with easy_install instead of pip can solve the problem. I tried this, to no avail. Any help would be great. -
Django, S3 secure files - blue question mark instead of image
I host my static and media within AWS S3, I believe this is setup correct and is working. the files are currently public but I would like to make them all private, so that django acts as proxy for them. thus far I can get the image url correctly I get the type and the file and then I output it to a http response, I think im pretty close, however it returns a blue question mark instead of the image at the moment def get_file(request, file_id): import requests from django.http import HttpResponse from PIL import Image from io import BytesIO file_object = SiteFiles.objects.get(pk=file_id) if file_object.site_image: image_data = requests.get(file_object.site_image.url) image = Image.open(BytesIO(image_data.content)) return HttpResponse(image, content_type='image/{}'.format(image.format)) elif file_object.site_file: file_data = requests.get(file_object.site_image.url) return HttpResponse(pdf_data, content_type='application/{}'.format('type')) else: return redirect('sites:file_not_found') I have PIL confirmed as getting the image when I run some testing: >>> image_data = requests.get(file_object.site_image.url) >>> img = Image.open(BytesIO(image_data.content)) >>> img <PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=640x480 at 0x7F55F2E29780> -
How to pass url value in django to views
My url.py is as below, from myapp import views urlpatterns = [ url(r'^myapp/get_requests/$', views.get_requests), ] Now my views.py is as below, @api_view(['GET']) def get_request(request): #How can I get request ID (base url here)? return HttpResponse('test') In the above if I do request in my browser with url as below it reaches my get_request method, http://localhost:8080/myapp/get_requests/ But the same gives error 404 when I try with some ID in the end as below, http://localhost:8080/myapp/get_requests/40 Now How can I get this ID number 40 in my views.py method? -
Using signals pre-delete, how to turn it off on some occasions?
Using Django: 1.10 Issue: Turn off pre_delete signal and receiver sometimes I want to use pre_delete to delete other related records for a model. And not call it at certain times even when I do want to delete the main model What did I try? I tried overriding the delete function in the main model PalletContent like this: def delete(self, *args, **kwargs): self.auto_delete_line_item = False if 'auto_delete_line_item' in kwargs: self.auto_delete_line_item = kwargs['auto_delete_line_item'] del kwargs['auto_delete_line_item'] return super(PalletContent, self).delete(*args, **kwargs) And then in the pre_delete @receiver(pre_delete, sender=PalletContent) def auto_delete_line_item(sender, instance, **kwargs): if instance.auto_delete_line_item: EntryFormHelper.remove_entry_form_line_item_from_pallet_content( pallet_content=instance) ExitFormHelper.remove_exit_form_line_item_from_pallet_content_if_any( pallet_content=instance) And then in the appropriate calls: I expect this to activate the pre_delete: pallet_content.delete(auto_delete_line_item=True) I expect this not to activate the pre_delete: pallet.pallet_contents.all().delete() What I got back was: File "/usr/../signals.py", line 31, in auto_delete_line_item if instance.auto_delete_line_item: AttributeError: 'PalletContent' object has no attribute 'auto_delete_line_item' -
How can I get the foreign field's name in queryset?
I have a Disk model, which has three ForeignKey: class Disk(models.Model): diskEssenceType = models.ForeignKey(to=DiskEssenceType, related_name='disks') # "SAS", "SSD" 等 diskOsType = models.ForeignKey(to=DiskOSType, related_name='disks') # "系统盘" "数据盘" 两种选择 hostType = models.ForeignKey(to=HostType, related_name='disks', on_delete=models.CASCADE) price = models.DecimalField(max_digits=8, decimal_places=2, default=0.00) # 单价 def __str__(self): return self.diskEssenceType.name + "-" + self.hostType.name def __unicode__(self): return self.diskEssenceType.name + "-" + self.hostType.name I use queryset : qs = Disk.objects.filter(hostType=obj) Its queryset data is like bellow, after use model_to_dict convert: { "price": 5.0, "diskOsType": 1, "hostType": 6, "diskEssenceType": 1, "id": 4 }, But I want to get the diskEssenceType's name, and the diskOsType's name, not its id, how to do with that? -
How to force function to evaluate queryset every time it is called
I'm creating a social media site in django, in which each user can have multiple accounts, each with their own posts, friends etc. In order to determine which account to use when loading templates, I have defined this function: def get_active_account(request): for account in Account.objects.filter(user=request.user): if account.active: return account Most views will then call get_active_account when they need to evaluate the currently active account. Now, the problem arises when changing the active account. In the view: def set_active(request, pk): account = get_object_or_404(Account, pk=pk) account.set_active() return redirect('/') In the Account model: def set_active(self): for account in Account.objects.filter(user=self.user): account.active = False account.save() self.active = True self.save() This appears to do nothing; anything referencing the active account will still show the previously active account, and trying to create a post etc. will do it under the old account. After refreshing, however, everything is as it should be. From what I've read, this is a problem with the get_active_account function evaluating the queryset once and then returning a cached version when it is called later (although this may be a totally incorrect assumption). How do I fix the problem, and have everything work without needing a browser refresh? -
<Disk: > is not JSON serializable
In my serializer, I have a SerializerMethodField field: class CloudHostParamsSerializer(ModelSerializer): """ 根据hosttype id返回云服务器购买需要的参数 """ cputypes = CPUTypeSerializer(many=True, read_only=True) memtypes = MEMTypeSerializer(many=True, read_only=True) bandwidths = BandWidthTypeSerializer(many=True, read_only=True) #disks = HostTypeDiskSerializer(many=True, read_only=True) disks = serializers.SerializerMethodField() class Meta: model = HostType exclude = [ "availablearea", ] def get_disks(self, obj): qs = Disk.objects.filter(hostType=obj) dict = {"系统盘": [], "数据盘": []} for item in qs: if item.diskOsType.name == "系统盘": dict["系统盘"].append(item) elif item.diskOsType.name == "数据盘": dict["数据盘"].append(item) return dict in it I return a dictionary, but when I access the API, there comes a issue: TypeError at /api/userfront_product/cloudserver/cloudparams/hosttype/6/ is not JSON serializable My views.py is bellow: class CloudParamsAPIView(RetrieveAPIView): """ 根据hosttype id得到的 """ serializer_class = CloudHostParamsSerializer permission_classes = [] queryset = HostType.objects.all() -
How to set initial value in Django UsercreationForm
I am beginner in Django and developing a user registration page using the UserCreationForm from django.contrib.auth.forms. But, unable to set the initial values for password1 and password2 fields. My requirement is when opening the usercreation form the password and re-enter password fields should get filled with an default password. I have tried this way but unable to achieve this requirement. views/user.py if request.method == "POST": form = UserCreationForm(request.POST) if form.is_valid(): user = form.save() else: form = UserCreationForm(initial={'password1':'testing123','password2':'testing123'}) Any help would be appreciated. -
Copying user-uploaded media for local Django development
When I'm developing my apps locally, I obviously need to use local storage for all my media. In production, I am using S3 for these files. Is there any way to sync between these two? Or is the only way for my local site to see the latest images that users have uploaded on to the live site to regularly copy the media from S3 to my local storage? -
How to trigger clean method from model when updating?
When I save my form I perform validation of data that is defined in my model def clean(self): model = self.__class__ if self.unit and (self.is_active == True) and model.objects.filter(unit=self.unit, is_terminated = False , is_active = True).exclude(id=self.id).count() > 0: raise ValidationError('Unit has active lease already, Terminate existing one prior to creation of new one or create a not active lease '.format(self.unit)) How can I trigger same clean method during simple update without a need to duplicate clean logic in my update view?(In my view I just perform update without any form) Unit.objects.filter(pk=term.id).update(is_active=False) -
Django deployement with mysqldb
Hello for some time I was using sqlite db for local trsting and deployement but I found that it isn't the better solution for some project that's why I have some question about mysql db how you can associate it with django project and how you can deploy your project with this db -
Django signals not working
I have a custom function that runs when a credit is added to the CreditsHistory table, which is called by a signal: def update_credits(sender, instance=None, **kwargs): if instance is None: return sum = CreditsHistory.objects.filter(member=instance.member).aggregate(Sum('credits_amount')) instance.member.n_credits = sum['credits_amount__sum'] instance.member.save() post_save.connect(update_credits, sender=CreditsHistory) post_delete.connect(update_credits, sender=CreditsHistory) Credits are updated everyday for certain members, but the n_credits field in the Members model is not updated for all members who get a new CreditHistory instance. I guess there is some sort of time out happening, or the database can't cope with the aggregation of the large CreditsHistory table for multiple members.. How can I debug this? -
Django templates {% regroup %} : prevent regrouping if grouper value is None
Currently working on a e-commerce project (with django-oscar), I have an issue regarding products display on the basket template. I use the {% regroup %} tag because I have several types of products : standalone, parent or children. Each basket line corresponds to a product, and if several of them are children sharing the same parent product, I want them to be regrouped under their common parent. However, I want standalone products to stand on their own. My queryset is the following : in_stock_lines = request.basket \ .all_lines() \ .order_by('product__parent', 'date_created') \ .filter(attached_to=None, product__product_class__name='Produit standard', is_customized=False) In basket.html: {% regroup in_stock_lines by product.parent as parent_list %} {% for parent in parent_list %} {% if parent.grouper %} {% include "basket/partials/_basket_non_customized_product.html" %} {% else %} {% include "basket/partials/_basket_non_customized_standalone_product.html" %} {% endif %} {% endfor %} The thing is that I don't want the regroup to act in the {% else %} part, because they are standalone products and are not supposed to be regrouped. But as their product.parent, i.e. the grouper is None, they are. Is there way to prevent the {% regroup %} to act for a certain grouper value ? I could make two distinct queries in my views.py to … -
How to get objects by State in REST API
I am working on an SPA angular/django, I have designed action ressources to be retrieved by Id (this way I can better handle cache in front). However, front needs for some features to retrieve actions by state instead of id : Option 1 Create new root api/actions/:state Option 2 Return list of action ids by state in GET: api/projects/:id route. fetch state related ids using existing root api/actions/:id Whis option would be cleaner ? -
Django custom manager to filter nearby through related model
I have two models shop and address. class Shop(BaseModel): name = models.CharField(max_length=100, blank=True, null=True) address = models.ForeignKey(Address, blank=True, null=True, on_delete=models.SET_NULL) objects = LocationManager() Address Model class Address(BaseModel): latitude = models.DecimalField(max_digits=16, decimal_places=14, blank=True, null=True) longitude = models.DecimalField(max_digits=16, decimal_places=14, blank=True, null=True) status = models.NullBooleanField(null=True) I have created a custom Manager for Shop model class LocationManager(models.Manager): def nearby(self, latitude, longitude, proximity): """ Return all object which distance to specified coordinates is less than proximity given in kilometers """ # Great circle distance formula # acos will not work in sqlite gcd = """ 6371 * acos( cos(radians(%s)) * cos(radians(latitude)) * cos(radians(longitude) - radians(%s)) + sin(radians(%s)) * sin(radians(latitude)) ) """ queryset = self.get_queryset().select_related('address') \ .exclude(latitude=None) \ .exclude(longitude=None) \ .annotate(distance=RawSQL(gcd, (latitude, longitude, latitude))) \ .filter(distance__lt=proximity) \ .order_by('distance') return queryset Now I want to find nearby shops using custom manager: Shop.objects.nearby(13.244334,72.329832,20) But i am getting error Cannot resolve keyword 'latitude' into field. Choices are: address, address_id, name How can i use address field to find nearby shop? -
FIle/Path selection dialogue in Django Project
for my bachelor thesis I´ll have to code a tool in Django, which will have to select a file / filepath to work with it. I´v been searching for that for a while now, but haven´t found anything: I´d like to have a GUI selection method for browsing to a location on the filesystem, select a file and store it with its corresponding path in an object containing the filecontents (will be XML) and the filepath of the file in a FilePathField. I´m new to Django development, so take it easy on my poor soul, please :) .......... -
Django Model: Meta: how to have default ordering case-insensitive
I am having a Django Model as shown below: I know that we can set the default ordering in the Meta class. class Ingredient(models.Model): name = models.CharField(max_length=200,unique=True,null=False) slug = models.SlugField(unique=True) class Meta: ordering = ["name"] As the ordering is set to name here. What i found is, it is ordering by case-sensitive. So how to make it case-insensitive -
slow on a queryset. Is this my way of doing things? Or the return of the base that is ready
I think I do not do things right on one of my views. My model: class FacebookBien(models.Model): uid = models.IntegerField(primary_key=True) ref_agence = models.ForeignKey(FacebookAgence, db_column='ref_agence') loyer = models.FloatField() prix = models.FloatField() ville = models.CharField(max_length=200) code_postal = models.CharField(max_length=200) ref_type_bien = models.IntegerField() surface_totale = models.FloatField() source = models.CharField(max_length=200) nombre_de_pieces = models.IntegerField() date_creation = models.DateTimeField() list_source = models.TextField() class Meta: managed = False db_table = 'recette_facebook\".\"vue_facebook_bien_recherche' My serializer: class FacebookBienSerializer(serializers.ModelSerializer): ref_agence = FacebookAgenceBienSerializer(read_only=True) class Meta: model = FacebookBien fields = '__all__' extra_fields = ['ref_agence'] class FacebookAgenceBienSerializer(serializers.ModelSerializer): class Meta: model = FacebookAgence fields = ['site_web'] My pagination: class SmallPagesPagination(PageNumberPagination): def get_paginated_response(self, data): return Response({ 'pagination': { 'next': self.get_next_link(), 'previous': self.get_previous_link(), 'count': self.page.paginator.count, 'total_pages': self.page.paginator.num_pages, 'current': self.page.number, }, 'results': data, }) def get_page_size(self, request): return 6 When I use this view it's perfect I have all the objects instantly: class Test(generics.ListAPIView): queryset = FacebookBien.objects.all() pagination_class = SmallPagesPagination serializer_class = FacebookBienSerializer This view return 63 600 objects When i use this view it's the same it's instantly: class BienAgence(generics.ListAPIView): queryset = FacebookBien.objects pagination_class = SmallPagesPagination def get(self, request, *args, **kwargs): ras = request.GET res = ras.dict() if FacebookBien.objects.filter(ref_agence=int(kwargs['ref_agence'])).exists(): requete = self.queryset.filter(ref_agence=int(kwargs['ref_agence'])) if (res['type'] == 'bien'): requete = requete.filter(prix__gte=int(res['p_mini'])) if res['p_maxi'] != '5000000': requete = requete.filter(prix__lte=int(res['p_maxi'])) if (res['prix'] … -
How can I achieve one single form, pre-populated with data from two different Profile instances?
I have a model, Pair, and another model Profile. An instance of the model Pair will be made with a form that draws from two different Profile instances. So, how do I pre-populate a single form with bits of information from two Profiles and also create it? Two models: Profile & Pair: class Profile(models.Model): ... favorites = models.CharField(max_length=150) class Pair(models.Model): requester = models.ForeignKey(Profile) accepter = models.ForeignKey(Profile) requester_favorite = models.CharField(max_length=50) accepter_favorite = models.CharField(max_length=50) The form so far: class PairRequestForm(forms.Form): your_favorites = forms.CharField(max_length=50) partners_favorites = forms.CharField(max_length=50) Code Explanation: The way it works is, a user(requester) will request the initiation of a pair with the PairRequestForm to the potential accepter. The form should be pre-populated with the "favorite" of each individual user. I'm not sure how to wire up the views.py since I need to obtain two objects. class PairRequestView(FormView): form_class = PairRequestForm template_name = 'profile/pair_request.html' success_url = "/" def is_valid(self, form): return note: The pair must be pre-populated with current information from the Profile. However, the form will not update any old information(will not save() any Profiles)--it will simply create a new Pair instance.