Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
momentJs with class not work correctly django
hi i have a difficulty with moment.js first entry it good but after i have invalid date . I call my data in front with {{....}} : {% for lastRequest in listLastRequeteClient %} <!-- en attente --> <li class="collection-item"> <span class="title">{{ lastRequest.categoryName }}</span> <div class="row"> <div class="col s5 ultra-small leftalign "style="padding-left: 0px"> {{ lastRequest.nameRequest }} </div> <div class="col s3 ultra-small center-align"> <span class="countDateTime">{{ lastRequest.dateRequest }}</span> </div> <div class="col s4 ultra-small "> {% if lastRequest.isWaitingWorking == True %} <span class="new badge orange" data-badge-caption="En attente"></span> {% elif lastRequest.isWaitingWorking == True %} <span class="new badge blue" data-badge-caption="En cours"></span> {% elif lastRequest.isFinish == True %} <span class="new badge" data-badge-caption="Effectué"></span> {% endif %} </div> </div> </li> % endfor %} and my Javascript : function countDateEntry() { $(".countDateTime").each(function() { // get it Oct. 27, 2017, 2:27 p.m var dateEntry = $(this).text(); console.log(dateEntry); // format it var delSpace = dateEntry.replace(/ /gi, ""); var delVir = delSpace.replace(/,/gi, ""); var delDoublePoint = delVir.replace(/:/gi, ""); var FinishSerialize = delDoublePoint.replace(/\./gi, ""); console.log(FinishSerialize); // test is date is valid console.log(moment(FinishSerialize, 'MMMDYYYYhma').isValid()); var formatMomentDate = moment(FinishSerialize, 'MMMDYYYYhma').fromNow(); console.log(formatMomentDate); //$(this).text(formatMomentDate); }); } but show my console.log invalid date : First entry it is ok after it is bad . Oct. 27, 2017, 2:27 p.m. … -
DateInput in django admin form
I'm editing the form of my app admin section. model.py class Friend(models.Model): id = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) genre = models.CharField(max_length=1, choices=(("M", "Male"), ("F", "Famale"))) birth_date = models.DateField() admin.py class FriendAdmin(admin.ModelAdmin): change_form_template = 'admin/change_form.html' change_list_template = 'admin/change_list.html' admin.site.register(Friend, FriendAdmin) form.py class FriendForm(admin.ModelAdmin): form = Friend fields = ('birth_date',) widgets = {'birth_date': forms.DateInput(attrs={'class': 'form-control'})} I expect that my form contains only the "birth_date" field and that it has the "form-control" class and the "DateInput" type. Nevertheless, my form contains all the fields and the "birth_date" is a simple text field. What am I doing wrong? P.S. I've imported bootstrap, bootstrap-daterangepicker, jquery and moment library and I've added this code to my change_form.html page: <script type="text/javascript"> $('.datepicker').datepicker(); </script> -
Use Django proxy model class when obtaining ManyToMany fields through related_name field
Is there a way to force a related ManyToMany field to use a Proxy class instead of the model that is associated with it? I have the following code: # Code in models.py class Member(models.Model): username = models.CharField(max_length=100) class BaseGroup(models.Model): member = models.ManyToManyField('Member', related_name='groups') class Group(BaseGroup): class Meta: proxy = True def some_method(self): return 'something' # Code in view: member = Member.objects.first() group = member.groups.first() print group.some_method() The code above throws the error: "Group object has no attribute 'some_method'", because the "member.groups.first()" line returns a "BaseGroup" instead of the proxy "Group", therefore I cannot use the methods that I implemented on the proxy class. Is there a way to inform the ManyToManyField (or the query) to return the proxy class instead of the base model? -
Does Jupyter support 'read-only' notebooks?
My team is currently developing a fairly quick clustering job using Pandas for business analysts. We're planning on hosting a local server where the end user can input a few parameters to be used during the routine execution, which will access an internal database and then return a CSV file. A Jupyter server would be ideal for us, but the problem is that we can't have the user being able to edit the underlying code - all he needs to do is supply the parameters and start job execution. Converting it to HMTL, I think, turns everything static and means we can't delived updated data on demand. Plan B is just making a small django app but I'm wondering if there's a way to accomplish what I need with Jupyter itself, or else if there's any better alternative for similar use cases? We don't even plan to display any widgets, just provide the user with the raw data output. thanks in advance -
django-parler translations for abstract model
My django app must be translatable, static pages and models too. For translating models I'm using django-parler app. This works fine, but for simple models, I mean, models that doesn't inherits from an abstract model class. Let's say that we have a Vehicle abstract model class Vehicle(TranslatableModel): translations = TranslatedFields( description=models.CharField(max_length=100) ) class Meta: abstract = True and a child model which is Car: class Car(Vehicle) """...""" This raised me this error: TypeError: Can't create TranslatedFieldsModel for abstract class Vehicle. I'd like still using django model inheritance. So, what can I do for translating my models using django-parler, it support translations for abstract models or I'll need to use another app to achieve this, in that case any suggestion on any? -
Upgrade issues in django from version 1.7.9 to 1.11.6, unknown command runfcgi
I am working on updating django from 1.7.9 to 1.11.6. While using 1.7.9 we use runfcgi on our production server. Looks like runfcgi does not exist in 1.11.6. When i do $ python manage.py help runfcgi does not show up. For someone who uses runfcgi, what is the right path forward for 1.11.6 ? Any recommendation / pointers would be helpful. -
Wagtail proper way to add settings to a stream block
say we have a stream block as: class CarouselStreamBlock(StreamBlock): image = StructBlock([ ('file', ImageChooserBlock()), ('caption', RichTextBlock( classname='caption' )), ]) We have a scenario that we want to give the admin editor the ability of setting each carousel's width, height, bgcolor etc... I have tried to add that settings as another struct block named to the carousel itself with a max_length of 1. class CarouselStreamBlock(StreamBlock): settings = StructBlock([ ('align', blocks.ChoiceBlock(choices=[('center', 'Center'), ('right', 'Right'), ('left', 'Left'), ], default='center', max_length=10) ), ('width', blocks.IntegerBlock(required=False ) ), ('background_color', blocks.CharBlock(max_length=10, required=False)) ], icon='cog' ) image = StructBlock([ ('file', ImageChooserBlock()), ('caption', RichTextBlock( classname='caption' )), ]) But I am not satisfied with this way. Is there a better way of doing this? -
What is best way to return object permission with instance using Django Rest Framework and django-guardian
I'm using Django Rest Framework and django-guardian (for per object permissions), what is best way to return object permission with instance. For example now request "/api/v1/objects/" returns: { "id":0, "category": "string", "name": "string", "address": "string", } but I want return object with permissions: { "id":0, "category": "string", "name": "string", "address": "string", "permissions": { "change": true, "delete": true } } this would be useful, for example, if the user does not have the right to delete the object, on the frontend do not display the delete button. Below is project structure: #Model class Object(models.Model): owner = models.ForeignKey(User) category = models.ForeignKey(Category, null=True, default=None) name = models.CharField(max_length=255) address = models.CharField(max_length=255, default='') #Serializer class ObjectSerializer(ModelSerializer): is_folder = BooleanField(read_only=True) class Meta: model = Object fields = ('id', 'category', 'is_folder', 'name', 'address') #ViewSet class ObjectsViewSet(BaseViewSet, RetrieveModelMixin, ListModelMixin, CreateModelMixin, UpdateModelMixin, DestroyModelMixin): queryset = Object.objects serializer_class = ObjectSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly, ObjectPermission) def get_queryset(self): queryset = super(ObjectsViewSet, self).get_queryset() return queryset.filter(owner=self.request.user) #Permission class ObjectPermission(permissions.BasePermission): def has_permission(self, request, view): if request.method in ['GET']: return request.user.has_perm('view_object') if request.method in ['POST']: return request.user.has_perm('add_object') if request.method in ['PUT', 'PATCH']: return request.user.has_perm('change_object') if request.method in ['DELETE']: return request.user.has_perm('delete_object') return False def has_object_permission(self, request, view, obj): if request.method in ['GET']: return request.user.has_perm('view_object', obj) if request.method … -
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