Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: use first name instead of username in login success message
I am using the following view to display a welcome back message when users login successfully. I want to use first name instead of the username attribute in the message, I tried to implement methods such as request.user.get_short_name(), but somehow I could not get it right. Is there a short way for this or I have to define a method inside the class? class LoginView(SuccessMessageMixin, FormView): form_class = AuthenticationForm template_name = 'registration/login.html' success_message = 'Welcome back %(username)s!' -
Django: determine language on a mobile device?
I read on internationalization and localization in the django documentation (https://docs.djangoproject.com/en/1.9/topics/i18n/) - but somehow I missed the point, how Django actually determines the language - and how it would be possible to adapt it's default behaviour. It's about displaying a website on a mobile device in the correct language. I'm on Django 1.9 -
Django template inheritance not rendered
I'm following the django docs on template inheritance, and I think my code is correct but it doesn't work, the template people_index.html is not rendered. I have three templates, base.html, base_index.html, people_index.html, each one inherited on the previous. Like this: base.html {% include "base/header.html" %} <body> {% include "base/navbar.html" %} {% include 'base/messages.html' %} <div class="container container-content"> {% block content %} {% endblock content %} </div><!-- /.container --> </body> </html> base_index.html {% extends "base/base.html" %} <h3 class="snps-slim-font">Index de {{ index_of }}</h3> <div class="input-group"> <span class="input-group-addon">Filtrar</span> <input id="filter" type="text" class="form-control" placeholder="Ingrese un criterio"> </div> <table class="table table-hover table-condensed"> {% block table_content %} {% endblock table_content %} </table> And finally people_index.html {% extends "base/base_index.html" %} {% block table_content %} <thead> <tr> <th class="snps-slim-font">APELLIDOS</th> <th class="snps-slim-font">NOMBRES</th> <th class="snps-slim-font">DOCUMENTO</th> <th class="snps-slim-font">CUIL</th> <th class="snps-slim-font">ACCIONES</th> </tr> </thead> <tbody class="searchable"> {% for person in object_list %} <tr> <td>{{ person.last_names }}</td> <td>{{ person.first_names }}</td> <td>{{ person.document_number }}</td> <td>{{ person.cuil_number }}</td> <td class="snps-text-align-center"> <a href="{% url 'people:person-detail' person.id %}" title="ver perfil"><i class="glyphicon glyphicon-eye-open" aria-hidden="true"></i></a>&nbsp;<a href="{% url 'people:person-update' person.id %}" title="editar perfil"> <i class="glyphicon glyphicon-edit" aria-hidden="true"></i></a></td> </tr> {% endfor %} </tbody> {% endblock table_content %} The view if someone asks: class PersonListView(LoginRequiredMixin, PermissionRequiredMixin, ListView): model = Person template_name = 'people/people_index.html' … -
Django: Messaging
Here's the 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 & 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 re-orders it's name & place it to the top). But, It's not changing the order of users 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. Also, I have to use {{ users.sender }} OR {{ users.receiver }} in order to print the users name which is a problem itself in case of ordering & distinct users. How can I fix this problem? -
Django - filter with multiple para
I am trying to create a filter with multiple parameters. I found the first answer of this link is useful, so took his idea. However, I don't know how to create a string variable containing all values.Here is my code: {% with amount_comments|to_string+","+limit_amount_comments|to_string as args %} {% if page_nr|page_not_over_amount:args %} <a href="{% url 'post:detail' topic.id page_nr|increase:1 %}">Next Page</a> {% endif %} {% endwith %} and this is to_string filter: @register.filter(name='to_string') def to_string(value): return str(value) then page_not_over_amount filter using that args: @register.filter(name='page_not_over_amount') def page_not_over_amount(page_nr, args): if args is None: return False else: arg_list = [arg.strip() for arg in args.split(',')] comment_amount = arg_list[0] comment_limit = arg_list[1] if page_nr*comment_limit < comment_amount-comment_limit: return True else: return False But I get this exception: Could not parse some characters: amount_comments|to_string|+","+limit_amount_comments||to_string Thanks in advance! -
Running python bot in django background
I've got a django project with simple form to take users details in. I want to use python bot running in the background and constantly checking django database for any changes. Is it Celery the right tool for this job? Any other solution? Thank you -
Write to elastic search from inside Django view
I'm trying to sync a local SQLite database-entry with an elastic search index. Here is the view: def sync_greasebook(request, model_id): data = create_json(model_id) es = Elasticsearch(hosts=[{'host': 'my_host', 'port': '9200'}]) res = es.index(index='my_index', doc_type='my_doctype', id=model_id, body=data) return redirect('/') And error at line 4: ConnectionError(: Failed to establish a new connection: getaddrinfo() argument 2 must be integer or string) caused by: NewConnectionError(: Failed to establish a new connection: getaddrinfo() argument 2 must be integer or string) The put to elastic search works normally. Am I missing knowledge that doesn't allow this behavior inside Django? Any help would be much appreciated -
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 ?