Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Serializer to filter relations base on arbitrary attributes
I'm new to DRF, what I have works but I am interested if there is a better way to do it: I have a PrimaryKeyRelatedField serializer to enumerate a many-to-many relation. It works fine, i.e.: mobile_forms = serializers.PrimaryKeyRelatedField( allow_empty=True, many=True, queryset=MobileForm.objects.all(), required=False) My question is that for this relation, I always only want to return related items that have their deleted status set to False. In order to achieve this I am doing: active_mobile_forms = serializers.SerializerMethodField() def get_active_mobile_forms(self, obj): return obj.mobile_forms.filter(Q(deleted=False)).values_list('pk',flat=True) It seems wrong to me to have to create a separate serializer to filter the objects returned. Based on my understanding of the queryset argument to the PrimaryKeyRelatedField is used to validate input, so it is not appropriate to filter here. Basically, I'm interested in the best practice for filtering a PrimaryKeyRelatedField relation when objects are returned via a serializer. Any insight would be appreciated. -
formset is_valid removes object data in django
i am using a formset in a form in django. i fetch an order object in code and get on fulled data object but when i call formset.is_valid it removes all data of order object and set them to None or default value. i do not know what happens. this is views.py def assign_order_to_printer(request, order_id): design_formset = forms.modelformset_factory(model=DesignAndColoration, extra=0, form=AddDesignAndColorationForm, fields=['print_machine', 'design_image', 'high_quality_design_image', 'width', 'height'], can_delete=True) order = Order.objects.get(id=order_id) if request.method == 'POST': form = AddOrderForm(request.POST, instance=order, enable=['print_machine']) formset = design_formset(request.POST, request.FILES, queryset=order.designandcoloration_set.all()) if form.is_valid() and formset.is_valid(): order = form.save(commit=False) order.status = order_status_assigned instances = formset.save(commit=False) for instance in instances: instance.order = order instance.save() order.save() for obj in formset.deleted_objects: obj.delete() return redirect(reverse('products:list_accepted_orders_pm')) else: form = AddOrderForm(instance=order, enable=['print_machine']) formset = design_formset(queryset=order.designandcoloration_set.all()) return render(request, 'product_management/printer_manager_assign_printer.html', { 'order': order, 'form': form, 'design_formset': formset, }) this is forms.py class AddDesignAndColorationForm(forms.ModelForm): class Meta: model = DesignAndColoration exclude = [] widgets = { 'design_image': forms.ClearableFileInput(attrs={'category': 'image'}), 'high_quality_design_image': forms.ClearableFileInput(attrs={'category': 'image'}) } class AddDesignAndColorationFormSet(BaseFormSet): def clean(self): for form in self.forms: if not form.cleaned_data: form.add_error('design_image', 'فرم ناقص است.') elif 'design_image' not in form.cleaned_data: form.add_error('design_image', 'عکس طراحی وجود ندارد.') elif 'print_number' not in form.cleaned_data: form.add_error('print_number', 'تعداد وجود ندارد.') -
image.picker : how to initialize edit form with corresponding image?
With the folliwing code I get this wrong result : nose.proxy.AssertionError: 302 != 200 : Couldn't retrieve redirection page '/mes_dossiers/': response code was 302 (expected 200) what is wrong with my code ? from django.test import TestCase, RequestFactory, Client from ..models import * from ..views import * from django.core.management import call_command class Cas(TestCase): def setUp(self): call_command('loaddata', 'fixture_users.json', verbosity=1) call_command('loaddata', 'dclicapp_tests_appareils_isoles.yaml', verbosity=1) def test_dossier_duplicate(self) : request = self.factory.get('/dossier/3/copier/', follow = True) request.user = User.objects.get(id=3) pk = 3 response = dossier_duplicate(request, pk) response.client = Client() self.assertRedirects(response,'/mes_dossiers/',status_code=302, target_status_code=200) -
Accessing request.user in a class based view
I want to display the current user when I load the template using this view. Is there a way to do it? class IndexView(generic.ListView): template_name = 'app/template.html' context_object_name = 'drinks' def get_queryset(self): return Drinks.objects.all() -
ModuleNotFoundError: No module named 'win32api' right after I install channels
I am buidling a chat app with WebSockets and django channels. I run 'pip install channels' it gets installed successfully. Then I install 'asgi_redis'. That too gets installed. Now when I try to import channels.asgi it gives me error. Also suddenly my manage.py shell stops working. In other django projects it works fine. Error when I try to access shell: C:\Users\gdhameeja\Desktop\chatapp\chat>manage.py shell Traceback (most recent call last): File "C:\Users\gdhameeja\Desktop\chatapp\chat\manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "C:\Users\gdhameeja\AppData\Local\Programs\Python\Python36\lib\site-packages\django-1.11.6-py3.6.egg\django\core\management\__init__.py", line 364, in execute_from_command_line utility.execute() File "C:\Users\gdhameeja\AppData\Local\Programs\Python\Python36\lib\site-packages\django-1.11.6-py3.6.egg\django\core\management\__init__.py", line 338, in execute django.setup() File "C:\Users\gdhameeja\AppData\Local\Programs\Python\Python36\lib\site-packages\django-1.11.6-py3.6.egg\django\__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\gdhameeja\AppData\Local\Programs\Python\Python36\lib\site-packages\django-1.11.6-py3.6.egg\django\apps\registry.py", line 116, in populate app_config.ready() File "C:\Users\gdhameeja\AppData\Local\Programs\Python\Python36\lib\site-packages\channels\apps.py", line 17, in ready monkeypatch_django() File "C:\Users\gdhameeja\AppData\Local\Programs\Python\Python36\lib\site-packages\channels\hacks.py", line 10, in monkeypatch_django from .management.commands.runserver import Command as RunserverCommand File "C:\Users\gdhameeja\AppData\Local\Programs\Python\Python36\lib\site-packages\channels\management\commands\runserver.py", line 5, in <module> from daphne.server import Server, build_endpoint_description_strings File "C:\Users\gdhameeja\AppData\Local\Programs\Python\Python36\lib\site-packages\daphne\server.py", line 9, in <module> from twisted.internet.endpoints import serverFromString File "C:\Users\gdhameeja\AppData\Local\Programs\Python\Python36\lib\site-packages\twisted\internet\endpoints.py", line 41, in <module> from twisted.internet.stdio import StandardIO, PipeAddress File "C:\Users\gdhameeja\AppData\Local\Programs\Python\Python36\lib\site-packages\twisted\internet\stdio.py", line 30, in <module> from twisted.internet import _win32stdio File "C:\Users\gdhameeja\AppData\Local\Programs\Python\Python36\lib\site-packages\twisted\internet\_win32stdio.py", line 9, in <module> import win32api ModuleNotFoundError: No module named 'win32api' Everything before installing channels seems to be working fine. settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'chat', 'channels',] CHANNEL_LAYERS = { … -
social media feed aggregation using python/django
I am trying to build an API that connects with all social media APIs (Facebook, Twitter, Instagram, Google+, LinkedIn) but am unable to decide whether this solution is feasible or does there exist some open source tool that provides social media aggregation? Please highlight the basic process of connecting to multiple APIs -
Django model choice field default value not working
I am working on a basic Django site. I have added a Model field named 'status' in the models.py file as shown below: from django.db import models class Person(models.Model): USED_STATUS = ( ('Y', 'Used'), ('N', 'Not used'), ) status = models.CharField(max_length=1, choices=USED_STATUS, default=USED_STATUS[1][0]) But when I phpmyadmin into the database, the Default Value of 'status' model field is None which should have been 'N'. Also when I try to INSERT a record using Python SQL script into the same Database table, it throws an error: "Warning: (1364, "Field 'status' doesn't have a default value")". I have search the whole forum but can't find any similar problem, Please help. -
ajax post request to view
I am trying to make a simple ajax request to a view but keep having a not Found error for the given url: Not Found: /myapp/start_session/1/scan_ports/ "POST /myapp/start_session/1/scan_ports/ HTTP/1.1" 404 5711 js $(document).ready(function() { $.ajax({ method: 'POST', url: 'scan_ports/', data: {'csrfmiddlewaretoken': '{{csrf_token}}'}, success: function (data) { alert("OK!"); }, error: function (data) { alert("NOT OK!"); } }); }); url url(r'^scan_ports/$',views.ScanPorts,name='scan_ports'), view @login_required def ScanPorts(request): user = request.user if request.method == 'POST': currentSetting = models.UserSetting.objects.filter(isCurrent=True) if currentSetting.serialPort: print("GOT IT!") return HttpResponse('') Is the ajax request not set properly? -
Django admin custom user model delete permission
in my application, based on Django 1.9, i have a custom implementation of the user admin model and i would like to allow deleting of user not only to Stuff user, but i need to handle programmatically this permission. So i've overrided has_delete_permission to allow to anyone to delete the user admin model: def has_delete_permission(self, request, obj=None): return True but the admin always says to me this: Deleting the user 'usertest@gmail.com' would result in deleting related objects, but your account doesn't have permission to delete the following types of objects: - user any idea to solve it? Thanks and sorry for my english -
Implementing a post-save logic by overriding save_related in Django Admin
There is some related posts, but none of them is actually specific to this problem. I'm trying to implement a post-save logic in one of my nested Django admin form. By nested I mean having inlines. I've been able to implement a logic by overriding save_model like so, def save_model(self, request, obj, form, change): #Added logic here using obj return super(SomeModelAdmin, self).save_model(request, obj, form, change) Obviously, if changes were made in one of the inlines, my logic was not considering it since save_modelis applied only on the parent object. I found a Django ticket on this issue. It suggest that save_related should be used instead since it now handles this kind of problem (see this). Therefore I tried, def save_related(self, request, form, formsets, change): #Added logic here using form.instance return super(SomeModelAdmin, self).save_related(request, form, formsets, change) But I have the same behavior as above where changes seems not to be saved when using my logic. Is there something I'm doing wrong here ? -
How to implement a/b testing on Django 1.11? [on hold]
Almost week i try to implement this thing to production, but all packages are out-of-date. Maybe someone who made this a short while ago can help? -
Django SQL Server ForeignKey that allows NULL
I've been struggling with this issue for some time. I'm switching one of my apps from Postgres to SQL Server database and I'm facing an issue with ForeignKey field. I'm running latest SQL Server version with Django 1.11 and using django-pyodbc-azure app. class Owner(models.Model): name = models.TextField() dog = models.ForeignKey('Dog', related_name='+') class Dog(models.Model): name = models.TextField() owner = models.ForeignKey('Owner', null=True, related_name='+') When I try to insert a new record I get the following message: dog = Dog.objects.create(name='Rex') owner = Owner.objects.create(name='Mike', dog=dog) dog.owner = owner dog.save() ('23000', u"[23000] [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Violation of UNIQUE KEY constraint 'UQ__owner__EF6DECB9214EF1D9'. Cannot insert duplicate key in object 'dbo.owner'. The duplicate key value is (). (2627) (SQLExecDirectW)") -
django admin redactor with jet template
how i can solve this? The other fields are behind of redactor widget -
Django: Messages App
Here's my model, class Message(models.Model): sender = models.ForeignKey(User, related_name="sender") receiver = models.ForeignKey(User, related_name="receiver") msg_content = models.TextField() created_at = models.DateTimeField(auto_now_add=True) I wants to order the Users based upon who sent a message to request.user or to whom request.user sent a message most recently! As we see on social networks. This is what I tried, users = User.objects.filter(Q(sender__receiver=request.user) | Q(receiver__sender=request.user)).annotate(Max('receiver')).order_by('-receiver__max') This code is working fine only when request.user sends someone a message. It's not changing the ordering of messages in case if someone sends a message to request.user. I also tried, users = Message.objects.filter(sender=request.user, receiver=request.user).order_by("created_at") But, I could't filter out the distinct users. It's showing equal number of users as messages. How can I fix this problem? Thank You! -
Wand can't open existing file
I want to open pdf file and get the only first page and save it as image. I've used this solution and it worked perfect. It still works in my local environment, but it fails to work in Travis recently. So, yes, this code from my unittest and I'm trying to run it in Travis. I have a test pdf file and I want to open it: import os from wand.image import Image root_path = 'some/correct/path' filename = 'two_page_pdf.pdf' full_path = os.path.join(root_parg, filename) Image(file=open(full_path, mode='rb'), resolution=300) # Error!!! ----------------------------------------------- DelegateError Traceback (most recent call last) <ipython-input-2-1b1fd9537a14> in <module>() ----> 1 Image(file=open(full_path, mode='rb'), resolution=300) ~/virtualenv/python3.5.3/lib/python3.5/site-packages/wand/image.py in __init__(self, image, blob, file, filename, format, width, height, depth, background, resolution) 2738 b'buffer.' + format) 2739 if file is not None: -> 2740 self.read(file=file, resolution=resolution) 2741 elif blob is not None: 2742 self.read(blob=blob, resolution=resolution) ~/virtualenv/python3.5.3/lib/python3.5/site-packages/wand/image.py in read(self, file, filename, blob, resolution) 2820 r = library.MagickReadImage(self.wand, filename) 2821 if not r: -> 2822 self.raise_exception() 2823 2824 def close(self): ~/virtualenv/python3.5.3/lib/python3.5/site-packages/wand/resource.py in raise_exception(self, stacklevel) 220 warnings.warn(e, stacklevel=stacklevel + 1) 221 elif isinstance(e, Exception): --> 222 raise e 223 224 def __enter__(self): DelegateError: Postscript delegate failed `/tmp/magick-5ypXvY6l': No such file or directory @ error/pdf.c/ReadPDFImage/677 Check file: os.path.isfile(full_path) == True … -
Using array parameters in a Django POST request
How to get array paramaters posted to django backend? I am using a jQuery plugin (DataTables Editor) that POSTs a data array parameter like data[id][fieldname][value] How do I get django to accept and use these parameters. -
how to login user from email or phone OTP in django
I want to remove the password feild and use mobile or email to send OTP and user should login through that OTP! I'm not getting a clear idea on how to do it can anyone help. Thank you -
How to create new tables in Database for each day in Django
I have an understanding question because I'm thinking about how I should manage my data in Django or the database. It is a table with about 2000 lines per day and 8 columns. I would like to store all daily data of the last 10 years into the database and add new data every day. It is a good idea to create a database table for each day. In Django, a table is created for each model, but it is not intended for the inventor to create 5000 models in Django. Is it the only way I use raw SQL to create the tables? Or is there a way I have not discovered in the documentation? -
compress image size before saving in database in javascript?
Is there any way to compress or reduce image size during uploading at client side and before saving in database in javascript? There are some options i have seen but they are using PHP i want that in javascript with HTML. I am using Django framework so it will be easier to implement in JS rather than in PHP. When we are uploading that image it should be compressed automatically and then it will be saved in database. -
ImportError raised trying to import a function
Context: I am trying to build a Django app that uses this package:django-minio-storage. I am trying to extend a certain class in the package with the following class: @deconstructible class MinioStoreStorage(MinioStorage): def __init__(self, bucket_name): client = create_minio_client_from_settings() base_url = bucket_name # base_url = get_setting("MINIO_STORAGE_STATIC_URL", None) bucket_name = bucket_name auto_create_bucket = True presign_urls = True super(MinioStoreStorage, self).__init__( client, bucket_name, auto_create_bucket=auto_create_bucket, base_url=base_url, presign_urls=presign_urls ) Problem: I can not import the function create_minio_client_from_settings. This function resides in the file storage.py of the package. The same file where resides the class MinioStorage. I can also import successfully another function (get_setting) that is in the same file and use it with no problem, but trying to do the same for create_minio_client_from_settings raises an ImportError. storage.py Here is a snippet of the code of the package: @deconstructible class MinioStorage(Storage): """An implementation of Django's file storage using the minio client. The implementation should comply with https://docs.djangoproject.com/en/dev/ref/files/storage/. """ ... ... ... def get_setting(name, default=_NoValue, ): result = getattr(settings, name, default) if result is _NoValue: print("Attr {} : {}".format(name, getattr(settings, name, default))) raise ImproperlyConfigured else: return result def create_minio_client_from_settings(): endpoint = get_setting("MINIO_STORAGE_ENDPOINT") access_key = get_setting("MINIO_STORAGE_ACCESS_KEY") secret_key = get_setting("MINIO_STORAGE_SECRET_KEY") secure = get_setting("MINIO_STORAGE_USE_HTTPS", True) client = minio.Minio(endpoint, access_key=access_key, secret_key=secret_key, secure=secure) return … -
Django send new sessionId Cookie even though previous session cookie is not expired
On page load , I look at the (Firefox) developer console, in the network cookie tab. I see Django is correctly creating a new session with expires date two weeks ahead. Refreshing the /admin/login/?next=/admin/ page a few times, I see Django send another sessionId cookie (after less than a minute) Basically the problem I am seeing is that the admin user get logged out after a few refreshing What can cause that? -
Search results using ajax in django
I am searching the products from the database using this search bar, but as soon as this search bar shows me results the header(dark blue area)part also expands along with the search results something like this. I want when search results are shown the header should not expand, the search results should go over the header. My search box code is like this- <div class="search_box"> {% csrf_token %} <form> <div class="form-group"> <input type="text" id="search" name="search" class="form-control" placeholder="Search"> <ul id="search-results" class="list-group"> </ul> </div> </form> </div> i am using django with ajax, so i am displaying my search result like this- {% if p1.count > 0 %} {% for p in p1 %} <li class="list-group-item"><a href="/products/product_info/{{p.id}}/">{{p.productname}}</a></li> {% endfor %} {% else %} <li>None to show!</li> {% endif %} -
Wagtail, accessing home page in jinja2 templates
I have two pages extending a base.html. home_page and works_page. I am trying to add a favicon image to the base.html. I have decided to add a favicon field to home_page which is my root page. <link rel='icon' href='/media/{{page.favicon.file}}' /> When active page is works_page the {{page}} has no favicon field and I get an error. Is there a way to access always the root page from templates? as {{ root_page }} maybe? -
Django REST Framework Extension recursive nested urls
I want to create URLs for CMS portion of project I have following models class Category(models.Model): name = models.CharField(max_length=150) parent = models.ForeignKey('self', blank=True, null=True) class Page(models.Model): title = models.CharField(max_length=255) content = models.TextField() slug = models.CharField(max_length=255) category = models.ForeignKey(Category, related_name='pages') I want the following URL structure for my categories /categories/{parent category}/ /categories/{parent category}/{child category}/.../{child category}/pages/ How would I accomplish this with DRF-Extensions or any other plugin? -
Loading django based webpage with Apache and mod_wsgi, haystack takes upto 10 sec.
WSGIScriptAlias / /var/www/swpdoc/swpdoc/wsgi.py <Directory /var/www/swpdoc> Require all granted </Directory> WSGIDaemonProcess swpdoc python-home=/var/www/swpdoc/venswpdoc python- path=/var/www/swpdoc WSGIProcessGroup swpdoc Any suggestion to improve the loading time ?