Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I did not show big drill down button
I did not show large content drill down button. I load json file and the content of the file become drill down button's content.But now only small content drill down buttons are shown.json is like {'items': {'---': '---', ‘A’: ‘a’, ‘B’: ‘b’, ‘C: ‘c’, ‘D’: ‘d’}, 'type1': { "---":"---", "a1":"a1", "a2:"a2", "a3":"a3", "a4":"a4" }, 'type2': { "---":"---", "b1":"b1", "b2:"b2", "b3":"b3", "b4":"b4" }, 'type3': { "---":"---", "c1":"c1", "c2:"c2", }, 'type4': { "---":"---", "d1":"d1", "d2:"d2", "d3":"d3" }, } views.py is from collections import OrderedDict from django.shortcuts import render import json from django.http import JsonResponse def index(request): with open('./data/company_demand.json', 'r') as f: json_data = json.loads(f.read(), object_pairs_hook=OrderedDict) preprocessed = [] counter = 0 for key in ["type1", "type2", "type3", "type4"]: values = [(i + counter, value) for i, value in enumerate(json_data[key].values())] preprocessed.append((key, values)) counter = len(json_data[key]) return render(request, 'index.html', {'json_data': json_data}, {'preprocessed': preprocessed}) index.html is <select id="mainDD" data-placeholder="Choose" class="chzn-select" style="width:600px;"> {% for i in json_data.items.values %} <option>{{ i }}</option> {% endfor %} </select> {% for key, values in preprocessed %} <select name="type" id="{{ key }}"> {% for counter, value in values %} <option value="{{ counter }}">{{ value }}-{{counter}}</option> {% endfor %} </select> {% endfor %} But now this part <select id="mainDD" data-placeholder="Choose" class="chzn-select" style="width:600px;"> … -
ID and Class Name Delimiters in HTML
Django==1.11.5 Googl tells us not to use underscores: https://google.github.io/styleguide/htmlcssguide.html#ID_and_Class_Name_Delimiters Well, it is ok. But let's have a look at how to behave in the reality of Django. Let's open django/contrib/admin/templates/admin/index.html. We can see: <div id="content-main"> As if a hyphen is Ok for Django. But on the other hand if one organizes a Django form then opens its HTML, they will see something like this: id="id_keeper_not_absent" Well, this id was automatically created by this code: forms.py keeper_not_absent = forms.BooleanField(label='Keeper absent', required=False) Well, now we have underscores in HTML element ids. It is also Ok. But mixing doesn't seem Ok. Could you help me understand why Django itself uses such a mix and what should we ourselves use? -
How to set a path to virtual environment for sublime text 3 plugin to work correctly
I am trying to install a plugin called "Django manage commands" in sublime text 3. and after installation, I got the following message Remember to set the path to the directory where your virtual environments are installed in "python_virtualenv_paths" for the plugin to work correctly, as many directories as you need can be added. How can I do this? I found the same message in other plugins as well. Thanks for your time in advance '_' -
How to you join two models with a specific requirement
I have two models Model A class Affiliate(models.Model): instructor = models.OneToOneField(Profile) Model B class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) instructor = models.BooleanField(default=False, blank=False) My goal is in my django admin to show a list of Profiles where instructor = True, right now I am getting all of the instructors, how can I limit this list. class AffiliateAdmin(admin.ModelAdmin): fields = ['instructor'] This works but it gets the whole list of profiles. I only want the profiles that have instructor = True. I have tried limiting the profile on the affiliate model with no success. Any help is appreciated. -
Django issue with argon2 hasher in live production
So I have just setup my Digital Ocean droplet (server) and have been working to get this site to work, however I have been coming across error after error. I finally got the site to load the login page (which is what should happen), but when I login I get an error that Argon2 Pass Hasher couldn't load. I really have no idea what the problem is, as everything was working perfectly while in development. Here is the error: ValueError at /accounts/login/ Couldn't load 'Argon2PasswordHasher' algorithm library: No module named argon2 Here are my settings: """ Django settings for django_project project. Generated by 'django-admin startproject' using Django 1.8.7. For more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.8/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates') MEDIA_DIR = os.path.join(BASE_DIR, 'media') # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'h&*(yq942_a^pa+ty&wh(bl9s4d#z^*_6cmeb#5&49jb^r$&!f' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = ( 'django.contrib.admin', … -
Database Queries: Fast alternatives to Django's order_by()
I've been teaching myself Django and SQL, and one thing I've noticed is that when working with large tables (> 1,000,000 records), specifying an ordering is painfully slow. For example: Model.objects()[offset:limit] might take a few milliseconds, assuming offset and limit are a small enough range. However: Model.objects()[offset:limit].order_by('name') Could take 10 or 20 seconds, depending on the number of rows in the table. I understand why this is happening; all rows must be checked to ensure that the correct results are returned. I also understand that this is more an SQL problem and not a Django problem, it's just easier for me to explain it with Django code. So these are my questions: Since I see Django production websites display ordered data from extremely large tables, how do they achieve this without each query taking >10 seconds? After I solve the first question, how could I extend my Django application to allow ordering of multiple columns (name, date, value, etc)? My intuition says that the answer to the first question is to insert each record in the order I want it displayed so that no ordering is necessary when performing queries, but that seems difficult to maintain. Also, that means that … -
I wanna add number which is correspond to the number of this list's content
Now index.html is <html> <head> <script type="text/javascript" src="//code.jquery.com/jquery-1.11.0.min.js"></script> <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/chosen/1.8.2/chosen.jquery.min.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/chosen/1.4.2/chosen.jquery.js"></script> <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/chosen/1.4.2/chosen.css"> </head> <body> <select id="mainDD" data-placeholder="Choose" class="chzn-select" style="width:600px;"> {% for i in json_data.items.values %} <option>{{ i }}</option> {% endfor %} </select> <select name="type" id="type1"> {% for j in json_data.type1.values %} <option>{{ j }}</option> {% endfor %} </select> <select name="type" id="type2"> {% for k in json_data.type2.values %} <option>{{ k }}</option> {% endfor %} </select> <select name="type" id="type3"> {% for l in json_data.type3.values %} <option>{{ l }}</option> {% endfor %} </select> <select name="type" id="type4"> {% for m in json_data.type4.values %} <option>{{ m }}</option> {% endfor %} </select> <script type="text/javascript"> $(document).ready(function () { $('#mainDD').on('change', function() { console.log($(this).val()); console.log($('#mainDD :selected').text()) ; var thisType = "type" + $(this).val(); for(i=1; i<5; i++) { var thisId = "type" + i; console.log(thisType + " " + thisId); if(thisType !== thisId) { $("#"+thisId).hide(); } else { $("#"+thisId).show(); } } }).trigger('change'); }); </script> </body> </html> I wanna add number to tag like .So my ideal output is <select name="type" id="type1"> <option value="1">a-1</option> <option value="2">a-2</option> <option value="3">a-3</option> <option value="4">a-4</option> </select> <select name="type" id="type2"> <option value="5">b-1</option> <option value="6">b-2</option> <option value="7">b-3</option> <option value="8">b-4</option> <option value="9">b-5</option> </select> <select name="type" id="type3"> <option value="10">c-1</option> <option value="11">c-2</option> </select> <select name="type" id="type4"> <option … -
Duplicate key issue when loading back.json file PostgreSQL
I have a PostgreSQL database that where I performed python manage.py dumpdata to backup the data into a json file. I created a new PostgreSQL database, performed a migrate, and everything worked like clockwork. When I tried to load the backup.json file with python manage.py loaddata backup.json it, gives me this error. Could not load contenttypes.ContentType(pk=15): duplicate key value violates unique constraint "django_content_type_app_label_76bd3d3b_uniq" DETAIL: Key (app_label, model)=(navigation, navigation) already exists. I checked phpPgAdmin, and there is a row for News. Is there a way to load the backup json file without including the content types, or better yet dump everything except for content types data ? -
Convert serialized object to json in Django
I'm coding unit tests for a serializer. I have got a serializer object from the serializer that I'm testing (This is actual serialized content). I have serialized the sample data using from django.core import serializers and got the json (This is the expected content which is in json). Could anyone please let me know how do I convert either (expected/actual) into class object/json, so that I can assert both? Below is the code I'm trying: obj = mixer.blend('register.Register', first_name='first_name') actual_serialized_content = RegisterSerializer(data=Register.objects.filter(first_name='first_name').values()) expected_serialized_content = serializers.serialize('json',Register.objects.filter(first_name='first_name')) I'm all new to Django and unit testing, if the above approach isn't right, please suggest. -
Global View-Context in Django App
Currently I've a class which I call in every single view for some global context variables which I use in my templates. It looks like this: class WikiContext(): def getWikiContext(self, view, request): context = { 'app': request.resolver_match.app_name, 'controller': view.__class__.__module__.split('.')[-1], 'action': view.__class__.__name__.lower(), 'categories': CategoryModel.objects.all() } return context I call it like this in every single view: context = WikiContext().getWikiContext(self, request) Is it possible to make it a little less code? I don't wanna repeat the call in every single view if possible. Thank you. -
django ManifestStaticFilesStorage 500 error
django 11.5 python 3.5.2 I would like to attach MD5 to the file, but there will be error 500 information, opened the debug, I can not see where the error appears. (English is not my native language; please excuse typing errors.) settings.py STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage' STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') templates <!-- Favicons --> {% load static %} <link rel="icon" type="image/x-icon" href="{% static "favicon/favicon.ico" %}"> <link rel="apple-touch-icon" href="{% static "favicon/apple-touch-icon-precomposed.png" %}"> <!-- Bootstrap --> <link href="{% static "css/bootstrap.min.css" %}" rel="stylesheet"> <link href="{% static "css/style.css" %}" rel="stylesheet"> python3 manage.py collectstatic You have requested to collect static files at the destination location as specified in your settings: /data/mysite/static This will overwrite existing files! Are you sure you want to do this? Type 'yes' to continue, or 'no' to cancel: yes Post-processed 'admin/css/login.css' as 'admin/css/login.a846c0e2ef65.css' Post-processed 'admin/css/base.css' as 'admin/css/base.31652d31b392.css' Post-processed 'admin/css/fonts.css' as 'admin/css/fonts.494e4ec545c9.css' Post-processed 'admin/css/changelists.css' as 'admin/css/changelists.f6dc691f8d62.css' Post-processed 'admin/css/rtl.css' as 'admin/css/rtl.4c867197b256.css' Post-processed 'admin/css/forms.css' as 'admin/css/forms.15ebfebbeb3d.css' Post-processed 'admin/css/dashboard.css' as 'admin/css/dashboard.7ac78187c567.css' Post-processed 'admin/css/widgets.css' as 'admin/css/widgets.5e372b41c483.css' Post-processed 'css/style.css' as 'css/style.476c9dc9ef58.css' Post-processed 'css/bootstrap.min.css' as 'css/bootstrap.min.5c7070ef655a.css' Post-processed 'admin/css/dashboard.css' as 'admin/css/dashboard.7ac78187c567.css' Post-processed 'admin/css/changelists.css' as 'admin/css/changelists.f6dc691f8d62.css' Post-processed 'admin/css/base.css' as 'admin/css/base.6b517d0d5813.css' Post-processed 'admin/css/fonts.css' as 'admin/css/fonts.494e4ec545c9.css' Post-processed 'admin/css/rtl.css' as 'admin/css/rtl.4c867197b256.css' Post-processed 'admin/css/forms.css' as 'admin/css/forms.2003a066ae02.css' Post-processed 'admin/css/widgets.css' as 'admin/css/widgets.5e372b41c483.css' Post-processed 'admin/css/login.css' … -
how to avoid increasing url in django
I am new to Django and learning it by developing small projects. Currently i am creating login app.I am facing below issue, i have written on form tag in one template: <form method="GET" action="login_page/"> {% csrf_token %} <button type ="submit"> Login</button> </form> after clicking submit button i goes to login/page url. And in the other template i have written below form tag, <form method="GET" action= "Welcome/"> {% csrf_token %} <button type ="submit"> Sign Up</button> </form> and my urls are: urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^login_page/', include('login.urls')) ] urlpatterns=[ #url(r'^$',TemplateView.as_view(template_name='base.html'),name='base'), url(r'^$',views.HomeView.as_view(),name='home'), url(r'^Welcome/$', views.WelcomeView.as_view(), name='Welcome'), #url(r'^Welcome/$',TemplateView.as_view(template_name='Welcome.html'),name='Welcome'), url(r'^logout/$',TemplateView.as_view(template_name='Logout.html'),name='Logout'), url(r'^home/$',views.HomeView.as_view(),name='home') ] but the issue is as i goes on and click submit buttons url keeps increasing, like http://localhost:8000/login_page/ localhost:8000/login_page/Welcome/ localhost:8000/login_page/Welcome/login_page and hence it gives error as it can not find 3rd url. how to correct it. ? can we go to views for action in form tag? -
django-filter - show only relevant filter values
I am using django-filters and can't figure out how to display only relevant to my queryset filter values. From code below I am displaying products by specific category but I receive all filter values that might not be applicable to that category. How do I display only relevant filter values? models.py Class Product(models.Model): name = models.CharField(max_length=512, unique=True, db_index=True) slug = models.SlugField(max_length=512, unique=True, db_index=True) categories = models.ManyToManyField(Category, related_name='products') description = models.TextField() status = models.BooleanField(default=True) manufacturer = models.CharField(max_length=64) common_attributes = JSONField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateField(auto_now=True) Class ProductFilter(django_filters.FilterSet): manufacturer = django_filters.AllValuesMultipleFilter(name='manufacturer', widget=forms.CheckboxSelectMultiple) Class Meta: model = Product fields = ['manufacturer'] views.py def show_category(request, category_slug): category = get_object_or_404(Category, slug=category_slug) subcategories = Category.objects.filter(parent_id=category.id) products = ProductFilter(request.GET, queryset=Product.objects.filter(categories=category).annotate(starting_price=Min('variant__price'))) breadcrumbs = Category.get_parents(category.id) return render(request, 'catalog/category.html', {'category' : category, 'subcategories' : subcategories, 'breadcrumbs' : breadcrumbs, 'products' : products}) -
How do I separate user accounts in Django ?
I am using Django to create an app that allows recording of medical information however I am having problems with seperating the user accounts so currently all users see the same information entered. Anyone familiar with django knows how to set the proper permissions and roles and is willing to help a newby out? I want the user to only access to the account the user creates and the records that the user create. This is my github link If you are able to to help I would really appreciate it. -
Digital Ocean 502 Bad Gateway
I just setup my Digital Ocean droplet and and have been following a tutorial to get Django setup. However, upon restarting gunicorn my site now just has an error page: 502 Bad Gateway nginx/1.10.3 (Ubuntu) I am new to this stuff so I have no idea what the problem, please help! From my Nginx error logs I see this: 2017/09/25 22:23:51 [error] 2140#2140: *10 upstream prematurely closed connection while reading response header from upstream, client: 110.72.37.75, server: _, request: "GET / HTTP/1.0", upstream: "http://unix:/home/django/gunicorn.socket:/" 2017/09/25 22:24:02 [error] 2140#2140: *12 upstream prematurely closed connection while reading response header from upstream, client: 110.72.37.75, server: _, request: "GET / HTTP/1.0", upstream: "http://unix:/home/django/gunicorn.socket:/" 2017/09/25 22:24:13 [error] 2140#2140: *16 upstream prematurely closed connection while reading response header from upstream, client: 110.72.37.75, server: _, request: "HEAD /manager/html HTTP/1.0", upstream: "http://unix:/home/django/gunicorn.socket:/manager/html" 2017/09/25 23:38:16 [error] 2140#2140: *25 connect() to unix:/home/django/gunicorn.socket failed (111: Connection refused) while connecting to upstream, client: 68.81.142.218, server: _, request: "GET / HTTP/1.1", upstream: "http://unix:/home/django/gunicorn.socket:/", host: "104.236.213.167" 2017/09/25 23:38:17 [error] 2140#2140: *25 connect() to unix:/home/django/gunicorn.socket failed (111: Connection refused) while connecting to upstream, client: 68.81.142.218, server: _, request: "GET / HTTP/1.1", upstream: "http://unix:/home/django/gunicorn.socket:/", host: "104.236.213.167" -
Django login error: “attempt to write a readonly database” in IIS
I have a Django web app installed in IIS 10 and I applied some models into the db.sqlite3 but when I tried to log into the django/admin/login I encountered the error: OperationalError at /admin/login/attempt to write a readonly database. I have found solutions to this problem in sqlite3 error attempt to write a read only database, Django admin backend, attempt-to-write-a-readonly-database-django and all of them mention to change the permissions of the database folder. I changed the permissions of that folder by deselecting the option Read-only (Only applies to files in folder) but it seems that when I hit the Apply button it does not make any change because I check again the folder and it has the Read-only option activated. Questions: Is there any way to change this permission by any command terminal in powershell? Do I have to do any extra step in IIS to make the db.sqlite3 working? Any help is welcome! -
Django models: Inherit from variable abstract base class
I'm hoping to inherit to a child class from a variable abstract base class. So a child class would not have to inherit from a pre-defined base class and would instead be able to inherit from any one class of multiple base classes. Ideally, the models would be setup like so: class Orders(models.Model): order_number = models.IntegerField() # Orders metrics class Meta: abstract = True class Fees(models.Model): fee_number = models.IntegerField() # Fee metrics class Meta: abstract = True class Transactions(Inherit from either Orders or Fees): transaction_number = models.IntegerField() # Transaction metrics Transactions would be able to inherit from either orders or fees as they could both be a source of a transaction. Generic foreign keys could be implemented to allow for variable foreign key reference within the Orders model and Fees model but I am curious if there is a way to do this without using generic foreign keys. Is there a specific arrangement, mixin, decorator, property, or method that will allow for association of a child class with a variable abstract parent class? -
Django how to make a url that looks like 'a/main' or 'b/main' or 'c/main'?
I am trying to create a url that can either be a/main b/main c/main The url should look something like this: url(r'^(a|b|c)/main$', view.as_view()) Then I should be able to get which value it(a, b or c) is from the args to the view. -
Insert One to One field value in django
I have the following models. class PatientInfo(models.Model): lastname = models.CharField('Last Name', max_length=200) firstname = models.CharField('First Name',max_length=200) middlename = models.CharField('Middle Name',max_length=200) ... def get_absolute_url(self): return reverse('patient:medical-add', kwargs={'pk': self.pk}) class MedicalHistory(models.Model): patient = models.OneToOneField(PatientInfo, on_delete=models.CASCADE, primary_key=True,) ... and upon submitting PatientInfo form it will go to another form which supply the MedicalHistory Details. I can see my PatientInfo data as well as MedicalHistory data but not linked to each other. Below is my MedicalCreateView which process my MedicalHistory form. class MedicalCreateView(CreateView): template_name = 'patient/medical_create.html' model = MedicalHistory form_class = MedicalForm def post(self, request, pk): form = self.form_class(request.POST) if form.is_valid(): patiente = form.save(commit=False) physician_name = form.cleaned_data['physician_name'] # do not delete patient = PatientInfo.objects.all(id=self.kwargs['pk']) MedicalHistory.patient = self.kwargs['pk'] patiente.save() messages.success(request, "%s is added to patient list" % physician_name ) return redirect('index') else: print(form.errors) This is how I set MedicalHistory.patient field using the PatientInfo.pk MedicalHistory.patient = self.kwargs['pk'] -
Override Django User Model
I'm writing a Django app. I wanted to override the Django User Model for the following reasons: 1) I want to use LDAP for authentication. Therefore, Django authentication is not necessary for me. 2) I already have a user table and I want to reuse that table. I do not want Django to create a dup table for me. Also the table structure doesn't "fit" Django User model very well. Therefore, I'd like to override the Django User class. Does anyone have any good example good that I can learn from? -
Django / making clone of reddit comment system
I try to make clone of reddit. For now I can get comments and sub comments. I couldn't make comment/subcomment/sub_sub_comment. How should I get the comment and childrens with tree structure without using mptt or any library. I want to make with generic relations. models.py class Comment(models.Model): entry_comment = models.TextField(max_length=160) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') def __str__(self): return self.entry_comment def descendants_comments(self): ct = ContentType.objects.get_for_model(self) childs = Comment.objects.filter(content_type=ct, object_id=self.pk) result = [] for child in childs: result.append(child) result.append(child.descendants_comments()) return result post_detail.html <section> <h1>Comments</h1> <div class="comments-bg"> {% for comment in comments %} <div class="comment-per-style"> <div class="comment-style">{{ comment.entry_comment }}</div> <ul> {% for subcomment in comment.descendants_comments %} <li>{{ subcomment.entry_comment }}</li> {% endfor %} </ul> </div> <button type="button" class="btn btn-success btn-sm reply-button">Reply</button> <form class="comment-form" action="{% url 'sub-comment' comment.id %}" method="post"> {% csrf_token %} <input id="entry_comment" class="form-input" type="text" name="entry_comment" maxlength="100" required /> <input type="submit" value="Submit comment"> </form> {% endfor %} </div> -
Django template doesn't load
Am following the Django Website's tutorial, currently on Pt3(https://docs.djangoproject.com/en/1.11/intro/tutorial03/) Tutorial states: "This code should create a bulleted-list containing the “What’s up” question from Tutorial 2. The link points to the question’s detail page." After adding the template and running the server I still only see this previous page and no updated template , what's wrong here? Thanks for your help! django_proj/mysite/polls/urls.py from django.conf.urls import url from . import views urlpatterns = [ #ex: /polls/ url(r'^$', views.index, name='index'), # ex: /polls/5/ url(r'^(?P<question_id>[0-9]+)/$', views.detail, name='detail'), # ex: /polls/5/results/ url(r'^(?P<question_id>[0-9]+)/results/$', views.results, name='results'), # ex: /polls/5/vote/ url(r'^(?P<question_id>[0-9]+)/vote/$', views.vote, name='vote'), ] django_proj/mysite/polls/views.py from django.shortcuts import render from django.http import HttpResponse from .models import Question def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] template = loader.get_template('polls/index.html') context = { 'latest_question_list': latest_question_list, } return HttpResponse(template.render(context, request)) def detail(request, question_id): return HttpResponse("You're looking at question %s." % question_id) def results(request, question_id): response = "You're looking at the results of question %s." return HttpResponse(response % question_id) def vote(request, question_id): return HttpResponse("You're voting on question %s." % question_id) def index(request): return HttpResponse("At Polls Index") /django_proj/mysite/polls/templates/polls/index.html {% if latest_question_list %} <ul> {% for question in latest_question_list %} <li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li> {% endfor %} </ul> {% else %} <p>No polls are available.</p> … -
Sync App-Backend user table with wordpress login
I programmed a Backend for an app. In the Backend is of course the login/registration endpoint. The problem is that my client had the new idea of synchronizing his Wordpress Blog with the app. And now he wants that when an user registers himself in the App, then he can log in the Wordpress and when an user registers himself in the Wordpress Blog, he can log in the App. My problem is that I'm not specialized either in Wordpress nor in PHP. I was watching the wp-login.php file, but didn't find a good result. I'm thinking of using the Backend Endpoint with Wordpress, I can guess that Wordpress could work as a client. Then I could use the same Login-Backend-Function with the App and with Wordpress and it should work. I was reading this kind of post in Internet, but is not that way, I don't want to register an user in Wordpress from the app, but the other way, I would like to register an user in the App or in Wordpress and log him in the App or Wordpress, but using the Django Endpoints of the Backend. I did't think that it would be so complicated. Maybe … -
object that was saved with commit=False, still saved
I have a very big model, with steps form. So I decided on each page get previous object and update his attributes in form. In first form I do: def save(self, commit=False): obj = super(FirstForm, self).save(commit=False) obj.id = 999999999 self.request.session['obj'] = pickle.dumps(obj) self.request.session.save() return obj Id is requires for mtm. So I set default one. Then on last step in view I do: obj = self.request.session.get('obj') obj = pickle.loads(obj) obj.id = None # remove temporary id obj.save() But Django save two objects. One normal object and one empty with id 999999999 . Why ? I tried do: obj = super(FirstForm, self).save(commit=False) obj.id = 999999999 self.request.session['obj'] = pickle.dumps(obj) self.request.session.save() obj.delete() But it didn't help. -
how does django-rest-framework- javascript web token work with django to auth users?
How does the Django-rest-framework-jwt work with django? It seems that the token is not part of the database which doesn't make sense. What is the behind the scenes when we add JWT to our settings?