Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - How to call a session in a module different than views.py?
I'd like to call a session that was set at views.py in my forms.py. Is that possible? I tried to do that but I faced some issues with 'request'. forms.py from django import forms class exampleform(forms.Form): a = 'test' # I would like to replace this 'test' by a data stored in a session set in views.py options_list = [ (a, a), ('b', 'b'), ('c', 'c'), ] options_form = forms.ChoiceField(required=False, choices=options_list,widget=forms.RadioSelect(attrs={'class':'example_form'}), label='') views.py from django.shortcuts import render from .forms import exampleform def example(request): option_a = '123' request.session['my_session'] = option_a form = exampleform context = { 'form': form, } return render(request, 'example/index.html', context,) I don't try to import the value instead of make a session, because this value will be created inside the same view that I call the form. Therefore I would get a circular error. I hope that to store this value in a session, and then send it to my form will not raise this circular issue. P.S. I'm a beginner on programming. -
Resolving Fatal status in Supervisor and Django
I am using Digital Ocean Ubuntu server to deploy my Django project and follow this guide to set it all up: A Complete Beginner's Guide to Django - Part 7 I am the process of configurig Gunicorn and Supervisor and I get the following error: I am logged in as non-root but sudo user that I have created called betofolio. My django project is called betofolio. Below is a screenshot of what my folders look like: Following the steps from the tutorial: Create a new file named gunicorn_start inside /home/betofolio: vim gunicorn_start I insert the following: #!/bin/bash NAME="betofolio" DIR=/home/betofolio/betofolio USER=betofolio GROUP=betofolio WORKERS=3 BIND=unix:/home/betofolio/run/gunicorn.sock DJANGO_SETTINGS_MODULE=betofolio.settings DJANGO_WSGI_MODULE=betofolio.wsgi LOG_LEVEL=error cd $DIR source ../venv/bin/activate export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE export PYTHONPATH=$DIR:$PYTHONPATH exec ../venv/bin/gunicorn ${DJANGO_WSGI_MODULE}:application \ --name $NAME \ --workers $WORKERS \ --user=$USER \ --group=$GROUP \ --bind=$BIND \ --log-level=$LOG_LEVEL \ --log-file=- Then I save and exit. Make this file executable: chmod u+x gunicorn_start Create two empty folders, one for the socket file and one to store the logs: mkdir run logs Configuring Supervisor Create an empty log file inside the /home/betofolio/logs/ folder: touch logs/gunicorn.log Now create a new supervisor file: sudo vim /etc/supervisor/conf.d/betofolio.conf [program:betofolio] command=/home/betofolio/gunicorn_start user=betofolio autostart=true autorestart=true redirect_stderr=true stdout_logfile=/home/betofolio/logs/gunicorn.log Then: sudo supervisorctl reread sudo supervisorctl update Now … -
Django run background script using subprocess, passing primary key to script to retrieve object
I have been figuring on how to run a script on background, so that i can process an object without having the user to wait for the server to respond. Right now, I have come across subprocess, however, I couldn't figure how to pass the primary key of the object to the script, so that the background script could retrieve the object from within it. Views.py import subprocess, sys def allocate_request(request, event_id): event = get_object_or_404(MeetingEvent, id=event_id) subprocess.Popen([sys.executable, 'sorting.py', str(event_id)], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) return HttpResponse("Request Submitted.") and in the same directory, Sorting.py import sys class Organize: #... try: event_id = sys.argv[2] event = MeetingEvent.objects.get(id=event_id) Organize(event=event) except MeetingEvent.DoesNotExist: pass except IndexError: pass but it seems like sub script isn't able to fetch the primary key argument, neither i could pass the check using django's console. I wonder what is wrong with my code. Would appreciate any help :) -
could not translate host name "postgres" to address
I use PostreSQL and Django 1.8 in my app. I have an error: django.db.utils.OperationalError: could not translate host name "postgres" to address: nodename nor servname provided, or not known but I cannot find a please where host name "postgres" is set, because I have set host name to localhost. DATABASE_USER = MY_DATABASE_USER = admin DATABASE_HOST = MY_DATABASE_HOST = localhost DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'default_db', 'USER': os.getenv('DATABASE_USER', ''), 'PASSWORD': os.getenv('DATABASE_PASSWORD', ''), 'HOST': os.getenv('DATABASE_HOST', ''), 'PORT': '5432', }, 'my_db': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.getenv('MY_DATABASE_NAME', 'my_dev'), 'USER': os.getenv('MY_DATABASE_USER', os.getenv('DATABASE_USER', 'admin')), 'PASSWORD': os.getenv('MY_DATABASE_PASSWORD', os.getenv('DATABASE_PASSWORD', '')), 'HOST': os.getenv('MY_DATABASE_HOST', os.getenv('DATABASE_HOST', '')), 'PORT': '5432', } } Can I fix that error? -
Django Fixtures and Test Server
Okay so I've run into an interesting testing problem. One of my apps uses a MYSQL FULLTEXT index which I have to create manually since I can't specify it on my model creation. This works fine, except now it's created a problem testing. My test routine loads up the data using Fixtures, but it won't create the Index so my search functions fail. I can create the index manually but everytime I try to run manage.py testserver, it recreates the database so I lose the index. Is there a way I can integrate my function so that it is run anytime the databases are recreated? -
Django, Elasticsearch and maybe Haystack
I am trying to use Elasticsearch to provide good search capabilities to a Django project. This is not a technical question, but I would rather hope that you can provide insight into my situation and help me choose the right approach, wether you have experience with the technologies discussed below or based on some best practices of development in general. My environment is kind of complex and there is a lot of compatibility issues that should be taken into consideration. I will spare you the details, but here are some constraints that should be kept in mind: I have to use the version 5 of Elasticsearch Haystack is only compatible with the versions 1 and 2 of Elasticsearch Synchronization of DB and Elasticsearch should be near real-time, meaning I can't use a cron job, and that a latency of a minute is tolerable. I have messed around with the Python Elasticsearch client and its more high-level version Elasticsearch DSL. They worked when it comes to inserting, retrieving data... from Elasticsearch. I also tried using Haystack to integrate Elasticsearch into my project. More specifically I successfully used celery-haystack to handle the synchronization between the database and Elasticsearch. Even though the celery-haystack … -
routing with django and AngularJS
I new to AngularJS and trying to set up Django with AngularJs, however, I have some issues with handling the routing with those two frameworks. so far I've set up like below: When I run http://localhost:8000/index.html it works and shows me the file, but when I run http://localhost:8000/test as I wrote in app.js it gives me standard Django 404 error. What am I missing? urls.py urlpatterns = [ url(r'^index.html/$', ] app.js var app = angular.module("myApp", ["ngRoute"]); app.config(function($routeProvider) { $routeProvider .when("/test", { templateUrl : "index.html", controller: "MainCtrl" }) }); app.controller("MainCtrl", function ($scope) { $scope.msg = "test"; }); index.html {% load static %} <html ng-app="myApp"> <head> </head> <body> <div> test </div> <script src="{% static 'js/general/angular.min.js' %}" type="text/javascript"></script> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-route.js"></script> <script type="text/javascript" src="{% static 'js/app.js' %}"></script> </body> </html> -
'function' object has no attribute '_meta' inlineformset_factory django
I'm trying to create a form that submits a model with a foreign key but i got this error : Traceback (most recent call last): File "C:\Users\~\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\exception.py", line 41, in inner response = get_response(request) File "C:\Users\~\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\~\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\~\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\views\decorators\csrf.py", line 58, in wrapped_view return view_func(*args, **kwargs) File "~.py", line 21, in wrap return function(request, *args, **kwargs) File "~.py", line 32, in wrap return function(request, *args, **kwargs) File "~.py", line 428, in example PostFormSet = inlineformset_factory(User, Post, fields=('longitude', 'latitude', 'placename', 'explanation', )) File "C:\Users\~\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\forms\models.py", line 1038, in inlineformset_factory fk = _get_foreign_key(parent_model, model, fk_name=fk_name) File "C:\Users\~\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\forms\models.py", line 980, in _get_foreign_key opts = model._meta AttributeError: 'function' object has no attribute '_meta' model.py class Post(models.Model): owner = models.ForeignKey(User,on_delete=models.CASCADE,related_name="posts",blank=False,null=False) </other fields>... class PostImage(models.Model): owner = models.ForeignKey(Post,on_delete=models.CASCADE,related_name="images",blank=False,null=False) views.py def example(request): context = { 'hellow we':"qfqf" } print(request.user) PostFormSet = inlineformset_factory(User, Post, fields=('longitude', 'latitude', 'placename', 'explanation', )) print("------------------------------------------------------------") print(frm.errors) return JsonResponse(context, encoder=JSONEncoder) -
Django - Displaying selected by checkboxes columns of table
I have a table with 60 columns and I want to make a selection by columns, using checkboxes. How can I display selected by checkboxes columns of table? -
Django form with multiple checkboxes
I am really new to Django! I have a page that displays items with checkboxes next to them. The number of items/checkboxes varies. When a button is pressed, I want the corresponding checked item to be modified. So far, I have tried to wrap it all in one form: <form method="post"> {% csrf_token %} {% for event in items %} {{ event.eventID }} <input type="checkbox" value="{{ event.eventID }}" name="choices"> {% endfor %} <button type="submit">Approve</button> </form> I want to collect them in a Django form field. I am trying to use ModelMultipleChoiceField: class ApproveEventForm(forms.Form): choices = forms.ModelMultipleChoiceField(queryset = Event.objects.all(), widget=forms.CheckboxSelectMultiple()) And in my views, I want to edit the selected items: def approve_event(request): if request.method == "POST": form = ApproveEventForm(request.POST) print(form.errors) if form.is_valid(): for item in form.cleaned_data['choices']: item.approved = True item.save() else: form = ApproveEventForm() unapproved = Event.objects.filter(approved=False) return render(request, 'app/approve_event.html', {'items': unapproved}) My form is not valid and form.errors prints: choices "" is not a valid value for a primary key. How can I fix this? Or is there another way to access the selected items? -
Class Based FormView
I have researched this issue for a couple of days and can't seem to find what I'm looking for exactly. I have searched ModelChoiceField as well as ChoiceField on StackOverflow as well as Google and there are many variations of my question but nothing exactly. In a nutshell, I am trying to use a Class Based FormView and then capture the user selection and pass it to a Class Based ListView. Here is my code. Forms.Py class BookByStatus(forms.Form): dropdown = forms.ChoiceField(choices=[],required=False) def __init__(self, user, *args, **kwargs): super(BookByStatus, self).__init__(*args, **kwargs) self.fields['dropdown'].widget.attrs['class'] = 'choices1' self.fields['dropdown'].empty_label = '' self.fields['dropdown'].choices = Book.objects.values_list("author","author").distinct("Publisher") The code above works fine, and shows me the output I'm looking for on my view. No issues there....Then I have my FormView... class BookByStatusView(LoginRequiredMixin,FormView): model = Book form_class = BookByStatus template_name = 'xyz123/publisher.html' success_url = reverse_lazy('Book:book_by_list') def get_form_kwargs(self): kwargs = super(BookByStatusView, self).get_form_kwargs() kwargs['user'] = self.request.user return kwargs def form_valid(self, form): BookByStatusView = form.cleaned_data['dropdown'] return HttpResponseRedirect(BookByStatusView.get_absolute_url1()) The code above works fine, but takes me to the ListView below which I can't seem to pass the dropdown value to....I've tried several different iterations of get_form_kwargs as well as changed my form to ModelChoiceField, but still can't seem to understand how to get a … -
Serverless and NewRelic
I'm using the latest version of the Serverless framework and am trying to integrate NewRelic into my applications. I have both Django as well as Flask applications (-> Python!) which I'd like to monitor with NewRelic. I integrated the framework as documented (by wrapping the WSGI application) and set the NewRelic timeout variables accordingly to make sure data is getting sent. In my NewRelic dashboard I'm able to see the project but no data is reported. Has anyone had success getting this running? Thanks! -
django the way to access data from input form
The title looks cliche, but I didn't find the solution that fits in my situation :( My symptom is when I click the modify button and then I write down the information on new window that is implemented by bootstrap div part. However, my database doesn't change at all. Please ignore ... in codes, I delete attributes that looks messy. Codes can have typo, because I wrote it down manually to find a bug, but I didn't find :( I tried in view.py, address_modify makes return Httpresponse(street), but It returned None. That is what I have been stuck in for days. I appreciate! Best view.py def address_modify(request, adid): cat = get_object_or_404(Address, adid=adid) if request.method == "POST": old_adid = adid email = request.user.email street = request.POST.get("street", None) city = request.POST.get("city", None) ... Address.objects.filter(adid=adid).update(..., street=street, city=city, state=state, ...) return redirect('/address/') return redirect('/address/') template ( I name it address.html) <button class="btn btn-success" data-toggle="modal" data-target="#modify">MODIFY</button> <div class ="model fade" id="modify" role="dialog"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <from action="" method="POST">{% csrf_token %} </div> <div class="modal-body"> <input type="text" name="street"> <input type="text" name="city"> ... ... <input type="text" name="zipcode"> </div> <div class="modal-footer"> <a href="{% url 'address_modify' i.adid %}">{% csrf_token %} <button type="button" class="btn btn-primary">Save Change</button></a> <div></form> urls.py … -
ValueError at /author/admin/ in Django
I have the following blog project : urls.py conf : url(r'^author/(?P<author>\w+)/$', views.getAllPosts, name='grabAuthorPosts') posts/models: class Post(models.Model): title = models.CharField(max_length=200) summary = models.CharField(max_length=500, default = True) body = models.TextField() pub_date = models.DateTimeField(default=timezone.now) category = models.ManyToManyField('Category') author = models.ForeignKey(User, default=True) slug = models.SlugField(max_length=100, unique=True, blank=True) def __str__(self): return self.title def slug(self): return slugify(self.title) posts/views: def getAllPosts(request, author=False): latest_posts = Post.objects.all().order_by('-pub_date') comments = Comment.objects.all().order_by('-pub_date') author_posts = latest_posts.filter(author=author) context = { 'latest_posts':latest_posts, 'comments':comments, 'author_posts':author_posts } return render(request, 'posts/getAllPosts.html', context) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=500, blank=True) location = models.CharField(max_length=30, blank=True) birth_date = models.DateField(null=True, blank=True) templates/posts/getAllPosts: <a href={% url 'grabAuthorPosts' author=post.author.username%}> {{post.author}}</a> I am trying to make it so that when the post.author link is clicked, the user will be taken to a page consisting of posts related to that particular author. The link formulation itself seems ok, as when clicked on a post created by admin, the url reads : "localhost/author/admin/ I believe my problem is in getting the context variable author_posts to work. I'm new to Django so any explanation greatly appreciated. latest_posts, as well as author=False is used elsewhere in the template to get all posts regardless of author, which works fine. The error is : ValueError at /author/admin/ … -
How to retrieve additional JSON data from request in django ModelSerializer
I have a model serializer that creates a Program object, along with another OutboundProgram object. The json I receive has all the details of a program object and the additional ones I need to create the OutboundProgram. How do I retrieve the additional fields because serializer only reads the fields for a certain object. P.S. our team lead doesnt want me to use a nested JSON json received by the request: { "linkage": "AP", "name": "something", "academic_year": 2017, "terms_available":[1,2], "is_graduate": false, "requirement_deadline":"2011-10-16", "institution": 3 } models.py class Program(SoftDeletionModel): linkage = ForeignKey(Linkage) name = CharField(max_length=64) academic_year = ForeignKey(AcademicYear) terms_available = ManyToManyField(Term) is_graduate = BooleanField() def __str__(self): return self.name class OutboundProgram(SoftDeletionModel): program = ForeignKey(Program) requirement_deadline = DateField() institution = ForeignKey(Institution) serializers.py class OutboundProgramSerializer(ModelSerializer): class Meta: model = Program fields = "__all__" def create(self, validated_data): terms = validated_data.pop('terms_available') program = Program.objects.create(**validated_data) for term in terms: program.terms_available.add(term) program.save() print(validated_data) return program Any kind of help would be useful. Thanks! -
Django rest HyperlinkedModelSerializer with nested custom field
I have my model as follows class Asset(models.Model): name = models.CharField(('name'), max_length=50, blank=True) manufacturer = models.CharField(('manufacturer'), max_length=100, blank=True) address = models.CharField(('address'), max_length=100) owner = models.ForeignKey(User,on_delete=models.CASCADE) class Lease(models.Model): OPEN = 'OPEN' APPROVED = 'APPROVED' CLOSEREQUESTED = 'CLOSEREQUESTED' RENEWREQUESTED = 'RENEWREQUESTED' CLOSED = 'CLOSED' REJECTED = 'REJECTED' STATUS_CHOICES = ( (OPEN,'OPEN'), (APPROVED, 'APPROVED'), (CLOSEREQUESTED, 'CLOSEREQUESTED'), (RENEWREQUESTED, 'RENEWREQUESTED'), (CLOSED,'CLOSED'), (REJECTED, 'REJECTED'), ) user = models.ForeignKey(User, related_name='user',on_delete=models.CASCADE) asset = models.ForeignKey(Asset,related_name='asset',on_delete=models.CASCADE) start_date = models.DateField(auto_now=False) end_date = models.DateField(auto_now=False) status = models.CharField(choices=STATUS_CHOICES,default=OPEN,max_length=20) How can I write a serializer for Lease model so that I will be able to create new lease resource if I am sending the ids only for the user and asset fields. I have written a serializer as below but it is not getting created for the json payload below. class LeaseSerializer(serializers.HyperlinkedModelSerializer): class Meta: asset = serializers.StringRelatedField(source='assetId',) user = serializers.Field(source='lesseeId') model = Lease fields = ('assetId','startDate','endDate','lesseeId') Payload { "assetId":"", "startDate":"", "endDate":"", "lesseeId":"" } Do I need to create custom serializer in this case ? -
djangrestframework to display model in foreign key
Please excuse the title. Im not quite sure how ask this question without just showing. In django I have two models. class people(models.Model): name=models.TextField(max_length=100) nickname=models.TextField(max_length=100) class visits(models.Model): person=models.OneToOneField(people) visitdate=models.DateTimeField(auto_now=True) and then a serializer for the restapi. #serializers.py class VisitsSerializer(serializers.ModelSerializer): class Meta: model = visits fields=("id","person","date") When the API returns the dictionary, it looks like this. {id:1,person:1,visitdate:11/23/17} Is there a way to make the API return the actual values that are associated with the person with id 1? like so. {id:1,person:{id:1,name:foo,nickname:bar},visitdate:11/23/17} -
When should you use redirect instead of just calling the target view function directly?
Sometimes views need to make decisions about workflow and direct to different areas. For example def view_switchboard(request): if request.POST['data'] == 'option A': return redirect('Appname:viewA') elif request.POST['data'] == 'option B': return redirect('Appname:viewB') else: # in third case, we just need to do some speciailised actions also done elsewhere, for DRY we put it all in one place - actionC return redirect('Appname:actionC_as_view') However, the following is also possible: def view_switchboard(request): if request.POST['data'] == 'option A': return view_viewA(request) elif request.POST['data'] == 'option B': return view_viewB(request) else: result = actionC(request) context = do_more_processing(result) return render('switchboard_template',context) In fact, wouldn't the second option always be possible negating the need for redirect function all together? How inefficient is redirect? What is the right circumstance and wrong circumstances for using redirect? Any other tips for handling workflows of views? -
Creating multiple wagtail home pages
How do I create multiple static pages in wagtail such as home, about, contact, ectetera which are dependent upon the domain - not subdomain. I found the docs non-intuitive do I simply create a Page in admin under the root page such as Domain1HomePAge, Domain2HomePage, etcetera and set the root page under the sites in wagtail admint o point to this root page? -
Django form posts data with no errors, but does not register as 'is_valid'
I am creating my first Django form and I can see the data passing successfully to the console through my logging, but it does not save to the database because the post data is not registering as 'is_valid'. I would love to know why. Template - newpost.html <form method='POST' action=''>{% csrf_token %} {{newPost.as_p}} <input type='submit' value='Create Post'> </form> Form - forms.py class PostEntry(forms.ModelForm): class Meta: model = Entry fields = [ "image", "body", "user", "slug", "publish" ] Model - models.py class Entry(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1) image = models.ImageField(upload_to="") body = models.TextField() slug = models.CharField(max_length=6, unique=True, default=rand_slug()) publish = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) def __str__(self): return self.slug def get_absolute_url(self): return '/posts/%s/%s' % (self.user, self.slug) class Meta: verbose_name = "Entry" verbose_name_plural = "Entries" ordering = ["-created"] View - views.py def NewJournalDetail(request): newPost = PostEntry() if request.method == "POST": print(request.POST.get("body")) # successful print(request.POST.get("image")) # successful print(request.POST.get("slug")) # successful print(request.POST.get("user")) # successful print(request.POST.get("publish")) # successful if newPost.is_valid(): # NOT successful print(newPost) instance = newPost.save(commit=False) instance.save() else: print('not valid') print(newPost.errors) # NO errors context = { "newPost": newPost, } return render(request, "newpost.html", context) Console Output [23/Nov/2017 10:19:51] "GET /create/ HTTP/1.1" 200 894 this is text from the body image.PNG 1FP2is 1 … -
Wagtail Migration error when removing Streamfield block
I had a Streamfield block based on SnippetChooserBlock which I removed, which was fine, migrations were fine. ('call_to_action_snippet', SnippetChooserBlock(CallToActionSnippet,icon="success",template='myapp/blocks/cta_snippet.html')), When I then tried to then also remove the CallToActionSnippet from my models, I get an error when running makemigrations from an older migration file: AttributeError: 'module' object has no attribute 'CallToActionSnippet' Any ideas what I'm doing wrong here? I know SF custom blocks can't be removed if they're based on certain block types but I thought a SnippetChooserBlock would be ok. thanks Joss -
Count Object in Models Django
I have a problem with creating a modelfield which Count number of people who like an article. I have class Like: class Reaction(models.Model): user = models.ForeignKey(User) article = models.IntegerField(null=True, blank=True) date = models.DateTimeField(auto_now_add=True, null=True) and class Article: from api.reactions.models import Reaction class Article(models.Model): user = models.ForeignKey(User) post = models.TextField() likes = models.IntegerField(default=0) def __str__(self): return self.post def calculate_likes(self): likes = Reaction.objects.count(article=self.pk) self.likes = likes self.save() return self.likes But likes wont be counted. What's wrong with this? Please help me. Thanks! -
Django: strange reverse match
In my app, I've got a view which generates a form. When this form is valid the view redirect to another view which is another form, but I have an error message with the reverse match. My views.py: def uploadData(request, dataType, method): if method == 'single': if dataType == 'Sequence-has-SNP': if request.method == 'POST': form = SeqHasSnpForm(request.POST) if form.is_valid(): idSequence = form.cleaned_data['seq_linked'] return redirect('addSNPsSeq', idSequence) else: form = SeqHasSnpForm() return render(request, 'myapp/upload_sequence-has-snp.html', locals()) else: ... else: ... def uploadSNPsToSeq(request, idSequence): seq = Sequence.objects.get(PK_idSequence = idSequence) thisSeqHasSnp = Seq_has_SNP.objects.filter(FK_idSequence = seq.PK_idSequence) snpAll = SNP.objects.all() if request.method == 'POST': form = SelectSNPsForSeqForm(request.POST, snps=snpAll, seqHasSnps=thisSeqHasSnp) if form.is_valid(): print('Yeaaahhh!') else: form = SelectSNPsForSeqForm(snps=snpAll, seqHasSnps=thisSeqHasSnp) print(form) return render(request, 'myapp/SNPs-to-add-to-sequence.html', locals()) my urls.py urlpatterns = [ url(r'^SNPs-to-add-to-sequence_(?P<idSequence>.+)$', views.uploadSNPsToSeq, name='addSNPsSeq'), url(r'^upload_(?P<dataType>[A-Za-z-]+)_(?P<method>(single|batch))$', views.uploadData, name='upload'), ... url(r'^$', views.home, name='home') ] I have my 2 templates called upload_sequence-has-snp.html and SNPs-to-add-to-sequence.html. The 2 forms are OK because I have access to my first form and for example select a form.cleaned_data['seq_linked'] equal to TEST. I can see the result in the terminal of print(form) in uploadSNPsToSeq, but the last line of this view raise a NoReverseMatch error: NoReverseMatch at /myapp/SNPs-to-add-to-sequence_TEST Reverse for 'upload' with arguments '('', '')' not found. 1 pattern(s) tried: … -
Django angular error
I'm learning Angularjs and I want to integrate it with django. I'm following the tutorial in angularjs site. First I try the code in an static html page (not django), that works fine. html: <html ng-app="phonecatApp"> <head> <script src="angular.min.js"></script> <script src="app.js"></script> </head> <body> <!-- Use a custom component to render a list of phones --> <phone-list></phone-list> </body> </html> js: // Define the `phonecatApp` module var phonecatApp = angular.module('phonecatApp', []); // Register `phoneList` component, along with its associated controller and template angular. module('phonecatApp'). component('phoneList', { template: '<ul>' + '<li ng-repeat="phone in $ctrl.phones">' + '<span>{{ phone.name }}</span>' + '<p>{{ phone.snippet }}</p>' + '</li>' + '</ul>', controller: function PhoneListController() { this.phones = [ { name: 'Nexus S', snippet: 'Fast just got faster with Nexus S.' }, { name: 'Motorola XOOM™ with Wi-Fi', snippet: 'The Next, Next Generation tablet.' }, { name: 'MOTOROLA XOOM™', snippet: 'The Next, Next Generation tablet.' } ]; } }); When I try the same in django templates like this: {% extends 'qhcba/base.html' %} {% block ng_app %}phonecatApp{% endblock ng_app %} {% block content %} <div ng-controller="PhoneListController"> <div> {% verbatim %} <phone-list></phone-list> {% endverbatim %} </div> </div> {% endblock %} it renders the phone list code commented, like this: <phone-list><ul><!-- … -
problems getting bootstrap.js to work while using Django
I have a very simple site using the django templating engine. in this site i use Bootstrap for design and basic js. the css components from bootstrap totaly work but i cant get js to work: {% load staticfiles %} <!doctype html> <html lang="en"> <head> <title> blah </title> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}" type="text/css"/> </head> <body> <!-- Navbar --> <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <a class="navbar-brand" href="/">blah</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarTogglerDemo02" aria-controls="navbarTogglerDemo02" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarTogglerDemo02"> <ul class="navbar-nav mr-auto mt-2 mt-lg-0"> <li class="nav-item active"> <a class="nav-link" href="/">Home <span class="sr-only">(current)</span></a> </li> <li class="nav-item"> <a class="nav-link" href="#">Link</a> </li> <li class="nav-item"> <a class="nav-link disabled" href="#">Disabled</a> </li> </ul> <form class="form-inline my-2 my-lg-0"> <input class="form-control mr-sm-2" type="search" placeholder="Search"> <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button> </form> </div> </nav> <!-- Space between Navbar and Body --> <div class="border-row" style="width:100%; margin-bottom: 15px;"></div> <!-- Fullscreen Container --> <div class="container-fluid" style="min-height:100%; width:100%;"> <p>hi</p> </div> <script src="{% static '/js/jquery.js' %}"></script> <script src="{% static '/js/bootstrap.min.js' %}"></script> </body> </html> screenshot of resulting page screenshot the css und js files are delivered to the browser as the following log will show, but i also …