Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Modify Django for loop every four iterations
I have a calendar generated by Django and styled with Bootstrap. Here is the code in the Django template : <div class="content"> {% for month in period.get_months %} <div class="col-md-3"> <div class="row row-centered"> <button class="btn btn-custom active" href="{% url "month_calendar" calendar.slug %}{% querystring_for_date month.start 2 %}">{{month.name}}</button> </div> <div> {% month_table calendar month "small" %} </div> </div> {% endfor %} </div> Now, since months have a different number of weeks they have different heights I would like to avoid something like this: I understand from this answer that the best solution would be to use a clearfix. So, how can I modify the for loop in my template so that Django inserts an extra line <div class="clearfix"></div> every four items? -
Localization Django-admin (translations)
I didn't find how I can translate the django admin. I found how to translate models, but I want to translate sentence that the django-admin uses, such as: Add model_name Home Delete Selected model_name Recent Actions Etc. How can I do it? -
How does django know which user owns what data?
If for example I want to show a zero(0) for all users to see, and I want all users to add one(1) to the number With their Identity only shown for superusers. And how to make sure that each user only can add one time, and of course what is the Security requirements that have to be done to prevent unautohrized Access to change any of this or to get any information? I understand this is a big topic, but could someone briefly explain for me what parts of Programming that are involved, and maybe some good books on these topics? Excuse me my English, and thanks for any help! -
Reverse for 'x' with arguments '(1,)' not found. 1 pattern(s) tried: ['grupe/(?P<grupa_id>[0-9]+)/(?P<elev_id>[0-9]+)/$']
I was trying to build a django app which would let me access some groups that contain student(elev) objects. I can't make Elev objects show, tho. Elevi urls.py from django.conf.urls import url from . import views app_name = 'elevi' urlpatterns = [ #/ url(r'^$', views.index, name = 'index'), #/Grupe/id url(r'^grupe/(?P<grupa_id>[0-9]+)/$', views.connect, name="connect"), #/Grupe/id/elevi_id url(r'^grupe/(?P<grupa_id>[0-9]+)/(?P<elev_id>[0-9]+)/$', views.elev_individual, name="elev_individual") ] Elevi views.py from django.shortcuts import render,get_object_or_404 from .models import Grupa,Elev def index(request): toate_grupele = Grupa.objects.all() context = {"toate_grupele" : toate_grupele} return render(request,'Elevi/test.html',context) def connect(request,grupa_id): grupa = get_object_or_404(Grupa, pk = grupa_id) return render(request,'Elevi/connect.html',{'grupa':grupa}) def elev_individual(request,elev_id): elev = get_object_or_404(Elev, pk = elev_id) return render(request,'Elevi/elev_individual.html',{'elev':elev}) test.html {% if toate_grupele %} <ul> {% for grupa in toate_grupele %} <li><a href ="{% url 'elevi:connect' grupa.id %}">{{ grupa.nume_grupa }}</a></li> {% endfor %} </ul> {% else %} <p>Nu sunt grupe salvate</p> {% endif %} connect.html <h1>{{ grupa.nume_grupa }}</h1> <h3>Lista Elevi:</h3> <ul> {% for elev in grupa.elev_set.all %} <li><a href="{% url 'elevi:elev_individual' elev.id %}">{{ elev.nume_elev }} {{ elev.prenume_elev }}</a></li> {% endfor %} </ul> elev_individual.html <p>{{ elev.nume_elev }} {{ elev.prenume_elev }}</p> -
Django DRF HyperLinkedRelatedField referencing a specific model's source id
In the TrackSerializer class below from serializers.py, I'd like to have a url field that creates a hyperlink to the related Artist.id but it's creating a hyperlink to the Track.id instead even when I specify queryset=Artist.objects.all() in the HyperLinkedRelatedField. How do I make a hyperlink to the Artist.id? models.py class Artist (models.Model): name = models.CharField(max_length=100) slug = AutoSlugField(populate_from='name', unique=True, slugify=custom_slugify,) def __str__(self): return self.name def get_absolute_url(self): return reverse("profiles:detail", kwargs={"slug": self.slug}) class Track (models.Model): artist = models.ForeignKey(Artist, related_name="tracks", on_delete=models.SET_NULL, verbose_name="Artist") title = models.CharField(max_length=100, verbose_name="Title") def __str__(self): return self.title serializers.py class TrackSerializer(serializers.ModelSerializer): artist = serializers.StringRelatedField() url = serializers.HyperlinkedRelatedField( queryset=Artist.objects.all(), source='id', ##I need Artist.id, not Track.id view_name='api:artist-detail', ) class Meta: model = Track fields = ('id', 'artist', 'url',) class ArtistSerializer(serializers.ModelSerializer): name = serializers.CharField() slug = serializers.SlugField() url = serializers.HyperlinkedRelatedField( source='id', many=False, read_only=True, view_name='api:artist-detail' ) tracks = TrackSerializer(many=True, read_only=True) class Meta: model = Artist fields = ('id', 'name', 'slug', 'url', 'tracks') views.py class TrackViewSet(viewsets.ModelViewSet): queryset = Track.objects.all() serializer_class = TrackSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly,) pagination_class = StandardResultsSetPagination class ArtistViewSet(viewsets.ModelViewSet): queryset = Artist.objects.all() serializer_class = ArtistSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly,) pagination_class = StandardResultsSetPagination -
How do I prefetch related objects for a list of already fetched ones?
I'm displaying 7 random objects on a home page. For that I use solution based on this answer: class ProductManager(models.Manager): def random(self, n_products, filter={}, select_related=None): n_products_total = self.filter(**filter).count() if n_products_total == 0: return [] r = [self.random_impl(n_products_total, filter, select_related) for i in range(n_products)] return [p for p in r if p is not None] def random_impl(self, n_products, filter, select_related=None): random_index = randint(0, n_products - 1) try: return self.filter(**filter) \ .select_related(select_related)[random_index] except IndexError: return None random_products = Product.objects.random(7, filter={'enabled': True}, select_related='category') If I pass prefetch_related=Prefetch('productphoto_set', queryset=ProductPhoto.objects.order_by('pk')) to random_impl method, it prefetches 1 photo at a time for each product. Which is not surprising. Can I prefetch related objects manually after products has already been fetched? -
Pass *args in django templates
I did use django pagination, but there is a problem with urls, here is my urls.py: `url(r'^/blog/$', blog_view.main, name='blog'), url(r'^/blog/page/(?P<page_id>\d{0,9})$', blog.post, name='blog_page'), My views.py: def post(request, page_id=None): posts = Posts.objects.all() pageid = page_id return render(request, 'base.html', {'posts': posts, 'pageid': pageid,}) My base.html which use bootstrap: {% url 'blog_page' as blog_page %} # Blog page need follow patterns <ul> {% for post in posts %} <li {% if request.path == htt://myblog.com/blog/page/5 %} class="active" {% endif %}>{{ post.title }}</li> # When I put blog_page django shows error. Help me how to put something to fix this condition. {% endfor %} </ul> -
How to tell django app where my react-ootstrap fonts are?
I am using react-boostrap and I want to use bootstrap glyphicons. Currently I haven't been able to render glyphicons on front-end.The issue that I've tracked down is that the fonts aren't being loaded from the correct URLs. Front-end is using this url http://0.0.0.0:8000/448c34a56d699c29117adc64c43affeb.woff2 [returns 404 obviously] it should have been: http://0.0.0.0:8000/static/448c34a56d699c29117adc64c43affeb.woff2 Here is my webpack.config.js. So how do I tell the front-end where to load the fonts from? -
Many-to-Many Misunderstanding in Django
I am new to web development so this question might not be straightforward but please bear with me. Im working on a social network in which a user could follow another user in two different ways...anwyways...i created two models to define the relationships. A many-to-many relationship as follows. How do i make this models totally independent of each other? so lets say a user could have 500Followers and 200Guests?? i used th javascript code below to toggle the follow button but its increases both. This might not be a great overview of the problem but thats because i am new to this. but please try. I am using django by the way. class Follower(models.Model): user_from = models.ForeignKey(User, related_name='rel_from_set') user_to = models.ForeignKey(User, related_name='rel_to_set') created = models.DateTimeField(auto_now_add=True, db_index=True) class Meta: ordering = ('-created',) def __str__(self): return "{} is now a following".format(self.user_from, self.user_to) class Guests(models.Model): user_fromt = models.ForeignKey(User, related_name='yel_from_set') user_tot = models.ForeignKey(User, related_name='yel_to_set') created = models.DateTimeField(auto_now_add=True, db_index=True) class Meta: ordering = ('-created',) def __str__(self): return '{} follows {}'.format(self.user_from, self.user_to) User.add_to_class('follows', models.ManyToManyField('self', through=Guests, related_name='guest', symmetrical=False)) User.add_to_class('follows', models.ManyToManyField('self', through=Follwer, related_name='guest', symmetrical=False)) View def user_follow(request): user_id = request.POST.get('id') action = request.POST.get('action') if user_id and action: try: user = User.objects.get(id=user_id) if action == 'follow': Contact.objects.get_or_create(user_from=request.user, user_to=user) create_action(request.user, … -
Django: Check JWT Token Validity After Changing Password In Server
I'm creating a django app which is basically an API for another android app. I'm using JWT for authentication. The situation is: user obtains a JWT token by giving his username and password. system admin changes that user's password in the django admin. the previous JWT token is till valid in the django app. How do I make the JWT token invalid if the password is changed in the server? How would the android app would know? -
Phantom Brackets in Ajax Call when sending an Array to Django
I am trying to send a normal javascript array through an Ajax call and something weird is happening. Here's my function: // Save new Strategy $('.tab-pane').on('click', 'button.saveStrat', function() { var stratType = $('#typeValue').val(); // Set by newEntry method in swot-nav.js var label = $('#newStratLabel').val(); // Form element in new_swot_modal.html var details = $('#newStratDetails').val(); // Form element edit_swot_modal.html var entries = []; // Build a list of SWOT entries that the user has identified as associated to this strategy. $('input.entryCheckbox[type=checkbox]').each(function () { if (this.checked) { entries.push($(this).val()); } }); console.log(entries); $.ajax({ url: '/add_swot_strategy/', type: "POST", data: { 'type': stratType, 'label': label, 'details': details, 'entries': entries }, dataType: 'json', success: function (data) { appendNewItem(data, swotType) } }); resetAddForm() }); And here is how my Django test server receives it: <QueryDict: {'label': [''], 'type': ['A'], 'details': [''], 'entries[]': ['16', '23', '26']}> What's with the extra brackets after the entries label? Is this intended behavior? Can I go ahead and do it this way or am I breaking the rules? -
Nginx Django after add SSL get too many redirects error
Fist of all sorry for my bad english. I'm having a problem configuring LetsEncrypt in my webapp, i make it work now i can access using https://www.myproject.com but if i try to use www.myproject.com, myproject.com or even https://myproject.com without the www i always get the error ERR_TOO_MANY_REDIRECTS. This is my nginx config in /etc/nginx/sites-available/myproject server { listen 80; listen [::]:80; server_name myproject.com www.myproject.com; return 301 https://$server_name$request_uri; } server { # SSL configuration listen 443 ssl http2; listen [::]:443 ssl http2; include snippets/ssl-myproject.com.conf; include snippets/ssl-params.conf; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/user; } location /media/ { root /home/user; } location /.well-known { alias /home/user/myproject/.well-known; } location / { include proxy_params; proxy_pass http://unix:/home/user/myproject.sock; } } I check a lot of questions like mine but in php projects try the solutions but still not found one to solve my problem. if helps i have to say that i have cloudflare free configure for my domain Thanks! -
how to use redirect at listview on django
I want to use redirect at listview on django. if user'name is yusl, he connect to www.photo.com/user/yusl, he can see his photo list. and if he connect to www.photo.com/user/dksdl, it makes him to redirect www.photo.com/user/yusl. but there are error. error is TypeError at /user/user/ context must be a dict rather than HttpResponseRedirect. Request Method: GET Request URL: http://ec2-13-124-23-182.ap-northeast-2.compute.amazonaws.com/user/user/ Django Version: 1.11.1 Exception Type: TypeError Exception Value: context must be a dict rather than HttpResponseRedirect. Exception Location: /home/ubuntu/my_env/lib/python3.5/site-packages/django/template/context.py in make_context, line 287 Python Executable: /home/ubuntu/my_env/bin/python Python Version: 3.5.2 Python Path: ['/home/ubuntu/project', '/home/ubuntu/my_env/lib/python35.zip', '/home/ubuntu/my_env/lib/python3.5', '/home/ubuntu/my_env/lib/python3.5/plat-x86_64-linux-gnu', '/home/ubuntu/my_env/lib/python3.5/lib-dynload', '/usr/lib/python3.5', '/usr/lib/python3.5/plat-x86_64-linux-gnu', '/home/ubuntu/my_env/lib/python3.5/site-packages'] Server time: Sun, 4 Jun 2017 17:41:21 +0000 this is my views.py class PhotoListView(ListView): model = Photo def get_context_data(self, **kwargs): username = self.kwargs['username'] User = get_user_model() user = get_object_or_404(User, username=username) if not user == self.request.user: return redirect('index') context = super(PhotoListView, self).get_context_data(**kwargs) context['photo_list'] = user.photo_set.order_by('-posted_on','-pk') return context this is urls.py url(r'^user/(?P<username>[\w.@+-]+)/$', PhotoListView.as_view(), name='photo-list'), -
How to take data from a form in order to search and filter in MongoDB
I am trying to take the data from a form in order to use that data as a filter and redirect to the page that contains the table with all the filtered data. I am using Django 1.10.5, Python 3.6 and MongoDB with Pymongo. I don't want to save the data of the form, I just need it for the filtering. This is what I have done: <---Views---> def BuscaProyecto(request): form = FormBuscaProyecto(request.GET or None) if form.is_valid(): datos = Proyectos.objects.filter(AñoPresentación__icontains=AñoPresentación & Status__icontains=Status) return render_to_response('busca_profesional.html', locals(), context_instance=RequestContext(request)) <---html---> <div id="Proyectos"> <form action="" method="post" role="form"> {% csrf_token %} <div class="col-xs-12 col-sm-12 centered"> <!-- Año de Presentación --> <div class="col-xs-3 col-sm-3 centered"> <div class="form-group"> <input name="AñoPresentación" type="date" class="form-control"/> </div> </div> </div> <div class="col-xs-12 col-sm-12 centered"> <!-- Status --> <div class="col-xs-2 col-sm-2 centered"> <label for="Status" class="control-label">Status</label> </div> <div class="col-xs-3 col-sm-3 centered"> <div class="form-group"> <select id="Status" name="Status" class="selectpicker form-control" data-width="100%" style="display"> <option value="APROBADO">Aprobado</option> <option value="DENEGADO">Denegado</option> </select> </div> </div> </div> <!-- Botón de Buscar --> <div class="centered"> <button type="submit" class="btn btn-primary btn-lg"> <span class="glyphicon glyphicon-search"></span> Buscar </button> </div> -
Using django authentication system with existing data
I have a very old cgi/perl system with a user table. The passwords are stored as output (computed hash) of 'crypt' function. I am looking to migrate the system to Django. I would like to keep the user data while using the Django table structure. One option would be to copy all the user/password data to 'auth_user' table and use a custom authentication function since I have existing passwords generated with crypt. Do I have a better option? Also, if I go with the option I have described above, how can this be implemented? -
Getting a list of authors with the numbers or counts of their respective posts in django
I'm trying to get author's list from my post model which has a field (author_name) related to the author model with a (ForeignKey).Using Post.objects.all() gets the list alright, but if I have a John Doe (Author) with 3 posts, I get John Doe listed three times with the respective post title. What I want is to list John once with numbers (count) of his posts so far. Thanks. -
beginner django -> retrieve data from SQL db
So, I just followed a tutorial that helped me set up my Django project, online. The "templates" are now available online, on a VPS called "vultr". On the same server, I have a SQL database with some data. I would like to know how can I make one of my Django templates retrieve the data from the SQL database and show them? I've tried looking up on Google, but I'm still a beginner and it's really too hard for me to understand and pick the rights info's that fits me. Thanks -
Django aggregation to retrieve queryset based on identical start and end times
I have a model which looks like this: class Event(models.Model): date = models.DateField(blank=True, null=True) start_time = models.TimeField(blank=True, null=True) end_time = models.TimeField(blank=True, null=True) I am trying to compose a single line command which would retrieve a list or query set of all Event objects in my database, where every element in a subset is grouped by an identical date, start_time, and end_time, and the elements of each subset should be ordered by start_time. I have been trying to use Django aggregations, but unable to get things to work right. Is this possible with aggregations, and if so, how would I do it best? -
Parsing and displaying nested JSON in Django Template
I am trying to print the results of an API call which is returning JSON results nested relatively deeply. I am doing this project with Python 2.7 and Django 1.11. I have the following view.py function: def nlu_analysis(request): if request.method == 'POST': text2send = request.POST.get('text2send') natural_language_understanding = NaturalLanguageUnderstandingV1( version='2017-02-27', username='####', password='####') response = natural_language_understanding.analyze( text=text2send, features=[features.Entities(), ..., features.SemanticRoles()]) return render(request, 'watson_nlu/analysis.html', {'data': response}) When I use the following template code in my .html file: {% for k in data.keywords %} <p>Text - {{ k.text }}</p> <p>Relevance - {{ k.relevance }}</p> {% endfor %} to parse and display JSON with one level of nesting like this: 'keywords': [{ 'relevance': 0.946673, 'text': 'eyes' }] Everything is great and it displays 'eyes' and 0.946673 as expected. I can't figure out the appropriate syntax for getting to the 'anger', 'joy', etc. results that are nested more deeply such as this: { 'emotion': { 'document': { 'emotion': { 'anger': 0.195192, 'joy': 0.082313, 'sadness': 0.644314, 'fear': 0.207166, 'disgust': 0.103676 } } } What is the most efficient method for accomplishing this objective? It is definitely NOT: <p>Anger - {{ data['emotion.document.template.anger'] }}</p> Advance newbie gratitude and good juju for your help. -
security user registration django rest endpoint
I want to implement a user registration endpoint using django rest framework. The endpoint would be public and anyone could potentially register a new user to be able to access the restricted version of the site. The registration endpoint would take a POST action and a JSON object containing let's say first name, last name, email and password. The problem is because of the nature of the endpoint being public someone could program a pyCurl script to create a bunch of new users, I want to avoid that. How can I secure my endpoint properly to avoid that? I have no idea at the moment on what course of action to take. I could make a registration page using CSRF and a django template. That could be a solution and let the rest of the application could run under angular2. Ideally I want to avoid that. any ideas? thanks -
In Django,how do I keep track of the changes every time a user makes to the objects of a class and how do I copy the changes to another class?
Employee Management System In this code everytime I delete an object of the Class employee i want to copy the fields name and num to the object of Class left.And every time I make changes to each field i.e. Post and Salary , for the object of Class employee, i want copy to changes to Sal and Post of Class Salary1. from django.db import models class employee(models.Model): name=models.CharField(max_length=100) num=models.CharField(max_length=200) address=models.CharField(max_length=200) post=models.CharField(max_length=300) salary=models.CharField(max_length=200) def __str__(self): return self.name+' - '+self.post class salary1(models.Model): employee=models.ForeignKey(employee,on_delete=models.CASCADE) Sal=models.CharField(max_length=1000) Post=models.CharField(max_length=100) class left(models.Model): nm=models.CharField(max_length=100) number=models.CharField(max_length=200) -
How to resolve an ImportError working with a graphene django basic setup through tutorial?
I have started working through the graphen_django tutorial for a basic setup using Django and GraphQL. However, I am unable to progress any further due to an import error: ImportError at /graphql Could not import 'cookbook.schema.schema' for Graphene setting 'SCHEMA'. ImportError: No module named schema. Request Method: GET Request URL: http://127.0.0.1:8000/graphql Django Version: 1.11.2 Exception Type: ImportError Exception Value: Could not import 'cookbook.schema.schema' for Graphene setting 'SCHEMA'. ImportError: No module named schema. Exception Location: /home/mackie/Code/graphene_django_tutorial/env/local/lib/python2.7/site-packages/graphene_django/settings.py in import_from_string, line 78 Python Executable: /home/mackie/Code/graphene_django_tutorial/env/bin/python Python Version: 2.7.12 Python Path: ['/home/mackie/Code/graphene_django_tutorial/cookbook', '/home/mackie/Code/graphene_django_tutorial/env/lib/python2.7', '/home/mackie/Code/graphene_django_tutorial/env/lib/python2.7/plat-x86_64-linux-gnu', '/home/mackie/Code/graphene_django_tutorial/env/lib/python2.7/lib-tk', '/home/mackie/Code/graphene_django_tutorial/env/lib/python2.7/lib-old', '/home/mackie/Code/graphene_django_tutorial/env/lib/python2.7/lib-dynload', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/home/mackie/Code/graphene_django_tutorial/env/local/lib/python2.7/site-packages', '/home/mackie/Code/graphene_django_tutorial/env/lib/python2.7/site-packages'] Server time: Sun, 4 Jun 2017 16:29:46 +0000 You can see the current state of the code here in a minimal repo. I think that my problem has something to do with how I'm running the server: python3 manage.py runserver. Or maybe how I am importing. But I don't know how to do any more debugging from here. Everything is exactly as stated in the tutorial and nothing seems especially incorrect to me. I'm using Linux with virtualenv as well if that matters. Let me know if you need any more information I'll be carefully monitoring the thread. -
can not show angular apps data in django template
Please help me to solve this problem.This angular code works locally but can not work in django template. I call this static files end of the body of base.html <script src="{% static "js/angular.min.js" %}"></script> <script src="{% static "js/restangular.min.js" %}"></script> <script src="{% static "js/angular-ui-router.min.js" %}"></script> This is contactlist.html <div id="contactlist" ng-app="newApp"> <div class="container" ng-controller="angCtrl"> <h1 class="text-center">Search contact for {{myModel}}</h1> <form> <div class="input-group"> <input type="text" class="form-control" ng-model="myModel" placeholder="Search Contact"> <div class="input-group-btn"> <button class="btn btn-default" type="submit"> <i class="fa fa-search"></i> </button> </div> </div> </form> <div class="all"> <table class="table table-hover text-center"> <thead> <tr> <th class="text-center">Id</th> <th class="text-center">Name</th> <th class="text-center">Contact Number</th> </tr> </thead> <tbody> <tr ng-repeat="contact in contactlist | filter:myModel | orderBy: 'name'"> <td>{{contact.id}}</td> <td>{{contact.name}}</td> <td>{{contact.contact}}</td> </tr> </tbody> </table> </div> </div> </div> This is app.js var app = angular.module('newApp', []); app.controller('angCtrl', function($scope) { $scope.name = ""; }); app.controller('angCtrl', function($scope) { $scope.contactlist = [ {id:'1',name:'raisul',contact:'+8801723844330'}, {id:'2',name:'Rafikul',contact:'+8801723564330'}, {id:'3',name:'Shariful',contact:'+8801726864330'}, {id:'4',name:'kamarul',contact:'+8801723764330'}, {id:'5',name:'Ashraful',contact:'+8801728864330'}, {id:'6',name:'Jamarul',contact:'+8801723964330'}, {id:'7',name:'Rahul',contact:'+8801723861330'}, {id:'8',name:'Rashidul',contact:'+8801725864330'}, ] }); It shows the table element but can not show any data -
Django get or create with a ForeignKey error: "No such table"
Before i try to add data to my database (Django = 1.9.5). I want to check if it's already exists. Soo using the get_or_create function should be the function i need right? However it doesn't work somehow. Here are my classes: models.py: from django.db import models class Reporter(models.Model): first_name = models.CharField(max_length=30) class Article(models.Model): article_name = models.CharField(max_length=100) reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE) fillDatabase.py from secondDbApp.models import Reporter,Article def addEntry(first_name, article_name): rep, created = Reporter.objects.get_or_create(first_name=first_name) if created: rep.save(using="secondDb") obj, created = Article.objects.get_or_create(article_name=article_name,reporter= rep) if created: obj.save(using="secondDb") print("good") else: print("bad") else: print("bad") tests.py from secondDbApp.fillDatabase import addEntry addEntry("John","ArticleName") Here is what i do (my database doesn't exist yet) soo: makemigrations secondDbApp migrate --database=secondDb test secondDbApp And this is the error: django.db.utils.OperationalError: no such table: seconddbapp_reporter Trying to add data the "normal" way works though. Soo something like this: rep = Reporter(first_name=first_name) rep.save(using="secondDb") I don't understand whats wrong with my database. Thank you! -
Django: proper way to handle form with POST to the same page
I am new to Django and have completed the 7 part tutorial on their website. Part four of their tutorial introduces a form on the page details which posts to votes (a view that does not display anything) and then returns results on success or otherwise returns you to details. However, what if you had a page that you wanted to POST to itself (e.g. updating the value of something related to that page, which is calculated server side). Note: I have gotten this to work, but I would like to know if I am doing it right for I am confused about a few things. So the code for my page currently looks something like: def post_to_self_page(request, object_id): obj = get_object_or_404(Obj, pk=object_id) # if update sent, change the model and save it model_updated = False if 'attribute_of_obj' in request.POST.keys(): obj.attribute_of_obj = request.POST['attribute_of_obj'] obj.save() model_updated = True # do some stuff with obj # specify the context context = { 'obj': obj, } if model_updated: # good web practice when posting to use redirect return HttpResponseRedirect(reverse('my_app:post_to_self_page', args=(object_id,))) return render(request, 'my_app/post_to_self_page.html', context) so in this case when the view is first called I grab the object if it exists. Then I …