Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Gunicorn Service Environment File Format?
I'm deploying a Django project on an ubuntu machine using gunicorn and nginx, following this tutorial to do it. I have a gunicorn service that looks like this, similar to the one in the tutorial: [Unit] Description=gunicorn daemon After=network.target [Service] User=ubuntu Group=www-data WorkingDirectory=/home/ubuntu/project/mysite EnvironmentFile=/home/ubuntu/.virtualenvs/projectenv/bin/postactivate ExecStart=/home/ubuntu/.virtualenvs/projectenv/bin/gunicorn --access-logfile - --workers 10 --bind unix:/home/ubuntu/project/mysite.sock mysite.wsgi:application [Install] WantedBy=multi-user.target Since, as I understand, the gunicorn service is run in a completely new environment instead of my project's virtual environment I need to find another way to pass it environment variables. I found this page which says I can add an EnvironmentFile to my service file, which I did above. I directed the environment file to my virtualenv's postactivate script, which looks something like this: #!/bin/bash # This hook is sourced after this virtualenv is activated. export DJANGO_DEBUG=False ... Which doesn't work, unsurprisingly. What is the correct format for this EnvironmentFile to be in? -
How do I integrate Django class-based views, modelforms, and bootstrap datetimepicker?
After following this Django docs tutorial, my form isn't working. There are two problems. When I submit the form it doesn't update my object, even if I exclude the optional fields (tags, due_date) and just change the text field of the item. When I try to update the date it complains that it is not a valid datetime. It was working fine before I implemented a ModelForm. Is it not recommended using ModelForm when using JavaScript libraries like bootstrap datetimepicker that expect different date formats than those of the Django model? Am I just overlooking a workaround? Error message when I use the DateTimeField in the form: Enter a valid date/time. Error message when I use the CharField in the form: '10/09/2017 5:41 PM' value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format. models.py class Tag(models.Model): created = models.DateTimeField(default=timezone.now, blank=True) name = models.TextField(null=True, blank=True) def __str__(self): return self.name def friendly_created_date(self): created = self.created return created.strftime('%B %d, %Y, %I:%M %p') class Item(models.Model): text = models.TextField(default='') tags = models.ManyToManyField(Tag, blank=True, null=True) due_date = models.DateTimeField(blank=True, null=True) forms.py from django import forms from todos.models import Item, Tag class ItemForm(forms.ModelForm): class Meta: model = Item fields = ['text', 'tags', 'due_date'] text = … -
Django query filter using large array of ids in postgre db
I have bumped into a pretty weird problem passing a query in django to my postgresql database. When I filter my query using large array of ids, the query is very slow and goes up to 70s... After looking for an answer I saw this post which gives a solution to my problem, simply change the ARRAY [ids] in IN statement by VALUES (id1), (id2), ... I tested the solution with a raw query in pgadmin, the query goes from 70s to 300ms... So my question is: How can I do the same command (i.e. not using an array of ids but a query with VALUES) in Django ? Thanks you :) -
Connecting a Numpy calculation with a Django API
I have 3 matrices stored in cache that are used in a calculation process. Overall, they have 50.000 lines and 500 columns. Every time that I need to perform that calculation, I duplicate those 3 matrices, manipulate them, perform the calculation and delete them from the cache. The calculation is triggered by a web service call and the result of the calculation feeds the web service output. The web service is managed by a Django application, while the matrices and the calculation are managed by a Numpy-based application. My problem is related to performance. Every time that Django gets a web service call, it triggers the Numpy-based application that access the cache to duplicate the matrices. The problem is that accessing the cache and duplicating the matrices is taking 5 seconds. In my view, duplicating the matrices should be virtually instantaneous, so I assume the problem is related to accessing the cache. I used the cache solution because it’s the only way that I found to keep the matrices permanent and not related to user sessions. Generally speaking, I have two options to solve the problem: 1) improving the current solution to make the cache access and matrices duplication an … -
Django ModelForm 'instance' param not working as expected
I am using Django's forms to validate API PATCH requests. In the "view" (which I use in quotes because it isn't really a view directly, it is a restless Resource, but that should be irrelevant here) which handles this patch request, self.data contains a dictionary of changes to some of the fields of the License object. I want to instantiate a ModelForm with the instance of the object to be changed. Clearly, though, I am misunderstanding how this works. See below: def handle_patch(self, pk): license = License.objects.get(id=pk) form = LicenseResourceForm(self.data, instance=license) if not form.is_valid(): print(form.errors) If I pass a few fields as data to the above function, form.errors complains about every other required field of the License model, meaning I'm clearly not understanding how setting an instance on a ModelForm works. I added a few debug prints to Django's ModelForm code itself in the clean() method, and as it begins to do the cleaning process, I can see that self.instance is populated with the instance of License that I expect, which confuses me - the ModelForm object knows the instance, but isn't using it to "fill in the blanks" so to speak. So what am I misunderstanding? I must be … -
django shell not detecting new module
Hello I have a django app name "celery_tasks" with the following directory structure: . ├── apps.py ├── emitter ├── __init__.py ├── kse ├── mongo I have added a new module name kse which contains two files: ├── __init__.py ├── lol.py The __init__.py in the kse module contains from .lol import lol And the lol.py file contains the following class: class lol: @staticmethod def x(): return True def __init__(self): pass The issue is that I cannot access the kse module via django shell: >>> import celery_tasks >>> celery_tasks.kse Traceback (most recent call last): File "<console>", line 1, in <module> AttributeError: module 'celery_tasks' has no attribute 'kse' However the mongo and emmiter modules are accessible: >>> celery_tasks.mongo <module 'celery_tasks.mongo' from '/Users/kheshav/Linux_projects/rockynode.io/App/rockynode/celery_tasks/mongo/__init__.py'> >>> celery_tasks.emitter <module 'celery_tasks.emitter' from '/Users/kheshav/Linux_projects/rockynode.io/App/rockynode/celery_tasks/emitter/__init__.py'> I have created the kse module in the same way i did for the mongo and emitter module but am not being able to access the kse module. Did i missed something? Thank you -
GET request with XHR object, URI component name not found
I'm trying to create a text box which upon having a character entered in it, queries the server. I'm getting the following error and I don't understand why: Traceback (most recent call last): File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/utils/datastructures.py", line 83, in __getitem__ list_ = super(MultiValueDict, self).__getitem__(key) KeyError: 'lift_string' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/workout/workoutcal/views.py", line 71, in get_lifts search_str = request.GET['lift_string'] File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/utils/datastructures.py", line 85, in __getitem__ raise MultiValueDictKeyError(repr(key)) django.utils.datastructures.MultiValueDictKeyError: "'lift_string'" I'm getting it when I enter a character inside of this text box: <input id="lift" name="lift_string" type="text" onkeyup="getLifts()"> This is the associated javascript of the text box: function addURLParam(url, name, value){ url += (url.indexOf("?") == -1 ? "?" : "&"); url += encodeURIComponent(name) + "=" + encodeURIComponent(value); return url; } function getLifts(){ var xhr = createXHR(); xhr.onreadystatechange = function(){ if (xhr.readyState == 4){ if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304){ document.getElementById("xhrPar").innerHTML = xhr.responseText; } else { document.getElementById("xhrPar").innerHTML = "Request was unsuccessful: "+xhr.status; } } }; var url … -
How to make correct paginaton via ajax Django?
let's say I have to sort, it works, everything is displayed, but I can not do pagination, it turns out, I have absolutely all the goods, sorted items, it turns out that there are 200 objects, and they are all displayed, how to make it about 9, that is, 9 objects were displayed, then click on the next country, and the following products were output from the sorted categories !? def sorting_by_ajax(request): return_dict = {} data = request.POST categorys_slug = data.get("category_slug") category_of_relation_sheps = data.get("category_of_relationsheep") if len(data.getlist('categoryes[]')) == 0: categoryes_list = data.get('categoryes') else: categoryes_list = data.getlist('categoryes[]') if len(data.getlist('brands[]')) == 0: brands_list = data.get("brands") else: brands_list = data.getlist('brands[]') discount_list = data.get("discount_list") product_himself_list = Product.objects.filter(refers_to__name_of_category__in=categoryes_list, brand__name_of_brand__in=brands_list) paginator = Paginator(product_himself_list, 9) # Show 25 contacts per page page = request.GET.get('page') try: product_himself = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. product_himself = paginator.page(1) except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. product_himself = paginator.page(paginator.num_pages) return_dict["products"] = list() for product in product_himself_list: new_product = {} new_product["product_id"] = product.id new_product["product_brand"] = product.brand.name_of_brand new_product["product_name"] = product.name_of_product new_product["product_id"] = product.quantity_of_goods if product.discount: new_product["product_price"] = product.price_with_discount else: new_product["product_price"] = product.price_of_product new_product["product_slug"] = product.product_slug new_product["product_description"] = … -
Need advice about a proper way how to make a price range filter (price slider)
Oscar has a such structure of facet configuration: OSCAR_SEARCH_FACETS = { 'fields': { 'rating': { 'name': _('Rating'), 'field': 'rating', 'options': {'sort': 'index'} }, 'vendor': { 'name': _('Vendor'), 'field': 'vendor', }, } 'queries': { 'price_range': { 'name': _('Price range'), 'field': 'price', 'queries': [ (_('0 to 1000'), u'[0 TO 1000]'), (_('1000 to 2000'), u'[1000 TO 2000]'), (_('2000 to 4000'), u'[2000 TO 4000]'), (_('4000+'), u'[4000 TO *]'), ] }, } } queries are 'static' and I want to make it a dynamic dependant on a price of products inside a categories. Based on the OSCAR_SEARCH_FACETS, Oscar using the next code # oscar/apps/search/search_handlers.py class SearchHandler(object):: # some other methods def get_search_context_data(self, context_object_name=None): # all comments are removed. See source link above. munger = self.get_facet_munger() facet_data = munger.facet_data() has_facets = any([data['results'] for data in facet_data.values()]) context = { 'facet_data': facet_data, 'has_facets': has_facets, 'selected_facets': self.request_data.getlist('selected_facets'), 'form': self.search_form, 'paginator': self.paginator, 'page_obj': self.page, } if context_object_name is not None: context[context_object_name] = self.get_paginated_objects() return context generates the next context: {'facet_data': { 'rating': { 'name': 'Рейтинг', 'results': [{'name': '5', 'count': 1, 'show_count': True, 'disabled': False, 'selected': False, 'select_url': '/catalogue/category/hardware/cpu_2/?selected_facets=rating_exact%3A5'}]}, 'vendor': { 'name': 'Vendor', 'results': [ {'name': 'AMD', 'count': 103, 'show_count': True, 'disabled': False, 'selected': False, 'select_url': '/catalogue/category/hardware/cpu_2/?selected_facets=vendor_exact%3AAMD'}, {'name': 'INTEL', 'count': … -
Internal Server Error when docker container is deployed to Elastic Beanstalk
I follow the instructions here: http://glynjackson.org/weblog/tutorial-deploying-django-app-aws-elastic-beanstalk-using-docker/ on how to deploy a very basic django app in docker container to Elastic Beanstalk. Everything went smoothly. When I check the container locally it works perfectly (showing the standart Congratulations on your first Django-powered page. text). It is uploaded to EB correctly. But when I open the page, it reports 'Internal server error'. Why is it so? the content of Dockerrun.aws.json: { "AWSEBDockerrunVersion": "1", "Logging": "/var/eb_log" } the content of Dockerfile (just copied from Glyn's web-page): # Base python 3.4 build, inspired by https://github.com/Pakebo/eb-docker-django-simple # Python 3.4 | Django FROM python:3.4 MAINTAINER Glyn Jackson (me@glynjackson.org) ############################################################################## # Environment variables ############################################################################## # Get noninteractive frontend for Debian to avoid some problems: # debconf: unable to initialize frontend: Dialog ENV DEBIAN_FRONTEND noninteractive ############################################################################## # OS Updates and Python packages ############################################################################## RUN apt-get update \ && apt-get upgrade -y \ && apt-get install -y RUN apt-get install -y apt-utils # Libs required for geospatial libraries on Debian... RUN apt-get -y install binutils libproj-dev gdal-bin ############################################################################## # A Few pip installs not commonly in requirements.txt ############################################################################## RUN apt-get install -y nano wget # build dependencies for postgres and image bindings RUN apt-get install -y python-imaging python-psycopg2 ############################################################################## … -
class based templateview context is not rendering
I have a template view that is supposed to take in a user submitted search. I planning to use the get method to do a query in the get_context_data so that I can show some results on the HTML. Unfortunately, my get_context_data does not work while the get method and dispatch in my templateview works fine. The get_context_data does not run at all when the user submits the search. class PollSearchView(TemplateView): template_name = 'polls/polls_search.html' def get(self, request, **kwargs): self.request.session["search"] = request.GET.get("search") return render(request, 'polls/polls_search.html') def dispatch(self, *args, **kwargs): dispatch = super(PollSearchView, self).dispatch(*args, **kwargs) #exit if no search if self.request.GET.get("search") == None: pass return redirect('/') return dispatch def get_context_data(self, **kwargs): context = super(PollSearchView, self).get_context_data(**kwargs) search = self.request.session.get("search") context["test"] = search return context I have another class that is redirecting to the class above based a user input through a form. class HomeView(TemplateView): template_name = "home.html" def get_context_data(self, *args, **kwargs): context = super(HomeView, self).get_context_data(*args, **kwargs) context["form"] = SearchForm() return context I think the form works completely fine, why the get_context_data does not take in any information baffles me, and I seek alternative ways to render the context based on my results from get. Any guidance on why this does not work and … -
Virtualenv created a folder, but the result its not I wanted
I created a folder via virtualenv command, but the result its not I wanted. [root@localhost opt]# virtualenv my_env New python executable in /opt/my_env/bin/python2.6 Also creating executable in /opt/my_env/bin/python Installing setuptools, pip, wheel...done. My system is CentOS 6.5. Before I created my folder I upgraded my python 2.6 to python 3.6. Than I wanted to create a isolated environment for practice Django. Unfortunately, the folder include a python 2.6 foler, its should be python 3.6, who can tell me what happened? -
Object level permissions not working properly in Django REST Framework
So I want to allow only the owner of a certain object to PATCH it. Here's my custom permission: class IsOwner(permissions.BasePermission): """ Custom permission to only allow owners of an object to edit it. """ def has_object_permission(self, request, view, obj): # Permissions are only allowed to the owner of the snippet. if request.method in permissions.SAFE_METHODS: return True return obj.email == request.user And here's the call from the view: class Profile(APIView): authentication_classes = (authentication.TokenAuthentication,) permission_classes = (IsOwner,permissions.IsAuthenticated, ) def patch(self,request,email): user = get_user_model().objects.get(email=email) self.check_object_permissions(request, user) .... However, even if obj.email and request.user have the same value (I printed them), I get You do not have permission to perform this action -
show distance in km or m of each restaurant
I have implemented the feature of showing nearby restaurant from the given coordinates using postgis and geodjango. But I need to find the distance in km or m based on the distance it is nearby from user or given coordinates. I know question related to distance is asked in SO but this one is a bit different. I am showing the list of restaurant(list view) not a detail of restaurant that I will have specific restaurant location from the id. So i need an idea how should I now show the distance for each restaurant in the restaurant list view. My idea is should I pass the lat and lng(that I am passing from the url) as context and use template filter for calculating the distance by doing from django.contrib.gis.geos import GEOSGeometry pnt = GEOSGeometry('SRID=4326;POINT(40.396764 -3.68042)') pnt2 = GEOSGeometry('SRID=4326;POINT( 48.835797 2.329102 )') pnt.distance(pnt2)*100 Here is the code in detail def nearby_restaurant_finder(request, current_lat, current_long): from django.contrib.gis.geos import Point from django.contrib.gis.measure import D user_location = Point(float(current_long), float(current_lat)) distance_from_point = {'km': 500} restaurants = Restaurant.gis.filter( location__distance_lte=(user_location, D(**distance_from_point))) restaurants = restaurants.distance(user_location).order_by('distance') context = { 'restaurants': restaurants } return render(request, 'restaurant/nearby_restaurant.html', context) url(r'^nearby_restaurant/(?P<current_lat>-?\d*.\d*)/(?P<current_long>-?\d*.\d*)/$', views.nearby_restaurant_finder, name="nearby-restaurant"), {% block page %} {% for restaurant in restaurants %} … -
Testing Form In Django With A User Object
I am working on testing - and I have a little form with a good chunk of logic in the clean method. My test looks like this: class DependentFormTest(TestCase): def test_dependent_form_birthdate_out_of_range(self): form_data = { 'first_name': 'Bill', 'last_name': 'Robusin', 'birth_date': '10/12/1801', 'gender': 'Male', 'relationship': 'dependent', 'street_address_1': '123 Any lane', 'city': 'Billson', 'state': 'WA', 'zip': '50133', } form = DependentForm(data=form_data) self.assertFalse(form.is_valid()) In my clean method there is a bit where I access some information about the current user. The snippet that fails looks like this: user_benefit = Benefit.objects.get(user=self.user) This line is what causes my test to error with the following error: Benefit matching query does not exist This is true, because in the test 'user' is 'None'. How do I set a user in my test so that I can test this forms validity? -
Testing with Django: stuck at test database creation
I was having some trouble running tests for my app and I managed to solved them in this previous post. Now executing python manage.py test does go through without raising any errors, but it gets stuck at database creation: When the test database doesn't exist it does create as I can see in pgAdmin, but it gets stuck in the process with this message: enter code hereCreating test database for alias 'default'... It is stuck here forever, so when I finish the process manually and run test again, it says the database exists and prompts me to either delete it and create anew, or cancel the process. I type 'yes' and the process is stuck again with this other message: Destroying old test database 'default'... With pgAdmin open I can't immediately see any new test_dbname database, but if I close and open it again I can, there test_dbname is, but the test task is just stuck there and doesn't go through... A workaround to this problem is this solution, disabling migrations. This way it no longer gets stuck at those messages and the default test is run. . ---------------------------------------------------------------------- Ran 1 test in 0.002s OK However, this just seems to … -
ImportError for Stripe when running Django development server
I'm having trouble importing the stripe module in Django 1.9.6 on a new configuration. I have previously been able to use the same setup (in a virtualenv with a list of requirements) on multiple servers and on my local development device. On calling python manage.py runserver I get the following: Unhandled exception in thread started by <function wrapper at 0x6a0443689d70> Traceback (most recent call last): File "/var/venv/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/var/venv/local/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/var/venv/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 249, in raise_last_exception six.reraise(*_exception) File "/var/venv/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/var/venv/local/lib/python2.7/site-packages/django/__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/var/venv/local/lib/python2.7/site-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/var/venv/local/lib/python2.7/site-packages/django/apps/config.py", line 123, in create import_module(entry) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) ImportError: No module named stripe Initially I thought this was related to the PYTHONPATH used, however, running /var/venv/bin/python, declaring the explicit path to the Python binary in the virtualenv, results in the same error. However, I can run the Python interpreter through /var/venv/bin/python, and calling import stripe does not result in this error. stripe is declared in my installed_apps config in Django. I've tried reinstalling both the module and the virtualenv, and I have no … -
Changes to django's urls.py not reflected online
I'm running a Django application using NGINX and UWSGI. My URLpatterns used to be this: urlpatterns = [ url(r'^$', views.index), url(r'^binaryQuestionApp/',include('binaryQuestionApp.urls')), url(r'^pointlocations/',include('pointlocations.urls')), url(r'^attributesFromPointsApp/',include('attributesFromPointsApp.urls')), url(r'^admin/', admin.site.urls), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Yet, I wish to change it to this: urlpatterns = [ url(r'^$', views.index), url(r'^collections/',views.collections), ## new line ## url(r'^binaryQuestionApp/',include('binaryQuestionApp.urls')), url(r'^pointlocations/',include('pointlocations.urls')), url(r'^attributesFromPointsApp/',include('attributesFromPointsApp.urls')), url(r'^admin/', admin.site.urls), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Yet, after pushing this to my server (and the .py file does change on the server) I consistently get Django's 404 page: Using the URLconf defined in data_collection_project.urls, Django tried these URL patterns, in this order: ^$ ^binaryQuestionApp/ ^pointlocations/ ^attributesFromPointsApp/ ^admin/ ^media\/(?P<path>.*)$ The current URL, randomurltoget404page, didn't match any of these. If I change something else, for the sake of testing, I can get the change to work. For example, I can make changes to the .html file that url(r'^$', views.index), eventually points to, which is update on my site. How do I get Django to update the URLpatterns? Related questions tell me to restart uwsgi or nginx, which I've tried using sudo service uwsgi restart to no avail. -
Django ORM: Calculation of average result in conditional expression methods
I'd like to annotate a field by using conditional expressions. However, Django ORM doesn't allow to compare Avg('rating') and 5. I could calculate average rating before the query but I don't know whether it's a proper and efficient way. queryset = ( Item.objects.filter( status='Live' ).annotate( group=Case(When(Avg('rating')=5, then=0)) ) ) -
Django webapplication Failed to load the native TensorFlow runtime. in Heroku
I have try to deploy my AI application in Heroku with Tensorflow. Im getting error like Failed to load the native Tensor Flow runtime. thanks in advance. -
Django ORM Multicolumn join
Users of my app are able to block other users so blocked users won't see their blockers anywhere in the app. I have following models class User(models.Model): blocked_users = models.ManyToManyField( 'self', symmetrical=False, through='Block') class Block(models.Model): class Meta: unique_together = ('from_user', 'to_user') from_user = models.ForeignKey('User', related_name='blocked') to_user = models.ForeignKey('User', related_name='blocked_by') So now I'm trying to make Django do the following query that will return users who didn't block currently logged in user. SELECT * FROM user LEFT OUTER JOIN block ON (block.from_user_id = user.id AND block.to_user_id = 1) WHERE block.id is null where 1 is an id of the currently logged in user. -
Django: Load form with dynamic fields
I created a form with multiple dynamic fields (no class attributes) which are added to self.fields in the __init__ function like this: class CustomForm(django.forms.Form): def __init__(dynamic_fields, *args, **kwargs): super(CustomForm, self).__init__(*args, **kwargs) for name, field in dynamic_fields.items(): self.fields[name] = field dynamic_fields = {'val1': IntegerField(), 'val2': FloatField()} CustomForm(dynamic_fields) Now, I don't know how to load the Form after a POST request. Normally, I would do something like: custom_form = CustomForm(request.POST) if custom_form.is_valid(): data = custom_form.cleaned_data ... But as the fields are not known to Form when super is called, I don't know how to load fields manually afterwards. Ideas? -
What does "name" mean in Django-url?
I was wondering, when using the url from (django.conf.urls import url), what does name = 'insert-something' mean? For example, when making a url for registering a new user: url(r'^register', views.register, name='register') What does name='register' mean here? Why is it necessary? Thank you! -
Regex for Django signed token
I have created a signed token using Django in order to create a URL for validating email addresses. I now need to ensure my urlpattern matches the token Django creates. The token is created using the following function: from django.core import signing def create_token(verify_code, partial_token): token = { 'verify_code': verify_code, 'partial_token': partial_token } return signing.dumps(token) And I have the following url + regex: url(r'^email/validation/(?P<signed_token>[^/]+)/$', core_views.email_validation, name='email_validation') Basically, I need to confirm that the regex (?P<signed_token>[^/]+) will pickup all possible tokens created using that function. -
Add modelChoiceField to userCreationForm
I've created a custom user creation form using an extended user model in django. The extended user model is linked to another group model. I've been trying to add a group choicefield to the registration form by using a modelChoiceField but it seems that the modelChoiceField is only available to a ModelForm class and not to a UserCreationForm Is there a way to replicate a modelChoiceField in a userCreationForm? my models class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) usertype = models.CharField( max_length=10, ) employeeID = models.CharField( unique=True, max_length=10, ) group = models.ForeignKey( Group, on_delete = models.CASCADE, default = 1, ) class Group(models.Model): name = models.CharField( unique=True, max_length=50,) forms.py class SignUpForm(UserCreationForm): usertype = forms.ChoiceField( choices=EMPLOYEE_TYPE_CHOICES, label="User Type", ) employeeID = forms.CharField(label="Employee ID") group = forms.ModelChoiceField( choices=Group.objects.all(), label="Group", empty_label = None, ) class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2', 'employeeID', 'usertype', 'group')