Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Apache/mod_wsgi/django/arch linux woes since 64 bit upgrade, despite being able to import all libraries
I've been trying to figure out what's causing this issue for hours but with no luck. Since migrating my arch linux installation to 64 bit I've found my django sites don't work, with error 500. I'm using python2, which is 64 bit: >>> import struct >>> print struct.calcsize("P") * 8 64 And I also have 64 bit mod_wsgi2: https://www.archlinux.org/packages/community/x86_64/mod_wsgi2/ Here's an example log: [Mon Feb 20 21:42:40.312829 2017] [wsgi:error] [pid 19537] [client 146.179.195.99:62898] mod_wsgi (pid=19537): Target WSGI script '/home/james/sites/dse/django.wsgi' cannot be loaded as Python module. [Mon Feb 20 21:42:40.312872 2017] [wsgi:error] [pid 19537] [client 146.179.195.99:62898] mod_wsgi (pid=19537): Exception occurred processing WSGI script '/home/james/sites/dse/django.wsgi'. [Mon Feb 20 21:42:40.312916 2017] [wsgi:error] [pid 19537] [client 146.179.195.99:62898] Traceback (most recent call last): [Mon Feb 20 21:42:40.312953 2017] [wsgi:error] [pid 19537] [client 146.179.195.99:62898] File "/home/james/sites/dse/django.wsgi", line 12, in <module> [Mon Feb 20 21:42:40.312997 2017] [wsgi:error] [pid 19537] [client 146.179.195.99:62898] from django.core.wsgi import get_wsgi_application [Mon Feb 20 21:42:40.313006 2017] [wsgi:error] [pid 19537] [client 146.179.195.99:62898] File "/usr/lib/python2.7/site-packages/django/__init__.py", line 3, in <module> [Mon Feb 20 21:42:40.313056 2017] [wsgi:error] [pid 19537] [client 146.179.195.99:62898] from django.utils.version import get_version [Mon Feb 20 21:42:40.313066 2017] [wsgi:error] [pid 19537] [client 146.179.195.99:62898] File "/usr/lib/python2.7/site-packages/django/utils/version.py", line 3, in <module> [Mon Feb 20 21:42:40.313078 2017] [wsgi:error] … -
How can i sum the content of a django model
I have this model: class Transfer(models.Model): transfer_code = models.CharField(max_length=30, blank=True, null=True) sender_name = models.CharField(max_length=30, blank=True, null=True) amount = models.IntegerField(blank=True, null=True) recipient_name = models.CharField(max_length=30, blank=True, null=True) time_sent = models.DateTimeField(auto_now_add=True, auto_now=False) received = models.BooleanField(default=False) time_received = models.DateTimeField(auto_now_add=False, auto_now=False, null=True) def __unicode__(self): return self.transfer_code This is my view where i want to calculate the total amount in the table: def listtransfersall(request): title = 'ALL TRANSFERS' queryset = Transfer.objects.all() for instance in queryset: total = 0 total += instance.amount print total context = { "title": title, "queryset": queryset, "total": total, } return render(request, "listtransfersall.html",context) This prints the amount in the table individually. How can i get the total and assign it to the total variable? -
What the wrong with this command? 'python manage.py startapp' command is showing following error?
(myApplication) django@django-py:~/Desktop/tryTen/src$ python manage.py startapp profiles Traceback (most recent call last): File "manage.py", line 18, in "Couldn't import Django. Are you sure it's installed and " ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? -
Django Formset not working
I was experimenting with the formsets provided in django forms. Here is the forms.py from django import forms class NewForm(forms.Form): username = forms.CharField(max_length=100, label="Username") email = forms.EmailField(label="email") city = forms.CharField(label="city") Views.py from django.shortcuts import render # Create your views here. from .forms import NewForm from django.forms import formset_factory def formview(request): if request.method == 'POST': form = NewForm(request.POST) if form.is_valid(): username = form.cleaned_data['username'] city = form.cleaned_data['city'] email = form.cleaned_data['email'] print(type(form.cleaned_data)) NewFormSet = formset_factory(NewForm) formset = NewFormSet() for form in formset: print(form) for k,v in form.cleaned_data.items(): print(k,v) else: print("ddd") form = NewForm() formset = 0 return render(request, 'form.html', {'form':form,'formset':formset}) Earlier it was working fine But The thing is when I added this formset code it showed error Template: <html> <head> <title>The Form</title> </head> <body> <form method='POST'>{% csrf_token %} {% for field in form %} {{ field.error }} <br /> {{ field.label }} {{ field }} <br /> {% endfor %} <input type="Submit" value="Submit"> </form> {% for f in formset %} <form method='POST'>{% csrf_token %} {% for field in f %} {{ f.error }}<br /> {{ f.label }} {{ f }} <br /> {% endfor %} </form> {% endfor %} </body> </html> Please help. -
Django - Form Post redirect to previous page, with information
I apologize if this was already answered, I could not figure out from the answers concerning redirect a way to do the following... I am trying to create a Django admin-like interface, where you can chain click a '+' icon next to a foreign key to add it on the fly if it is not already present. In the Admin Site, when you post the form it will return you to the previous page with the foreign key field you were filling out pre-populated with the new foreign key you created. I have followed / modified code that Dan Gentry wrote years back in his blog post titled. "More RelatedFieldWidgetWrapper – My Very Own Popup" My current code looks like this: Forms.py class AssetForm(forms.ModelForm): model = forms.ModelChoiceField(queryset=AssetModel.objects.all(), required=True) def __init__(self, *args, **kwargs): super(AssetForm, self).__init__(*args, **kwargs) self.fields['model'].widget = CustomRelatedFieldWidgetWrapper(self.fields['model'].widget, reverse('inventory:newModel'), True) class Meta: model = Asset fields = ('__all__') widgets = { 'purchaseDate': DateInput(), } labels = { 'serialNumber': 'Serial Number', } ... class AssetModelForm(forms.ModelForm): class Meta: model = AssetModel fields = ('__all__') labels = { 'modelName': "Model Name", 'depreciationPolicy': "Depreciation Policy", } widgets.py class CustomRelatedFieldWidgetWrapper(RelatedFieldWidgetWrapper): """ Based on RelatedFieldWidgetWrapper, this does the same thing outside of the admin interface the … -
Django celerybeat periodic task only runs once
I am trying to schedule a task that runs every 10 minutes using Django 1.9.8, Celery 4.0.2, RabbitMQ 2.1.4, Redis 2.10.5. These are all running within Docker containers in Linux (Fedora 25). I have tried many combinations of things that I found in Celery docs and from this site. The only combination that has worked thus far is below. However, it only runs the periodic task initially when the application starts, but the schedule is ignored thereafter. I have absolutely confirmed that the scheduled task does not run again after the initial time. My (almost-working) setup that only runs one-time: settings.py: INSTALLED_APPS = ( ... 'django_celery_beat', ... ) BROKER_URL = 'amqp://{user}:{password}@{hostname}/{vhost}/'.format( user=os.environ['RABBIT_USER'], password=os.environ['RABBIT_PASS'], hostname=RABBIT_HOSTNAME, vhost=os.environ.get('RABBIT_ENV_VHOST', '') # We don't want to have dead connections stored on rabbitmq, so we have to negotiate using heartbeats BROKER_HEARTBEAT = '?heartbeat=30' if not BROKER_URL.endswith(BROKER_HEARTBEAT): BROKER_URL += BROKER_HEARTBEAT BROKER_POOL_LIMIT = 1 BROKER_CONNECTION_TIMEOUT = 10 # Celery configuration # configure queues, currently we have only one CELERY_DEFAULT_QUEUE = 'default' CELERY_QUEUES = ( Queue('default', Exchange('default'), routing_key='default'), ) # Sensible settings for celery CELERY_ALWAYS_EAGER = False CELERY_ACKS_LATE = True CELERY_TASK_PUBLISH_RETRY = True CELERY_DISABLE_RATE_LIMITS = False # By default we will ignore result # If you want to see … -
Strange performance behavior on postgis PointField query
PostgreSQL= 9.6.1 POSTGIS="2.3.0 r15146" GEOS="3.5.0-CAPI-1.9.0 r4084" PROJ="Rel. 4.9.2, 08 September 2015" GDAL="GDAL 2.1.1, released 2 016/07/07" LIBXML="2.9.1" LIBJSON="0.12" RASTER My User class class User(AbstractUser, TimeStampedModel): """Custom user model. Attributes: avatar (file): user's avatar, cropped to fill 300x300 px location (point): latest known GEO coordinates of the user location_updated (datetime): latest time user updated coordinates notifications (dict): settings for notifications to user is_appuser (bool): if True user can access to apps """ AVATAR_IMAGE_SIZE = (300, 300) avatar = imagekitmodels.ProcessedImageField( upload_to=upload_user_media_to, processors=[ResizeToFill(*AVATAR_IMAGE_SIZE)], format='PNG', options={'quality': 100}, editable=True, null=True, blank=True ) location = gis_models.PointField(default=Point(x=0, y=0, srid=4326), blank=True, srid=4326) location_updated = models.DateTimeField(null=True, blank=True, editable=False) notifications = HStoreField(null=True) is_appuser = models.BooleanField(default=True) # so authentication happens by email instead of username # and username becomes sort of nick USERNAME_FIELD = 'email' # Make sure to exclude email from required fields if authentication # is done by email REQUIRED_FIELDS = ['username'] def __str__(self): return self.username class Meta: verbose_name = 'User' verbose_name_plural = 'Users' def get_conferences(self): """Get confrences where the user is attendee. Returns: QuerySet of conferences. """ return Conference.objects.filter(attendees=self) Now if I query the record with all fields, the performance of the query is 70ms, as seen from screenshot 1. If I remove 'location' field from the query … -
Run Subprocess on Server Between Page Loads on Django
I'm very new to python and Django and I'm trying to figure out the correct way to do something within Django. I have a Django app half completed, but I'm not sure how to run the subprocess in between. I have a python script that takes 3 variables and inserts them into a subprocess that runs a single command on OpenSSL. This is a simplified version of this python script: issuer = "path/to/file" serial = "hex number goes here" URL = "http URL here" arequest = subprocess.check_output "openssl", "ocsp", "-nonce", "-noverify", "-issuer", issuer, "-serial", serial, "-url", URL]) print(arequest) This script that I have works. What I'm aiming to do is to have subprocess.check_output run in Django between a page load, such that: Page 1 accepts field inputs for the variables and the user clicks submit. The variable field data is input into the subprocess.check_output command and this is run on the server to give arequest. Page 2 displays the results of arequest in a text field. I also don't want anything stored within the database other than information outside the scope of this question. I know that in order to do this, I will need to get information using either … -
Cannot upload profile picture in django model
I want the user to upload the profile picture on the profile page but it is not storing it in the media/documents folder, and yes, I have put enctype="multipart/form-data" in the html form and the method is post. I'm new to django so please provide a simple solution models.py class User(models.Model): first_name=models.CharField(max_length=20) last_name=models.CharField(max_length=20) username=models.CharField(max_length=25, primary_key=True) password=models.CharField(max_length=15) email_id=models.CharField(max_length=30, default='NULL') profile_pic=models.ImageField(upload_to='profilepics/%Y/%m/%d/',height_field=200,width_field=200,default='') forms.py class ProfilePicForm(forms.ModelForm): class Meta: model=User fields=['profile_pic'] views.py def upload(request): if request.method == 'POST': try: pic=ProfilePicForm(request.POST,request.FILES) m=User.objects.get(pk=username) m.profile_pic=pic.cleaned_data['image'] m.save() except: pass -
ProgrammingError while opening admin table
I am using django with postgres database. When loading the admin,clicking on Course Table, I get a classic error: ProgrammingError at /admin/user_profile/course/ relation "user_profile_course" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "user_profile_course" I tried makemigrations, and migrate it again but no success. Would you please help me how to handle it? My models.py looks like: class Course(models.Model): name=models.CharField(max_length=30) number_of_sessions=models.IntegerField() student=models.ManyToManyField(User, through='Registration') -
Django Creating A Team Function
I want to design a simple app using Django. The design is as follows: Each user has their own unique ID in the database called id which exists in the auth_user table already equipped with Django. Then I have a Team_ID which is another unique id that represents a team in table called team_profile. In this table I have the following columns: Member1, Member2, Member3. Currently, a user can create a team and this will set Member1 to the id if the creator. Each user also has a profile page and in this profile page their is an invite button. This is where I am stuck. I am trying to write the invite function but I have absolutely no idea where to start. In the ideal world, I would like a notification to be sent to the invitee and the invitee can accept or decline the invitation. If the member accepted the invitation then Member2 will have this person's id. I am currently reading up on a lot of stuff but in the meantime if anyone of you guys have any suggestions that would be great. Thanks -
Django Models Decimal quantize result has too many digits for current context
Until today i got my models like that: class Ambiente1m(models.Model): Zona = models.CharField(max_length=10,default=0) Timestamp = models.DateTimeField(default=datetime.datetime.now) Temperatura1 = models.IntegerField() Humedad1 = models.IntegerField() But i tried to get Temperatura and Humedad as a Decimal (4,2) and adding 2 more columns to it: class Ambiente1m(models.Model): Zona = models.CharField(max_length=10,default=0) Timestamp = models.DateTimeField(default=datetime.datetime.now) Temperatura1 = models.DecimalField(max_digits=4, decimal_places=2) Humedad1 = models.DecimalField(max_digits=4, decimal_places=2) Temperatura2 = models.DecimalField(max_digits=4, decimal_places=2) Humedad2 = models.DecimalField(max_digits=4, decimal_places=2) Adding default values for Humedad -1 and 99.99 for Temperatura. Then i used the python manage.py makemigrations, and migrate. I get the following trace: python manage.py migrate Operations to perform: Apply all migrations: admin, contenttypes, sessions, auth, SmartFICApp Running migrations: Applying SmartFICApp.0017_auto_20170220_1830...Traceback (most recent call las t): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.p y", line 353, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.p y", line 345, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 348, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 399, in execute output = self.handle(*args, **options) File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/m igrate.py", line 200, in handle executor.migrate(targets, plan, fake=fake, fake_initial=fake_initial) File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/executor.py" , line 92, in migrate self._migrate_all_forwards(plan, full_plan, fake=fake, fake_initial=fake_ini tial) File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/executor.py" , line 121, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_ initial) File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/executor.py" , line 198, in apply_migration state = migration.apply(state, … -
How to Update Existing Conda Environment with .yml file
This was asked here and never answered so I'll give it a shot. How do you update an existing conda env with another .yml file. I need the .yml format because my conda environment has conda-forge, conda, and pip packages. I have a base.yml file that looks like this: base.yml (shortened version) name: myenv channels: - conda-forge dependencies: - django=1.10.5 - pip: - django-crispy-forms==1.6.1 I created this environment with conda env create -f base.yml Now I need to add some more packages. Another issue is that with Django projects, for example, multiple requirements files are used (local, production, etc.). I've tried creating a local.yml file that imports base.yml like this: local.yml (shortened version) channels: dependencies: - pip: - boto3==1.4.4 imports: - requirements/base.yml conda install -f local.yml does not work. Anyone familiar with this issue? -
How to generate a responsive chart with django-nvd3
I am using django-nvd3 to generate graphs for my django website. More specifically I'm trying to draw a multiBarHorizontalChart and the number of charts per page varies. Also, I'm drawing the charts inside a bootstrap 3 container/div. Looking at some examples in the documentation I realized that you can customize your chart by adding some keywords to your extra dictionary. The list of possible keywords can be found in http://python-nvd3.readthedocs.io/en/latest/classes-doc/NVD3Chart.html but there is no explanation regarding what each keyword actually does (some are quite self-explanatory others are not). There is a keyword named resize - whose default value is False - which I thought would make the charts responsive if set to True. Indeed if I set resize to True I can see a call to nv.utils.windowResize(chart.update); when I inspect the source code of my web page but the charts are still unresponsive. Does anyone now how to make this work? -
How to combine multiple heterogenous model forms into one form in Django
I'm very confused. I have several models, say A,B,and C which I'd like to combine into a single form. Right now in my template I have one html form and within it I include modelforms for A, B, and C. This works but it's ugly when I submit...I'd like to get the models to save automatically the way a single modelform does via subclassing CreateView. It doesn't seem like modelformsets help here. Is this possible in Django??? Thanks -
Accessing wagtail form submission data programmatically
Traditionally, I accept user form submissions (ie. contact us) with a standard Django ModelForm. I have a celery beat process that picks up entries that should be processed further (email notifications, etc). When it succeeds, the task will set some bookkeeping attributes so I know to ignore them in the future. With Wagtail, it's not immediately obvious to me if it's actually possible to pick through form submissions and post-process them. By default, they are all the AbstractFormSubmission type, which essentially serializes the form data into a single json blob. If I have multiple forms, is it possible to iterate over submissions of a specific type and get their data? Each form instance has a get_submission_class() method, but this just returns the parent FormSubmission and doesn't provide a mechanism to get submissions of that form type. I would like a get_submissions() type of method that allows me to get that form data from the concrete form object (the one I defined in the models.py). -
Django-backend with Aurelia-frontend. Defining models in each of them violating DRY-principle?
In my recent project I'd like to try out an Aurelia-frontend with a Django-backend. I did some projects with Django and want to use Django REST API for my backend. I'm new to Aurelia and read the documentation several times. Now I'm wondering if it would be good practice to explicitly define models (eg. User with nickname, email, mobile, address etc.) in the Aurelia-frontend because in Django I already defined my models in the models.py for the database. Since I fetch/ the data via api to my Django application I could maybe omit it. In the Aurelia "getting started"-section of the documentation they defined the ToDo-model in a separate file, but the data wasn't attached to a database. Doing this seems to me like doing it twice (in back- and frontend) and violates the DRY principle. What would you think is good practice? Thanks for your recommendations! -
User Profile has no user
I am using django-registration with a custom user model and have defined a UserProfile model as well. I have defined a custom user model so that I can usee the email as the username. When I submit the registration form I get the error: Exception Type: RelatedObjectDoesNotExist Exception Value: CreativeUserProfile has no user. Here's the code: class User (AbstractUser): ''' Custom User Model ''' email = models.EmailField(verbose_name = "email address", max_length = 255, unique = True) joined = models.DateTimeField(auto_now_add = True) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) USERNAME_FIELD = "email" REQUIRED_FIELDS = [] objects = CustomUserManager() class CreativeUserProfile (models.Model): ''' Registered Creative who can post previous work and search and apply for jobs ''' user = models.OneToOneField(User, on_delete = models.CASCADE) USERNAME_FIELD = "email" def set_password(self, raw_password): # whatever logic you need to set the password for your user or maybe self.user.set_password(raw_password) I really can't understand what I'm doing wrong. Any help would be appreciated. Thanks -
How trigger automatically a download using django and angularjs?
For each request the url is different: Django side: def download_file_from_location(request): url = get_file_url() response = HttpResponseRedirect(url) return response JS side: $scope.downloadFile = function () { $http({ url: '/api/download_file_from_location/', method: "POST" }) } What is missing here in order to download start automatically? -
Error installing Pillow (Django)
I'm having trouble getting Pillow to install. Here's the full traceback: Collecting Pillow Using cached Pillow-4.0.0-cp27-cp27m-macosx_10_6_intel.macosx_10_9_intel.macosx_10_9_x86_64.macosx_10_10_intel.macosx_10_10_x86_64.whl Collecting olefile (from Pillow) Using cached olefile-0.44.zip Installing collected packages: olefile, Pillow Running setup.py install for olefile ... error Complete output from command /usr/bin/python -u -c "import setuptools, tokenize;__file__='/private/var/folders/bt/_3d4816x12d95tzvcp_0302w0000gn/T/pip-build-UyBMYN/olefile/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /var/folders/bt/_3d4816x12d95tzvcp_0302w0000gn/T/pip-QHsEXV-record/install-record.txt --single-version-externally-managed --compile: running install running build running build_py creating build creating build/lib copying OleFileIO_PL.py -> build/lib creating build/lib/olefile copying olefile/__init__.py -> build/lib/olefile copying olefile/olefile.py -> build/lib/olefile copying olefile/README.rst -> build/lib/olefile copying olefile/README.html -> build/lib/olefile copying olefile/LICENSE.txt -> build/lib/olefile copying olefile/CONTRIBUTORS.txt -> build/lib/olefile running install_lib creating /Library/Python/2.7/site-packages/olefile error: could not create '/Library/Python/2.7/site-packages/olefile': Permission denied ---------------------------------------- Command "/usr/bin/python -u -c "import setuptools, tokenize;__file__='/private/var/folders/bt/_3d4816x12d95tzvcp_0302w0000gn/T/pip-build-UyBMYN/olefile/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /var/folders/bt/_3d4816x12d95tzvcp_0302w0000gn/T/pip-QHsEXV-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /private/var/folders/bt/_3d4816x12d95tzvcp_0302w0000gn/T/pip-build-UyBMYN/olefile/ The error seems to be 'Permission denied' when attempting to create the folder; though I cannot understand why... My machine is running Mac OSX, and I'm using Terminal to run the commands for this Django project. -
How to display InLine objects in Django Admin Interface
This is my current Admin Interface: A user inputs text through a form & model called "UserText". I have written a function using NLP to extract only the questions from the UserText. I would like each of these individual questions to be displayed in each "User question" section of the Admin Interface. As of now, I cannot get that to work. Here is my current code: Models.py class UserText(models.Model): user_input = models.TextField() class Question(models.Model): user_text = models.ForeignKey( UserText, on_delete=models.CASCADE, blank=True, null=True, ) user_questions = models.CharField(max_length=2000) Views.py def user_text_view(request): form = forms.UserTextForm() if request.method == 'POST': form = forms.UserTextForm(request.POST) if form.is_valid(): UserText = models.UserText Question = models.Question user_input = request.POST.get('user_input', '') user_input_obj = UserText(user_input = user_input) user_questions_obj = Question(user_text = user_input_obj, user_questions = Question_Init(user_input_obj)) user_input_obj.save() user_questions_obj.save() print("Thanks for the questions!") else: form = forms.UserTextForm() return render(request, 'text_input_form.html', {'form': form}) Admin.py class QuestionInLine(admin.StackedInline): model = Question display = ('user_questions_obj') @admin.register(UserText) class UserTextAdmin(admin.ModelAdmin): model = UserText display = ('user_input') inlines = [ QuestionInLine, ] And finally my function: def Question_Init(user_input_obj): Beginning_Question_Prompts = ("Who","Whom","What","Where","When","Why","Which", "Whose","How","Was","Were","Did","Do","Does","Is") Ending_Question_Prompts = ("?",":","...") questions = [] text1 = user_input_obj.user_input textList = sent_tokenize(text1) for sentence in textList: if sentence.startswith(Beginning_Question_Prompts): questions.append(sentence) if sentence.endswith(Ending_Question_Prompts): questions.append(sentence) return questions I know this is a … -
Printing UserProfile variables Django
I am using UserProfile (https://docs.djangoproject.com/en/1.9/topics/auth/customizing/#extending-the-existing-user-model) and am trying to print one of the variables in my templates. I found this post from 5 years ago which is seeming to ask this same question, but the solution has not worked for me: Django - Userprofile field in my template Here is my models.py: class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) department = models.CharField(max_length=100) phone = models.CharField(max_length=100) And my admin.py: from .models import UserProfile class UserProfileInline(admin.StackedInline): model = UserProfile can_delete = False verbose_name_plural = 'userprofile' class UserAdmin(BaseUserAdmin): inlines = (UserProfileInline, ) admin.site.unregister(User) admin.site.register(User, UserAdmin) And here is what I'm trying to print: {{ request.user.get_profile.phone }} The field is visible in my admin panel and has a value, but nothing is printed when I try that. Any thoughts on where I went wrong? Thanks! -
Django multiple html paremeters
I'm trying to catch two parameters but I don't know how to send them via html. This is the urls.py: app_name = 'series' urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^(?P<serie_id>[0-9]+)/$', views.season, name='season'), url(r'^(?P<serie_id>[0-9]+)/(?P<season_id>[0-9]+)/$', views.chapter, name='chapter'), url(r'^login/$', views.login, name='login'), ] This is the html: <ul> {% for season in season_list %} <li><a href="{% url 'series:chapter' season.id %}">{{ season.season_name }}</a></li> {% endfor %} </ul> This is the view: def chapter (request, serie_id, season_id): season = Season.objects.get(pk=season_id) chapter_list = season.chapter_set.all() return render(request, 'series/serie.html', {'chapter_list': chapter_list}) I'm having this error: Reverse for 'chapter' with arguments '(1,)' and keyword arguments '{}' not found. 1 pattern(s) tried: [u'series/(?P<serie_id>[0-9]+)/(?P<season_id>[0-9]+)/$'] How I can solve it? -
Make datetime field only for current and future time
I am creating a form for this model: class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): return self.question_text def was_published_recently(self): now = timezone.now() return now - datetime.timedelta(days=1) <= self.pub_date <= now The user should can select between the current time or some time in the future. If time in future is chosen, a normal time selection field should be shown. How could this be realized? -
How to run django + angular 2 + ionic2
I run django from python manage.py runserver I run angular 2 + ionic 2 from ionic serve I use proxy so ionic listen to "proxyUrl": "http://127.0.0.1:8000/api" in order to "work". My question is how can i build it or try it on a mobile phone ? if i use ionic view only ionic part is uploaded so for example i cannot login (because django part is not uploaded..) Any idea ?