Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Logged-in users see login and signup page (django-registration)
I'm using the django-registration with django 1.11. Following the docs I put the URL's and works fine. But the logged users see the login page and registration page (non-sense for me). I try redirect_authenticated_user=True in the URL, works for login page and not for register and crash on loggout. My question is : I need to get all of django-registration's URLs and put 'redirect_authenticated_user=True' the ones I want? I have to create views to see if the user is already logged in and redirect it? or maybe just check the template? obs.: I'm using only URL's and Templates od Django-registration -
Django_filters MultipleChoiceFilter on boolean field
What is the most elegant way to perfom cumulative filtering on boolean field with django_filters? The goal is to return both objects with field named foo set to True and False as a response to querystring ?foo=True&foo=False FOO_CHOICES = [(v, _('true') if v else _('false')) for v in MyModel.objects.values_list('foo', flat=True).distinct()] class MyFilterSet(django_filters.FilterSet): foo = django_filters.MultipleChoiceFilter(choices=FOO_CHOICES) class Meta: model = MyModel fields = ('foo', ) Unfortunately example from above does not work, I guess it's becuase BooleanField is not the same as CharField with predefined choices. -
Django: update choices field using human readable value?
I am using Django 1.9. I have a model as follows: class Report(models.Model): LANGUAGE_CHOICES = ( ('EN', 'English'), ('CY', 'Welsh') ) company = models.ForeignKey(Company) language = models.CharField( max_length=2, choices=LANGUAGE_CHOICES, default='EN' ) pdf_url = models.URLField(blank=True) Now I want to insert a value: report_obj, created = Report.object.update_or_create( company=company, language='English') But this fails with: psycopg2.DataError: value too long for type character varying(2) My data source contains "English" and "Welsh", not "EN" and "CY". How can I update using the human readable name? Or do I need to maintain a separate lookup list from the human readable name to the short value in my import script? -
Django Registration Redux
I want to implement the registration and login function using the Django registration Redux package. I follow step by step the Quick start guide: "" Run: python manage.py runserver And I put in the browser: And I get the page completely blank My project is in: Thank you for your help -
Side effect exception stopping test execution
I have the following situation: I'm testing a Django view, and I wrote a test in order to cover the flow when some exception have been raised. The view looks like something like this: class SomeView(View): # ... def get(self, *args, **kwargs): try: some_function_that_must_except() except Exception as error: # Flow I want to cover with test. else: # Flow already covered And the test: @mock.patch('some_function_that_must_except') def test_redirect_logic_fail(self, mock_some_function_that_must_except): # Configuring mock mock_some_function_that_must_except.side_effect = Exception('Exception raised on purpose') response = self.client.get( reverse('the-view-im-testing') ) # If the exception is raised then we should be redirected to # another view. self.assertRedirects(response, reverse('alternate-view')) So good, so far, but when I run this test I get this error message: line 1118, in _mock_call raise effect Exception: Exception raised on purpose and then the test stops. Why is this exception not been handled by my view? I'm using mock 2.0.0 and python 2.7.12. -
Django dynamically edit and save objects from a query-based table
Is it possible to take a query from a database that will grab all values from a given vaule i.e query = Table.objects.filter(x=y) send it to HTML like so: <table> <tr> <th>Value 1</th> <th>Value 2</th> <th>Value 3</th> </tr> {% for value in query %} <tr> <td>{{ value.val1 }}</td> <td>{{ value.val2 }}</td> <td>{{ value.val2 }}</td> </tr> {% endfor %} </table> Lets say the query returns 3 objects. That means the table will have 3 rows of data but in HTML all the <td> tags are the same. How can I identify each <td> per row so that I can manipulate the data and save it back to the database? I have tried with jquery, but I am only able to manipulate the first row. -
Testing login redirect
I am trying to write a test to see if my login redirects to the correct page. At the moment I am using this code which isn't working: def test_login_redirect(self): response = self.client.post( reverse('udt:login'), { 'username': 'admin', 'password': 'asdf1234' } ) self.assertRedirects(response, reverse('udt:table_list')) where udt:login equates to '/udt/accounts/login/' and udt:table_list equates to '/udt/table/'. The login functionality is Django's built-in login with a custom template. When I run the test I get the following error: AssertionError: 200 != 302 : Response didn't redirect as expected: Response code was 200 (expected 302) However, when I actually test the login functionality in the app I get this: [2017/05/30 14:43:22] HTTP POST /udt/accounts/login/ 302 [0.13, 127.0.0.1:60127] [2017/05/30 14:43:22] HTTP GET /udt/table/ 200 [0.15, 127.0.0.1:60127] which to me seems like it is in fact redirecting correctly. So, my question is what is wrong with my test that is causing the assertion error? I am pretty new to testing in Django so it could just be something that I am missing, but it seems like the test should be passing to me. Any help with this would be much appreciated. Thanks for your time. -
Do a request from soap in view
I'm trying to establish a connection with soap and get a response to send to template. But I'm stuck at requesting session from server. I don't know how to do the request and handle the data before making a proper request with session. I have just been able to do "handshake" with HttpResponse. My views.py def soap(request): import requests ipURL = 'http://URL' request = u"""<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"> <soapenv:Body> <login> <user>USERNAME</user> <pass>PASSWORD</pass> </login> </soapenv:Body> </soapenv:Envelope>""".format() encoded_request = request.encode('utf-8') headers = {"Host": "HOST", "Content-Type": "application/soap+xml; charset=UTF-8", "Content-Length": str(len(encoded_request)), "SOAPAction": ""} response = requests.post(url="http://URL", headers=headers, data=encoded_request, verify=False) soap_answer = response.content return HttpResponse(soap_answer) This will get me the response with a session key I need for further request. So I need to do another request with session key before sending response to template with xml. Can I do this in this view, or do I need to make a new 'def' that I send this response to? As you probably figured out by now, I'm new to Django. Just a few weeks in trying to learn. Be gentle ;) -
django template count for related models
I'm working on a rental project using django. I have an Inventory model and an owner's model. I'm trying to count in my template how many of the saved items in the Inventory belongs to a particular owner. Any help? Thanks. The owner model is related to the Inventory with a ForeignKey. -
Django tutorial. from . import views
I started to learn Django, I don't know python very well, so please forgive me, if the question is quite stupid). from . import views what is "." in this statement? Module's name? -
Unable to pinpoint Django's reason to 404 for all requests
I've come back to a Django project of mine after some time. Now all URLs I try to access 404 and I just can't determine the cause. The python webserver simply logs: Not Found: /http:/<ip>/test/ [<timestamp>] "GET http://<ip>/test/ HTTP/1.1" 404 1677 Whereas in the urls.py I have: url(r'^test/$', test), And test is a function I imported and simply does return HttpResponse("test ok"). In the settings.py: ROOT_URLCONF = '<projectname>.urls' The file structure is essentially: ├── <appname> │ ├── admin.py │ ├── apps.py │ ├── forms.py │ ├── __init__.py │ ├── migrations │ ├── models.py │ ├── templates │ ├── tests.py │ └── views.py # the view.py containing the discussed function ├── manage.py # manage.py ├── <projectname> │ ├── settings.py # settings.py │ ├── urls.py # the urls.py mentioned earlier │ └── wsgi.py [...] I can't find the reason why the requests 404. The debug screen displayed isn't helpful at all and doesn't differ between the ones that are supposed to work (e.g. /test/) and others that aren't supposed to work (/foo/). How can I find the culprit? -
ChunkedEncodingError with requests python
I am trying to connect to an API to receive data that I will use in my app. I use Django 1.9, Python 2.7 and I have the project mounted locally with the Apache server, using the mod_wsgi. To make the requests to the API I use requests, but when making a post request, passing it a code that I get in a previous request and a cookie, Django gives me error: "ChunkedEncodingError" Connection broken: error (10054, 'Interruption of existing connection by remote host') " I have searched the internet about it and the truth is that I have not been clear if it is mod_swgi, if django can not read chunked response ... and I can not find a solution to the problem. I have also looked at the Apache log, but no related error appears. This is the line in django that gives me the error: header = {'Content-Type': 'application / x-www-form-urlencoded', 'Cookie': cookie} answer = requests.post ('http://apiaddress.es/auth/OAuth20/Token', {'Authorization': 'Basic d2Vdfdsfdf', 'code': code, 'grant_type': 'authorization_code', 'redirect_uri ': ip,' response_type ':' code '}, headers = header) Someone who knows what is happening, and any solution? -
How to read a JSON file in Django
i work on a project with Django. I made a website in HTML/CSS/JS and a bot in Python. On my website (without Django and Python) i manage to read my JSON file like the screen : Click here to see the screen The JSON file that i'm using is this : { "1": [ [ "Comment puis-je m'inscrire \u00e0 l'IUT ? ", "Il faut suivre les instructions APB pour les futurs 1ere ann\u00e9es et pour une reconduction d'inscription pour des redoublants ou des futurs 2nd ann\u00e9es, il faut passer par l'intranet !" ] ], "0": [ [ "Qui a \u00e9t\u00e9 \u00e9lu Pr\u00e9sident de la France ?", "Emmanuel Macron" ] ] } As you can see, it's a very specific type. Indeed, my bot will use index to remove some statements. My problem is that i can't read it in Django... Because, after that, i got a Python function to select the index to remove a statement chosen by the user. Firts i need to implement this file .. Thanks ! -
Loop value is not JSON serializable in Django
In Django, I have this model: class CO(models.Model): email = models.CharField(max_length=100) in my view, I try to send email to multiple recipients using: addresses = CO.objects.all() data = { "personalizations": [ { "to": [{"email": address} for address in addresses], } ], ... but I get the following error: <CO: address@gmail.com> is not JSON serializable I tried with list(PR.objects.values()) and for address in json.dumps(addresses) but I receive bad request. -
Django: Search via GET request, POST request or in the URL?
I am implementing a search form in Django. I can do a POST or a GET request. Each has their use-cases (POST request, if I want to change data on the server, GET request, if I just want to get data from the server). Via POST request (the search keywords are not visiable in the URL, but rather in a dict in request.POST); cons: I cannot bookmark the search via GET request (the search keywords are visible in the URL, for intance localhost:8000/books/?author=schultz); cons(?): the part ?author=schultz cannot be processed by the URL handler (see [2] below). I need to read the data from request.GET.get("author", None) in my view function. or directly in the URL like so: localhost:8000/books/search/author/schultz ? The author in [1] says, that Django's preferred way to handle a URL is not via GET (like so: /category_check_view/?item_id=2, but rather like so /category_check_view/2) If I would like to implement search like this: localhost:8000/books/author/schultz, then I would have to process a GET request, read the params ?author=schultz via request.GET.get("author", None) and in my view do a redirect from this URL localhost:8000/books (in which I have a form and a GET request) to this localhost:8000/books/author/schultz. Does this approach make sense? Or … -
Django Admin adding a custom from for creating new objects
I have a model called a Story and I have another object called Images. I can currently edit them just fine using the Django admin. But I also need a parser to help add multiple stories quickly and easily. What I do is upload a bunch of image and text files to a directory. Then I parse the directory. I want to use each text file to pre-populate the fields in my Story. I do some preprocessing of the images (moving them, thumbnails, etc) and I want to be able to select which image goes with the current story. Basically I want a create form prepopulated with text from the text file and I want an inline list of the thumbnails to allow me to put a checkmark next to it if it belongs with the story I am editing. When I click save, I save the Story and Images, delete them from the directory and move on to the next text file. My issue is with Django admin. How do I create a prepopulated form (ideally the same Django admin create Story form) that also lists all my images so I can select them? Suggestions? -
Django and postgis on postgres using openshift v3
I am new to openshift v3 and am trying to deploy a django application that uses a postgres backend. I used the example https://github.com/openshift/django-ex as a starting point, wherein I removed the sample app and added my own app and code. I am using an edited version of the template django-postgresql-persistent.json to deploy the application from a private repo. When I try to deploy, the django container crashes whereas the postres container is deployed, albeit with some issues. The app uses geo search and I am encountering what I see as three issues: Issue #1. I do not think that Postgis is installed and enabled as an extension on the postgres db. I tried the below: postgres=# SELECT PostGIS_full_version(); ERROR: function postgis_full_version() does not exist LINE 1: SELECT PostGIS_full_version(); ^ HINT: No function matches the given name and argument types. You might need to add explicit type casts. postgres=# SELECT version(); PostgreSQL 9.5.4 on x86_64-redhat-linux-gnu, compiled by gcc (GCC) 4.8.3 20140911 (Red Hat 4.8.3-9), 64-bit (1 row) postgres=# SELECT PostGIS_version(); ERROR: function postgis_version() does not exist LINE 1: SELECT PostGIS_version(); ^ HINT: No function matches the given name and argument types. You might need to add explicit type casts. postgres=# … -
django - Why is my form not visible?
I have a question about forms in Django. I made a form in the forms.py class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('author', 'text',) But this form isn't rendering in the template i want: {% extends 'forum/base.html' %} {% block view %} <table> <tr> <th>Question:</th> <th>Tags:</th> <th>Date posted:</th> </tr> {% for item in query %} <tr> <td>{{ item.question }}</td> <td>{{ item.tag }}</td> <td>{{ item.created }}</td> </tr> </table> <br> <a class="btn btn-default" href="{% url 'forum:add_comment_to_post' question_url_id=item.id %}">Add comment</a> {% endfor %} <hr> {% for comment in querytwo %} <div class="comment"> <div class="date">{{ comment.created_date }}</div> <strong>{{ comment.author }}</strong> <p>{{ comment.text }}</p> </div> {% endfor %} {% endblock %} {% block formcomment %} <h1>New comment</h1> <form method="POST" class="post-form"> {% csrf_token %} {{ form }} <button type="submit" class="save btn btn-default">Send</button> </form> {% endblock %} This is my views.py: def add_comment_to_post(request, question_url_id): post = get_object_or_404(QuestionPost, pk=question_url_id) if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.save() return render(request, 'forum/thanks.html', {'form': form}) else: form = CommentForm() return render(request, 'forum/thanks.html', {'form': form}) Can anyone help me out? Iḿ fully stuck in this project with this.. Will this be related to maybe multiple views in one template? Or something else? -
Only query set the User "username" in Django rest framework
I'm using Django restframework for my app, and I want to get all the "usernames" from my User model from django.contrib.auth import get_user_model User = get_user_model() I'm using this for a serializer and for the the view : class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('username') class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer permission_classes = (AllowAny,) The problem is that it returns the username and also the hashed password, so is there any way to correct this ? thanks -
Loading up large datastructure on init for repeated use by celery task later (Django/Celery)
One of my celery tasks requires access to a very large data structure. This model is taxing on memory once loaded up and takes a very long time to do so. I am trying to avoid loading this multiple times, every time I call "score_model". Preferably, I'd like to load this data into memory once at initialisation so that it is available only to this task when required. (Usually pickle works great however this model does not serialise easily and so I cannot set it within cache. It would require a complex custom backend and I'm not convinced it would result in significant time savings.) The celery docs suggest I should create a base class. This SO answer was also very helpful Initializing a worker with arguments using Celery The answer hints at having objects made available upon initialisation for use later and works well for centralising common functions, keeping sessions open when used across workers. The following code works: tasks.py from celery import Task from celery.decorators import task class startup(Task): abstract = True def __init__(self): print "Loading..." self.score_model= load_and_bin('/opt/model.tar') @task(base=startup, bind=True, name="scoring") def scoring(self, pk): data = entries.objects.filter(geo_pk=pk) newscores = score_model(data) ...however this loads my model into memory multiple … -
Django regex url NoReverseMatch
I am bashing my head on this for a couple of hours now... I now silly. However, I don't know where the error is: So I have the following urls.py where the last line should allow me to serve a ticket object through the following url (e.g.) ticket/2/: urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^landing/$', views.landing, name='landing'), url(r'^login/$', views.user_login, name='login'), url(r'^logout/$', views.user_logout, name='logout'), url(r'^ticket/(?P<pk>[0-9])+/$', views.ticket_detail, name='ticket_detail'), ] then the view for the ticket detail is: def ticket_detail(request, pk): ticket_id = get_object_or_404(Ticket, pk=pk) return render( request, 'tickets/ticket_detail.html', context={'ticket': ticket_id, } ) However, for some reason I get the following error: django.urls.exceptions.NoReverseMatch: Reverse for 'detail' not found. 'detail' is not a valid view function or pattern name. Can someone please help? I went through the DetailView class as well and refactored the view, however same issue. I think it might be a matter of url regex... I hate regex :) -
How to create a userlog for Django and where to store it?
I want to capture the users' action from login to logout. I am using Python 3.5.2 Django 1.11 and database sqlite -
How to remove the option selected for ForeignKey from the available options for ManyToManyField when both are related to the same model in Django?
Consider the following scenario: class Show(models.Model): broadcaster = models.ForeignKey('User', related_name='broadcastedBy') listeners = models.ManyToManyField('User', related_name='listenedBy') I want that once a user has been selected (from a dropdown) as the 'broadcaster' for a show, his object should be removed from the options available for selecting 'listeners'. How to achieve this? (Assuming that I am using the Django admin panel for CRUD operations on this model) I could not find an existing question similar to this on StackOverflow. Any help would be highly appreciated. -
Not getting data from Django rest api to AngularJS
I am new to AngularJS and Djnago Rest Framework. I have created one web api which return list of customers in JSON format. I am getting proper data in RESTClient add-on of mozilla firefox. But i am not able to get data in AngularJS script. Here i have attached all the codes and error image as below: views.py (API code) class CustomerListView(APIView): renderer_classes = (JSONRenderer, ) def post(self, request, format=None): content = [] customer_list = Customer_tbl.objects.all() if customer_list: for customer in customer_list: content.append({ 'first_name': customer.cus_first_name, 'last_name': customer.cus_last_name, 'email': customer.cus_email, 'contact': customer.cus_contact }) return Response(content) test.html <!DOCTYPE html> <html ng-app="myTestModule"> <head> <script src="../scripts/angular.js"></script> <script src="../scripts/sample_page_test.js"></script> <link href="../css/style_new.css" rel="stylesheet" />--> </head> <body> <div ng-controller="customerController"> <table> <thead> <tr> <th>First Name</th> <th>Last Name</th> <th>Email</th> <th>Contact</th> </tr> </thead> <tbody> <tr ng-repeat="customer in customers"> <td>{{ customer.first_name }}</td> <td>{{ customer.last_name }}</td> <td>{{ customer.email }}</td> <td>{{ customer.contact }}</td> </tr> </tbody> </table> </div> ... ... ... </body> </html> sample_page_test.js var myTestApp = angular.module("myTestModule", []) myTestApp.controller("customerController", function ($scope, $http) { var url = "http://192.168.1.102:8000/stl_web_app/api/customer_list/"; $http.post(url).then( function(response) { $scope.customers = response.data; }); }); Error Image getting following error in Firebug console error.png Do i need to make any changes in settings.py of django application? So, Can anyone please help me to … -
how to implement fortnightly email notification in Django
I am relatively new to Django. I would like to send email notification fortnightly to the intended user. How do i do tat ?