Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django- URL namespace for an app
This was the root urls.py file for my Django Project: #root urls.py urlpatterns = [... url(r'^forms/', include(forms_builder.forms.urls)),] I've added a namespace because I want the "forms" URL's to be referenced from another app: #root urls.py urlpatterns = [... url(r'^forms/', include(forms_builder.forms.urls, namespace='forms_builder')),] #forms urls.py urlpatterns = [... url(r"(?P<slug>.*)/$", views.form_detail, name="form_detail"),] But now when I try to access the form_detail page like at for example /forms/my-example I get an error I didn't have before: NoReverseMatch at /forms/my-example/ Reverse for 'form_detail' with arguments '()' and keyword arguments '{u'slug': u'my-example'}' not found. 0 pattern(s) tried: [] -
Validate field with Rest api in Django or Ajax
I have a requirement in my html form where I need to validate a field with rest API call to one of the end point without submitting the form.I am using Django forms and javascript but need more details on how can I achieve it? Right now I have below javascript: sfarm_name_field_1 = $('#id_sfarm_name')[0]; sfarm_name_field_1.addEventListener("input", function() { var value = sfarm_name_field_1.value; if (value != 'a') { sfarm_name_field_1.setCustomValidity("SFarm name must be a!"); else { sfarm_name_field_1.setCustomValidity(""); } }); and HTML for this field is in Django form is: <div class="form-group"> {{ form.sfarm_name }} <span id="helpblock" class="help-block"><small>Accepts FQDN</small></span> </div><!-- /.form-group --> Important note: rest cal which we are going to use needs authentication so need to keep that also into the code. Pls let me know if someone can help me on same. -
Why is data returned from django.contrib.postgres.fields.JSONField a string?
Environment: Django 1.9.10 psycopg2 2.6.2 PostgreSQL 9.5.4 installed via Homebrew on macOS Sierra Python 3.5.2 installed via Homebrew Example model: from django.db import models from django.contrib.postgres.fields import JSONField class Foo(models.Model): data = JSONField() When I try to create an object, everything works as expected: from myapp.models import Foo x = Foo() x.data = {'some key': 'some value'} x.save() However, when I try to retrieve that data, the value of the .data attribute is a string: from myapp.models import Foo x = Foo.objects.order_by('-id')[0] # returns "{'some key': 'some value'}" x.data # returns <class 'str'> type(x.data) My question: how do I get back the dict so I can manipulate data within the JSON field? I can use eval(), but that's obviously extremely dangerous. -
Editing django admin change list item
So currently I have a django model admin page, with some extra fields specified. I want to be able to modify just 1 field so that instead of listing the value, I can click on it to go to a URL. Let's say the model is Product, and the field is ID. Right now it shows ID but I want to be able to click on the ID on the change list to go to the following URL: http://google.com/ID The http://google.com/ isn't saved anywhere. How would I go about doing this? Thank you! -
Invalid block tag: 'phone_nos', expected 'endblock'
I have pass a list of phone nos in my view through the context object and use it in a HTML select box. If the phones_nos list is empty I want to display a message but for some reason im unable to check if the phone_nos list is empty of not in the template. We are using Django==1.6 Template:- context = { 'phone_nos': [user.number for user in TwilioSMSDevice.objects.filter(user_id=User.objects.get(username=request.user).id)] } return TemplateResponse(request, self.index_template or 'two_factor_auth.html', context) <div class="form-row"> <label for="id-phone-number" class="required">Pick your Device:</label> <!-- <input type="text" id="id-phone-number"> --> if {% phone_nos %} <select id="id-phone-number"> {% for element in phone_nos %} <option value={{ element }}>{{ element }}</option> {% endfor %} </select> {% else %} In the else {% endif %} </div> Error:- Invalid block tag: 'phone_nos', expected 'endblock' -
Determining which paginated response contains my object
I'm working on an Angular view, but my question is rather theoretical. I have the following view and directive: The directive is a list selector which communicates with a paginated endpoint and responsible for navigating to other views. The view displays one (or more) objects detailed. The idea is that the view should be only concerned about the selected events, while the directive is responsible for displaying the list elements in a fixed order (decreasing creation date) and highlight the ones that are displayed in the view, so the only information they share is the list element ids (or the elements themselves). If the selected element is recent, then everything is fine (because it's on the first page), but if it's not on the first page, I'm in trouble. I was thinking about fetching more and more elements until all the selected elements are included in the directive list, but it doesn't sound like a nice solution. I was wondering if it's okay to return a paginated response containing all selected elements if I want to obey the REST principles? In other words, I'd add a get parameter which is similar to a filter parameter, only it tells the backend … -
Django add methods to django.db.models
I have a created a table that stores session environments for a program that has to manage authentication via multiple 3rd party SSO authentication frameworks. What I am trying to do is create a new method inside of my UserEnvironemntSession object so that I can do: from authentication import UserEnvironementSession, User, Environement #user and environement will be configured as part of a session somewhere and #This is just an example user = User.objects.get(username="username") environment = User.objects.get(pk=2) ues = UserEnvironemntSession.objects.get(user=user, environment=environement) user_session = ues.create_user_sso_session() The above code would look for a session for the given user/session objects then create a new authenticated session for the user. What I have done is created a new method in my UserEnvironementSession class as follows class UserEnvironmentSession(models.Model): user = models.ForeignKey("User", related_name = "userenvsession_user", on_delete=models.CASCADE) environment = models.ForeignKey("Environment", related_name = "userenvsession_environement", on_delete=models.CASCADE) session_token = models.CharField(max_length=200) def create_user_sso_session(self): ''' Generates a new user object from the UserEnvironmentSession. It will attempt to set the User.token and authenticate. If the auth token is expired. It will throw an error that can be used to initiate a new login process. ''' #Set up our SSO authentication auth = SSO.authentication.SSOAuthentication() auth.domain = self.environment.domain auth.auth_header = self.environment.header #configure our user with our … -
How to add functionality to the Admin login view?
I hope someone can help me with this. Scenario: 1) A user goes to our website /customer-area/ and gets logged in using the following Django code: account = authenticate(email=email, password=password) login(request, account) 2) Angular then sets a cookie to say she is logged in. 3) She then goes to /admin/ and is presented with the message: You are authenticated as user@user.com, but are not authorized to access this page. Would you like to login to a different account? She chooses to log in as an administrator. 4) She then goes back to /customer-area/. Problem: Angular checks a cookie to make sure she's authenticated but gets confused. The cookie says she's authenticated using the account she used in step (1) above, but Django thinks she's authenticated using the account she used in step (3) above. (Django is correct). This is causing all sorts of confusion for Angular. So I guess I need to add some functionality to the login view to destroy the Angular cookie when an admin logs in. Do any of you know how I can override the Admin login view? Or perhaps there is an easier way to deal with this problem which I cannot think of. Thanks … -
Stripe Django KeyError
I made this issue on Stripe's github https://github.com/stripe/stripe-python/issues/261#issuecomment-257270530 I write the following: import stripe #is better practice because this lib does that anyways. stripe.api_key = "sk_test_xyz" .... # create new_acct = stripe.Account.create( managed=True, country="US", email=request.POST['email'] ) profile.stripe_id = new_acct["id"] profile.stripe_keys_secret = new_acct["keys"]["secret"] profile.stripe_keys_publishable = new_acct["keys"]["publishable"] I get keyerror: 'Id' when I run it in Django. I even tinkered with exporting Obj -> Dict, with similar results. -
Atomically Compare-Exchange a model BoolField in Django
How can I atomically compare-exchange-save a value of Django model instance BooleanField? (Using PostgreSQL as the DB backend). Example use case: def compare_exchange_save(model_object, field_name, comp, exch): # How to implement? .... from django.views.generic.edit import FormView from django.db import transaction from my_app.models import LicenseCode class LicenseCodeFormView(FormView): def post(self, request, ...): # Get object matching code entered in form license_code = LicenseCode.objects.get(...) # Safely redeem the code exactly once # No change is made in case of error try: with transaction.atomic() if compare_exchange_save(license_code, 'was_redeemed', False, True): # Deposit a license for the user with a 3rd party service. Raises an exception if it fails. ... else: # License code already redeemed, don't deposit another license. pass except: # Handle exception ... -
Save drawn pillow image to user profile
I am trying to draw and then save an image to a one to one user profile that I have created. When I run through the process unauthenticated the flow is flawless and the image displays as expected; however, when I attempt to run through the process authenticated the image is never created. I have been struggling with this for some time now so any help would be greatly appreciated. Please see my code below. view def pat_image(request): # size definition size = request.session['size'] # img definition fit_card = '/Users/.../Documents/Projects/.../main/static/img/size-card.png' image = Image.open(fit_card, 'r') draw = ImageDraw.Draw(image) # amelia size line draw if size == 'XXS': draw.line([(212, 80), (282, 80)], fill=(0, 0, 0, 255), width=5) elif size == 'XS': ...(etc) stringio_obj = StringIO() # save img logic if request.user.is_authenticated: image.save(stringio_obj, format='PNG') image_file = InMemoryUploadedFile( stringio_obj, None, 'fit_card_' + request.user.email + '.png', 'image/png', stringio_obj.len, None) new_fit_card = Profile() new_fit_card.fit_card.save('fit_card_' + request.user.email + '.png', image_file) new_fit_card.save() else: response = HttpResponse(content_type='size_card.png') image.save(response, 'PNG') return response model class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) fit_card = models.ImageField(null=True, upload_to="fit_cards") -
Handling post back of Django all-auth in bootstrap 3 modal popup in Djano App
I am using the Django All-Auth app in my Django website with bootstrap 3 navbar template where in the Log In button is in the navbar on the top-right. The navigation is in a different file navbar.html which in turn in called by base.html Now I am able to load the login view (account_login) of Django all-auth in the modal popup. But however on entering wrong password the user is redirected to the accounts/login url page to show the error message of Wrong Password Entry. I need to display the error messages of all-auth in the same modal popup. I have treid the following link but of no use: How to get redirected to a popup after Facebook login Over-riding Django-allauth login/ registration urls with custom url/ pages How to POST the data from a modal form of bootstrap? https://www.abidibo.net/blog/2014/05/26/how-implement-modal-popup-django-forms-bootstrap/ Please find below the code for navbar.html {% load staticfiles %} <!-- Static navbar --> <nav class="navbar navbar-default navbar-static-top"> <div class="container-fluid"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="{% url 'home' %}"><img src="{% static 'img/THM_300.png' %}" class='img-responsive' style='width:200px'/></a> </div> <div id="navbar" class="navbar-collapse collapse"> <ul class="nav … -
Django is correctly using my 404.html but doesn't render the view from handler404 (debug=false)
I have been busy with it for 3 days before realising that something might be wrong from my views. When I have a 404 error on my website, its shows as a 404 OK or 302 OK but never the proper 404 error. I did a very simple test: handler404 = views.my_custom_error def my_custom_error(request): return HttpResponseRedirect("http://google.com") Absolutely nothing happens but my 404.html is still showing. So I'm wondering, what's the magic trick to use in order to have a proper 404 response? Or at least to be able to use our own view from a handler404? And I'm testing it on development server, so trust me: debug = false ;) EDIT: I deleted the handler404 = views.my_custom_error and this time I have the default blank page "page not found". I don't understand.. -
How to avoid unicode in fixtures
I have a simple fixtures file: [ { "model": "accounts.priceClass", "pk": 1, "fields": { "title": "Без скидки", "discount": 0 } }, { "model": "accounts.group", "pk": 1, "fields": { "name": "Розница", "price_class_id": 1, "slug": "client" } }, { "model": "accounts.group", "pk": 2, "fields": { "name": "Оптовики", "price_class_id": 1, "slug": "wholesaler" } }, { "model": "accounts.group", "pk": 3, "fields": { "name": "Дизайнеры", "price_class_id": 1, "slug": "designer" } } ] But when I try to execute ./manage.py loaddata accounts/fixtures/mock.json I get an error: django.core.exceptions.FieldDoesNotExist: Problem installing fixture 'SOME_PATH/accounts/fixtures/mock.json': Group has no field named u'price_class_id' But it has. I believe it's all because of unicode. How do I avoid unicode? -
How to debug Django 500 Internal Server Error
I am trying to complete this tutorial, but when I POST data to "register endpoint", application replies with 500 Internal Server Error. There is absolutely no clue in the development server console. No errors, no traceback... only: [31/Oct/2016 16:26:17] "POST /api/v1/accounts/ HTTP/1.1" 500 107853 What is the method of debugging such error? -
Flask continues communication between server and client
I am trying to make for example log in site. I want that when my client send me request (It go to other django application), the django app send the request to me, and if I want from flask I return question that the client should answer, after that maybe another question (It can be as many questions the server want). Hot to do continues communication in flask that after I return from the get function it will not exit the function and will wait for other input? Thanks -
Django can't see environment variables?
I'm trying to run Django (1.10) but getting an error: (.venv)$ ./manage.py runserver 0.0.0.0:8000 Traceback (most recent call last): File "./manage.py", line 10, in <module> execute_from_command_line(sys.argv) ... File "/home/myapp/myapp/myapp/myapp/settings/local.py", line 5, in <module> from .base import * File "/home/myapp/myapp/myapp/myapp/settings/base.py", line 64, in <module> 'NAME': utils.get_env_setting('RETR_DB_NAME'), File "/home/myapp/myapp/myapp/common/utils.py", line 13, in get_env_setting raise ImproperlyConfigured(error_msg) django.core.exceptions.ImproperlyConfigured: Set the RETR_DB_NAME env variable But the environment variable is set: (.venv) $ echo $RETR_DB_NAME myname The code in question looks like this: def get_env_setting(setting): """ Get the environment setting or return exception """ try: return environ[setting] except KeyError: error_msg = "Set the %s env variable" % setting raise ImproperlyConfigured(error_msg) ... 'NAME': utils.get_env_setting('RETR_DB_NAME'), How come I can see the environment variable, but Django can't? -
TemplateNotFound: theme_base.html
so I'm trying to set up a webpage, and one of my html files begins with {% extends "theme_base.html" %}. When I try to run the program, I get an error message saying "TemplateDoesNotExist" for theme_base.html. I don't think this is a file that I have to create; is there something I need to install to access this html file? I've already got pinax_theme_bootstrap installed; I thought that that was what I needed, but the error is still there. Thanks! -
How can I use the time format used in facebook in django admin for created date?
How can I use the time format used in facebook/twitter in django admin for like created date or any other dates like modified dates? To show 2 days ago Now A few minutes ago I have looked at django.contrib.humanize but I think i can only use it in a template or view. I am looking to use it in django admin. -
How to debug MSSQL driver issues from Ubuntu
Similar to another couple of questions I've seen, I'm in the dark place of having no choice other than to connect to MSSQL from Django. I'm intermittently (but around 50% of the time, the rest it works fine) getting the error: django.db.utils.Error: ('[08S01] [Microsoft][ODBC Driver 13 for SQL Server]TCP Provider: Error code 0x274c (10060) (SQLGetData)')y note: I also get this one sometimes: django.db.utils.Error: ('08S01', '[08S01] [Microsoft][ODBC Driver 13 for SQL Server]TCP Provider: Error code 0x68 (104) (SQLGetData)') I think it's network related, I've previously tried swapping out pyodbc versions, swapping between FreeTDS and Microsoft driver for unix, and trying pyodbc and pyodbc-azure. The machines in question are Vagrant boxes on a private network with fixed IPs (Ubuntu 16.04 and Windows 8), SQL Server is SQL Server Express 2016. I can't even work out how to find a more detailed log on the Windows side to work out why/how it keeps dropping/closing the connection. -
Is it a bad idea to put application code in virtual environment directory?
I'm working on a project with someone who followed a tutorial to setup a Django appplication using a venv environment. Everything is well done, but the tutorial suggested putting his application code inside the venv directory. In other words, he did something like this: pyvenv myenv cd myenv mkdir webapp cd webapp (...put in app code and run it...) Is this a bad idea? Are there any negative consequences? -
Why doesn't save() automatically call save_m2m()?
I understand if I do something like object.save(commit=False), my m2m relationships won't automatically get saved, but if I then later call object.save() I am forced to also call self.save_m2m(). Since I am calling save() I don't understand why I need to manually call save_m2m() too. Can someone explain the logic behind this? Thank you. -
Django: ContentTypes during migration while running tests
I migrated a ForeignKey to a GenericForeignKey, using the contrib.contenttypes framework. To access the ContentType object I need to migrate the data, I used this code: ContentType = apps.get_model('contenttypes', 'ContentType') my_model_content_type = ContentType.objects.get( app_label='my_app', model='my_model' ) The migration works when I run manage.py migrate, and I can then play with the updated model in the shell without problems. However, when I attempt to run manage.py test, I get the following error in the ContentTypes.object.get() line: __fake__.DoesNotExist: ContentType matching query does not exist. Querying for ContentType.objects.all() at that time returns an empty queryset. I have tried (as directed by another answer here in SO) to run this before my query, but to no avail: update_contenttypes(apps.app_configs['contenttypes']) update_contenttypes(apps.app_configs['my_app']) How can I ensure that the ContentType rows exist at that point in the test database migration? -
Django Jet dashboard not showing correctly after upgrade
I have a site running on Django, and I'm trying to install Oscar on it to add an e-commerce app onto it. I'm using Jet as the admin dashboard, and due to a problem with app naming conflicts (both Oscar and Jet have an app named "dashboard", which was fixed in version 1.0.0 of Jet), I've had to upgrade from Jet 0.1.4 to 1.0.2 (which in turn upgraded Django from 1.9.6 to 1.9.10). After the upgrade, I logged into the admin console to make sure nothing had broken, and sure enough, it had: Current state of the Jet dashboard (img) At first it seemed like a problem with the CSS files associated to Jet not being where they needed to be, but after copying them over and making sure they all are retrieved with a 200 OK on page load, the dashboard stays like this. I would obviously prefer to fix this problem without deleting and reinstalling, since there is a fair deal of configuration that I would have to replicate. Any ideas on what direction to take? -
Django Rest Auth custom reset password confirm url
With django-rest-framework, when you post a reset password (rest-auth/password/reset/), there is an email send to the user email. This email contains a confirmation URL. I would like to change this url because I'm on a REST app case, I want this email to point on my frontend instead of the django backend. With the confirmation email case, I had to override get_email_confirmation_url method from the AccountAdapter. But with the reset password case, I have no clue how to do it (there is no method in the adapter about reseting password). Any idea?