Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Restrict access to particular pages for non-authenticated users
I'm building a simple forum in Django and I've got two models - Topic and Subtopic. I need to restrict access to some topics and subtopics for non-authenticated users, so that they couldn't access them, while other topics and subtopics should remain accessible to all the users -- both authenticated and anonymous. How do I achieve that? -
Deploying Django app on Yocto
I am currently working on a project that requires to deploy a Django Application to a ConnectCore 6 UL SBC Pro which runs a custom version of Yocto project. I have been having a lot of issues to deploy my app onto this device, I would like to know if anyone has ever achieved to do this on Yocto. So far I am trying to deploy my application using Cherokee and it is not as easy as they let you think! -
RecursionError: maximum recursion depth exceeded. Why
It seems i did something wrong? Can not config my urls. I have this error. Code below: urls.py (Root, main urls of application) from django.conf.urls import url, include from django.contrib import admin from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'', include('shop.urls', namespace='root_detail')) ] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urls.py (my urls) from django.conf.urls import url from . import views urlpatterns = [ # Product list url(r'^$', views.product_list, name='product_list'), # Product list by category url(r'^(?P<category_slug>[-\w]+)/$', views.product_list, name='product_list_by_category'), # Product detail url(r'^(?P<category_slug>[-\w]+)/(?P<id>\d+)$', views.product_detail, name='product_detail'), ] I have this error RecursionError: maximum recursion depth exceeded -
Mpld3 inside of Django Views - "NoneType" Object has no attribute "split"
I am trying to make a request to my Django back-end with AJAX. I got the AJAX part working, but I am now trying to return an mpld3 figure to display it on the page. Here is my AJAX request: $.ajax({ type: "POST", url: url, data: data, dataType: "json", success: function(json){ }, }); This is my View: import mpld3 import matplotlib.pyplot as plt def get_figure(request): fig = plt.figure() plt.scatter(X, y) model = mpld3.fig_to_html(fig) data = {'Model': model} return JsonResponse(data) Any suggestions on why it could happen? Thanks in Advance -
using twython-django creating issues in libraries
I am trying to extract the tweets of the USES using my application. I was looking for a way to do it with DJango and I came across this thread on StackOverflow: How can I use Django Social Auth to connect with Twitter? From the thread I learned about twython-django library. I have a visit for sample to the github repository of the library. With the help of the instructions I have configured my application settings.py as: LOGIN_URL='/login' LOGOUT_URL='/logout' LOGIN_REDIRECT_URL='/' LOGOUT_REDIRECT_URL='/' TWITTER_KEY = 'xxxxx' TWITTER_SECRET = 'yyyyyyyyyyyyyyyyyyyyy' I used the following code in my Home.html to call the tweets: <div> {% for tweet in tweets %} {{ tweet.text }} {% endfor %} </div> But it is still a mystery from where the authentication will take place as there is nothing mentioned about the authentication in the library documentation. Well, then I tried t run the application as: python manage.py runserver This is what I got: An error: C:\Python27\lib\site-packages\sklearn\cross_validation.py:44: DeprecationWarning: This module was deprecated in version 0.18 in favor of the model_selection module into which all the refactored classes and functions are moved. Also note that the interface of the new CV iterators are different from that of this module. This … -
How to toogle src attribute of script when user click element?
I use bootstrap 3.3.7 in my Django project. I have modal with textarea. Inside that textarea in the corner I put icon. Here below in the picture you can see my textarea. When user click to the icon I change textarea size to full screen of the browser. Also to my textarea I use autosize plugin which adjust textarea height to fit text. In normal situation (when textarea small) I need to use autosize plugin. When I click icon and change textarea size I dont need to use this plugin. Question: How to toogle src attribute of script when I click icon? P.S. I have little conflict with autosize plugin when textarea in full size mode. Cause when I started to write in textarea in full size mode autosize plugin change it's height. For thats why I want to cancer this plugin when textarea in fullscreen mode. html: <div class="dashboard-wrapper"> <div id="dashboard-content"> <div class="modal fade"> <div class="modal-dialog modal-lg"> <div class="modal-content"> <form method="post" action=""> <div class="form-group"> <label for="body">Discription</label> <div class="textarea-wrapper"> <textarea name="body" class="form-control" id="body"></textarea> <i class="fa fa-arrows textarea-icon" aria-hidden="true"></i> </div> </div> </form> </div> </div> </div> </div> </div> <script id="" src="{% static 'js/autosize.js'%}"></script> JS: autosize(document.querySelectorAll('#body')); // Autosize for textarea with "body" id … -
Django number of products in basket by product ID
trying to count the number of items in my cart by specific product ID but struggling, e.g. 7 apples in basket. I have been trying to use the python count function but currently not working. I tried add the following code to my cart.py file but this didn't work: def count_prod(self, product) product_id = str(product.id) if product_id in self.cart: return count(self.cart[product_id]) This is my cart.py file from decimal import Decimal from django.conf import settings from shop.models import Product class Cart(object): def __init__(self, request): """ Initialize the cart. """ self.session = request.session cart = self.session.get(settings.CART_SESSION_ID) if not cart: # save an empty cart in the session cart = self.session[settings.CART_SESSION_ID] = {} self.cart = cart def __len__(self): """ Count all items in the cart. """ return sum(item['quantity'] for item in self.cart.values()) def __iter__(self): """ Iterate over the items in the cart and get the products from the database. """ product_ids = self.cart.keys() # get the product objects and add them to the cart products = Product.objects.filter(id__in=product_ids) for product in products: self.cart[str(product.id)]['product'] = product for item in self.cart.values(): item['price'] = Decimal(item['price']) item['total_price'] = item['price'] * item['quantity'] yield item def add(self, product, quantity=1, update_quantity=False): """ Add a product to the cart or update its … -
How do I 'Autofill' a CreateView field
I have a model called Artist, and now I'm working on building a comment section for the Artist DetailView. I've built a model called ArtistComment, created a CreateView and added this to the DetailView using modal divs so it looks nicer. The only issue is that when you click 'add comment' the modal shows both the 'artist' and the 'comment' fields. The artist field is a dropdown menu to select which artist the comment is applied to. I would like to be able to hide the 'artist' field, and have this auto-complete based on the page you follow the 'add comment' link from. I've managed to get the 'User' field to autocomplete with 'self.request.user' but whenever I try anything like self.request.artist_id it makes my modal form show blank. Can anyone help point me in the right direction to fix this issue? views.py: class ArtistCommentCreate(CreateView): model = ArtistComment fields = ['artist', 'message',] def get_success_url(self): return reverse('events:artistdetail', kwargs={'pk': self.object.artist_id}) def form_valid(self, form): form.instance.author = self.request.user return super(ArtistCommentCreate, self).form_valid(form) urls.py: url(r'^artist-(?P<pk>[0-9]+)/$', login_required(views.ArtistDetailView.as_view()), name='artistdetail'), url(r'^artistcomment/add/$', login_required(views.ArtistCommentCreate.as_view()), name='artistcomment-add'), artistdetail.html: <a data-toggle="modal" data-target="#artistcommentModal" href="{% url 'events:artistcomment-add' %}">Add A New Comment</a> <div id="artistcommentModal" class="modal fade" role="dialog"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-body"></div> </div> </div> </div> -
The code should filter events from the future, but it does not
I have project in old django version - 1.5 (I know better is to upated to newer version, but for now this is not an issue). I have code connecting with pure sql - I want to have only events from the future - display on list. Here is my code - some reason I got event from the past. I tried without MIN(date), but I got an error: more than one row returned by a subquery used as an expression def get_events(): return Events.objects.extra(select={'next_activity': 'SELECT MIN(date) FROM productions_activity WHERE productions_activity.production_id = home_teaser.production_id'}).filter(Q(online__lte=now()), Q(online_end__gte=now()) | Q(online_end__isnull=True)).order_by('next_activity') -
Error with django starting
I am working on pycharm, with a django project. Whenever I do the "run" thing, and I go to my home page or wherever " http://127.0.0.1:8000/.." Everything works fine, but I get this error : C:\Users\elmou\AppData\Local\Programs\Python\Python36-32\lib\importlib__init__.py:126: RemovedInDjango110Warning: django.core.context_processors is deprecated in favor of django.template.context_processors. return _bootstrap._gcd_import(name[level:], package, level) Should I change the django version or what ?! Thanks. -
Authenticating with JWT token generated externally in DJango
Can one use a token that is not generated by DJango for authentication purposes? In other words, can I get a token from an external source and then pass it to the DJango authentication/authorization system for use? TIA -
Django and strftime best practices
Could someone please comment on best practices regarding formatting dates in Django? More specifically I am trying to get the current day (Monday, Tuesday,...) translated in the current active language in Django. Using x.strftime('%A') always yields the day in English, which may not be the current language in Django. Thanks x. -
Combine DetailView and FormView Django AND get the current user
First of all I know that there are similar Posts like this. I tryed them all. I cant figure out how to combine them. I have a DetailView. In the DetailView i have a FormView. I want the user write something and (after submit) save the user and the text in a model. I am here to learn. I would appreciate it, if you explain how it works and not that is works. views.py class PostDetail(generic.DetailView): model = models.Post def get_context_data(self, **kwargs): context = super(PostDetail, self).get_context_data(**kwargs) context['form'] = forms.CommentForm return context class CommentsView(LoginRequiredMixin, generic.FormView): form_class = forms.CommentForm def __init__(self, *args, **kwargs): self.request = kwargs.pop('request', None) return super(PostDetail, self).__init__(*args, **kwargs) def save(self, *args, **kwargs): kwargs['commit'] = False obj = super(PostDetail, self).save(*args, **kwargs) if self.request: obj.author = self.request.user obj.save() return obj html: <form method="post" action="{% url "posts:comments" %}"> {{form}} {% csrf_token %} <input type="submit"> </form> urls.py urlpatterns = [ url(r"by/(?P<username>[-\w]+)/(?P<pk>\d+)/$", views.PostDetail.as_view(), name="single"), url('^comments/$', views.CommentsView.as_view, name='comments'), ] EDIT: i didnt finshed accidentally published it -
Redirecting used django invitation links
I am trying to update an existing Django app's login process because of a problem I have with the invitation links. If I send an invitation link it works as expected and takes the user through the sign-up form and into the site, but if they try to use that invitation link later to access the site again it give a 500 error (DoesNotExist: User matching query does not exist.). I want to redirect all expired invitation links to the main login page so that they can just login rather than going to the 500 error page. I am using Django 1.11 and the invitation backend (http://django-organizations.readthedocs.io/en/latest/reference/backends.html) I see that it has a get_success_url that I can use to send the original login to a home page, but is there a get_fail_url that I can use to send expired invitation links to a main login page? Or is there a better way to approach this problem? Here is my CustomerInvitations class that I send all /invitation/ urls to: ``` class CustomerInvitations(InvitationBackend): form_class = CustomUserRegistrationForm def __init__(self): super().__init__(Customer) def get_success_url(self): return "/" def invite_by_email(self, email, sender=None, request=None, **kwargs): try: user = self.user_model.objects.get(email=email) except self.user_model.DoesNotExist: user = self.user_model.objects.create(username=self.get_username(), email=email, password=self.user_model.objects.make_random_password()) user.is_active = … -
How to filter on prefetched data?
I have a model Article and several ArticleDescription (one for each language). class Article(models.Model): articleid = models.CharField(primary_key=True, max_length=100) def __unicode__(self): return str(self.articleid) class ArticleDescription(models.Model): article = models.ForeignKey(Article, on_delete=models.CASCADE) lang = models.CharField(max_length=2, default='en', blank=False, null=False) description = models.TextField(blank=True, null=True) class Meta: unique_together = ('article', 'lang') def __unicode__(self): return str(self.description) I use prefetch_related to get just the one description for my current language like this: desc = models.ArticleDescription.objects.filter(lang__iexact=translation.get_language()) The, I get the Articles I want: c = models.Article.objects.all().order_by('articleid').prefetch_related(Prefetch('articledescription_set', queryset=desc, to_attr='description_tr')) This all works fine, but I want to filter also on the (translated) description. A SQL query would look like this: SELECT A.*, AD.* FROM Article A LEFT JOIN ArticleDescription AD ON AD.lang='<<curlanguage>>' AND A.articleid=AD.articleid WHERE A.articleid='<<searchstring>>' OR AD.description='<<searchstring>>' How can I achieve that? I tried using filter(Q(articledescription_tr__icontains=search)), but that didn't work. -
How should a model object be passed to a helper function in Django
What is the correct way to pass a model object to a helper function in Django? E.g., I have a user object; u = User.objects,get(pk=1) and then want to perform some operations on u using the function helpers.foo() before saving back to DB. Should I pass the entire object and manipulate directly? Or just the ID then re-query the DB within the helper function to get the object again... -
Django Redirecting from views.py to html page
I am using Django 1.11. I have developed some html pages & have views.py I have page called forgotpassword.html where-in I take EmailId of user. I find the respective security question & want to display it to user to enter the answerfor it. I have another page called getpassword.html for this. Here is the code: 'def forgotpassword(request):' 'usercontemail = request.POST['useremail']' '#Get the securityquestion from Database' 'return redirect(request,'home/getpassword.html',{'squestion': squestion})' 'def getpassword(request):' '#Display security question, get the answer from user & proceeed' When user enters his email & hits submit I am able to see the input area for user to enter his security answer. But the url remains forgotpassword.html So when the user enters his Security Answer, I am getting error of useremail cannot be blank. This is because of the url problem. Can you please suggest workaround? -
How to make an Django Ajax Request with jQuery?
I am new to Ajax and want to make an Ajax Request to an view function in Django with jQuery, but I am stuck. I started with a simple example to check if it works var button = $('.any_button'); $(button).click(function() { var button_value = $(this).val(); $.ajax({ type: "POST", url: "/url-path/to-my/view-function/", dataType: "json", data: { "button_value": button_value }, beforeSend: function () { alert("Before Send") }, success: function () { alert("Success"); }, error: function () { alert("Error") } }); }); my view function: from django.http import JsonResponse def button_check(request): data = {"message": "Message"} return JsonResponse(data) My url path refer to views.button_check. I get the beforeSend alert and the error alert, but I expect the success alert. What did I miss? unfortunately I do not get ahead -
Django Rest Framework use DjangoModelPermissions on ListAPIView
I am playing around with the djangorestframework and my goal is to use DjangoModelPermissions on my view which reacts to a GET request. The official documentation says: The default behavior can also be overridden to support custom model permissions. For example, you might want to include a view model permission for GET requests. Source So I modified my model like the following: class User(AbstractUser): display_name = models.CharField(_('Display Name'), blank=True, max_length=255) class Meta: permissions = ( ("view_user", "Can view users"), ) def __str__(self): return self.username And the view: class UserListAPIView(ListAPIView): queryset = User.objects.all() serializer_class = UserSerializer permission_classes = (permissions.DjangoModelPermissions,) Settings: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.TokenAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.DjangoModelPermissions' ] } The problem is that my implemented UserListAPIView successfully returns a list of all objects to a user who doesn't belong to a Group and has no User Permission. It seems to me that the DjangoModelPermissions takes no effect. -
django - another application accessing temporary uploaded file
My Objective: I am trying to upload event log file (.evtx), convert it in the backend using LogParser tool into csv, and visualize the data afterward. The Logparser tool will be run by command line using os.system(cmdline_string). Basically I am trying to parse the uploaded file without saving the temporary uploaded file to the file system. My Problem: I am parsing the event log using Log Parser's command line. I cannot access the temporary uploaded file in appdata\local\temp using log parser's command line. Code: uploadfile.html <form method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="myfile"> <br> <button type="submit">Upload</button> </form> views.py import os import pandas as pd def uploadfile(): if request.method == 'POST' and 'myfile' in request.FILES: myfile = request.FILES['myfile'] filename, fileext = os.path.splitext(myfile.name) if fileext == '.evtx': cmdstring = "logparser " + \ "\"SELECT * INTO " + "output.csv" + \ " FROM " + myfile.temporary_file_path() + "\" " + \ "-i:EVT -o:CSV" os.system(cmdstring) # This will output error: # Cannot open <from-entity>: Error opening event log /path/to/uploadedfiles: # The process cannot access the file because it is being used by another process I am guessing that probably the temporary file is being accessed by django thus logparser cannot access the … -
Django Regex and {% url %} in templates
I am working with django and stuck in some problem: In my pages I need to display data of different user, 127.0.0.1/user_id/, 127.0.0.1/user_id/video for example 127.0.0.1/123456/video will display video of user with id 123456. I am having issues with regex in django url and template. Oh and 127.0.0.1/ is reserved for superuser, like if he has id of 111111 127.0.0.1/111111/ and 127.0.0.1/ will display same info urls.py urlpatterns = [ url(r'^((?P<id>\d+)/)?$', views.main_page, name='main_page'), url(r'^((?P<id>\d+)/)?video/$', views.videos_page, name='videos_page'), ] what I am currently doing in my templates is this: <a href="{{id}}/video/">Go to Video of user {{id}}</a> my question is - Is there a better way like using django's{% url 'video' id=id %} By the way I tried this approach in url it puts urls like that /video/{{id}}. Any ideas would be appreciated? -
Factory boy error : ValueError: save() prohibited to prevent data loss due to unsaved related object
I have a problem with factory boy, by searching I've found a post describing my exact case in another forum , but unfortunately with no responses. So I posted it here looking forward to have a response to this issue : My test fails with the message ValueError: save() prohibited to prevent data loss due to unsaved related object 'created_by' I thinking the problem in related to foreign key. I try to test Task model, this is how my code looks like class Task(models.Model): title = models.CharField(max_length=255, verbose_name='Заголовок') description = models.CharField(max_length=255, verbose_name='Описание') cost = models.DecimalField(max_digits=7, decimal_places=2, default=0, verbose_name='Цена') assignee = models.ForeignKey('users.User', related_name='assignee', null=True, verbose_name='Исполнитель') created_by = models.ForeignKey('users.User', related_name='created_by', verbose_name='Кем был создан') def __str__(self): return self.title I test it with factory boy that is how my factory boy class looks like class UserFactoryCustomer(factory.Factory): class Meta: model = User first_name = 'name' last_name = 'Asadov' username = factory.LazyAttribute(lambda o: slugify(o.first_name + '.' + o.last_name)) email = factory.LazyAttribute(lambda a: '{0}.{1}@example.com'.format(a.first_name, a.last_name).lower()) user_type = 1 balance = 10000.00 class UserFactoryExecutor(factory.Factory): class Meta: model = User first_name = 'Uluk' last_name = 'Djunusov' username = factory.LazyAttribute(lambda o: slugify(o.first_name + '.' + o.last_name)) email = factory.LazyAttribute(lambda a: '{0}.{1}@example.com'.format(a.first_name, a.last_name).lower()) user_type = 2 balance = 5000.00 class TaskFactory(factory.Factory): … -
objects.all() not working - django
i have below model, from django.db import models # Create your models here. class user_files(models.Model): Filename = models.CharField(max_length=50) Browse = models.FileField() and in my view i want all data from above model, my view is.. def user_in(request): if not request.user.is_authenticated: return render(request, 'accounts/logout.html') else: if request.method == 'POST': form_new = Fileupload(request.POST, request.FILES ) #instance=form_new.save(commit=False) #instance.save() if form_new.is_valid(): form_new.save() return redirect('in') else: form_new = Fileupload() data = user_files.objects.all() return render(request, 'accounts/in.html', {'form_new': form_new}, {'data':data}) and in my template i am writing, <div> {% if request.user.is_authenticated %} {% for da in data %} <h3>{{data.Filename}}</h3> {% endfor %} {% endif %} </div> but in my view, it is showing error for objects.all() as unresolved attribute. i am stuck . i am using pycharm. How to solve this? Thanks in advance -
Get email address from Google Sheets API
I'm using Google Sheets API in Django following this sample. I want to limit data operations on sheets of some specific email addresses. That is, some email addresses will get fewer features than the rest. For that, I need to know the email address of the authenticated user. How can I do so using Google Sheets API in Django? -
Best way to store mappings in a database
Suppose I have an employees table(with around a million employees) and a tasks table(with a few hundred tasks). Now, I have a mechanism to predict how probable(percentage) an employee is to complete the task -- let's say I have four such mechanisms, and each of the mechanism outputs it's own probability. Putting it all together, I now have n1(employees) times n2(tasks) times n3(mechanisms) results to store. I was wondering what would be the best way to store these results. I have a few options and thoughts: Maintain a column(JSONField) in either of employees or tasks tables -- Concern: Have to update the whole column data if one of the values changes Maintaining a third table predictions with foreign keys to employee and task with a column to store the predicted_probability -- Concern: Will have to store n1 * n2 * n3 records, I'm worried about scalability and performance Thanks for any help. PS: I'm using Django with postgres