Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django database queries per view in APIs
So I have been developing a Django server application that mostly works as an API endpoint for a mobile app, with about 30 different models, almost all of them having FKs to each other or other or being in MTM relationships. Now that we're going into production (but do not yet have a lot of users), I have noticed (using Silk) that the most complex query that fetches a bunch of objects as JSON makes about 500 SQL queries (and those objects each have about 5 FKs and 2 MTMs, which are all fetched as object fields in the JSON). The numbers don't seem to be too huge (as 50k qps seems to be a normal number for Postgres, which we are using as our DBMS), but I am getting worried about the future. Are those numbers normal in early production? What is the normal distribution of database requests per view for an API like the one I described? We are not currently using DRF, but I am looking towards it. Does it solve this problem? -
Like Button In Django Ajax
my like button is working fine without ajax with page reloading but it is having problem when done by implementing ajax. the like and unlike is happening in the backend (like is created and deleted in database on ajax Post request), but the like count,like,unlike button does not change in response on ajax post request, until the page is reloaded. Need Help here is the post model and like model for posting image and liking it in models.py class PostModel(models.Model): user = models.ForeignKey(UserModel) image = models.FileField(upload_to='user_images') image_url = models.CharField(max_length=255) caption = models.CharField(max_length=240) created_on = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now=True) has_liked = False @property def like_count(self): return len(LikeModel.objects.filter(post=self)) class LikeModel(models.Model): user = models.ForeignKey(UserModel) post = models.ForeignKey(PostModel) created_on = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now=True) url for liking in urls.py url(r'^like/', like_view), views.py def like_view(request): user = check_validation(request) if user and request.method == 'POST': form = LikeForm(request.POST) if form.is_valid(): #post_id = form.cleaned_data.get('post').id post_id=request.POST['post'] existing_like = LikeModel.objects.filter(post_id=post_id, user=user).first() if not existing_like: LikeModel.objects.create(post_id=post_id, user=user) else: existing_like.delete() return redirect('/feed/') else: return redirect('/login/') template.html {% for post in posts %} <form id="like_form"> {% csrf_token %} <input type="hidden" name="post" id="post_id"value="{{ post.id }}"> {% if post.has_liked %} <button class="btn btn-link unlike"type="submit"><i class="fa fa-heart" aria-hidden="true"style="color:#ed4956;"></i></button> {% else %} <button class="btn btn-link like"type="submit"><i … -
Django Tables2 : How to insert all labels in one column and data in another
I have a requirement for django tables2 to put all the lables in one column and their data in another respectively. For eg. Thanks in advance -
How to send message to HttpResponseRedirect in djanog?
I have added a middleware to session-out user with my logic. I am trying to redirect to login page with message. I am using HttpResponseRedirect(reverse('user_login')) for redirecting to my custom login page. So, how to pass values to page? -
Is friendship between Django Rest Framework and Netbeans(frontend) possible? Disabling csrf issue
I'm trying to write an application, and use Django Rest Framework as backend(and usual Django). I also use NetBeans to write and debug frontend. I felt good until start working with ajax calls. I have read a lot of docs and SO topics but still can not solve my question. My DRF view code is: @api_view(["GET", "POST"]) def hello_world(request): if request.method == 'POST': return Response({"message": "Got some data!", "data": request.data}) return Response({"message": "Hello, world!"}) I tried to unlock csrf protection using csrf_exempt decorator in urls.py: url(r'test', csrf_exempt(views.hello_world)), As well as roughly disable csrf in settings.py: MIDDLEWARE = [ #'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'anti_csrf.DisableCsrfCheck', 'django.middleware.common.CommonMiddleware', #'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] class DisableCSRF(object): def process_request(self, request): setattr(request, '_dont_enforce_csrf_checks', True) MIDDLEWARE_CLASSES = (DisableCSRF,) My frontend code for ajax call is: function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } var csrftoken = getCookie('csrftoken'); function csrfSafeMethod(method) { // these HTTP … -
How can i get the data of user in forms.py?
This form is for change user detail but i want to give previous value as placeholder so, How can i get the data of user in forms.py? forms.py class User_Detail1(forms.Form): name = request.User.get_full_name() firstname = forms.CharField(label='First Name', required=False, widget=forms.TextInput(attrs={'placeholder': name })) lastname = forms.CharField(label='Last Name', required=False) emailaddress = forms.EmailField(label='Email address', required=False) -
Element disappears when I add an {% include %} tag inside my for loop
Here's my template code for my comment queryset: {% block comments %} {% load el_pagination_tags %} {% paginate 10 comment_list %} {% for i in comment_list %} <div class='comment_div'> <div class="left_comment_div"> <p>{{ i.comment_text }}</p> </div> </div> {% include 'comment/comments.html' with comment_list=i.replies.all %} </div> {% endfor %} {% show_more %} {% endblock %} I'm using django el pagination to implement ajax pagination. On the 3rd line you can see I initially load 10 comments. With this package, comes a {% show_more %} element I can add which, when clicked, will load the rest of the comments. However, this {% show_more %}element disapears for some reason when I add {% include 'comment/comments.html' with comment_list=i.replies.all %}. For context, this include tag shows the replies for the current comment in the for loop. Does anyone have any idea why this include tag affects the {% show_more %} element? -
Share data between different test classes
I have a dedicated test class for each different component I need to test in a particular module. All these tests revolve around the same object/context so it could be an improvement in performance if the corresponding objects weren't created and inserted in the test database and then deleted for every single test class: class ContextTest(TestCase): fixtures = [...] @classmethod def setUpTestData(cls): pass # executes setUpTestData class Component1Test(ContextTest): pass # executes setUpTestData again class Component2Test(ContextTest): pass Is there any way I can ensure that setUpTestData is ran only once, while keeping my tests under different classes for clarity's sake? -
Multiple lookup fields for DetailAPIView in Django Rest Framework 3.7
I have an api list of posts with Django Rest Framework. Knowing that I slugify my post title, which a non-required attribute for my Post model, I want to make a lookup for the post api detail by either searching the pk (the lookup default in DRF) or the slug field if there is a one. In my api folder of the post application, I wrote the following views.py: class PostDetailAPIView(generics.RetrieveAPIView): queryset = Post.objects.all() serializer_class = serializers.PostDetailSerializer try: lookup_field = 'slug' except: lookup_field = 'pk' And proveded the corresponding urls.py: urlpatterns = [ url(r'^$', PostListAPIView.as_view(), name='list-api'), url(r'^(?P<slug>[\w-]+)/$', PostDetailAPIView.as_view(), name='detail-api'), url(r'^(?P<pk>\d+)/$', PostDetailAPIView.as_view(), name='detail- api'), ] This approach works perfectly when a post has a slugified (title) lookup. But the post detail view for a post with no slug shows the following: HTTP 404 Not Found Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "detail": "Not found." } I want a suggested approcah to show the post api detail for a both the pk and the slug fields lookup, preferably with no code repitition in the urls.py. -
Django LoginView doesn't override attributes
I'm trying to override attributes in my Django application and for some reason I cannot override some attributes of the LoginView. I've tried to do that both as my own class based view and directly on the urlconfig, passing the attributes as arguments to the as_view function, nothing worked. To be more specific, i'm trying to override the template_name but it seems like Django ignores my argument and still trying to look to 'registration/login.html', even though i've passed another path of my own HTML template in another directory. What am I doing wrong? Here is my code, or how I tried to use it: url(r'^accounts/logout/$', auth_views.LogoutView.as_view(template_name='accounts/login.html')), or class SigninView(LoginView): template_name = 'login.html' def get(request): form = LoginForm return render(request, self.template_name, {'form':form}) I've already tried to change the name (or the path) of my template name, both as the as_view function or on my created class based view, but Django looks always for this specific path - '/registration/login.html' - basically to the origin path. Therefore I assumed that Django doesn't recognise for some reason my overriding and looks for the original attributes as it's set in the LoginView. The error: TemplateDoesNotExist at /accounts/login/ registration/login.html Request Method: GET Request URL: http://localhost:8000/accounts/login/ Django … -
Django - static files is not working
I'm new to Django. I want to add my CSS file in template/index.html, but I don't know how to do it except in DEBUG mode. Project name: mercury App name: gamma /root/workspace/django/mercury/mercury/settings.py STATIC_URL = '/static/' STATIC_ROOT = '/root/workspace/django/mercury/static/' STATICFILES_DIRS = [ '/root/workspace/django/mercury/bootstrap/dist/', ] STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ) /root/workspace/django/mercury/gamma/templates/gamma/index.html <link href="{% static 'css/dashboard.css' %}" rel="stylesheet"> Full path of the originally dashboard.css file /root/workspace/django/mercury/bootstrap/dist/css/dashboard.css After running 'python manage.py collectstatic' /root/workspace/django/mercury/static/css/dashboard.css The output: [20/Oct/2017 12:27:48] "GET /static/css/dashboard.css HTTP/1.1" 404 98 I'm missing something? I tried numerous things but didn't helped. Thanks in advance! -
Django: can't reset superuser password if not set at installation [duplicate]
This question already has an answer here: How to automate createsuperuser on django? 8 answers I'm deploying Django automatically. I create a superuser at installation with the command : python manage createsuperuser --username me --email me@example.org --noinput When I do this no password is set for the account and I'm not able to change the password with the "Forget password" functionality. If I do : python manage changepassword me Then I can reset the password. This behavior comes from this code : return (u for u in active_users if u.has_usable_password()) What would be the way to "activate" the reset function for all users without hacking the core ? -
Django - Change a popup to a internal popup
I would like to change an external popup to an internal popup. Here my HTML code : {% for i in disabled_41 %} {% if i.workshop_id == wk.id %} <span onclick="return popup('disabled/check/{{ i.id }}')" id=redcircle></span> {% endif %} {% endfor %} Here my JS code : function popup(page) { window.open(page, "popup_test", "menubar=no, status=no [...]"); } I would like that everything in this popup appears in a little information's box near the red circle we clicked before. If possible, I would like to keep the url with {{ i.id }}, because this is one of the parameters of the function I used. Thanks a lot ! -
Django query with __range and F
I am trying to write a query that filters based on particular date. Let say i have three data in the db target_date = 28th of october today = 23rd of october data one publish_date = 26th of october data two publish_date = 24th of october data three publish_date = target_date # 28th of october My query needs to fetch all data that is three or less days before the target date. since target date is 28th of october, any data within the range of 26th, 27th and 28th (target date) should be fetched. query MyModel.objects. filter(publish_date__range= [F('publish_date'), F('publish_date') - timedelta(days=3)]) I am getting unexpected result. -
How to check if current url in list of urlpatterns?
I am a bit puzzled. I want to check if the current url of the website is in a specific subset of my urlpatters. Which function of django would do this? This is for a middleware that requests additional information before moving to a specific part of my website. class AuthorityMiddleware(object): def process_request(self, request): current_url = request.path_info if not request.user.is_anonymous() and current_url not in exclude_list: if not request.session.get('authority'): return get_the_authority(request) How should exclude list relate to the urlpatterns defined in urls.py? -
Django - context process query being repeated 102 times
I have built a context process that sends the logged on users permissions as a string into a template. Then based on that users perms I show or hide urls. However using the debug toolbar ive just seen that the query is run 102 times for a reason I do not know The debug (the ID changes and it looks as if there are 3 of each ID in the duplicates) SELECT `django_content_type`.`id`, `django_content_type`.`app_label`, `django_content_type`.`model` FROM `django_content_type` WHERE `django_content_type`.`id` = 35 Duplicated 102 times. 0.6862959744274587% 23.41 Sel Expl Connection: default /itapp/itapp/sites/views.py in site_detail_files(214) 'PageType' : 'files', /usr/local/lib/python3.6/contextlib.py in __enter__(81) return next(self.gen) /itapp/itapp/itapp/context_processors.py in UserPerms(34) 'Perms': str(all_perms), the function: def UserPerms(request): from django.contrib.auth.models import Permission all_perms = [] if str(request.user) != 'AnonymousUser': permissions = Permission.objects.filter(user=request.user) group_permissions = Permission.objects.filter(group__user=request.user) all_perms = [] for p in permissions: all_perms.append(p) for p in group_permissions: all_perms.append(p) return { 'Perms': str(all_perms), } added to templates in settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ BASE_DIR + '/templates/', ], 'APP_DIRS': True, 'OPTIONS': { 'debug' : DEBUG, 'context_processors': [ 'django.template.context_processors.debug', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.media', 'django.template.context_processors.static', 'itapp.context_processors.breadcrumb_history', 'itapp.context_processors.UserPerms', ], }, }, ] usage example: <li><a href="{% url 'sites:site_detail_circuits' SiteID %}">Circuits</a> {% if "Permission: sites | Circuit Data | Can add … -
Not able to change primary key name of authentication table
when i execute the command python manage.py makemigrations the result is You are trying to add a non-nullable field 'pk_bint_user_id' to appuser without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: 1) Provide a one-off default now (will be set on all existing rows with a null value for this column) 2) Quit, and let me add a default in models.py And my model is look like as follows: class AppUser(AbstractBaseUser): pk_bint_user_id = models.BigIntegerField(primary_key=True) email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) fk_bint_travel_agency_user_id_or_corporate_user_id= models.BigIntegerField(blank=True,null=True) chr_travel_agency_user_or_corporate_user =models.CharField('Agency user or Corporate user',max_length=5,blank=True,null=True) chr_user_type = models.CharField('User type code',max_length=5,blank=True,null=True) vchr_account_type=models.CharField('Account type',max_length=5,blank=True,null=True) vchr_account_status=models.CharField('Account status',max_length=5,blank=True,null=True) objects = MyUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] class Meta: db_table='tbl_user' All i want to customize the primary key into different name than "id", -
Django Class Based View with get_queryset()
I would like to use get_queryset() with Class Based View but I don't overcome to display variables in my template. The function is very simple : class MyClassView(LoginRequiredMixin, ListView) : template_name = 'my_template.html' model = Foo def get_queryset(self) : foo = Foo.objects.order_by('-id') bar = foo.filter(Country=64) return foo, bar And my template : <table style="width:120%"> <tbody> <tr> <th>ID</th> </tr> {% for item in foo %} <tr> <td>{{ foo.id }}</td> </tr> {% endfor %} </tbody> </table> <br></br> <table style="width:120%"> <tbody> <tr> <th>ID</th> </tr> {% for item in bar %} <tr> <td>{{ bar.id }}</td> </tr> {% endfor %} </tbody> </table> I have to use Context dictionary ? -
How to manage user content in django?
I want manage user posts. When someone create new post it's should display on admin, but not on html. If content is valid i want push on allow button and it will display on html for all users. i was try to google something, but nothing helpfull. I suppose logic must be like this: User create new post. Post displayed on admin panel. Admin allow the post. Post displayed in html. How it should work? -
Is it possible to combine a web dyno and bot dyno on Heroku django app?
I'm building a discord bot that gathers links from discord chat stream of specific server and channel. Bot is then suppose to publish the links on the website so they are not lost in discord but plain sight on website. This is school project where I don't want to put my money on. The problem this time is that I have a web dyno and bot (worker?) dyno on heroku and they both consume my dyno time so it cannot handle both because there are only 1000 free hours in Heroku. My guess is that the project could be ran in one dyno but I couldn't find out how so at the moment it's working as follows: Bot dyno: Bot is just one file that can be run as a script that runs 'forever'. So I run it with command python manage.py bot. Here's how the script works Web duno: Website is running with runserver like normal web dyno on heroku. In free heroku the dynos fall asleep after 30mins of inactivity so I have configured another free service to ping the website every half an hour to keep the bot online. This is odd behaviour in my opinion. Why … -
Django query - get first x elements which together exceed a specific amount for a field
I want to request the first x elements which together exceeds a specific amount, and I don’t know if this is somehow possible. Assuming that this is my model: class Article(models.Model): price = models.DecimalField(default=0.0, max_digits=7, decimal_places=2) If I order the „Articles“ by the „price“, I want the first „Articles“ which together exceed the „price“ of let’s say 100 Dollars. Is this somehow possible with annotating, summing, extra() or whatever?? Article.objects.order_by(„price“) ?????? Thanks for any help!!! -
How to extend django-registration form's clean_email() method?
from django import forms from registration.forms import RegistrationFormUniqueEmail class NewRegistrationForm(RegistrationFormUniqueEmail): # def __init__(self, *args, **kwargs): # super(NewRegistrationForm, self).__init__(*args, **kwargs) def clean_email(self): cleaned_data = super(NewRegistrationForm, self).clean_email() if "@iiitvadodara.ac.in" not in cleaned_data: raise forms.ValidationError("You must have a IIIT Vadodara email address to register.") return cleaned_data I want to extend the RegistrationFormUniqueEmail in django-registration to accept only email address which end with @iiitvadodara.ac.in. The method works but when I click on the activation link which is sent to my email address. It shows activation failed even when I do activation within time limit. Please help me my showing me the correct method to do this. -
Disable logging except in tests
Throughout my app I am using the following logger: logger = logging.getLogger() However, I want to disable it and disabling logging in general when running tests, so ontop of the tests.py file I included: logging.disable(logging.CRITICAL) But I would like to be able test-specific messages. I tried getting a new logger and setting a different level: logger = logging.getLogger('TestLogger') logger.setLevel(logging.DEBUG) But the disable call seems to affect it too. How can I disable all other loggers except for my logger using in the tests file? -
Django how to set input element's value attribute from views?
I want to set HTML input element's value attribute from Django views. Here is the code for that element: <input name="predict_file" type="text" id="photoCover" class="input-large" value="{{ fn }}" style="height:30px;"> and my view's code: def upload_predict(request): if request.method == 'POST' and request.FILES['predict_file']: predict_file = request.FILES['predict_file'] fs = FileSystemStorage() filename = fs.save(predict_file.name, predict_file) predict_file_location = fs.url(filename) return render(request, 'predict.html', {'fn':filename}) return render(request, 'predict.html', {'fn': 'No file uploaded yet'}) Is there anyone could help me to give out of this problem? -
Django vs PostgreSQL: how to queue write and read?
I have got the following problem: We have 3 components in the system - say, front-end, a Ruby app that deals with database write requests and a Django app that handles the read requests (from the same PostgreSQL database). At some point, the front-end updates (PUT) a record in the database via Ruby app and after that request, asynchronously sends another request to fetch the updated version of that record via Django app (GET). The problem is that the GET requests sometimes returns the old version of the record (not updated), that is, the Ruby app takes too long to update the database and before it is done, Django fetches the old version of the record. I am aware that my server is too "weak" for this kind of job and with a proper serving computer it will be fine, but it is not 100% guaranteed. I can think of few ways of dealing with that, just wondering if there is a proper way of fixing it? Thanks! P.S.: The Ruby and Django apps do not interact with each other and it is one of the important requirements!