Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Creating Polls app form Django
Trying to create a form for my polls app.But I am not able to include choices as well for it.I can only add polls right now through admin. (Its the official django polls app tutorial and i am trying to extend it further by adding a form) Models.py class Question(models.Model): question_text = models.CharField(max_length=200) publish_date = models.DateTimeField('date published',null=True,blank=True) def __str__(self): return self.question_text def get_absolute_url(self): return reverse('polls:index') class Choice(models.Model): question_text = models.ForeignKey(Question,on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text forms.py class QuestionForm(forms.ModelForm): question_text = forms.CharField(required=True) publish_date = forms.CharField(required=False) choice_text = forms.CharField(required=True) class Meta(): model = Question fields = ('question_text','choice_text') View To create Poll class CreatePoll(CreateView): redirect_field_name = 'polls/index.html' template_name = 'polls/poll_form.html' form_class = QuestionForm model = Question This is My Form View But the choice entered doesnt get saved.Saw in the admin view too -
python manage.py migrate make me frustated
Hi guys I got a problem when I used command of django-admin startproject mysite, it couldn't work but python -m django startproject mysite is ok. there has been another problems in my CneOs6.8, when inputed python manage.py migrate, which would : [root@localhost mysite]# python manage.py migrate Traceback (most recent call last): File "/usr/local/python3.5.0/lib/python3.5/site- packages/django/db/backends/sqlite3/base.py", line 31, in from pysqlite2 import dbapi2 as Database ImportError: No module named 'pysqlite2' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/python3.5.0/lib/python3.5/site- packages/django/db/backends/sqlite3/base.py", line 33, in from sqlite3 import dbapi2 as Database File "/usr/local/python3.5.0/lib/python3.5/sqlite3/init.py", line 23, in from sqlite3.dbapi2 import * File "/usr/local/python3.5.0/lib/python3.5/sqlite3/dbapi2.py", line 27, in from _sqlite3 import * ImportError: No module named '_sqlite3' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 22, in execute_from_command_line(sys.argv) File "/usr/local/python3.5.0/lib/python3.5/site- packages/django/core/management/init.py", line 364, in execute_from_command_line utility.execute() File "/usr/local/python3.5.0/lib/python3.5/site- packages/django/core/management/init.py", line 338, in execute django.setup () File "/usr/local/python3.5.0/lib/python3.5/site-packages/django/init.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/python3.5.0/lib/python3.5/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models() File "/usr/local/python3.5.0/lib/python3.5/site-packages/django/apps/config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "/usr/local/python3.5.0/lib/python3.5/importlib/init.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 986, in _gcd_import File " importlib._bootstrap>", line 969, in _find_and_load … -
Why does my aging Django 1.3.1 site say ''TemplateDoesNotExist at /admin/" after migration to a new server?
I have a Django v1.3.1 site on a now-compromised server (used to be on Python v2.7.3). I've been able to reconstruct the bulk of the content via a cache of the old admin site but after re-installing Python and Django on a new server instance (Python v2.7.12), I'm running across the following error: TemplateDoesNotExist at /admin/ admin/login.html Request Method: GET Django Version: 1.3.1 Exception Type: TemplateDoesNotExist Exception Value: admin/login.html Exception Location: /usr/local/lib/python2.7/dist-packages/django/template/loader.py in find_template, line 138 Python Executable: /usr/bin/python Python Version: 2.7.12 Python Path: ['/var/django/mysite', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages'] Server time: Sun, 15 Oct 2017 02:31:49 +0100 The relevant info from trying to load the templates: Django tried loading these templates, in this order: Using loader django.template.loaders.filesystem.Loader: /var/django/mysite/templates/admin/login.html (File does not exist) Using loader django.template.loaders.app_directories.Loader: Looking on the new machine for /admin/index.html I get: locate admin/login.html /usr/local/django/contrib/admin/templates/admin/login.html On the old machine I get: locate admin/login.html /root/build/Django/build/lib.linux-x86_64-2.7/django/contrib/admin/templates/admin/login.html /root/build/Django/django/contrib/admin/templates/admin/login.html /root/build/Django/tests/templates/custom_admin/login.html /usr/local/lib/python2.7/dist-packages/django/contrib/admin/templates/admin/login.html What have I missed in getting this up and running / how do I resolve this before I start upgrading to the latest Django version? -
How to query in django one to many
What I want to do? I have an app have three models:Series,Section and Episode,every one have a one-many query(by ForeignKey). just like this series-> many Section,section-> many Episode Now I will show a section with episodes information in series page, but it make more query. now code views.py series = Series.objects.get(id=series_id) section = Section.objects.filter(series=series) list.html {% for item in sections %} ... {% for episode in item.episode_set.all %} ... {% endfor %} ... {%endfor%} models.py class Section(models.Model): series = models.ForeignKey(Series) .... class Episode(models.Model): section = models.ForeignKey(Section) What I want to get ? an example code tell me how to query in views.py and use just little query. you can guess, in my code, if here are many section and many episode, it will have many query. Some idea. I use Laravel Before, In Laravel , it has a hasMany Function, I can use it to get other models items(Define by belongsTo). Is Django has same function? -
Django view does not redirect to details page
I've created a form and view in Django. I can see the add new post form when I go to http://localhost:8000/post/new/ but after I complete all required fields and click submit the page just refreshes itself and I am not redirected to the post details page. Here's my views.py def post_new(request): if request.method == "POST": form = PostForm(request.POST, request.FILES) if form.is_valid(): post = form.save(commit=False) post.createdAt = timezone.now() post.writer = request.user post.save() return redirect('posts:post_detail', pk=post.pk) else: form = PostForm() context = {'form':form} return render(request,"posts/post_new.html",context) Here's my urls.py: urlpatterns = [ url(r'^$', views.post_list, name="post_list"), url(r'^posts/(?P<post_title_slug>[\w\-]+)/$', views.post_detail, name='post_detail'), url(r'^post/new/$', views.post_new, name='post_new'), ] Here's my html: <div class="col"> <form method='POST' class='post_form' enctype='multipart/form-data'> {% csrf_token %} {{ form.non_field_errors }} <div class="form-row"> <div class="form-group col-md-6"> <label for="{{ form.title.id_for_label }}" class="col-form-label">Title</label> <input type="text" class="form-control" id="{{ form.title.id_for_label }}" name= "{{ form.title.html_name }}" placeholder="Enter post title"> {{ form.title.errors }} </div> </div> <div class="form-group"> <label for="{{ form.comment.id_for_label }}">Description here:</label> <textarea class="form-control" rows="5" id="{{ form.comment.id_for_label }}" name="{{ form.comment.html_name }}" aria-describedby="descriptionHelpBlock"></textarea> <small id="descriptionHelpBlock" class="form-text text-muted"> Describe your post in this text box. </small> {{ form.comment.errors }} </div> <div class="form-group"> <label for="{{ form.image.id_for_label }}">Upload picture here</label> <input type="file" id="{{ form.image.id_for_label }}" name="{{ form.image.html_name }}" class="form-control-file"> {{ form.image.errors }} </div> <br> <button type="submit" class="btn … -
503 error with apache domain when faking domain
I'm attempting to fake domains, on windows, for testing a django application locally that would be spread across domains for the different apps within it. I'm using XAMPP and have resolved loading the mod_wsgi module and set my hosts file to include localhost, jobs, and quotes My apache httpd.conf file looks like this: Listen Listen 80 ServerName ServerName localhost:8000 Virtual hosts NameVirtualHost * <VirtualHost *:80> ServerName jobs ServerAlias jobs.io *.jobs.io DocumentRoot "C:\Users\username\Desktop\VirtualEnviornment\EnvName\Name\" WSGIScriptAlias / "C:\Users\username\Desktop\VirtualEnviornment\EnvName\Name\wsgi.py" <Directory "C:/xampp/apache"> Order deny,allow Allow from all </Directory> </VirtualHost> Shouldn't this be serving my application when I go to jobs.io or quotes.io in my browser? All I get is: Service Unavailable The server is temporarily unable to service your request due to maintenance downtime or capacity problems. Please try again later. Apache Server at jobs.io Port 80 -
Why does Django AssertFormError throw a TypeError: argument of type 'property' is not iterable?
I'd like some help or advice on how to test for errors in one of my Django forms. It's responsible for ensuring the user enters a valid session ID which is used as a authentication token for a 3rd party API. Valid IDs are 32 characters long and alphanumerical. I've chosen an approach that validates the field, rather than the model. When I manually test this using the development server it works as expected. I.E. if the user pastes a string of the wrong length or with the special characters, the field's validate method creates errors which are then displayed via a for loop around the form errors in the html template. I don't understand the following error. I've temporarily modified testcases.py to prove that the errors are being passed to it - so why is context[form].errors a 'property' and how did it get there? I'm using Django 1.10 and Python 3.5.1 ====================================================================== ERROR: test_index_sessid_short_strings (poe.tests.TestBannerButtons) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/adam.green/Documents/workspace/poe-client/poetools_project/poe/tests.py", line 105, in test_index_sessid_short_strings self.assertFormError(response, 'form', "new_sessid" , 'The Session ID needs to be exactly 32 characters long') File "/Users/adam.green/.virtualenvs/poe-tools/lib/python3.5/site-packages/django/test/testcases.py", line 421, in assertFormError if field in context[form].errors: TypeError: argument of type 'property' is not iterable … -
Mock keeps calling real function
I'm trying to mock a function. When I try to mock the function core.use_cases.add_owner_to_place the mock doesn't work. It keeps printing "Ouch". I've tried to test mocked_add_owner_to_place.called and it returns False. Does anyone know why it keeps using the real function even if I mock it? views.py: from core.use_cases import add_owner_to_place class CreatePlace(LoginRequiredMixin, FormView): template_name = 'place/create_place.html' form_class = PlaceForm success_url = reverse_lazy('place_list') def form_valid(self, form): place = form.save() add_owner_to_place(place, self.request.user) return super(CreatePlace, self).form_valid(form) tests.py: from unittest.mock import patch, Mock @patch('core.use_cases.add_owner_to_place') @patch('core.forms.PlaceForm.is_valid') @patch('core.forms.PlaceForm.save') def test_save_should_be_called(self, mocked_save, mocked_is_valid, mocked_add_owner_to_place): self.client.post(reverse('place_create'), data={}) self.assertTrue(mocked_save.called) uses_cases.py: def add_owner_to_place(place, user): print('Ouch') -
Django: Returning a template with POST parameters
I have a table with multiple rows, each of which has an 'edit' button. On clicking this button, the user should redirect to a form with his details already prefilled. Now, I have defined data attributes inside the 'edit' button's definition: <a href='#' class="edit-user" data-email="abc@gmail.com">edit</a> Using JQuery, I'm deriving the value of the 'email' data attribute and passing it in a POST request to /add-edit-user, which is also mapped to the page which has my form: $( ".edit-user" ).click(function() { var url = base_url + '/add-edit-user/'; var data = { 'email': $(this).data('email'), 'csrfmiddlewaretoken': csrftoken, }; // $.post(url, data); $.post(url, data).done(function(result) { console.log(result); }).fail(function(error) { console.log(error); }); }); The /add-edit-user URL maps to the following view where I'm trying to define my form object and pass on as a context variable to my template file: def add_edit_users(request): form = AddUpdateForm(request.POST or None) data = {'form': form} return render(request, 'add_edit_users.html', data) Now, my assumption was that if the user clicks on the 'edit' button, I'd set the 'email' parameter in a data attribute and pass it on in my POST request to /add-edit-user URL, after which I'll render my form template with the form object as a context variable which will display … -
How to delete arguments from url
I need to generate keys by clicking button and to show generated ones. Here my view: @user_passes_test(lambda u: u.is_superuser) def get_key(request): if(request.GET.get('create_new_key')): for_whom = request.GET.get('for_whom') create_key(for_whom) created_keys = RegistrationKey.objects.all() return render(request, 'registration/get_key.html', { 'created_keys':created_keys, }) And template: <!DOCTYPE html> <html> {% include "core/header.html" %} <body> <form action="#" method="get"> <input type="text" name="for_whom"/> <input type="submit" class="btn" value="Create" name="create_new_key"> </form> <ul> {% for created_key in created_keys %} <p>{{created_key.key}}</p> <p>{{created_key.for_whom}}</p> {% endfor %} </ul> </body> {% include "core/footer.html" %} </html> Now when I'm clicking the button on page http://127.0.0.1:8000/get_registration_key/ the key is generating but now I'm at http://127.0.0.1:8000/get_registration_key/?for_whom=&create_new_key=Create#, so refreshing this page would generate more keys. I really need to cut this arguments from url but don't understand how. -
ng-show not updating with $timeout function
I'm trying to write my own photo slider so that the image and text I have on my Django homepage will fade from one to the next (and then repeat). I created a timeout function to loop a $scope.current_slide variable from 1-3, and back to 1 at a set interval. I'm using ng-show on each so that when the $scope.current_slide variable is equal to the number of slide, each picture will appear. The problem I'm having: The images aren't cycling through when I use the timeout function. However! I know in theory my code should work because when I make a button, and use ng-click to allow the button to increment a an angular 'click' variable (1, 2, 3, etc.) the correct pictures show up. The pictures just don't scroll correctly with the timeout function. I added $scope.$apply() thinking this would fix it, but nothing changed. I have the JS file within my home.html page so that it can dynamically pull the total number of slides from Django. home.html <script> var myApp = angular.module('myApp', ['ngRoute', 'ui.bootstrap', 'ngAnimate']); myApp.controller('myController', ['$scope', '$timeout', function($scope, $timeout) { $scope.timeInMs = 0; console.log("We are here in CTRL Controller"); $scope.current_slide = 1; // FUNCTION EXECUTES EVERY FEW … -
django different domain url routing using {% url %} and app urls
How would I setup django url routing to reroute to a specific domain for each app's urls? Meaning: Let's say I have an app "Jobs" and I want to route to "jobs/list" to view a lsit of all jobs which is on domain: "(name)jobs.io" whereas my main app is on (name).io. These links are in the navbar. I've ported django-multiple-domains to Django 1.11 and have the setting, used by the middleware, setup to use each apps urls based upon the domain but this doesn't seem to take care of using the {% url %} tag. -
django rest 400 responce when putting date field
I am putting a datetime value to my drf backend. This is my code: models.py class MyModel(models.Model): .... date = models.DateField(blank=true, null=true) ..... serializers.py class MyModelSerializer(ModelSerializer): class Meta: model = MyModel fields = '__all__' views.py class UpdateNRetrieve(RetrieveUpdateAPIView): queryset = MyModel.objects.all() serializer_class = MyModelSerializer lookup_field = 'pk' On my settings.py I have this: REST_FRAMEWORK = [ ..... 'DATE_FORMAT': '%d/%m/%Y', 'DATE_INPUT_FORMATS': '%d/%m/%Y', ..... ] And also this: LANGUAGE_CODE = 'it-IT' TIME_ZONE = 'Europe/Rome' USE_I18N = True USE_L10N = True USE_TZ = True When i make a PUT request from my front-end I am getting a 400 error (bad request) whit this value: date:"04/12/1984" I always get this response: Date has wrong format. Use one of these formats instead: %, d, /, %, m, /, %, Y." I can't realize where is my error! -
Django how to get record id from ModelForm
I've been banging my head on this for weeks but I am determined to get ModelForm to work! When you process a POST with data received from a ModelForm, I understand that you need to get the original record from the database and then create a new form using that original record as the 'instance'. This is documented in the Django docs as follows: >>> from myapp.models import Article >>> from myapp.forms import ArticleForm # Create a form instance from POST data. >>> f = ArticleForm(request.POST) # Save a new Article object from the form's data. >>> new_article = f.save() # Create a form to edit an existing Article, but use # POST data to populate the form. >>> a = Article.objects.get(pk=1) >>> f = ArticleForm(request.POST, instance=a) >>> f.save() In this example they know that the pk of the record they are looking for is 1. BUT, how do you know the pk if you're reading data from request.POST, assuming that the POST is based on data you previously wrote to the screen? ModelForm doesn't store the pk. So, from where do you pick this up? Without it, how do you know which record to pull out of the DB … -
formatting data from a DateField using ModelForm - Django 1.11
I'm creating an edit view that uses ModelForm, and I'd like the form's date field to appear in the following format: "%d/%m/%Y". However, regardless of what I do, when the edit page is called, the date is displayed in the format "%m-%d-%Y". models.py class Pessoa(models.Model): nome = models.CharField(max_length=255, null=False) sobrenome = models.CharField(max_length=255, null=False) cpf = models.CharField(max_length=14) data_nascimento = models.DateField() rg = models.CharField(max_length=15, null=False) responsavel = models.ForeignKey('Pessoa', related_name='dependentes', blank=True, null=True) foto = models.ImageField(upload_to='pessoas') usuario_alteracao = models.CharField(max_length=255, blank=True, null=True) data_criacao = models.DateTimeField(auto_now_add=True) data_alteracao = models.DateTimeField(auto_now=True) settings.py (DATETIME_INPUT_FORMATS and DATE_INPUT_FORMATS) DATE_INPUT_FORMATS = ['%d/%m/%Y'] DATETIME_INPUT_FORMATS = ['%d/%m/%Y'] pessoas_forms.py class PessoaForm(ModelForm): data_nascimento = DateField( input_formats=settings.DATE_INPUT_FORMATS, widget=DateInput(attrs={'class': "input", 'placeholder': "Ex.: dd/mm/aaaa", "OnKeyPress":"mask('##/##/####', this)"})) class Meta: model = Pessoa fields = ['nome', 'sobrenome', 'cpf', 'data_nascimento', 'rg', 'foto'] exclude = ['usuario', 'usuario_alteracao', 'data_criacao', 'data_alteracao', 'responsavel'] widgets = { 'nome': TextInput(attrs={'class': "input"}), 'sobrenome': TextInput(attrs={'class': "input"}), 'cpf': TextInput(attrs={'class': "input", 'placeholder': "Ex.: 000.000.000-00", "OnKeyPress":"mask('###.###.###-##', this)"}), 'rg': TextInput(attrs={'class': "input"}), } views.py def get(self, request, id): try: pessoa = Pessoa.objects.get(id=id) except ObjectDoesNotExist: messages.warning(request, 'Not Found.') return redirect('pessoas') pessoa_form = PessoaForm(instance=pessoa) context = { 'pessoa_form': pessoa_form, 'id': pessoa.id } return render(request, 'sagasystem/configuracoes/pessoas/editar_pessoa.html', context) -
ImportError at /admin/ No module named 'honeywordHasher.hashers.honeywordgen'; 'honeywordHasher.hashers' is not a package
Hye . i try to make my own customize password hasher and i still cannot manage to import it because of this error . how to fix this error ? complete traceback: During handling of the above exception (module 'honeywordHasher.hashers' has no attribute '__path__'), another exception occurred: File "C:\Users\Adila\Envs\tryFOUR\lib\site-packages\django\core\handlers\exception.py" in inner 41. response = get_response(request) File "C:\Users\Adila\Envs\tryFOUR\lib\site-packages\django\core\handlers\base.py" in _get_response 217. response = self.process_exception_by_middleware(e, request) File "C:\Users\Adila\Envs\tryFOUR\lib\site-packages\django\core\handlers\base.py" in _get_response 215. response = response.render() File "C:\Users\Adila\Envs\tryFOUR\lib\site-packages\django\template\response.py" in render 107. self.content = self.rendered_content File "C:\Users\Adila\Envs\tryFOUR\lib\site-packages\django\template\response.py" in rendered_content 84. content = template.render(context, self._request) File "C:\Users\Adila\Envs\tryFOUR\lib\site-packages\django\template\backends\django.py" in render 66. return self.template.render(context) File "C:\Users\Adila\Envs\tryFOUR\lib\site-packages\django\template\base.py" in render 207. return self._render(context) File "C:\Users\Adila\Envs\tryFOUR\lib\site-packages\django\template\base.py" in _render 199. return self.nodelist.render(context) File "C:\Users\Adila\Envs\tryFOUR\lib\site-packages\django\template\base.py" in render 990. bit = node.render_annotated(context) File "C:\Users\Adila\Envs\tryFOUR\lib\site-packages\django\template\base.py" in render_annotated 957. return self.render(context) File "C:\Users\Adila\Envs\tryFOUR\lib\site-packages\django\template\loader_tags.py" in render 177. return compiled_parent._render(context) File "C:\Users\Adila\Envs\tryFOUR\lib\site-packages\django\template\base.py" in _render 199. return self.nodelist.render(context) File "C:\Users\Adila\Envs\tryFOUR\lib\site-packages\django\template\base.py" in render 990. bit = node.render_annotated(context) File "C:\Users\Adila\Envs\tryFOUR\lib\site-packages\django\template\base.py" in render_annotated 957. return self.render(context) File "C:\Users\Adila\Envs\tryFOUR\lib\site-packages\django\template\loader_tags.py" in render 177. return compiled_parent._render(context) File "C:\Users\Adila\Envs\tryFOUR\lib\site-packages\django\template\base.py" in _render 199. return self.nodelist.render(context) File "C:\Users\Adila\Envs\tryFOUR\lib\site-packages\django\template\base.py" in render 990. bit = node.render_annotated(context) File "C:\Users\Adila\Envs\tryFOUR\lib\site-packages\django\template\base.py" in render_annotated 957. return self.render(context) File "C:\Users\Adila\Envs\tryFOUR\lib\site-packages\django\template\defaulttags.py" in render 322. return nodelist.render(context) File "C:\Users\Adila\Envs\tryFOUR\lib\site-packages\django\template\base.py" in render 990. bit = node.render_annotated(context) File "C:\Users\Adila\Envs\tryFOUR\lib\site-packages\django\template\base.py" … -
multiple forms in Django createView class
I'd like to create a formView(based on Django build-in CreateView class) to allow creating new user records, which are from two different models. Both models sounds like one is user model and another is user profile model. I wish one form with one submit button to approach it, but I found only one form_class could be assigned in one createView class in Django. So I wonder is that possible to use CreateView to approach it? if not, any solution recommended? Appreciated if any assistance from you. -
Django - licensing application (connecting an app with particular domain)
I would like to sell my app. The only problem is to protect the source code. I would like to allow to use it with only one particular domain (one license = one domain). Is it possible to prevent reuse code on another domains? By now every user can change allowed host by simply editing setting.py file. I don't have any idea how can I prevent that. Is there any third party app for licensing functionality? -
Python/Django vs JS/HTML5 to build a CASAbrowser-like website?
I want to build a web interface which looks like this browser for a scientific application (click on the play button and move the position scroller to see the demo). Here is a screenshot of the browser : I was wondering which language/framework would be the best suited for this task ? A python/Django combination or JS/HTML5 ? Besides the GUI part (buttons, scrolls, ..) I want the freedom to add multimedia components (a video, a speech signal, ..) and scatter plots. -
Locally test different domain url configuration in Django
As the title says how do i test different domain not subdomain url routing? I'm using a middleware as follows: class MultipleDomainMiddleware(MiddlewareMixin): def process_request(self, request): url_config = getattr(settings, 'MULTIURL_CONFIG', None) if url_config is not None: host = request.get_host() if host in url_config: request.urlconf = url_config[host] Where the url_config[host] value points to app.urls in the settings MULTIURL_CONFIG dictionary. Each app is on a different domain. Now, when locally testing I'm on localhost:8000/ so how can I test this so I can test my routing schema as well as shared data across the domains locally? -
Python/Django: How to show both main model and 'foreign-key model' together in HTML
Good Day SO, I am a beginner in Django and python, just started learning two days ago. Currently, I am trying to do my filtering of data in views.py and creating a context to be shown in my main page that contains both the initial model and the 'foreign-key' model. However, I am having trouble finding help online, even though this is a simple question.. Here goes.. Models involved: class Plan(models.Model): plan_ID = models.CharField( primary_key=True, max_length=8, validators=[RegexValidator(regex='^\w{8}$', message='Length has to be 8', code='nomatch')] ) plan_crisisID = models.ForeignKey(Crisis, on_delete=models.CASCADE) plan_status = models.CharField(max_length=50) class Crisis(models.Model): crisis_ID = models.CharField( primary_key=True, max_length=4, validators=[RegexValidator(regex='^\w{4}$', message='Length has to be 4', code='nomatch')] ) crisis_name = models.CharField(max_length=50) Views.py for HTML: def home(request): template = loader.get_template('pmoapp/home.html') crisisList = Crisis.objects.filter(crisis_status='Ongoing').order_by('-crisis_ID') context = { 'crisisList': crisisList, #'planList': planList } return HttpResponse(template.render(context, request)) And finally, my HTML page: <tbody> {% if crisisList %} {% for crisis in crisisList %} <tr> <td>{{ crisis.crisis_ID }}</td> <td><a href="/report/{{ crisis.crisis_ID}}">{{ crisis.crisis_name }}</a></td> <td>{{ crisis.crisis_dateTime }}</td> <td>planid</td> <td>planstatus</td> </tr> {% endfor %} {% else %} <p>No crisis available.</p> {% endif %} </tbody> I have several things that I do not know how to do here.. so sorry and bear with me.. I have a many-to-one relationship between … -
Inheriting a Django crispy form in all pages of my website
I am building my website with Django. I have built a newsletter app for my website where users can join the newsletter group by putting their email address. I am sending the form as a context variable to "base.html". I have another html file called "carousel.html" which is my homepage. This html file contains the tag {{ % include "base.html" % }} However, in my "urls.py", when I use "carousel.html" as a templateview, urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', TemplateView.as_view(template_name = 'carousel.html'))] I don't see the form. Basically, I am unable to inherit the form in the right way. Here is what the actual form should look like The right form And this is what it looks like now How the form looks now -
Oscar Partner Model to OnetoOne
Trying to update theOnetoOneField so that I can have multiple partners with their own dashboard. I'm not sure if I have my paths right too. I keep getting Permission denied! for an user that I manually selected to be a partner to test if it works. where im trying to update partner models.py from oscar.apps.partner.abstract_models import AbstractPartner from django.contrib.auth.models import User from django.utils.translation import ugettext_lazy as _ from oscar.apps.partner.models import * class Partner(AbstractPartner): user = models.OneToOneField( User, related_name="partner", blank=True, verbose_name=_("Users")) my path App |--app (main) |--oscarapp (oscar app) |----partner |------models.py |----oscarapp |------__init__.py |------settings.py -
django urls throwing error in browser
i switched from the general url format to creating a urls.py file for each app so after moving the urls I get an error Reverse for 'trending' not found. 'trending' is not a valid view function or pattern name urls.py from django.conf.urls import url from . import views from django.contrib import admin app_name = 'posts' urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^trending/$', views.trending, name='trending'), url(r'^ranking/$', views.post_ranking, name='rank'), url(r'^create/$', views.create, name='create'), ] general urls.py url(r'^', include('posts.urls' , namespace="posts")), template <li><a href="{% url 'trending' %}"><i class="fa fa-hashtag"><small class="notification-badge">5</small></i> Trending</a></li> <li><a href="{% url 'index' %}"><i class="fa fa-level-down"></i> Recent</a></li> additional codes would be added on request. -
Django library for rest auth Google, Instagram, VK, ant others?
I need SOCIAL REST AUTH in my Django project for SPA, and iOS app. All library I've found have only Facebook and Twitter REST auth. Is there any library, which has all what I need for another famous social: Google, Instagram, VK... ?