Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django : redirect depending on selected choice
Based on the Django official poll tutorial, I wish to redirect people depending on the selected choice on a form. models.py class Poll(models.Model): question = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') class Choice(models.Model): poll = models.ForeignKey(Poll) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) The template This template displays a form with four radio buttons. <h1>{{ poll.question }}</h1> {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %} <form action="{% url 'polls:vote' poll.id %}" method="post"> {% csrf_token %} {% for choice in poll.choice_set.all %} <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" /> <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br /> {% endfor %} <input type="submit" value="Vote" /> </form> views.py This view with the vote function redirects def vote(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) try: selected_choice = p.choice_set.get(pk=request.POST['choice']) except (KeyError, Choice.DoesNotExist): # Redisplay the polls voting form. return render(request, 'polls/detail.html', { 'polls': p, 'error_message': "You didn't select a choice.", }) else: selected_choice.votes += 1 selected_choice.save() # Always return an HttpResponseRedirect after successfully dealing # with POST data. This prevents data from being posted twice if a # user hits the Back button. return HttpResponseRedirect(reverse('polls:results', args=(p.id,))) How can I set a condition on this vote function to render different templates depending on the selected_choice? -
Unable to find the solution for this error : Django: django.db.utils.IntegrityError: NOT NULL constraint failed: book_comment.related_post_id
In short: I have created a Post model and Comment model and created a comment form, I am serving a single url which will show all posts, related comment and a comment form to enter new comments. With a submission page is reloaded with new comments. But when I submit the comment I get the error: django.db.utils.IntegrityError: NOT NULL constraint failed: book_comment.related_post_id This is one answer that looked promising but I am unable to do something. I think it is not getting parent post id. Long Version: This is my model File: def user_image_path(instance, filename): return f"profile/user_{random.randint(1,1000)}_{filename}" class Post(models.Model): post_title = models.CharField(max_length=250) post_creator = models.CharField(max_length=150) creator_pic = models.ImageField(upload_to=user_image_path) post_body = models.TextField() post_created = models.DateTimeField(auto_now_add=True) post_updated = models.DateTimeField(auto_now=True) def __str__(self): return f"{self.post_title} **{self.post_creator}**" class Comment(models.Model): related_post = models.ForeignKey(Post, related_name="comments") comment_creator = models.CharField(max_length=150) comment_body = models.CharField(max_length=1024) comment_created = models.DateTimeField(auto_now_add=True) comment_updated = models.DateTimeField(auto_now=True) def __str__(self): return f"{self.comment_creator}" This is my form: from django import forms from .models import Post, Comment class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ['comment_creator', 'comment_body'] This is views: from django.shortcuts import render, HttpResponseRedirect,reverse from .models import Comment, Post from .forms import CommentForm # Create your views here. def servePage(request): if request.method == 'POST': form = CommentForm(request.POST) if … -
How to pass value to field of form in Django template if the value depends by the value of another variable in the same loop?
I tried to pass default value to a form in loop. The Value depends by the value of another variable in the same loop. My code: forms.py class BuildingForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.building_type = kwargs.pop('building_type') self.town = kwargs.pop('town') super(BuildingForm, self).__init__(*args, **kwargs) self.fields['building_type'].initial = self.building_type self.fields['town'].initial = self.town class Meta: model = Building fields = ('ap', 'building_type', 'town') views.py As I understand I should change building_type=building_list. This is list, but I need one string for every iteration. def town(request): user_town = (Town.objects.filter(character__user=request.user)) building_list = Building.objects.filter(building_type__building__town__character__user=request.user) defence = list((BuildingType.objects.filter(building__town__character__user=request.user) .aggregate(Sum(F('defence')))).values())[0] if request.method == "POST": form = BuildingForm(request.POST, building_type=building_list, town=user_town[0]) if form.is_valid(): ap = form.save(commit=False) ap.save() return redirect('town/town.html') else: form = BuildingForm(building_type=building_list, town=user_town[0]) return render(request, 'town/town.html', {'user_town': user_town, 'building_list': building_list, 'defence': defence, 'form': form}) template should be like ( I know that this isn't work): {% for building in building_list %} {{ building.building_type.name }}</b>; needs ap: {{ building.building_type.cost }}; current ap: {{ building.ap }} {{ form.building_type=building.building_type.id }} {% endfor %} In the end the page must be like: this html page Any idea how to do this? -
Inserting multiple related model values in template with for loop
I am trying to post multiple values from different models in a for loop in a template. It is not doing what I am planning. I want to display a count of LeadActions that belong to Leads in a table. I did comment the part out that is not working as well. The table should display the list of Leads and the the count of how many overdue actions(LeadActions) there are for that specific lead. My View class LeadListView(LoginRequiredMixin, generic.ListView): login_url = '/scrty/login/' template_name = "nodiso/leadslist.html" model = models.Leads def get_context_data(self, **kwargs): ctx = super(LeadListView, self).get_context_data(**kwargs) ctx['actions']= models.LeadActions.objects.all() return ctx def get_queryset(self): return models.Leads.objects.filter(company=self.request.session['compid'],archive=False) My template <table class="table"> <thead> <th>Name</th> <th>Overdue Tasks</th> <th>Total Tasks</th> </thead> {% for lead in leads_list %} {# {% for action in action_list %}#} <tr> <td><a href="{% url 'nodiso:leaddetail' lead.id %}">{{lead.name}}</a></td> <td><span class="badge">{{ actions.name|length }}</span></td> <td><span class="badge">42</span></td> </tr> {# {% endfor %}#} {% endfor %} </table> The Models class LeadActions(models.Model): lead = models.ForeignKey(Leads) name = models.CharField(max_length=265) crdate = models.DateField(auto_now_add=True) Duedate = models.DateField() creator = models.CharField(max_length=265) overdue = models.IntegerField(null=True,blank=True) def __str__(self): return self.name class Leads(models.Model): company = models.ManyToManyField(Company) user = models.ManyToManyField(settings.AUTH_USER_MODEL) name = models.CharField(max_length=265) email = models.EmailField(max_length=265) tel = models.IntegerField() archive = models.BooleanField(default=False) dateenq = models.DateField(auto_now_add=True,null=True) def … -
Django multi modelform into one from in html page
I use the Django built-in models.User as basic user model, plus a model called Profile containing other user information, which has a one-to-one field relation to User. class Profile: user = models.OneToOneField(User) nickname = models.CharField() bio = models.CharField I would like to use modelform for both model in the register view. And in the register page, the html form literally contains field in both User and Profile, and this form will be submitted with all params in the POST, which means in the view function I have to handle two modelform with one POST params dictionary. I have no idea how to implement this view function. -
Pipenv in production: how to recreate a new environment from scratch
I am currently considering the switch from pip / virtualenv to pipenv for my web projects (mainly Django). I still lock on one specific point of my workflow. TL;DR Is there a pipenv command to create a new environment from scratch (new interpreter, no packages), then install the dependencies, then set it as the default for the current directory ? Let's take a quick example. I have a project installed on my debian server, with the following structure: /srv └── project ├── .git/ ├── etc/ ├── sources/ ├── venv_20170922/ └── venv -> venv_20170922 Currently when I need to deploy it, I want to limit as most as possible the duration the website is offline. Please see this simplified views of steps I usually follow (indentation is here only to help understanding the process): cd /srv/project git pull virtualenv -p python3 venv_20171015 source venv_20171015/bin/activate pip install -r sources/requirements.txt pushd sources python manage.py migrate python manage.py collectstatic popd deactivate supervisorctl stop myproject # Now the website is offline ln -f -s venv_20171015 venv supervisorctl start myproject # Now the website is back online With this process, the website is offline only a few moment, only the time needed to stop, to update … -
Ajax success applies to all elements, how to avoid it?
I'm doing a small project, learning how to use Ajax and it turned out to be a little uncomfortable, when I press the like button, the counter increases or decreases in all the elements, for example if I like to question 1, in the question 2 and 3 also change the like and put the same counter as the one in question 1 and this changes with the same value of question 1 for all questions, How can I avoid it? This is my script $(".like-button").click(function(e){ e.preventDefault(); $.ajax({ type: 'POST', url: "/like/", data: {'slug': $(this).attr('name'), 'csrfmiddlewaretoken': '{{csrf_token}}'}, dataType: "json", success: function(response){ sl = $(".show-likes"); sl.html(response.likes_count); }, error: function(rs, r){ alert(rs.responseText); } }); }); this is my html template {% for tweet in tweets %} <!--Card--> <div class="card col"> <!--Card content--> <div class="card-body"> <!--Title--> <h4 class="card-title">{{tweet.title}}</h4> <!--Text--> <p class="card-text">{{tweet.text}}</p> <button type="button" name="{{tweet.slug}}" class="btn btn-primary like-button">Likes <span class="show-likes"> {{tweet.total_likes}} </span> </button> </div> </div> <hr> {% endfor %} Inside of like button I got a for show "total_likes" And how could I add a little more realtime to this? I'm using Django as Backend. Thank you very much for your time and have an excellent day. -
Pycharm with django throws ImportError: cannot import name 'unittest'
I am working through the django Tutorial, and am trying to get the test cases to run with pycharm. I have encountered a problem however. When i run the command: app test i am faced with this exception: test framework quit unexpectedly: F:\programming\Python\python.exe "F:\programming\JetBrains\PyCharm 2017.2.4\helpers\pycharm\django_test_manage.py" test a F:\programming\Projects\pycharm\untitled Testing started at 4:54 PM ... Traceback (most recent call last): File "F:\programming\JetBrains\PyCharm 2017.2.4\helpers\pycharm\django_test_manage.py", line 157, in <module> utility.execute() File "F:\programming\JetBrains\PyCharm 2017.2.4\helpers\pycharm\django_test_manage.py", line 110, in execute from django_test_runner import is_nosetest File "F:\programming\JetBrains\PyCharm 2017.2.4\helpers\pycharm\django_test_runner.py", line 42, in <module> from django.utils import unittest ImportError: cannot import name 'unittest' Process finished with exit code 1 Apparently, the django_test_manage.py file does not work. How can i fix this? this happens even when the test.py class is empty. So it must be a problem with pycharm then(?) I am using Pycharm Pro 2017.2.4, Django 2.0 and Python 3.6 My run/debug configurations are just the basic, preset Django Settings that pycharm does thank you!! -
Celery scheduled tasks with expiration time for each task instance?
I have a django app with celery 4.1.0 and celery beat with database scheduler. What I want is to run periodic tasks from admin site and set expiration time for each of this tasks. expire property in PeriodicTask is a time scheduler stops creating new messages for that task but i want the expiration to revoke tasks which are scheduled but are older than some value e.g. one hour. how to do this? I am really confused with celery documentation and differences between different versions of it. -
NoReverseMatch at /account/profile
I'm getting the following error message when attempting to run a JS function and Ajax click call on a button press. NoReverseMatch at /account/profile/ Reverse for '' not found. '' is not a valid view function or pattern name. I know it's because the url, but i'm not sure what is incorrect with my url. in the JS my var is defined as var url = '{% url requestaccess %}'; in the ajax i'm attempting to call the url using: $.ajax({ url: url, data: JSON.stringify({ report_id: SelectedItems }), dataType: 'json', type: 'post', success: function (data) { The URL.py is setup as: url(r'^requestaccess/$', views.requestaccess, name='requestaccess') My entire block of code is: <script> $(document).ready(function () { var SelectedItems = []; $('.checkbox').click(function () { var SelectedItems = $(this).val(); var index = SelectedItems.indexOf(SelectedItems); var url = '{% url requestaccess %}'; if (index == -1) { SelectedItems.push(SelectedItems); } else { SelectedItems.splice(index, 1); } }); $('#submit-button').click(function (event) { event.preventDefault(); $.ajax({ url: url, data: JSON.stringify({ report_id: SelectedItems }), dataType: 'json', type: 'post', success: function (data) { } //missing comma before closing curly brace }); }); }); </script> -
Failed to generate or install certificate
I am using Zappa to deploy to my Django code to AWS Lambda. In that process I have to renew my Domain SSL certificate as it has expired. I tried to create new by doing So I tried to create a new SSL key by doing $ openssl genrsa 2048 > account.key; And Added my Domain name and Path to zappa_settings.json file. I tried to run $ zappa certify production This is what the Error I am getting $ zappa certify production Calling certify for stage production.. Are you sure you want to certify? [y/n] y Certifying domain xxxx.domain.com .. Error registering: 400 { "type": "urn:acme:error:malformed", "detail": "Provided agreement URL [https://letsencrypt.org/documents/LE-SA-v1.1.1-August-1-2016.pdf] does not match current agreement URL [https://letsencrypt.org/documents/LE-SA-v1.2-November-15-2017.pdf]", "status": 400 } Failed to generate or install certificate! :( ============== I find the link https://letsencrypt.org/documents/LE-SA-v1.2-November-15-2017.pdf has nothing but "404 Not Found" Error. what is the problem ? And also do we have to run $ zappa certify everytime we need to renew the certificate ? -
All-auth / Crispyform : Error messages not displayed
I'm working on the all-auth authentification process of my website and I encounter a problem: I can't see the error messages of the login / signup views, when I do something wrong (bad password, not typing same password in signup for ex.) the page just reload. Views.py class CustomLogin(LoginView): """ Custom login view from Allauth """ def get_context_data(self, **kwargs): context = super(CustomLogin, self).get_context_data(**kwargs) context.update({'title': self.title, 'help_text': self.help_text}) return context title = 'Connectez-vous' help_text = 'Veuillez rentrer votre login et votre mot de passe pour vous connecter.' form = CustomLoginForm template_name = "allauth-custom/allauth-card.html" Forms.py class CustomLoginForm(LoginForm): def __init__(self, *args, **kwargs): super(CustomLoginForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_id = 'signup_form' self.helper.form_class = 'signup' self.helper.form_method = 'post' self.helper.form_action = reverse('thankyou') # and then the rest as usual: self.helper.form_show_errors = True self.helper.form_show_labels = False self.helper.add_input(Submit('Log in', 'log in')) Template {% extends "base.html" %} {% load socialaccount %} {% load bootstrap3 %} {% load crispy_forms_tags %} {% load i18n %} {% bootstrap_messages %} {% block content %} <section id='masthead'> <div class="container "> <div class="row justify-content-center"> <div class="card col-6 "> <div class="card-body"> <h4 class="card-title">{{title}}</h4> <p class="card-text">{{help_text}}</p> {% if form.errors %} <div class="alert alert-danger"> {% for field in form %} {% for error in field.errors %} <strong>{{ … -
Render Foreign Key in template as Checkboxes instead of Select in Django
Say we have this Model: class Event(models.Model): name = models.CharField('Nome do evento', max_length=50) code = models.CharField('Código de entrada', max_length=10) artists_list = models.ForeignKey(ListGroup, on_delete=None, related_name='lists_names', null=True) and this View class HomeView(LoginRequiredMixin, TemplateView): template_name = 'home.html' def get_context_data(self, **kwargs): context = super(HomeView, self).get_context_data(**kwargs) context['form'] = CreateEventForm(self.request.POST or None) context['defaultTitle'] = 'Novo Evento' context['formTitle'] = 'Criar' return context def post(self, request, *args, **kwargs): context = self.get_context_data(**kwargs) form = context['form'] print(form) if form.is_valid(): form.save() return self.render_to_response(context) and this Form class CreateEventForm(forms.ModelForm): class Meta: model = Event fields = ('name', 'code', 'artists_list',) Everything works great, but I would like to be able to select multiple entries that my Foreign key will retrieve. So I would like to render each entry as a checkbox instead of a select. How can I achieve that? I already searched a lot and only found about general charfields, nothing about Foreing Key Here's how its rendering -
Django: Switched from single-settings file to multi-settings package, now I get: AttributeError: module 'core.settings' has no attribute '...'
I have a settings folder under core module with an __init.py and a prod.py, dev.py, base.py. I added a variable to my base.pycalled SITE_DIRECTORY. Then, I modify this variable in my dev.py which is set as my DJANGO_SETTINGS_MODULE through an ENV variable. When I run the following code: from core import settings urlpatterns = [ url(r'^' + settings.SITE_DIRECTORY, include('frontend.urls'), name='frontend'), url(r'^' + settings.SITE_DIRECTORY + 'admin/', admin.site.urls), url(r'^' + settings.SITE_DIRECTORY + 'static/(?P<path>.*)$', views.serve), ] I get: AttributeError: module 'core.settings' has no attribute 'SITE_DIRECTORY' I have no idea why... Since I am now using a multi-settings package, do I have to change my import statement from from core import settings to something else? -
Django running on http://127.0.0.1:8000/ instead of my website
Django running on http://127.0.0.1:8000/ instead of my website when i try to run python manage.py runserver Validating models... 0 errors found November 15, 2017 - 19:51:37 Django version 1.6.11.6, using settings 'connect_eko.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. but i have installed django application in website. -
jQuery $(this).change (Show another element if current input was changed)
I want to show one element if current input was changed. $('.type_number') .change(function () { $(this) $('.check-update').css('display', 'block') }) html How to say jquery if current was changed show another element This creates a difficulty for me and besides I can not figure out how to do it. Please explain me if someone knows about it -
How to resolve inconsistent annotation in Django?
I have the following 2 lines of code: CategoryContextSum = CategoryContext.annotate(Total_Revenue=Sum('revenue')).order_by('-Total_Revenue') CategoryContextAvg = CategoryContext.annotate(Average_Revenue=Avg('revenue')).order_by('-Average_Revenue') The avg query yields a querylist of objects where the category comes first, followed by the revenue. So basically: [SomeCategory, avgrevenue],[OtherCategory, avgrevenue] The sum query on the other hand yields the revenue followed by the category, so basically: [sumrevenue, SomeCategory],[sumrevenue, OtherCategory] Now I have tried flipping the queries around and changing the variable names so far, but I cannot seem to figure out why in the heck these 2 statements are behaving so differently. Does anybody know what could influence annotation behavior in Django? -
Django-Rest-Framework APIView returning a model object and an image
suppose that I want to return in a APIView.get a (non model) object conatining 2 properties, one of them is a model object, and the other is a binary Image I've tried several ways and had problems with serializer. thanks! Serializer: class MyCustomSerializer(serializers.ModelSerializer): class Meta: model = MyCustom fields = '__all__' View: class MyCustomGet(APIView): def get(self, request, format=None): serializer = MyCustomSerializer obj = s.get_custom() return Response({"obj": serializer(obj.obj).data, "image": obj.image}) get_custom: class CustomClass: obj = None image = None def get_custom(): r = CustomClass() r.obj = MyCustom.objects.all().first() r.image = PIL.Image.open('file/path.png') return r -
How to use custom models in Django?
Followed the Django Quickstart tutorial here and it all worked wo/ problems. Now when I added a custom APIView I started having trouble. Namely the custom models I created. Here is my views.py class ValuationDetails(APIView): def get(self, request, format=None): serializer = ValuationRequestSerializer(data=request.data) if serializer.is_valid(): return Response('Valuation report', status=status.HTTP_201_CREATED) Here is my ValuationRequestSerializer: class ValuationRequestSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = ValuationRequest fields = ('street', 'number', 'latitude', 'longitude') Here is my ValuationRequest: from django.db import models class ValuationRequest(models.Model): def __init__(self, street, number, latitude, longitude): self.street = street self.number = number self.latitude = latitude self.longitude = longitude The first exception was: RuntimeError: Model class valuationservice.valproperty.model.val_models.ValuationRequest doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. Then I added in the setting.py INSTALLED_APPS a line 'valuationservice.valproperty.model.val_models' The second exception after that was: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. I guess there are two questions: How can I use custom models in Django? What is missing that the Django doesn't like by throwing the first exception? Python version 2.7.12 Thanks! -
django authentication with 3 attributes
I would like to have 3 attribute authentication in my Django app company name (company model) username (user model) password (user model) reason for this is that i want to have unique company name and username IS ONLY unique for each company. (meaning can have duplication of username) Currently, its username and password (https://imgur.com/a/W6IwQ) authentication, using auth_views from django.contrib.auth import views as auth_views my sign in html https://gitlab.com/firdausmah/railercom/blob/master/railercomapp/templates/employee/sign_in.html <form method="POST"> {% csrf_token %} {% bootstrap_form form %} <button type="submit" class="btn btn-pink pull-right">Sign In</button> </form> Here are my current model: https://gitlab.com/firdausmah/railercom/blob/master/railercomapp/models.py class Company(models.Model): name = models.CharField(max_length=30) class Employee(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='employee') company = models.ForeignKey(Company) https://gitlab.com/firdausmah/railercom/blob/master/railercom/urls.py urlpatterns = [ ... url(r'^employee/sign-in/$', auth_views.login, {'template_name': 'employee/sign_in.html'}, name = 'employee-sign-in'), url(r'^employee/sign-out/$', auth_views.logout, {'next_page':'/'}, https://gitlab.com/firdausmah/railercom/blob/master/railercomapp/views.py views that requires login, so how am I to handle this as well. there is no definition for sign-in since its handled by django.contrib.auth @login_required(login_url='/employee/sign-in/') def employee_home(request): return render(request, 'employee/home.html', {}) What do I need to do to change this ? (accepting 3 attributes for authentication) Do I need to create a separate model for authentication model ? If I create a separate authentication model how do I handle urls that requires login using the new authentication model like … -
Bootstrap footer is not at the bottom of any page
I've seen a few of these on Stack Overflow, but the questions that have been asked don't lead to an answer which solves my issue. Please take the time to look over my code before marking it down or flagging it as a duplicate. I'm working through a book called "Beginning django CMS". I'm finding that a few parts are out of date, and that might be the issue here. It's tough for me to say because I'm new to web design. The footer isn't in a <div>, and I've gone over the padding to see if that helps. Those are the kinds of issues that come up as answers to questions that have previously been posted on Stack Overflow. I'm being left with a footer which begins ends an inch from the bottom of the screen. Does anyone know what might be causing this? I've checked this in Chrome and Edge so far, both come up with the indent. Here's the HTML: {% load cms_tags staticfiles sekizai_tags menu_tags %} <!doctype html> <html> <head> <meta charset="utf-8"> <meta http-equiv"X-UA-Compatible" Content = "IE=Edge"> <meta name = "viewport" content="width=device-width", initial-scale=1> <link rel="icon" href="favicon.ico"> <title>{% block title %}MyBlog Title{% endblock title %}</title> <link href="https://cdnjs.cloudfare.com/ajax/libs/twitter-bootstrap/3.3.4/css/bootstrap.min.css" … -
Redirect to same page from two forms POST method in django
I am trying to save data from two forms which are on the same html template.After saving the data i want to stay on the same page. This is my urls.py: urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^register/$',views.register, name='register'), url(r'^login/$',views.login_view, name='login'), url(r'^register/success/$',views.register_success, name='register_success'), url(r'^category/$',views.get_category,name='getcategory'), url(r'^#/$',views.save_bookmark,name='savebookmark'), url(r'^#/$',views.save_tag,name = 'savetag'), url(r'^home/$',views.home,name='home'), ] save_bookmark and save_tag are the two views which are being called on the two form submit buttons. But when i click on the submit button of the second form which should call save_tag, it is going to the save_bookmark view probably because of the same url action and i get this error: NOT NULL constraint failed: bookmark_userbookmark.bookmark So how can i stay on the same page/url by clicking on these two submit buttons. -
django forms: could not get manually added(HTML) nested object fields
I am trying to implement django admin like inline addition of related objects in my app. Totally new to django but I am experienced with ROR and Laravel and happen to be good with ajax, so I don't want to go into nested formsets from django and want to add related objects form using ajax as I would traditionally do in anywhere else. Just be careful about naming of input fields so you can get them on controller side nicely in an array. In form.html I am simply adding something like this; <label class="control-label">Name</label> <input name="items[1][name]" class="form-control"/> <label class="control-label">Attr</label> <input name="items[1][attr]" class="form-control"/> This is just an example to give you visual of how my html is generated. I've mutiple items in my form. Traditional on server side I would get a form object(request input) like this; at-least in Laravel [form=> [ "some_attr"=>"val", "items"=> [ "1"=> [ "name"=>"some name", "attr"=> "some val" ] ] ] ] The main point here is that I would get and array of items in my request on controller side and can iterate over it. PROBLEM I am doing everything same as described above but when I am trying to access data from controller side. It … -
How Can I perform "read from random", "write to all" in Django Multiple Database System
I want to create replica of my primary database in django. I have done some searching and found this. Here I found that how to read from random database, but my question is that how can I perform write operation on all databases(primary+replica)? Or any way to sync both databases after each write. -
Django OAuthToolkit Scopes per specific method
I'm using Django Rest Framework and OAuthTookit. I want that the scope provided by the token should be HTTP Method specific. For eg:- GET, PUT, DELETE of the same APIView should have different scopes. Following are my APIs. class MyView(RetrieveUpdateDestroyAPIView): permission_classes = [TokenHasScope] required_scopes = ['scope1'] serializer_class = ModelSerializer queryset = Model.objects.all() Currently, the scope is set at the class level, which means to access all the GET, PUT & DELETE method, the token should have scope1. I want that there should be different scope for different HTTP methods. How can I set different scope for different methods?