Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get hour and minute integers from TimeField in Django?
I have a TimeField() which saves a time. I want to create a model method that finds if user has arrived after 9:00. def late(self): t = strptime(self.time, "%H:%M") hour = int(t.tm_hour) min = t.tm_min if hour > 9: return True What's wrong with this code? -
How to implement group permission with tastypie
I have done the djano authorization multiauthentication with django tastypie. Now I need to implement the groups and permission with the same. Tried couple of ways but now working. Is anybody implemented the same. -
how to truncate image from a section which contains both images and texts in html format
i have made a description field which contains both images and texts. i have done this using froala editor. now i want to display a thumbnail view which contains some part if description, so m using "truncatewords" tag for it. The problem that i am facing is that when an image is before the text content than django is showing full image, which does not look good. i don't want to diaplay any image of the description field in thumbnail view, only the text. how can i do it?? please help this is my html code line for that: <div>{{card.desc|truncatewords:8|safe}}</div> -
Django jMeter Api testing fail due to http timeout connection fail
Jmeter config: webserver: server name: 120.0.0.1 port no: 9000 Timeouts Connect: Blank Response: Blank Method: GET Thread user: 500 Ramp-up: 1 loop count: 1 (check box not checked) In 500 user 70 user fail here is code @api_view(['GET']) def country_list(request): #country = cache.get('country') try: countryData = Country.objects.values('country_id','country_name').all().order_by('country_name') #countryData = Country.objects.extra(select={'name': 'country_name','id':'country_id'}).values('id','name').all().order_by('country_name')[:5] serializer = CountrySerializer(countryData,many=True) #cache.set('country', serializer.data, 30) return JsonResponse({'data': serializer.data, 'error': 0 }) except (KeyError, Country.DoesNotExist): return JsonResponse({ 'error': 1 }) and response is here Thread Name: country 1-169 Sample Start: 2017-05-26 15:43:44 IST Load time: 21014 Connect Time: 0 Latency: 0 Size in bytes: 2015 Sent bytes:0 Headers size in bytes: 0 Body size in bytes: 2015 Sample Count: 1 Error Count: 1 Data type ("text"|"bin"|""): text Response code: Non HTTP response code: java.net.ConnectException Response message: Non HTTP response message: Connection timed out: connect HTTPSampleResult fields: ContentType: DataEncoding: null -
Set drop down list of a custom form accept list data from view in Django
I am new in django and python programming. I want to display table list(each table of the database) in a drop down list of a custom form. Table list comes from view.py by parameter passing to the form. I use following code getting from somewhere in this site. But, this is not working. Please help me. **Form.py** class SpacecraftID(forms.Form): def __init__(self,*args,**kwargs): choices = kwargs.pop('choices') #self.choices = kwargs.pop('choices') produces same error super(SpacecraftID,self).__init__(*args,**kwargs) scID = forms.MultipleChoiceField(required=False, widget=forms.CheckboxSelectMultiple, choices=choices) **View.py** def form_initialize(request): cursor = connection.cursor() cursor.execute("USE django_db") cursor.execute("SHOW TABLES") tables_list = [] i = 0 for (table_name,) in cursor: tables_list.append(table_name) if request.method == 'POST': form_ID = SpacecraftID(request.POST,choices=tables_list) if form.is_valid(): scID = form_ID.cleaned_data['scID'] else: form_ID = SpacecraftID(choices=tables_list) return render(request, 'InterfaceApp/table_list.html', {'form': form_ID}) -
django rest framework: include related model fields in same path
class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ('id','product_id','sku', 'title','price','images') class WishListSerializer(serializers.ModelSerializer): product = ProductSerializer() class Meta: model = WishList fields = ('wishlist_id','product',) I have two serializers. Wishlist and Product. I want to list all wishlist products. It works fine now. But the product details is in "product" key element. Can I remove that product key, and show the product details along with the wishlist_id ? Present result: { "count": 2, "next": null, "previous": null, "results": [ { "wishlist_id":1, "product": { "id": 1460, "product_id": "04396134-3c90-ea7b-24ba-1fb0db11dbe5", "sku": "bb4sd817", "title": "Trinity Belt", } }, { "wishlist_id":2, "product": { "id": 596, "product_id": "52588d22-a62c-779b-8044-0f8d9892e853", "sku": "ml346", "title": "Martina Liana", } } ] } Expected result: { "count": 2, "next": null, "previous": null, "results": [ { "wishlist_id":1, "id": 1460, "product_id": "04396134-3c90-ea7b-24ba-1fb0db11dbe5", "sku": "bb4sd817", "title": "Trinity Belt", }, { "wishlist_id":2, "id": 596, "product_id": "52588d22-a62c-779b-8044-0f8d9892e853", "sku": "ml346", "title": "Martina Liana", } ] } -
Django - Form issue
I'm using Django 1.11 with python 3.6. I have a form, when the form is sent without any radio button checked, the form is valide. However, if I send the form with the radio button "sex" checked, no matter if it's a man or a female, the form is not valide. Do you know what is the problem ? template : <form action="{% url 'games' %}" method="POST"> {% csrf_token %} <p>{{ form.identifiant|add_class:"form-control"|attr:"placeholder:Quel sera votre identifiant unique ?"|attr:"name:identifiant" }}</p> <p>{{ form.email|add_class:"form-control"|attr:"placeholder:Indiquez-y votre email !"|attr:"name:email" }}</p> <p>{{ form.password|add_class:"form-control"|attr:"placeholder:Créer votre mot de passe ici."|attr:"name:password" }}</p> <p>{{ form.confirm_password|add_class:"form-control"|attr:"placeholder:Retaper votre mot de passe."|attr:"name:confirm_password" }}</p> <p>{{ form.sex|attr:"" }}</p> <input class="btn btn-lg btn-primary" type="submit" value="Continuer"> </form> forms.py class MinimumRegisterForm(forms.Form): identifiant = forms.CharField( max_length=50, ) email = forms.EmailField( ) password = forms.CharField( widget=forms.PasswordInput, ) confirm_password = forms.CharField( widget=forms.PasswordInput, ) sex_choice = ( ('H', 'Homme'), ('F', 'Femme'), ) sex = forms.MultipleChoiceField( widget=forms.RadioSelect(), choices=sex_choice, ) views.py def view_games(request): if request.method == 'POST': form = MinimumRegisterForm(request.POST) if form.is_valid(): identifiant = form.cleaned_data['identifiant'] email = form.cleaned_data['email'] password = form.cleaned_data['password'] confirm_password = form.cleaned_data['confirm_password'] sex = form.cleaned_data['sex'] form = GamesRegisterForm() return render(request, 'games.html', locals()) else: messages.add_message(request, messages.INFO, 'Formulaire invalide') return redirect(view_register) else: return redirect(view_register) Many thanks for your help. -
Using django-compressor does not compress js
I can't for the life of me get compress js to work, compress css works fine. Rather than double post the entire thing, I've added a github issue here with all the details. https://github.com/django-compressor/django-compressor/issues/858 Does anyone have any ideas? -
Stream a file from remote url in django with resume support
I'm trying to stream a file from a remote URL directly to user without downloading it in my server. I tried using the code someone recommended here: Stream file from remote url to Django view response But i can't find a way to add resume support. I tried getting HTTP_RANGE and add a range header to requests.get but it doesn't work. Is there any way to add resume support or even any other way to server file from remote URL with resume support? -
Django atomic select for update not locking table for recursive calls?
I have a table which is created and populated in PostgreSQL via the following commands : CREATE TABLE my_lock ( id integer, CONSTRAINT id_pkey PRIMARY KEY (id) ) ; INSERT INTO my_lock VALUES (1) ; INSERT INTO my_lock VALUES (2) ; This table is represented by the following Django model from django.db import models from django.db import transaction class MyLock(models.Model): class Meta(object): db_table = 'my_lock' Next, I have the following methods : from contextlib import contextmanager @contextmanager def acquire_lock(): with transaction.atomic(): lock = MyLock().objects.select_for_update.filter(id=1) yield lock def first_method(): print "In first method" acquire_lock() print "Lock acquired in first_method()" second_method() def second_method(): print "In second method" first_method() The acquire_lock() method is a Python generator, which runs a SELECT FOR UPDATE query in a transaction. This should take a lock on the row with id = 1, and since the transaction does not finish when yield lock is called, keep holding that lock. Thus, if we call first_method(), the following output should be printed : In first method Lock acquired in first_method() In second method In first method However, in reality on calling first_method(), the following gets printed : In first method Lock acquired in first_method() In second method In first method … -
Form object has no attribute 'save_m2m' django
I have some trouble with form in views, i created CBV CreateView. So it working good and it saves the form but i have error 'ProductForm' object has no attribute 'save_m2m, if i don`t use form.save_m2m it will not add images to my product, but will add it to media. So here we have model.py class Product(models.Model): class Meta: verbose_name = 'Продукт' verbose_name_plural = 'Продукты' shop = models.ForeignKey(Shop, verbose_name='Название магазина') category = models.ForeignKey(Category, verbose_name='Название категории') title = models.CharField(max_length=255, verbose_name='Название товара') slug = models.SlugField(_("Название на транслите"), max_length=50, unique=True, blank=True, null=True) price = models.DecimalField(null=True, blank=True, verbose_name='Цена', decimal_places=0, max_digits=10) sell_count = models.PositiveIntegerField(_("Количество продаж"), default=0, null=True, blank=True) discount = models.PositiveIntegerField(null=True, blank=True, verbose_name='Скидка') currency = models.CharField(null=True, max_length=255, verbose_name='Валюта', default='сом') quantity = models.IntegerField(verbose_name='Количество', default=0) delivery_type = models.CharField(verbose_name='Вид доставки', choices=DELIVERY_TYPES, default='self', max_length=255) delivery_cost = models.FloatField(verbose_name='Стоимость доставки', default=0, null=True, blank=True) # settings = models.ManyToManyField('ProductSettings', verbose_name='Характеристика') availability = models.CharField(_("Наличие"), max_length=100, choices=AVAILABILITY_TYPES, default='available') published = models.BooleanField(default=True) short_description = models.TextField(max_length=300, null=True, blank=True, verbose_name='Короткое описание товара до 300 символов') long_description = RichTextUploadingField(null=True, blank=True, verbose_name='Полное описание') images = models.ManyToManyField('Media', verbose_name='Изображения продукта', blank=True) objects = ProductPublishedManager() class Media(models.Model): class Meta: verbose_name = "Изображение" verbose_name_plural = "Изображения" image = models.ImageField(upload_to='images') Here i have forms.py class ProductForm(forms.ModelForm): class Meta: model = Product exclude = ['slug', 'objects', … -
Django: how to check if Q object is empty?
I am chaining nodes to a Q object the following way: q = Q() for filter in filters: if filter_applies(filter): q.add(Q(some_criteria), Q.OR) What means the q object might or might not have been chained a node. Later on I am trying to apply the q object in a filter, but only if this is not empty: if q.not_empty(): some_query_set.filter(q) How can I check that q is not the same than it was when defined? -
how to fetch username and password in django using session?
I have a LDAP based django login. Now I need username and password to perform some function via django view. Can someone help me out with this? -
Django, gunicorn, and nginx proxy: static files give 404
I am running a development of a django project via gunicorn on my local machine. For reasons™, I want to set up nginx as a proxy for it. So far so, good: location /intranet { return 301 /intranet/; } location /intranet/ { rewrite ^/intranet(.*) /$1 break; proxy_redirect default; proxy_pass http://127.0.0.1:8000; } This does the trick nicely. However, none of the static files are severed: all I get is 404 for those. How can I modify the above nginx configuration so that the static content is severed? Note that using https::127.0.0.1:8000, the static files are served just fine. -
Nor working with django-nested-admin
when I try add new inline in django-nested-admin counter js not working enter image description here -
Delete admin inlines on form data change
I have three inlines in my admin and I just want to delete one inline among them whenever a model field in header got changed. I tried below code and its working fine but gets delete all the three inlines instead of desired one inline. def save_formset(self, request, form, formset, change): formset.save() if 'total' in form.changed_data: for x in formset.forms: obj = x.instance obj.user = request.user obj.delete() -
Why is not celery executing periodic task?
Apologies if my question is too basic, But unfortunately i couldn't understand how to use periodic tasks properly from official documentation/tutorial. I wanted to create periodic task executing function every 300 seconds (5 minutes), deleting all objects of model Trades which have existed longer than 300 seconds. So i simply created a file called tasks.py under Project/Home directory (directory which consists of models.py, urls.py, views.py and etc.) And i added this script: from celery.decorators import periodic_task from Home.models import Trades import datetime @periodic_task(run_every=300) # Run every 5 minutes. def remove_old(): for i in Trades.objects.all(): time_now = timezone.now() time_generated = i.generation_date time_elapsed = time_now - time_generated if int(time_elapsed.total_seconds()) > 300: # If an object has existed longer than 5 minutes, It must be deleted. i.remove() For some reason, no objects were deleted after 5 minutes, Even though they were generated yesterday, I'm sure they are older than 300 seconds. What could the problem be? Is there something with my code? -
Can I create two apidoc.json files into django project?
Recently I started learning apidocjs and I have some problems, like can I create two apidoc.json file. Because I need to create apidoc for django project, and some api's will be into one link like link/apidoc/index1.html and second one like link/apidoc/index2.html. And also I have api for login, and I need to use it into first and second link. I haven't any idea how to do it. -
Django: Restrict file type on MULTIPLE uploads
I'm still new to Django and have found some excellent answers on how to restrict the type of file uploaded through Django's FileField. However, these answers deal with the case of a single file upload. I am dealing with the case of a multiple file upload, like so: forms.py from django.core.exceptions import ValidationError class DocumentForm(forms.Form): def clean_docfile(self): file = self.cleaned_data["docfile"] if not file.name.endswith('.txt'): raise ValidationError(u'Error: Text files only.') return file docfile = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True}), label='Select some files' ) models.py from django.db import models from myproject.myapp.validators import validate_file_extension class Document(models.Model): docfile = models.FileField(upload_to=_upload_path, validators = [validate_file_extension]) validators.py from django.core.exceptions import ValidationError def validate_file_extension(value): if not value.name.endswith('.txt'): raise ValidationError(u'Error: Text files only.') I want the user to be able to upload multiple files at one time, but have all files rejected if at least one file is the incorrect file type. Currently, clean_docfile only seems to check the name of the file that appears last alphabetically. So, the file selection [A.txt, B.txt, C.png] does not upload (as intended), but [A.txt, B.png, C.txt] does upload (when it shouldn't). When I look at the value of the object self.cleaned_data["docfile"] within my clean_docfile function, it appears to only store the attributes of the file that … -
Django form warning messages
My Django form asks for a specific number (1345 in this case). Yet if the user types in some other number a warning message appears indicating the upper/lower bound of the allowed integer. How do I prevent these specific warning messages? The response to a false input should always be: "Wrong." What is the easiest way to achieve this behavious? #models.py class Player(): code = models.PositiveIntegerField(min=1345,max=1345) #etc #template.html {% formfield player.code with label="What is the code?" %} -
Django rest nested APIView routes
I'm relatively new to Django & Django rest - previously built only very simple apps. Currently facing a problem with using a nested routes. Here are my related configs: main urls.py: urlpatterns = [ url(r'^'+root_url+'/swagger', swagger_schema_view), url(r'^' + root_url + '/', include('payments.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) app's urls.py: urlpatterns = [ url(r'payments', views.PaymentsView.as_view(), name='index'), url(r'payments/charge', views.PaymentsChargeView.as_view(), name='charge'), ] app's views: import logging from django.views.decorators.csrf import csrf_exempt from django.utils.decorators import method_decorator from rest_framework.authentication import BasicAuthentication from mysite.csrf_exempt import CsrfExemptSessionAuthentication from rest_framework.views import APIView from rest_framework.response import Response import stripe try: from django.conf import settings except ImportError: pass logger = logging.getLogger(__name__) @method_decorator(csrf_exempt, name='dispatch') class PaymentsView(APIView): authentication_classes = (CsrfExemptSessionAuthentication, BasicAuthentication) def get(self, request, *args, **kwargs): print('here GET PaymentsView') return Response('good') def post(self, request, *args, **kwargs): print('here POST PaymentsView') return Response('good') @method_decorator(csrf_exempt, name='dispatch') class PaymentsChargeView(APIView): authentication_classes = (CsrfExemptSessionAuthentication, BasicAuthentication) def get(self, request, *args, **kwargs): print('here GET PaymentsChargeView') return Response('good') def post(self, request, *args, **kwargs): print('here POST PaymentsChargeView') return Response('good post') Problem: requests both to /payments and /payments/charge GET/POST always processed by PaymentsView (ex: POST to /payments and to /payments/charge gives me 'here POST PaymentsView' in console) -
add field to a form if necessary django
I am trying to make a form which has an option of adding multiple objects at a time. I want it to have a button "add another" - when clicked a new form field would appear for adding additional object. If there was an previous not submitted input I want the form to keep it. Is it possible to use templates tags for this(i.e. django template tags and not javascript)? -
Admin override form fields attributes
I'm building a profile driven admin for an app I'm building. Users have some permissions on parts of a hierarchy tree (displayed as a select in the admin form), and I'ld like to display only this part of the tree in the select. I'ld like to change the queryset attribute of this select field. The form has no knowledge about the request (user), So I can't et it in the __init__ of it. I've tryed to set form.base_fields in ModelAdmin.get_form(), but I've side effects with this method: some users can see trees of other users, and have an error message, due to permission. The only way to avoid those errors is to reload the project (at web server level), which is not an option... I've also tryed to override the ModelAdmin.get_fields() method, but it does not seems to be called. Have someone an idea on how to do this ? -
can't use lookup_expr list in django_filters class?
it works,url: /user?u=root class UserFilter(django_filters.rest_framework.FilterSet): u = django_filters.rest_framework.CharFilter(name='username', lookup_expr='contains') class Meta: model = User fields = ['username','u'] but when i changed it to class UserFilter(django_filters.rest_framework.FilterSet): u = django_filters.rest_framework.CharFilter(name='username', lookup_expr=['contains']) class Meta: model = User fields = ['username','u'] url:/user?u__contains=root can't work. django 1.11.1 django-filter 1.0.4 djangorestframework 3.6.3 -
Detect when a unique url is accessed for the first time
For example say I have a website called website.com. When the url website.com/stackoverflow is accessed for the first time, I want to store the value stackoverflow in my database. Is this possible, and how would I do it?