Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework: Filter/Validate Related Fields
I have two models: Foo which carries an owner field and Bar which has a relation to Foo: class Foo(models.Model): owner = models.ForeignKey('auth.User') name = models.CharField(max_length=20, null=True) class Bar(models.Model): foo = models.OneToOneField(Foo, related_name='bar') [...] I use HyperlinkedModelSerializer for representation: class BarSerializer(serializers.HyperlinkedModelSerializer): foo = serializers.HyperlinkedRelatedField(view_name='foo-detail', queryset=Foo.objects.all()) [...] class Meta: model = Bar fields = ('foo', [...]) class FooSerializer(serializers.HyperlinkedModelSerializer): owner = serializers.SlugRelatedField(read_only=True, slug_field='username') bar = serializers.HyperlinkedRelatedField(view_name='bar-detail', read_only=True) class Meta: model = Foo fields = ('name', 'bar', 'owner') My views look like this: class FooViewSet(viewsets.ModelViewSet): queryset = Foo.objects.all() serializer_class = FooSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwner,) def get_queryset(self): user = self.request.user if not user.is_authenticated(): return Foo.objects.none() if user.username == "admin": return Foo.objects.all() return Foo.objects.filter(owner=user) def perform_create(self, serializer): serializer.save(owner=self.request.user) class BarViewSet(viewsets.ModelViewSet): queryset = Bar.objects.all() serializer_class = BarSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwner,) def get_queryset(self): user = self.request.user if not user.is_authenticated(): return Bar.objects.none() if user.username == "admin": return Bar.objects.all() return Bar.objects.filter(foo__owner=user) I don't whant User A to be able to see User B's stuff and vice versa. That works pretty well so far with one exception: User A created an instance of Foo but doesn't instantly create an instance of Bar linking to Foo. Now User B can guess the URL to User A's Foo instance and … -
django error:can't specify the download filename
def download(request): f=open("next_op.xls") data = f.read() f.close() response = HttpResponse(data, content_type = './application/vnd.ms-excel') response['Content-Disposition'] = 'attachment; filename="nextop.xls"' return response when I use this code,i can download the file correct,but the filename is invalid. I don't know why. I need some help . THANKS -
django AJAX POST request is showing 500 error?
MY ajax code is $(function(){ $('#search').keyup(function(){ $.ajax({ type:"POST", url:"/abc/search/", data:{'search_text':$('#search').val(), 'csrfmiddlewaretoken' : $("input[name=csrfmiddlewaretoken]").val(), }, success: searchsuccess, datatype: 'html' }); }); }); function searchsuccess (data, textStatus, jqXHR){ $('#search_result').html(data); } my view is def search_college(request): if request.method == 'POST': search_text=request.POST['search_text'] else: search_text = "" colleges = Collage.objects.filter(col_name__contains=search_text) render(request, "ajax_search.html", {'colleges': colleges}) my Form is- <form>{% csrf_token %} <input type="text" id="search" name="search"> </form> I am 500 (internal server error ) after ajax post call? How can i solve it?? -
How to get order/transaction id in django-oscar?
I have written my own payment gateway integration module for django-oscar. When user clicks on checkout, he is redirected to my payment gateway page. Here i need unique order id or transaction id from the django-oscar. I have basket details like basket id, amount etc. But not sure how to get order id or transaction id. basically I need some unique id to identify the current order. -
Getting TypeError when I am trying to run server using Django?
I found questions which were close to the question asked by me, but the solutions I found there were not useful to me. Using django version 1.10.1 Output to python manage.py runserver Performing system checks... Unhandled exception in thread started by <function wrapper at 0xb6838064> Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/runserver.py", line 121, in inner_run self.check(display_num_errors=True) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 374, in check include_deployment_checks=include_deployment_checks, File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 361, in _run_checks return checks.run_checks(**kwargs) File "/usr/local/lib/python2.7/dist-packages/django/core/checks/registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "/usr/local/lib/python2.7/dist-packages/django/core/checks/urls.py", line 14, in check_url_config return check_resolver(resolver) File "/usr/local/lib/python2.7/dist-packages/django/core/checks/urls.py", line 24, in check_resolver for pattern in resolver.url_patterns: File "/usr/local/lib/python2.7/dist-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/usr/local/lib/python2.7/dist-packages/django/urls/resolvers.py", line 313, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/usr/local/lib/python2.7/dist-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/usr/local/lib/python2.7/dist-packages/django/urls/resolvers.py", line 306, in urlconf_module return import_module(self.urlconf_name) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/home/sidgupta234/Desktop/Hack/guide/guide/urls.py", line 21, in <module> url(r'^$', "hacko.views.home", name='home'), File "/usr/local/lib/python2.7/dist-packages/django/conf/urls/__init__.py", line 85, in url raise TypeError('view must be a callable or a list/tuple in the case of include().') TypeError: view must be a callable or a list/tuple in the case of include(). urls.py file … -
Multiple docker compose environments for same code base
I'm using Cookiecutter scaffold for my Django project and I follow the same workflow documented for local docker environments. I have a dev.yml compose file for a local setup. I have a testing env setup which is very different from a local setup(installs test dependencies, has different set of services specific to testing) called test.yml. I'm not able to spin up docker compose envs for both local development and testing env simultaneously. When I do a: $ docker-compose -f dev.yml up -d All the dev containers spin up fine. After this I do a: $ docker-compose -f test.yml up -d It just recreates all the above containers. Should I use a different network? Or should I give different names for the apps and services in test.yml? What is the best practice to run different set of docker compose envs for the same codebase simultaneously? Currently, I checkout the code in a different path and spin up the test env there, which seems to work. -
Redirect after activation complete Registration Redux
I am having trouble redirecting to the login page instead of the standard "Your account is activated" page. I sub-classed the view and added the URL. What am I doing wrong here? All help is appreciated. from registration.backends.default.views import ActivationView class MyActivationView(ActivationView): def get_success_url(self, user): return 'registration/login.html' url(r'^accounts/activate/complete$',ActivationView.as_view(),name='registration_activate'), -
How to force dropdown boostrap buttons in a nav bar to fill the entire container width?
I loaded css and js with <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11./jquery.min.js"> </script> <script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"> </script> <link rel="stylesheet" type="text/css" href="//netdna.bootstrapcdn.com /bootstrap/3.1.1/css/bootstrap.min.css"> In the body of the html I have a container which holds all parts of the page. If I use links without a dropdown the buttons auto fill the width of the container. However, once I switched to drop down buttons, the button widths do not auto size to fill the container. The code for the navbar is here: <div class="container"> <div class="masthead"> <h3 class="text-muted"></h3> <nav> <ul class="nav nav-justified"> <li> <div class="btn-group"> <button class="btn btn-primary dropdown-toggle " type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true"> Home </button> <ul class="dropdown-menu"> <li><a href="#">link</a></li> <li role="separator" class="divider"></li> <li><a href="#">Contact </a></li> </ul> </div> </li> <li> <div class="btn-group"> <button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Home </button> <ul class="dropdown-menu"> <li><a href="#">link</a></li> <li><a href="#">link</a></li> <li><a href="#">link</a></li> <li role="separator" class="divider"></li> <li><a href="#">Contact </a></li> </ul> </div> </li> <li> <div class="btn-group"> <button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Home </button> <ul class="dropdown-menu"> <li><a href="#">link</a></li> <li><a href="#">link</a></li> <li><a href="#">link</a></li> <li><a href="#">link</a></li> <li role="separator" class="divider"></li> <li><a href="#">Contact </a></li> </ul> </div> </li> <li> <div class="btn-group"> <button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Home </button> <ul class="dropdown-menu"> <li><a href="#">link</a></li> <li><a href="#">link</a></li> <li><a href="#">link</a></li> <li><a href="#">link</a></li> <li role="separator" … -
django-rest-framwork UpdateView, DeleteView occurs csrf token error?
I'm using django-rest-framework and implement very simple post CRUD API. But the problem is UpdateView and DeleteView occurs csrf error "detail": "CSRF Failed: CSRF token missing or incorrect." Strange thing is CreateView doens't require csrf and works very well. Here is my view and serializer views.py class PostEditAPIView(RetrieveUpdateAPIView): """ http://example.com/posts/1/edit """ queryset = Post.objects.all() serializer_class = PostUpdateSerializer lookup_url_kwarg = 'post_id' serializer.py class PostUpdateSerializer(serializers.ModelSerializer): class Meta: model = Post fields = [ "title", "content", ] I think this is enough for source code. After clicked button, How can I deal with csrf in API? -
Django - Built project broken
So basically, I have a DJANGO project that can be executed and work well. And I don't know why (maybe I upgrade my django or sth) that this is no longer working. First I try "python3 manage.py runserver" I get this from console: So I try to collect the static file with "python3 manage.py collectstatic" And I do have "ckeditor" in my static folder And I'm sure that my project is work because it still online somewhere. And notice 1 thing that in the project that my "manage.py" is not turning red. like this I know its just UI behavior but it seems that the project is broken. Anyone has idea bout it? -
django AttributeError: Manager isn't accessible via User instances
I have two models, which I want each to reference themselves. Which is purely so that I may see the users transactions in the admin panel. Transactions can't be created without a user. So I thought I'd use the save() and override it to let me save the newly created transaction model to the UserProfile which is attached to the User. But I'm getting a AttributeError: Manager isn't accessible via User instances I'm not sure if this is the right approach. And I'm not sure how I reach the UserProfile object through the user object. class transaction(models.Model): amount = models.IntegerField() investment_point = models.ForeignKey(investment_point, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return "amount: " + str(self.amount) + " - ip : " + str(self.investment_point.name) + " - user: " + str(self.user.username) def save(self, *args, **kwargs): self.user.objects.user_transactions.add(self) class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) ip = models.IntegerField(default=0) ingameName = models.CharField(max_length=50, default='NotSet') user_transactions = models.ForeignKey(transaction, on_delete=models.CASCADE, blank=True, null=True) console error: Traceback (most recent call last): File "C:\Anaconda3\Lib\site-packages\django\core\handlers\base.py", line 149, in get_response response = self.process_exception_by_middleware(e, request) File "C:\Anaconda3\Lib\site-packages\django\core\handlers\base.py", line 147, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Rasmus\workspace\Crowd\src\Cr\views.py", line 29, in register t = transaction.objects.create(amount=100, investment_point=i, user=u) File "C:\Anaconda3\Lib\site-packages\django\db\models\manager.py", line 122, in manager_method return … -
Receiving Null value from serializer while inserting into database using django rest framework
Null value generated while inserting into database from serializer using django rest framework? Serializer.py class TagsSerializer(serializers.ModelSerializer): class Meta: model = Tags fields = ('id','name') read_only_fields=('id','name') class PostedSerializer(serializers.ModelSerializer): class Meta: model = Posted fields = ('id','name') read_only_fields=('id','name') class BlogsSerializer(serializers.ModelSerializer): author = AccountSerializer(read_only=True,required=False) tags=TagsSerializer(read_only=True,many=True,required=False) postedin=PostedSerializer(read_only=True,required=False) class Meta: model = Blogs fields = ('id','author','title','tags','postedin','content','created_at','updated_at') read_only_fields=('id','created_at','updated_at') def get_validation_exclusions(self, *args, **kwargs): exclusions = super(BlogsSerializer, self).get_validation_exclusions() return exclusions + ['author'] Models.py class Posted(models.Model): name = models.CharField(_('Posted In'),max_length=255, unique=True) def __unicode__(self): return self.name class Tags(models.Model): name = models.CharField(_('Tag Name'),max_length=255, unique=True) def __unicode__(self): return self.name class Blogs(models.Model): author = models.ForeignKey(CustomUser) title=models.CharField(max_length=100) postedin=models.ForeignKey(Posted) tags= models.ManyToManyField(Tags) content = models.TextField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __unicode__(self): return '{0}'.format(self.title) views.py class BlogViewSet(viewsets.ModelViewSet): queryset=Blogs.objects.order_by('-created_at') serializer_class= BlogsSerializer def get_permissions(self): if self.request.method in permissions.SAFE_METHODS: return (permissions.AllowAny(),) return (permissions.IsAuthenticated(),IsAuthorOfBlog(),) def perform_create(self,serializer): print serializer serializer.save(author=self.request.user) return super(BlogViewSet,self).perform_create(serializer) Request Payload: (Developer tool: Chrome) {title: "test title", postedin: "1", tags: ["5"], content: "test content"} content : "test content" postedin : "1" tags : ["5"] title : "test title" Error in Preview: IntegrityError at /api/v1/blogs/ (1048, "Column 'postedin_id' cannot be null") -
Django customize model fields to show on template
I'm in a weird situation. I have following model. On a template i render only name and author. The thing is there is edit display button, when click on edit display. It should show all the fields name to choose. When i choose fields and save table's element should be updated as chosen fields. models.py class Finding(models.Model): name = models.CharField() isbn = models.CharField() author = models.ForeignKey() created = models.DateTimeField() shop = models.ManyToManyField() template(findings.html) <table> <tr> <td>{{name}}</td> <td>{{author}}</td> </tr> </table> I was thinking about using a session. But this should be dynamic and permanent. Every user may change showing fields according to their preference. How can i achieve this. -
Why am I getting the following error: NameError: name 'models' is not defined
Whenever I run the program, I get the following error: NameError at /table/ name 'models' is not defined It says that there's an error on line 4 in my views. Here is my views.py: from django.shortcuts import render def display(request): return render(request, 'template.tmpl', {'obj': models.Book.objects.all()}) Here is my models.py: from django.db import models class Book(models.Model): author = models.CharField(max_length = 20) title = models.CharField(max_length = 40) publication_year = models.IntegerField() Here is my urls.py: from django.conf.urls import url from . import views urlpatterns = [ # /table/ url(r'^$', views.display, name='display'), ] Can somebody please tell me what is wrong? -
Adding extra tag field to Django Wagtails StreamBlock
I am trying to add an H1 tag option to Wagtails StreamBlock and although it adds it as a selection, I am not getting expected results in the browser; the H1 tag is not being created. Here is my code class DemoStreamBlock(StreamBlock): h1 = CharBlock(icon='title', classname='title') h2 = CharBlock(icon='title', classname='title') ... And the result in the browser is shown in the screenshot below. I know I am missing something simple - any help would be appreciates. Thank you. -
Django custom context_processors in render_to_string method
I'm building a function to send email and I need to use a context_processor variable inside the HTML template of the email, but this don't work. Example: def send_email(plain_body_template_name, html_body_template_name): plain_body = loader.render_to_string(plain_body_template_name, context) html_body = loader.render_to_string(html_body_template_name, context) email_msg = EmailMultiAlternatives(body=plain_body) email_msg.attach_alternative(html_body, 'text/html') email_message.send() In my custom context_processor.py I just have a function that receive a HttpRequest and return a dict like {'foo': 'bar'}, and in the template I try to render using {{foo}}. I added the context_processor in the TEMPLATE['OPTIONS']['context_processors'] too. -
Django passing a variable to Httpresponseredirect throws exception
The problem I Have right now is that I get a : Reverse for 'documentation' with arguments '(1,)' and keyword arguments '{}' not found. 0 pattern(s) tried: [] when I try to redirect to another view using HttpResponseRedirect Here is my urls.py url(r'^documentation/([0-9])/$', views.documents, name='documentation'), here my views.py def view1(request): if request.method == 'POST': profe = request.POST.get('value') a = value.encode('ascii', 'ignore') b = int(a) return HttpResponseRedirect(reverse('documentation', args=(b,))) else: return render(request, "anhtml.html", info) def documents(request,valor): ...something... return render(request, "anotherhtml.html", ..something..) Thanks -
Difference between self.request and request in Django class-based view
In django, for class-based view like ListView and DetailView, methods like get() or post() or other functions defined by developer take parameters include self and request. I learnt that in self these is actually a self.request field, so wha's the difference between self.request and request? Example, this is the function in a class based view and used to handle user's login requirement: def login(self, request): name = request.POST['name'] pwd = request.POST['password'] user = authenticate(username=name, password=pwd) if user is not None: request.session.set_expiry(0) login(request, user) log_message = 'Login successfully.' else: log_message = 'Fail to login.' return HttpResponseRedirect(reverse('blog:testindex')) This is the function used to handle user's register: def register(self, request): user_name = self.request.POST['username'] firstname = self.request.POST['firstname'] lastname = self.request.POST['lastname'] pwd = self.request.POST['password'] e_mail = self.request.POST['email'] user = User.objects.create(username=user_name, first_name=firstname, last_name=lastname, email=e_mail) user.set_password(pwd) try: user.save() user = authenticate(username=user_name, password=pwd) login(self.request, user) except Exception: pass else: return HttpResponseRedirect(reverse('blog:testindex')) In the first function, it used data stored in request and in the second one, it used self.request, both work functionally. What's the difference? Thanks for your answers. -
Time zone issue with Django
I set the TIME_ZONE setting to UTC first. But now I want to remove it and be able to have different time zones for my users. When restarting the gunicorn and nginx it is still the same. The posts are 2 hours later than it should be. This is what I got in the DB: publish_date ------------------------------- 2016-09-21 09:08:40+00 2016-09-08 09:36:35+00 2016-09-07 09:08:42+00 2016-09-06 07:16:22+00 2016-09-06 01:50:58+00 2016-09-05 22:55:07+00 2016-09-05 16:22:37+00 2016-09-05 16:18:36.52146+00 2016-09-05 12:22:09.292926+00 2016-09-05 09:09:05+00 2016-09-04 19:00:12+00 2016-09-04 18:20:07.83214+00 2016-09-04 11:01:58+00 2016-09-04 10:02:29+00 2016-09-04 08:37:43.421796+00 2016-09-03 20:36:49+00 2016-09-03 13:42:06+00 2016-09-02 18:51:19+00 2016-09-02 18:36:16+00 2016-09-02 12:08:50+00 2016-09-02 10:33:28+00 2016-09-02 08:20:30+00 2016-09-02 08:18:36+00 2016-09-02 08:01:49.359479+00 2016-09-01 18:54:01.18064+00 2016-09-01 18:54:01.163647+00 2016-09-01 18:54:01.145824+00 2016-09-01 18:54:01.128807+00 2016-09-01 18:54:01.109296+00 2016-09-01 18:54:01.091886+00 2016-09-01 18:54:01.076142+00 2016-09-01 18:54:01.041784+00 2016-09-01 18:54:01.025924+00 2016-09-01 18:54:01.009529+00 2016-09-01 18:54:01+00 2016-09-01 18:54:00.988107+00 2016-09-01 18:54:00.971702+00 2016-09-01 16:58:54+00 2016-09-01 13:43:34+00 2016-09-01 13:38:35+00 2016-09-01 09:21:33+00 2016-09-01 09:17:41+00 2016-09-01 06:27:31+00 2016-08-31 22:41:13+00 2016-08-31 19:23:59.930632+00 2016-08-31 19:23:59.914006+00 2016-08-31 19:23:59.898492+00 2016-08-31 19:23:59.880307+00 2016-08-31 19:23:59.862554+00 2016-08-31 19:23:59.846515+00 (50 rows) It displays +00 which is UTC I think. It should however be GMT/UTC + 2:00. When checking postgresql (show timezone;): TimeZone ---------- UTC (1 row) What can I do about this and why is it happening? -
(Django) My "detailed" view page isn't working. The web page content is invisible
Hello I am trying to make a simply gallery app where the first view (listview) is a list of all the persons (which are the objects), and when a user clicks on one it proceeds to the next page with a given pk/id key. But when it comes to that page... the content is blank. Here is what I have: urls.py: urlpatterns = [ url(r'^$', ListView.as_view(queryset=Images.objects.all(), template_name='imgboard/home.html')), url(r'^imgboard/(?P<id>\d+)/$', views.voodoofunction, name='voodoofunction'), ] views.py (I feel like this is where the problem is): def voodoofunction(request, id=None): return render(request, template_name='imgboard/voodoo.html/') models.py class Images(models.Model): name_person = models.CharField(max_length=70) instagram = models.CharField(max_length=200) img_url = models.CharField(max_length=500) def __unicode__(self): return self.name_person class Meta: verbose_name_plural = 'Images' class Moreimages(models.Model): key = models.ForeignKey(Images, on_delete=models.CASCADE) img_url = models.CharField(max_length=500) def __unicode__(self): return str(self.key) class Meta: verbose_name_plural = "More Images" listview_code.html {% block content %} {% for object in object_list %} <p><a href="/imgboard/{{object.id}}">{{object.name_person}}</a></p> {% endfor %} {% endblock %} voodoo.html: {% block content %} <h2>{{ can }}<br></h2> <h4><a href="{{can.instagram}}">{{object.instagram}}</a></p></h4> <br> {% for object in object_list %} <p><img src="{{object.img_url}}", width=350, height="360></img>"</p> {% endfor %} {% endblock %} -
How to use rownum in mysql
In my case, I try to use this code for pa boardList = DjangoBoard.objects.raw('SELECT Z.* FROM(SELECT X.*, ceil( rownum / %s ) as page FROM ( SELECT ID,SUBJECT,NAME, CREATED_DATE, MAIL,MEMO,HITS \ FROM web_DJANGOBOARD ORDER BY ID DESC ) X ) Z WHERE page = %s', [rowsPerPage, current_page]) But, It's Oracle's code, Not for mysql. So, rownum has error. How can I do? -
how to reference angular component template from django app
I have the following angular component: angular. module('phoneList'). component('phoneList', { templateUrl: 'phone-list.template.html', controller: function PhoneListController() { this.phones = [ { name: 'Nexus S', snippet: 'Fast just got faster with Nexus S.', age: 1 }, { name: 'Motorola XOOM™ with Wi-Fi', snippet: 'The Next, Next Generation tablet.', age: 2 }, { name: 'MOTOROLA XOOM™', snippet: 'The Next, Next Generation tablet.', age: 3 } ]; this.orderProp = 'age'; } }); This template: templateUrl: 'phone-list.template.html', and the component are inside of my django app. I have placed the template in: myapp > templates > myapp > phone-list.template.html The reference gives me a 404 as well as angular error: http://127.0.0.1:8000/myapp/phone-list.template.html Do I need to create a django url entry? Do I need use a django url tag in the component? -
Forbidden (CSRF token missing or incorrect.) Django + AngularJs
When I try to render to my second page in my django framework I get following error. I think that there is something wrong with my url page and views.py but can't figure it out, nothing gives a step forward.. Forbidden (CSRF token missing or incorrect.): /renderbonds [06/Sep/2016 00:21:55] "POST /renderbonds HTTP/1.1" 403 2502 this is my html/django form <form action="{% url 'renderbonds'%}" method="post" > <input type="submit" value="calculate bonds" class='button expand radius'/> </form> Views.py python file: def home(request): tmpl_vars = { 'all_posts': Post.objects.reverse(), 'form': PostForm() } return render(request, 'pricing/bonds.html', tmpl_vars) def renderbonds(request): """render shortcut : http://stackoverflow.com/questions/10388033/csrf-verification-failed-request-aborted""" if request.method == 'POST': post_text = request.POST.get('the_post') response_data = {} post = Post(text=post_text, author=request.user) post.save() """DATA MEEGEVEN""" response_data['year'] = post.year response_data['cashflow'] = post.cashflow return HttpResponse( json.dumps(response_data), content_type="application/json" ) else: tmpl_vars = { 'all_posts': Post.objects.reverse(), 'form': PostForm() } return render(request,'pricing/bonds.html', tmpl_vars) my urls: urlpatterns = [ url(r'^$', views.calc,name='calc'), url(r'^$', views.home,'home'), url(r'^create_post/$',views.create_post,'create_post'), url(r'^renderbonds', views.home, name='home'), url(r'^/renderbonds', views.home, name='home'), url(r'^renderbonds/', views.home, name='home') ] -
How to reference Django application url in admin index template
I'm currently making changes to the admin/index.html template and I need to reference the url in my application using the name space 'hello' in a href tag for a link, but I'm having trouble doing at the admin level. The name of my application is clean and the url pattern in urls.py file is below. urls.py from django.conf.urls import url, include from . import views urlpatterns = [ url(r'^HelloWorld/$', views.hello, name='hello'), ] I'm trying to avoid hard coding the below href tag in admin/index.html. Any suggestions would be a great help <div> <h3>Hello World</h3> <a href="http://127.0.0.1:8000/clean/HelloWorld">Test</a> </div> -
Django. Customize action for model
I need to edit the "Add Object" action in the admin. It needs to redirect the user to a custom cause the logic required for adding objects is too complex to be managed in the admin. So, how do I make this possible? i.e: The picture shows a django-suit admin, but the question is the same. How can I make that button redirect to a custom url? Or, how can I create a similar button that redirects to a custom url (I could disable the default create and leave only the custom button).