Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
Copying permissions for groups django
I want to copy group permissions from one place to another. This is my code: from django.db.models import Q from django.contrib.auth.models import Permission, User, Group user_ids = Permission.objects.filter(codename='bags').values_list('user', flat=True) groups = Permission.objects.filter(codename='bags').values_list('group', flat=True) new = Permission.objects.get(codename='bags_new') for user in User.objects.filter(~Q(user_permissions__in=[new]), id__in=user_ids): user.user_permissions.add(new) Till here it is working fine. My problem is when i try to copy for groups its not working. I have tried the following: for group1 in Group.objects.filter(~Q(groups_permissions__in=[new]), id__in=groups): group1.group.permissions.add(new) Any suggestions? -
django-rest-framework there is no autogenerated form in the BrowsableAPi while using viewsets and routes?
Kindly assist on this. I cant seem to get the HTML form in the browsable API for django rest. I figured its coz its no the default behaviour while using genericViews. But while using Viewsets the HTML form on the BrowsableApi is not available.What would be problem? How do i include the HTML form into the Browsable Api? -
Set a cookie (django) and get its value
I need to set a cookie on multiple domains (cross-domaine cookie). In order to do that, I've done a django server which creates the cookie. I then need to "read" the cookie from other domains where I call this django cookies server. If I call it through an img, the cookie is well set. But with the image, I can't access the cookie. I've tried with a javascript script, for example : function httpGet(theUrl) { var xmlHttp = new XMLHttpRequest(); xmlHttp.open( "GET", theUrl, false );request xmlHttp.send( null ); return xmlHttp.responseText; } But each time I call this fonction, a new value is given for the cookie (it does not put the cookie on my browser). Is there a way to achieve what I want ? To get this cookie value with a javascript request ? Thanks, -
Does creating atomic transaction in django create a lock automatically
I have a code block within transaction.atomic() within a view. My question is does django create some inbuilt table locking behind the scenes. with transaction.atomic(): #code block that does database operations update_user() #this updates user table create_customer_products() #this updates user id to customer products table The reason is I get a "Lock wait timeout exceeded; try restarting transaction" error when I run the code block. The setup is django mysql on centos -
DRF serializer filtering
I have a serializer that gives me everything fine. ModelClassASerializer((serializers.ModelSerializer)): ..... status = serializers.SerializerMethodField() def get_status(self, obj): .... status = ModelB.objects.get(id=obj.id).status .... return status class Meta: model = ModelClassA fields = (...) But if I want to make a filtering based on that status, I can't. I am using django_filters.rest_framework.FilterSet for the filtering. What is the best way to do that? -
Django JQuery Autocomplete
I am trying to add an autocomplete field to my form. But I can't get t to work. I have tried almost every tutorial. The request is sent out fine,I'm gettin a 200 response. In the developer tools pane when I click the request ,on the Response tab I see the whole HTML file. Shouldn't there be a json formated something..?? Here's the code: models.py class Signers(models.Model): uid = models.IntegerField(primary_key=True) firstName = models.CharField(max_length=255) lastName = models.CharField(max_length=255) views.py def get_signers(request): if request.is_ajax(): q = request.GET.get('term', '') signers = Signers.objects.filter(uid__icontains=q)[:20] results = [] for s in signers: signer_json = {} signer_json['id'] = s.uid signer_json['label'] = s.uid signer_json['value'] = s.uid results.append(signer_json) data = json.dumps(results) print data else: data = 'fail' mimetype = 'application/json' return HttpResponse(data,mimetype) urls.py url(r'^get_signers/', views.get_signers, name='get_signers'), praxis.html (my template) <script> $(function() { $("#id_signerIds").autocomplete({ source: "get_signers/", minLength: 2, }); }); </script> <script> $(document).ready(function() { $('#id_submissionTimestamp').hide(); $('#id_issueDate').hide(); }); </script> {% endblock page_head %} {% block content %} <form method="POST" class="post-form">{% csrf_token %} <!--some other fields here... --> <div class="ui-widget"> <label for="id_signerIds">Signers: </label> <input id="id_signerIds"> </div> <button type="submit" class="save btn btn-default">Save</button> </form> {% endblock %} -
Django newbie and tutorial
I'm a complete Django newbie and I am following the tutorial: https://docs.djangoproject.com/en/1.11/intro/tutorial01/ I have got to the stage: from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^polls/', include('polls.urls')), url(r'^admin/', admin.site.urls), ] in mysite/urls.py, but when I do: python manage.py runserver I get a 404 error in the browser at the address http://localhost:8000/polls/ I am using python 2.7.6 and Django 1.11.5 Can someone please point out what might be wrong? -
Only allow django admin on site id 1
I want to only show the admin for my site with id 1. In other views I've defined this in the dispatch, but I haven't found a way to do this for the admin. I tried making a custom admin class, but I didn't see a way to do this either. Is there a way to define dispatch for admin, or limiting the sites where an admin shows? The dispatch I'm using: def dispatch(self, *args, **kwargs): try: if get_current_site(self.request).pk != settings.MY_SITE_ID: response = render(self.request, 'my_app/404.html') response.status_code = 404 return response except Site.DoesNotExist: response = render(self.request, 'my_app/404.html', {'site_doesnotexist': True}) response.status_code = 404 return response return super(MyView, self).dispatch(*args, **kwargs) -
How to use collections in Django Template
I have such collection: data[1]['Monday'] = 2 data[1]['Tuesday'] = 2 data[2]['Monday'] = 5 data[2]['Tuesday'] = 7 And would like to use it in django template. When I did: {{ data}} Everything is displaying correct. But if I try e.g.: {{ data.1 }} Then I see empty collection. Does anyone know why ? Thanks in advance,