Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use InlinePanel in ModelAdmin?
I'm setting up a model that needs to be created with a number of instances of a sub-model. I want to be able to edit and create this model in the admin interface so I'm adding it using ModelAdmin. According to the documentation I should be able to specify the fields/panels in accordance to normal Page types; however, when I add a InlinePanel I get an KeyError on the related field name. models.py class Application(models.Model): # other fields.... panels = [MultiFieldPanel([ FieldPanel('applicant'), FieldPanel('position'), FieldPanel('cover_letter'), FieldPanel('qualifications'), InlinePanel('references'), FieldPanel('draft'), ])] class Reference(models.Model): application = models.ForeignKey( Application, related_name='references', on_delete=models.CASCADE, blank=False, ) # other fields.... wagtails_hooks.py class ApplicationAdmin(ModelAdmin): model = Application menu_icon = 'mail' menu_order = 400 list_display = # other fields.... modeladmin_register(ApplicationAdmin) Error Request URL: http://127.0.0.1:8000/admin/involvement/application/create/ Django Version: 1.10.5 Exception Type: KeyError Exception Value: 'references' Exception Location: /[APPFOLDER]/venv/lib/python3.6/site-packages/wagtail/wagtailadmin/edit_handlers.py in init, line 627 I'm having trouble determining what I did wrong. Can anybody point me in the right direction? -
Webhook in Djnago
Does anybody have used Thorn webhook library in django before? I am trying to create a webhook for my django application using Thorn library https://github.com/robinhood/thorn#id22 According to documentation I have created a webhook model using ModelEvent and a subscriber who is subscribed to all events here is the webhook model: from thorn import ModelEvent, webhook_model @webhook_model class Article(models.Model): uuid = models.UUIDField() title = models.CharField(max_length=100) body = models.TextField() class webhooks: on_create = ModelEvent('article.created') on_change = ModelEvent('article.changed'), on_delete = ModelEvent('article.removed'), on_publish = ModelEvent( 'article.published', state__eq='PUBLISHED', ).dispatches_on_change(), def payload(self, article): return { 'title': article.title, } @models.permalink def get_absolute_url(self): return 'article:detail', None, {'uuid': self.uuid} Now whenever any changes happens to article model, it should POST the event to subscriber's provided url, however I am not getting any kind of POST request to subscriber's provided url when changes happens to article model. I am not quite sure how to get notification response whenever some changes happens in article model according to documentation this is what the response should be: {"event": "(str)event_name", "ref": "(URL)model_location", "sender": "(User pk)optional_sender", "data": {"event specific data": "value"}} Any help on this would be very appreciable Thanks -
Query in a recursive Many to Many relationship with a Through table, Django
My models.py is: User(models.Model): friendship = models.ManyToManyField('self', through='Friend', symmetrical=False) Friend(models.Model): from_user = models.ForeignKey('User', related_name='friends') to_user = models.ForeignKey('User', related_name='friends_of') accepted = models.BooleanField(default=False) To get a queryset of User instance of my friends, I'm currently doing something like: user_instance.friendship.all() | user_instance.user_set.all() This gives me a queryset of User instances of all Friend objects related to user_instance. What I want is, that of accepted = True only, something like: user_instance.friendship.filter(friendship__accepted=True) | user_instance.user_set.filter(friendship__accepted=True) Can anyone help? Thanks -
Rounding a timedelta to the nearest 15 minutes
I have a timedelta which I would like to round to the nearest 15 minutes. For example, 8h 40m would round up to 8h 45m and 8h 50m would round down to 8h 45m. What would be the best way to achieve this? -
Apply django template filter only on values of specific type
I want to apply a filter floatformat to a value in django template only if the variable is numeric type, otherwise don't apply any filter at all. for example, if I write {{value|floatformat}} then the filter floatformat should only be applied if the type of value is numeric (integer or float), and not in case of string. Is there any built-in filter in django template language to get data type? I can do that from views also, but just wished to know of I can do it in templates itself? -
Django 1.10 - How can babel.js access static files?
I have babeljs installed in my project. In docs this is how to compile javascript files: load file.js, try to transpile it with babeljs and copy the result into the template (acts the same as the include tag) {% babel "file.js" %} It works amazing, but I can include only files from my template directory. Problem: How to include static files, which are not stored inside template directory? -
How to install mod_wsgi for apache 2.4 and python 3.4 on windows?
I had apache 2.4 already installed with xampp.I tried adding mod_wsgi using the steps mentioned here But when I add the line LoadModule wsgi_module modules/mod_wsgi-py34-vc10.so Apache does not start. -
how to use UserPassesTestMixin in generic Updateview
views.py class ProfileEdit(UserPassesTestMixin, UpdateView): login_url = '/login/' model = User form_class = ProfileForm template_name="profile/profile_new.html" def test_func(request, user_id): user = User.objects.get(pk=user_id) if request.user == user.user: return True else: return HttpResponse("<h1>You will not be able to edit other profiles</h1>") i got this (test_func() missing 1 required positional argument: 'user_id') error! This Post addresses the same issue i want to solve. is it different for class based views. -
why do my django urls render the wrong template?
I'm suprised that I cannot access my product detail page through the url and I don't understand why since I've already done this basic thing plenty of times... I have a page where all my products are displayed, when the user click on a product he is redirected to the product detail, that's it. Somehow when I click a link linked to the product detail or type de correct path to the url it loads the same page where all the product are shown but it doesn't even call the product detail view, why so ? Here are the views : def rcdex(request): list = Liste.objects.all() return render(request, 'rcdex.html', {'list':list,}) def rc_detail(request, id): list = Liste.objects.get(id=id) return render(request, 'rc_detail.html', {'list':list,}) Here are the urls : url(r'^', views.rcdex, name="rcdex"), url(r'^rc/(?P<id>\d+)/$', views.rc_detail, name='rc_detail'), Here is how I call the rc_detail view on the template : <th><a href="{% url 'rc_detail' l.id %}">{{ l.entreprise }}</a></th> I don't get why it doesn't show me the correct template (rc_detail.html) but instead reload rcdex.html ? -
How to run 2 Django applications in CentOs server using Nginx?
there I'am trying to run 2 Django applications in one server and I am following this site and while running the uwsgi ,(it would be great if you can suggest some good articles ) It gives me following message : *** WARNING: you are running uWSGI without its master process manager *** your processes number limit is 4096 your memory page size is 4096 bytes detected max file descriptor number: 1024 lock engine: pthread robust mutexes thunder lock: disabled (you can enable it with --thunder-lock) uWSGI http bound on :8002 fd 4 spawned uWSGI http 1 (pid: 4557) uwsgi socket 0 bound to TCP address 127.0.0.1:59208 (port auto-assigned) fd 3 Python version: 2.7.5 (default, Nov 6 2016, 00:28:07) [GCC 4.8.5 20150623 (Red Hat 4.8.5-11)] Set PythonHome to /home/impact/Env/funimpact ImportError: No module named site Even If Install Site related module it shows me same error Need help , Thanks in advance !! -
Django Forms with ReactJS
Sorry if this seems like a dumb question but I have spent a lot of time on this and unable to figure out an ideal way to do this. I have Django forms rendered using Django templates. Now I want to add a React component to one of the form fields (and perhaps to more than one field in the long term). Based on what I have read so far, its seem best not to mix Django templating with React rendering and have Django serve only as backend API sending JSON data to React, while React takes over the entire form rendering. So I am now trying to re-render my forms entirely through React. Instead of forms.py, I have now created serializers.py to define what data is to be sent to React and have Django Rest Framework setup in my environment. Now I am trying to figure out how to send this data across. There are some good online tutorials (and SO posts) that talk about integrating Django/DRF with React but havent found a single example of end-to-end form rendering through React and DRF. Specifically, can anyone let me know what do I really write in my view that can … -
Model Managers in Django - Composition over Inheritance?
One of the things we got stuck on while designing a new Django project was the necessity of a Database Abstraction Layer, until we realised that the model managers in Django is the DAL. However, we needed more control over the specifics of data retrieval than what Django provided. The resulting consensus? To write custom managers, providing us the application-specific functionality we needed. But, my custom managers would look something like this. from django.db import models class PollManager(models.Manager): def get_all(self): return OpinionPoll.objects.all() class OpinionPoll(models.Model): question = models.CharField(max_length=200) poll_date = models.DateField() objects = PollManager() This works beautifully (for now). But I can see at least two major issues with this design (and it's not me alone) I won't ever be able to unit test my Manager properly, because it is very tightly coupled with the Django framework code. Say I wrote three custom methods in my manager, and it provides 20 on it's own. If my manager breaks, all 23 methods start failing together - when it should have really been the three which I wrote on my own. I figured out a possible way to work around this - using composition over inheritance. In other words, I write a custom … -
TypeError: 'function' object has no attribute '__getitem__' from urls.py
When I try to migrate (manage.py migrate) in Django, I get the following error: File "C:\Program Files\Python27\Scripts\Folder_Name\Folder_Name\urls.py", line 22, in <module> url[(r'^$',ListView.as_view(queryset=ABC.objects.all(),template_name="Folder_Name/Folder_Name.html"))], TypeError: 'function' object has no attribute '__getitem__' Below is what I have for Folder_Name/urls.py from django.conf.urls import url, include from django.views.generic import ListView, DetailView from Folder_Name.models import ABC urlpatterns = [ url[(r'^$', ListView.as_view(queryset=IOC.objects.all(),template_name="Folder_Name/Folder_Name.html"))], ] Any help will be appreciated. Thank you. -
Annotating weekly values
I have formed a statement with Django queryset API that gives me weekly averages for some data in my DB. The data returned is in this format: (6, 4.0), (9, 5.0) ... etc where the first value in each tuple represents the week number and the second value represents an average of data. However, the weeks are not sequential and are only included if there is data for that week. Notice how the first week is 6 and the second week is 9. I would like to get weeks 6, 7, 8, 9 instead of only returning weeks for which data exists. Is this possible using Django querysets and annotations? -
int() argument must be a string or a number, not 'Choice'
It is giving error that int90 argument must be a string or a number,not 'Choice' I am new to django rest framework Please HELP This is my serializers.py class VoteSerializer(ModelSerializer): class Meta: model=Vote fields='__all__' def from_native(self, data, files): data['poll_id'] = self.context['pollid'] return super(VoteSerializer, self).from_native(data, files) def validate(self, data): choice=data.get("choice",None) user=data.get("id",None) polid=data.get("poll_id") if not user and not choice: raise ValidationError("A user and choice has to be present") choice_poll_obj=Choice.objects.filter( Q(id=choice) | Q(poll=polid) ).distinct() user_obj=User.objects.get(id=user) if user_obj.exists() and choice_poll_obj.exists(): pass else: raise ValidationError("This choice/user is not valid for this question") return data This is my views.py class VotesAPIView (CreateAPIView) : serializer_class = VoteSerializer def post(self, request, *args, **kwargs): data = request.data # like request.post poll = Poll.objects.get(id=kwargs['pk']) poll_id=poll.id serializer = VoteSerializer(data=request.data,context={'pollid': poll_id}) if serializer.is_valid(raise_exception=True): new_data = serializer.data return Response(new_data, status=HTTP_200_OK) return Response(serializer.errors, status=HTTP_400_BAD_REQUEST) -
Is it possible to post an id when using nested serializers?
I want to be able to post an id for a nested serializer field like this : { venue:1, } These are the Venue and Event Serializers: class VenueSerializer(serializers.ModelSerializer): class Meta: model = Venue fields = '__all__' class EventSerializer(serializers.ModelSerializer): venue = VenueSerializer(many=False) user = serializers.PrimaryKeyRelatedField(read_only=True, default=serializers.CurrentUserDefault()) class Meta: model = Event fields = ('__all__') I want to post an existing venue id instead of using writable nested serializers I get this message as the response {"venue":["This field is required."]} -
DRF serializer get liked data with post by request user
i'm making a social app like facebook. when getting post(at news feed) data i would like to get boolean of if i pressed like about that post. in models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class Post(models.Model): uploader = models.ForeignKey(User) likes = models.IntegerField(default=0) point = models.IntegerField(default=0) isPointReceived = models.BooleanField(default=False) content = models.TextField() uploadedTime = models.DateTimeField(auto_now=True) # editedTime = models.DateTimeField() def __str__(self): return ("[uploader = " + self.uploader.username + "]") + (", [id = " + (str)(self.id) + "]") + ("[content = " + self.content[:50] + "]") class PostLike(models.Model): post = models.ForeignKey(Post, related_name='postLikes') liker = models.ForeignKey(User) def __str__(self): return "Like" + "| [Post = " + (str)(self.post) + "]" + ", [Liker = " + self.liker.username + "]" and in serializers.py class PostLikeSerializer(serializers.ModelSerializer): class Meta: model = PostLike fields = '__all__' class PostListSerializer(serializers.ModelSerializer): uploader = UserDetailSerializer() isMine = serializers.SerializerMethodField() isLiked = serializers.SerializerMethodField() postComments = PostCommentSerializer(many=True, allow_null=True) class Meta: model = Post fields = ('uploader', 'id', 'likes', 'point', 'isPointReceived', 'content', 'uploadedTime', 'postComments', 'isMine', 'isLiked',) def get_isMine(self, obj): requestUser = CurrentUserDefault() return obj.objects.fileter(uploader=requestUser).exists() # return obj.filter(uploader=requestUser) def get_isLiked(self, obj): requestUser = CurrentUserDefault() return PostLike.objects.filter(post=obj, liker=requestUser).exists() # # try: # PostLike.objects.get(post=obj, liker=requestUser) # return True # except: … -
Tree structure in select using ng-include
I have data in following structure "results":[ {"last_login":"","username":"","first_name":"","last_name":"","email":"", "cpeUsers":{ "id":82,"login_id":"","user_type":"","user_expiry_date":null, "user_org":"","parent":null, "childs":[{"id":82,"login_id":"","user_type":"", "user_expiry_date":null,"user_org":"","parent":null, "childs":["id":82,"login_id":"","user_type":"", "user_expiry_date":null,"user_org":"", "parent":null... and so on] }] } }] my models are like Auth_User Django's auth user Cpe_User parent = models.ForeignKey('self', related_name="childs") auth_user_id = models.OneToOneField(AuthUser, related_name='cpeUsers') I wrote angular code like <div class="col s6"> <label>Optgroups</label> <select class="" material-select watch> <option value="" selected>Choose your option</option> <option ng-repeat="user in users"> {{ verbatim }} {{ user.login_id }} {{ endverbatim }} <optgroup label="{{ user.login_id }}" ng-if="user.childs.length > 0" ng-include="'childs.html'"> </optgroup> </option> </select> </div> and my js ng-template is like <script type="text/ng-template" id="childs.html"> <option ng-repeat="user in user.childs"> {{ verbatim }} {{ user.login_id }} {{ endverbatim }} <optgroup label="{{ user.login_id }}" ng-if="user.childs.length" ng-include="'childs.html'"> </optgroup> </option> </script> I tried lot of combinations but couldn't get tree structure working. I would appreciate if you all can help me figure out how should I get it working or if there is a mistake in my current code. -
Django no object matches the given query but it should
I have the following problem my database is not empty and has the record that I need. But when I query the db it says that there is no such object matching the given query. I query the db from within a websocket using django-channels. Here is the corresponding code: @channel_session_user_from_http def ws_receive(message): username = message.user.username print(username) text = json.loads(message['text']).get('text') # Use my algorithm here score = score_argument.get_rating(text) # find the room with our users current_room = get_object_or_404(PairUsers, Q(username_a=username) | Q(username_b=username)) # current_room = PairUsers.objects.filter(Q(username_a=username) | Q(username_b=username)).first() # check which user you got and send the message to the other if current_room.username_b == username: current_room.score_b = score other_channel = Channel(current_room.reply_channel_a) message.reply_channel.send({'text': text}) other_channel.send({'text': text}) else: current_room.score_a = score other_channel = Channel(current_room.reply_channel_b) message.reply_channel.send({'text': text}) other_channel.send({'text': text}) Another thing that I noticed is that the print(username) does not print anything it just skips this line. I used message.user.username in different function that works so I am sure it should return the username -
How to call python function based on text box value
How to do trigger in python. I have one text box after user enter 10 digit mobile number. i need to call one python function in that i have to call API on it. because of that how to do trigger on python. <input type="text" name="mobile" placeholder="Please Enter 10 Digits mobile number" pattern="[789][0-9]{9}"> Please help me with this. -
django-leaflet + django-geojson: I can't place a marker in Admin (TypeError: L.drawLocal.draw.toolbar.finish is undefined)
This might be trivial but I can't find the mistake. I'm just getting the initial setup done following the documentation on GitHub. I've started a new app. Installed django-leaflet and django-geojson, created a minimal models.py as well as admin.py. When I try to place a marker on the map via the admin. Nothing happens, and the icons on the left for drawing markers and polygons is missing. I must be missing a dependencies, forgot something trivial. But I've been over and over the docs, and I must have stared myself blind. I haven't create a view or template. Only the model and admin. And migrated the database. Here is the console log from Chrome and Firefox. Chrome spritesheet.svg Failed to load resource: the server responded with a status of 404 (Not Found) leaflet.draw.js:9 Uncaught TypeError: Cannot read property 'title' of undefined at e.getActions (leaflet.draw.js:9) at e._createActions (leaflet.draw.js:9) at e._showActionsToolbar (leaflet.draw.js:9) at e._handlerActivated (leaflet.draw.js:9) at e.fireEvent (leaflet.js:6) at enable (leaflet.draw.js:8) at HTMLAnchorElement.s [as _leaflet_click33] (leaflet.js:8) Firefox 10:34:46.995 TypeError: L.drawLocal.draw.toolbar.finish is undefined 1 leaflet.draw.js:9:15973 L.DrawToolbar<.getActions http://127.0.0.1:8000/static/leaflet/draw/leaflet.draw.js:9:15973 L.Toolbar<._createActions http://127.0.0.1:8000/static/leaflet/draw/leaflet.draw.js:9:12001 L.Toolbar<._showActionsToolbar http://127.0.0.1:8000/static/leaflet/draw/leaflet.draw.js:9:12614 L.Toolbar<._handlerActivated http://127.0.0.1:8000/static/leaflet/draw/leaflet.draw.js:9:11700 o.Evented<.fire http://127.0.0.1:8000/static/leaflet/leaflet.js:5:4955 L.Draw.Feature<.enable http://127.0.0.1:8000/static/leaflet/draw/leaflet.draw.js:8:1810 o.DomEvent._on/h http://127.0.0.1:8000/static/leaflet/leaflet.js:6:11671 geodjango/settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.gis', 'leaflet', 'djgeojson', 'djangomap', … -
what is the best way to specify LOGIN_REDIRECT_URL in settings.py?
models.py def get_absolute_url(self): return reverse('user:user_profile', kwargs={ "slug": self.slug }) urls.py url(r'^(?P<slug>[\w.@+-]+)/$', ProfileView.as_view(), name='user_profile'), settings.py LOGIN_REDIRECT_URL = ('profile:user_profile') i am using auth_views.login for authenticating the user. is it necessary to write custom login view to override the LOGIN_REDIRECT_URL to pass the slug with it. This was my previous question. hope you get the idea of my question? -
Pycharm Live Template delete other block when surrounding text
I added Live Template for trans Django template block. It work ok when I surround text in template line without other django template blocks on line. But when I try surround "some alt text" string in line like this <div class="login-logo"><img src="{% static 'panel/images/logo.svg' %}" alt="some alt text"/></div> I get this line in result <div class="login-logo"><img src="{% trans 'some alt text' %}"/></div> Static block deleted, alt attribute deleted. Anyone know how to fix this? -
Model Manager class for DAO or not in Django
I need to introduce a DataAccessLayer that queries the database layer and returned the result to my service layer. Basic idea is service layer should not have any access to the database or what query is being done(Abstraction in layers) So is this a good approach to extend the Manager class and override the methods in that class class PollsManager(models.Manager): def get_all(self) super(PollsManager,self).all() class OpinionPoll(models.Model): question = models.CharField(max_length=200) poll_date = models.DateField() objects = PollManager() or creating a new class which acts as a data access layer(not extending manager class) class Number(models.Model): user_id = models.IntegerField(max_length=20) date = models.DateField() class DataAccess: def get_all(self): Number.objects.all() Even if I extend the manager class by creating a new class, it is just to add some new methods or override an existing implementation Any ideas about how I should implement a DAO in Django? -
Mysql getting weekly report between 2 dates
I need to get number of users registered in a week, given start date and end date. Right now the logic used is: week_days_list = [['2017-01-01', '2017-01-07'], ['2017-01-08', '2017-01-14']] for week in week_days_list: query = 'SELECT COUNT('*') AS `__count` FROM `user_table` INNER JOIN `user_auth` ON (`user_table`.`user_id` = `user_auth`.`id` ) WHERE `user_auth`.`date_joined` BETWEEN week[0] AND week[1];' Result is: __count 15 I want it to reduce it to 1 query. Eg: Week Interval | count '2017-01-01' | 15 '2017-01-08' | 12