Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
change boolean field to True after Payment?
i use stripe Api Payment method and i have a boolean filed in my database called ordered set to False i just want it to be True after payment here is my views.py: class OrderSummary(LoginRequiredMixin, View): def post(self, request, *args, **kwargs): order = Order.objects.get(user=self.request.user) #this is to bring the order delivered = order.ordered YOUR_DOMAIN = "http://127.0.0.1:8000" checkout_session = stripe.checkout.Session.create( payment_method_types=['card'], metadata={ "order_id":order.id, "order":order, "delivered":delivered }, mode='payment', success_url=YOUR_DOMAIN + "/", cancel_url=YOUR_DOMAIN + "/", ) return JsonResponse({'id': checkout_session.id}) and here is after payment webhook views: @csrf_exempt def stripe_webhook(request): payload = request.body sig_header = request.META['HTTP_STRIPE_SIGNATURE'] event = None try: event = stripe.Webhook.construct_event( payload, sig_header, endpoint_secret ) except ValueError as e: # Invalid payload return HttpResponse(status=400) except stripe.error.SignatureVerificationError as e: # Invalid signature return HttpResponse(status=400) if event['type'] == 'checkout.session.completed': #this is to bring the order session = event['data']['object'] customer_email = session["customer_details"]["email"] orders =session["metadata"]["delivered"] orders=True orders.save() print(session) # Passed signature verification return HttpResponse(status=200) but i got this error AttributeError: 'bool' object has no attribute 'save' -
Dajngo model foreign field with conditional
Let's say i have a movie related database and two fields:movie and person. person model can consist of directors, actors and writers and has fields id, name, profession. I know that we can create ForeignKey inside of movie model, pointing to person model, and my question is can fields like actor, director and writer be created or specified inside of movie model, having pointer to personmodel or NULL if that id'd person in not this field relates to? -
Setting up shibboleth SP with Django
I am a bit lost on where to start here. Right now I'm am trying to create a shibboleth SP sign on to allow students from my university to use the Shibboleth IDP to access a service I am working on. The stack now is Django backend with react front end and want to use Shibboleth's auth capabilities. As of now, I am having extreme difficulty finding where to start and how to actually implement a login with shibboleth. I was able to get the configurations for the login (SP private key, SP cert, Metadata, Shibd config, Attribute Map),but yet, no idea where to start or apply these. -
How to add empty_label in forms.ModelForm?
For instance, I have this code. How can I add the empty_label to the field Select. class NameForm(forms.ModelForm): class Meta: model = Model fields = ['choice',] widgets = { 'choice': forms.Select(attrs={'class': 'class'}, ??empty_label='lorem'??), } models.py class Book(models.Model): choice = models.ForeignKey('Another Model', on_delete=models.PROTECT, null=True) -
Django Serializer get name of foreign key
Good day SO. I saw dozens of SO answer about this but it is not working for me. Please point me on the right direction. With this model: class Major(models.Model): major_name = models.CharField(max_length=100, default='', null=False) is_active = models.BooleanField(default=True, null=False) def __str__(self): return self.major_name class Minor(models.Model): major = models.ForeignKey("Major", on_delete=models.CASCADE) minor_name = models.CharField(max_length=100, default='', null=False) def __str__(self): return self.minor_name I should use this serializer to get the major name in my minor serializer: class MinorSerializer(serializers.ModelSerializer): major_name = serializers.CharField(source='major.major_name', read_only=True) class Meta: model = Minor fields = ["id", "minor_name", "major_id", "major_name"] But major_name is not displayed on my json response. I also tried to Serialize Major first then call it on my minor: class MajorSerializer(serializers.ModelSerializer): class Meta: model = Minor fields = ["id", "major_name"] class MinorSerializer(serializers.ModelSerializer): major_name = MajorSerializer() class Meta: model = Minor fields = ["id", "minor_name", "major_id", "major_name"] But I got this error message instead "Got KeyError when attempting to get a value for field major_name on serializer MinorSerializer. \nThe serializer field might be named incorrectly and not match any attribute or key on the dict instance.\nOriginal exception text was: 'major_name'." Note. The same error message if I remove read_only = True on my first answer -
Querying Foreign Key models in Django
In a Django blog application, I have models for Tags, Articles, and News. Both Articles and News have a ForeignKey to Tag, which is used to group articles with the same Tags together. Tag Model # Tags class Tag(models.Model): name = models.CharField('Tag Name', max_length=100, unique=True) cover_image = models.ImageField('Cover Photo', upload_to='images/', null=True, blank=True) slug = models.SlugField(max_length=100, unique=True) description = RichTextField('Tag Description') Article Model class Article(models.Model): # tag TAGS = ( ('main', 'Main'), ('featured', 'Featured') ) ARTICLE_STATUS = ( ('draft', 'Draft'), ('published', 'Published') ) title = models.CharField('Article Title', max_length=100, unique=True) slug = models.SlugField(max_length=100, unique=True) magazine = models.ForeignKey(Magazine, on_delete=models.SET_NULL, null=True) date = models.DateField(auto_now=False, auto_now_add=False) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='+') image = models.ImageField('Cover Image') tag = models.ForeignKey(Tag, on_delete=models.SET_NULL, null=True, related_name='+') article_feature = models.CharField('Article Feature', choices=TAGS, max_length=20) article_status = models.CharField('Article Status', choices=ARTICLE_STATUS, max_length=20, default='draft') body = RichTextField('Article Body', null=False, blank=False) I need to write a view for each tag View and list all the articles attached to the tag. How do I that? -
what's wrong with this statement 'the about page' w'ont be rendered i am using django 1.11.9
Hello everyone i wanted to know if i am making any mistake in this view : ***** This is he main project urls module***** from django.conf.urls import url, include from django.contrib import admin from users import views as user_views from blog import views as blog_views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^', include('blog.urls')), url(r'^about/', include('blog.urls')) url(r'^register/', user_views.register, name='register'), ] ***** This is the blog urls module***** from django.conf.urls import url, include from . import views urlpatterns = [ url(r'^', views.home, name ='blog-home'), url(r'^about/', views.about, name ='blog-about') ] this is the views module from __future__ import unicode_literals from django.shortcuts import render from .models import Post # Create your views here. def home(request): context = { 'posts' : Post.objects.all() } return render(request, 'blog/home.html', context, { 'title':'Home' }) def about(request): return render(request, 'blog/about.html', { 'title':'About' }) this is the html page to be rendered {% extends "blog/base.html" %} {% block content %} {% if title %} <title>Django Blog - {{ title }}</title> {% else %} <title>Django-blog</title> {% endif %} <h1 class="heading">About Us Page Content</h1> {% endblock content %} -
Why does Django Reverse URL return app_name?
I am configuring my URLs as follows: router = DefaultRouter() router.register('personal', views.EventPersonalViewSet) router.register('public', views.EventPublicViewSet) app_name = 'event' urlpatterns = [ path('', include(router.urls)), ] I would expect to reverse the URLs like this: EVENT_PERSONAL_URL = reverse('event:personal-list') EVENT_PUBLIC_URL = reverse('event:public-list') However, I am only able to reverse one URL like this: reverse('event:event-list') Running manage.py show_urls returns the following configuration: /api/event/personal/ event.views.EventPersonalViewSet event:event-list /api/event/personal./ event.views.EventPersonalViewSet event:event-list /api/event/public/ event.views.EventPublicViewSet event:event-list /api/event/public./ event.views.EventPublicViewSet event:event-list Why would reverse() reference app_name rather than the specified path? -
Requested settings, but settings are not configured
This is Django, but it seems to be of no importance. This is Python anyway. I've created a reusable app Images. And I use it like this: https://dpaste.com/AMBGEKU9C import json import os import shutil import sys from enum import Enum import images.const.img_types as img_types import images.const.other as other import images.const.upload_sizes as upload_sizes # Breakpoint On line 11 I put a breakpont (marked in the coment). The next step over causes this exception: https://dpaste.com/HD4FGXWGW img_types.py: https://dpaste.com/4WJ6QXZAA other.py: https://dpaste.com/EPADER2NF upload_sizes.py: https://dpaste.com/DYQTZZ8PQ I just need constants and utils from images app. I don't know why the interpreter goes to the model whter settings are imported. I've come to my wit's end as to how to cope with this problem. Or at least to localize it. Could you help me? -
ImproperlyConfigured Error loading psycopg2 module No module named psycopg2
I'm using docker-compose on Ubuntu 20.04. I have this docker-compose.yml file -- two services, a PostGres DB and a Python/Django app version: "3.3" services: pgdb: image: postgres container_name: postgres-Django ports: - 5433:5432 environment: - POSTGRES_DB=postgres - POSTGRES_USER=userName - POSTGRES_PASSWORD=Password django: build: . container_name: django command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/vol/app ports: - "8000:8000" environment: DEBUG: 'true' depends_on: - pgdb This is the Dockerfile used to build the Python/Django container FROM python:3.8-alpine ADD . /app WORKDIR /app COPY ./requirements.txt /app/requirements.txt RUN python -m pip install -r requirements.txt COPY . /app Requirements.txt file content Django==2.2 gunicorn==20.0.4 psycopg2-binary==2.8.6 psycopg2==2.8.6 Python setting.py file DB related content: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'admin', 'HOST': 'pgdb', 'PORT': 5432 } } Note: HOSTNAME pgdb is the same written in docker-compose postgres service When I execute command "docker-compose run django(django app service name) python manage.py migrate", It throws exception "psycopg2 module not found" even its available in txt file and same django app configurations working fine when execute locally. I also tried by installing dependent libraries "libpq-dev and python3-psycopg2" but no luck Any help please how to get rid of this problem? -
Django Classes communication
I am trying to build demo site with live sport streams. We have 2 classes in Django Class Team will be used to store in DB all teams in league Match will be used to generate match stream page. So once I did those classes Im trying to use shell and create the first match in DB I created 2 teams with ids in db 1 and 2,but after I got stuck with creating first match. How to insert into Team1 and Team2 fields Team name from (Team Class) with ids 1 and 2? by using shell at least for now. from django.db import models # Create your models here. class Team(models.Model): name = models.CharField(max_length=50) league = models.CharField(max_length=50) def __str__(self): return self.name class Match(models.Model): team1 = models.ForeignKey(Team, on_delete=models.CASCADE, related_name='Team1') team2 = models.ForeignKey(Team, on_delete=models.CASCADE, related_name='Team2') link = models.URLField time = models.DateTimeField def __str__(self): return self.id -
Django combine two json objects to form a new array
I have two json objects as follow Id:1 {"points":[{"x":109,"y":286,"r":1,"color":"black"},{"x":108,"y":285,"r":1,"color":"black"},{"x":106,"y":282,"r":1,"color":"black"},{"x":103,"y":276,"r":1,"color":"black"},],"lines":[{"x1":109,"y1":286,"x2":108,"y2":285,"strokeWidth":"2","strokeColor":"black"},{"x1":108,"y1":285,"x2":106,"y2":282,"strokeWidth":"2","strokeColor":"black"},{"x1":106,"y1":282,"x2":103,"y2":276,"strokeWidth":"2","strokeColor":"black"}]} Id-2 {"points":[{"x":524,"y":343,"r":1,"color":"black"},{"x":523,"y":342,"r":1,"color":"black"},{"x":521,"y":339,"r":1,"color":"black"},{"x":520,"y":334,"r":1,"color":"black"},{"x":514,"y":319,"r":1,"color":"black"}],"lines":[{"x1":524,"y1":343,"x2":523,"y2":342,"strokeWidth":"2","strokeColor":"black"},{"x1":523,"y1":342,"x2":521,"y2":339,"strokeWidth":"2","strokeColor":"black"},{"x1":521,"y1":339,"x2":520,"y2":334,"strokeWidth":"2","strokeColor":"black"},{"x1":520,"y1":334,"x2":514,"y2":319,"strokeWidth":"2","strokeColor":"black"}]} I am trying to merge these two data onto a canvas I am able to retrieve a single file but combining them i am not able to do def loadDrawing(request): """ Function to load the drawing with drawingID if it exists.""" try: # Getting JSON object string of saved drawing. drawingJSONData = Drawing.objects.get(id = 1).drawingJSONText # drawingJSONData1 = Drawing.objects.get(id=1).drawingJSONText # drawingJSONData2 = Drawing.objects.get(id=2).drawingJSONText # Seding context with appropriate information context = { "loadIntoJavascript" : True, "JSONData" : drawingJSONData } # Editing response headers and returning the same response = modifiedResponseHeaders(render(request, 'MainCanvas/index.html', context)) return response -
How to put submitted data back in the form (update functionality)
I have been trying to make an 'update function' in my table so that my data can be changed by a user. So here is my html with the form where i want my data to go back in to, so when the user presses submit again it saves that value to the database: <h3>Add a location </h3></br></br> <div class="addition"> <form method="POST" action="" autocomplete="off"> {% csrf_token %} <div class="row"> <div class="col"> <input type="text" class="form-control" aria-describedby="emailHelp" placeholder="Location name" name="name" autocomplete="off"> </div> <div class="col"> <input type="text" class="form-control" aria-describedby="emailHelp" placeholder="Description" name="desc" autocomplete="off"> </div> <div class="col"> <button type="submit" class="btn btn-primary">Submit</button> </div></br></br> </form> </br></br> <h3>Overview locations</h3> <div class="table-responsive"> <table class="table table-striped table-sm"> <thead> <tr> <th>#</th> <th>Name</th> <th>Description</th> <th>Description</th> </tr> </thead> <tbody> {% for item in all_locations %} <tr> <td>{{ forloop.counter }}</td> <td>{{ item.name }}</td> <td>{{ item.desc }}</td> <td><a class="btn btn-sm btn-info" href="{% url 'update_location' item.id %}" >update</a></td> </tr> my views.py with my creation function and my update function def location(request): all_locations = Location.objects.all() if request.method == "POST": loc_form = LocationForm(request.POST or None) if loc_form.is_valid(): loc_form.save() return render(request, 'location.html', {"all_locations": all_locations}) else: return render(request, 'location.html', {"all_locations": all_locations}) return render(request, 'location.html', {"all_locations": all_locations}) def updateLocation(request, pk): all_locations = Location.objects.all() location = Location.objects.get(id=pk) loc_form= LocationForm(instance=location) name = loc_form.instance.name … -
Django ModelForm does not save in database
I am trying to make a simple to-do list in Django that each user could have their own task list so when they logged in they add a task and its save for themselves and the list only display their own tasks, but when I try to add a task from the template's form it won't save but when I add task manually from admin panel it work. my models.py from django.db import models from django.contrib.auth.models import User class Tasks(models.Model): user = models.ForeignKey(User, null=True,on_delete=models.CASCADE) title = models.CharField(max_length=200) check = models.BooleanField(default = False) date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title forms.py from django import forms from django.forms import ModelForm from .models import * class TaskForm(forms.ModelForm): class Meta: model = Tasks fields = '__all__' views.py: from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from .forms import * from .models import Tasks @login_required(login_url = 'login') def tasks(request): tasks = Tasks.objects.filter(user = request.user) context = { 'tasks': tasks } return render(request,'ToDo/list.html',context) @login_required(login_url = 'login') def add_task(request): form = TaskForm() if request.method == 'POST': form = TaskForm(request.POST) if form.is_valid(): form.save(commit=False) form.user = request.user form.save() return redirect('/') context = {'form' : form} return render(request,'ToDo/add.html',context) where is the problem? -
How to display table with group same values in the column on Django Admin
I have a Comment table on Django Admin: And I want to edit this table with the same values item that will display with a single row, and then after clicked on it will display another table contain user comment and datetime . I've read the documents and looked for ways to do it, but I haven't done it yet. Thanks so much for any advice to me !!! -
Django mongoengine - filter string that does not contains values from list
I'm trying to filter objects from mongodb using mongoengine in django. Assuming I have the following class: class Person(Document): name = StringField() I wanna filter all Person objects whose name does not contain "Jhon" or "Doe". I can achieve this with that code: Person.objects.filter( name__not__contains="Jhon" ).filter( name__not__contains="Doe" ) But I wanna do that with only one 'filter' calling. I've already tryed that: Person.objects.filter(name__not_contains=["Jhon", "Doe"]) But I get the following error: Traceback (most recent call last): File "/usr/local/lib/python3.6/code.py", line 91, in runcode exec(code, self.locals) File "<console>", line 1, in <module> File "/usr/local/lib/python3.6/site-packages/mongoengine/queryset/queryset.py", line 144, in count return super().count(with_limit_and_skip) File "/usr/local/lib/python3.6/site-packages/mongoengine/queryset/base.py", line 399, in count count = self._cursor.count(with_limit_and_skip=with_limit_and_skip) File "/usr/local/lib/python3.6/site-packages/mongoengine/queryset/base.py", line 1666, in _cursor self._cursor_obj = self._collection.find(self._query, **self._cursor_args) File "/usr/local/lib/python3.6/site-packages/mongoengine/queryset/base.py", line 1715, in _query self._mongo_query = self._query_obj.to_query(self._document) File "/usr/local/lib/python3.6/site-packages/mongoengine/queryset/visitor.py", line 90, in to_query query = query.accept(QueryCompilerVisitor(document)) File "/usr/local/lib/python3.6/site-packages/mongoengine/queryset/visitor.py", line 185, in accept return visitor.visit_query(self) File "/usr/local/lib/python3.6/site-packages/mongoengine/queryset/visitor.py", line 79, in visit_query return transform.query(self.document, **query.query) File "/usr/local/lib/python3.6/site-packages/mongoengine/queryset/transform.py", line 120, in query value = field.prepare_query_value(op, value) File "/usr/local/lib/python3.6/site-packages/mongoengine/fields.py", line 152, in prepare_query_value value = re.escape(value) File "/usr/local/lib/python3.6/re.py", line 276, in escape return bytes(s) TypeError: 'str' object cannot be interpreted as an integer Is that possible to achieve what I'm trying to get? -
Without using django forms how to validate and save form data
Suppose I have a 'question' model with two fields - title and content Now think of question creation form. Using django forms I can display it to template and validate using is_valid method. But I don't want to use django inbuilt forms. I want to write my forms in handwritten html and send it to server using POST method. How will validation and saving to database will work in this case? I am doing something similar to this guy but I am not satisfied with the existing answers -
Django blog. Why is part of the html not showing on all pages?
I am using django to create a blog where all posts are shown on the home page as well as on pages depending on their subject. While the basics as shown work, I am having difficulty with the following: This part of base.html is repeated on each page: <h1><a href="/">DR SMART.INFO</a></h1> <p>the web site for the analytical rugby fan</p> However this part only shows on index.html and not on other pages eg subject.html or post_detail.html <p> <ul> {% for subject in subjects %} <li><a href="{% url 'subject' subject.subject_slug %}">{{ subject }}</a></li> {% endfor %} </ul> </p> I would like it to show on the top of each page. Thanks for assistance with this. Roderic base.html {% load static %} <html> <head> <title>drsmart.info</title> <link rel="stylesheet" href="{% static 'css/blog.css' %}"> </head> <body> <h1><a href="/">DR SMART.INFO</a></h1> <p>the web site for the analytical rugby fan</p> <p> <ul> {% for subject in subjects %} <li><a href="{% url 'subject' subject.subject_slug %}">{{ subject }}</a></li> {% endfor %} </ul> </p> {% block content %} {% endblock %} </body> </html> index.html {% extends 'blog/base.html' %} {% block content %} {% for post in posts %} <div> <h2><a href="{% url 'post_detail' post.slug %}">{{ post.title }}</a></h2> <p>author: {{post.author}}, published: {{post.date_added }}</p> … -
How to correctly establish a connection between a user group and a database model?
I have two user groups Students and Teachers, I created the Group application, and there should be a 1xM connection between the group and the students, but how can I do this exactly with a group of users - students. I have the following idea: Create a separate Students and Teachers model, inherit from User and add a group there, etc. When registering, drop it into Students and immediately into the student role, when changing the role to Teacher, delete it from students. There is also an option with https://docs.djangoproject.com/en/3.1/topics/auth/default/#groups but how can this be done with a group of students? Please tell me how is it right? -
how to connect default profile image from aws s3 to user in django
hello i had connected to locat static but now i have aws storage static content and cannt connect path to database and cannt find similar tutorial how can i give path to save on database i also using docker instances postgresql is in another instance here is code models.py from django.db import models from django.contrib.auth.models import User from PIL import Image from django.core.files.storage import default_storage as storage class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.png', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' @property def followers(self): return Follow.objects.filter(follow_user=self.user).count() @property def following(self): return Follow.objects.filter(user=self.user).count() def save(self, force_insert=False, force_update=False, using=None, update_fields=None): super().save() img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.save(self.image.path) class Follow(models.Model): user = models.ForeignKey(User, related_name='user', on_delete=models.CASCADE) follow_user = models.ForeignKey(User, related_name='follow_user', on_delete=models.CASCADE) date = models.DateTimeField(auto_now_add=True) i will update if something is mising errors in debug Django Version: 3.1.5 Python Version: 3.9.2 Installed Applications: ['blog.apps.BlogConfig', 'users.apps.UsersConfig', 'crispy_forms', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'storages', 'app', 'corsheaders'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'corsheaders.middleware.CorsMiddleware'] Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/usr/local/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/app/web/users/views.py", line … -
Sending iOS Push Notifications using Django: HTTP/2-based APNs provider API and binary protocol
We need to send iOS push notifications using our Django based backend. Currently, we use this library https://github.com/jazzband/django-push-notifications for sending notifications. Recently, received this mail from Apple Developers. The HTTP/2‑based Apple Push Notification service (APNs) provider API lets you take advantage of great features, such as authentication with a JSON Web Token, improved error messaging, and per‑notification feedback. If you still send push notifications with the legacy binary protocol, make sure to upgrade to the APNs provider API as soon as possible. APNs will no longer support the legacy binary protocol after March 31, 2021. I saw that this library uses apns2 (https://pypi.org/project/apns2/) for sending push notifications on iOS and that uses HTTP/2 protocol for sending notifications. So, this library can continue to be used for sending iOS notifications right? Can anybody clarify that for me? Also, it would be great if someone could explain the meaning of legacy binary protocol, that would be great. -
In django, I can't understand how include function works
I just started learning Django. I can't understand how include function knows what is polls.urls. I don't import polls.urls but it works! from django.contrib import admin from django.urls import include, path urlpatterns = [ path('polls/', include('polls.urls')), path('admin/', admin.site.urls), ] -
Django canvas coordinates union of filtered json objects
i have a canvas which saves the user drawing as coordinates in json i am able to retrieve all coordinates and display the drawing made on canvas by searching through the drawing id but i am trying to filter all ids in the data set and make a union of all coordinates to display on the canvas example : say i have two array of coordinates Data-1 {"points":[{"x":109,"y":286,"r":1,"color":"black"},{"x":108,"y":285,"r":1,"color":"black"},{"x":106,"y":282,"r":1,"color":"black"},{"x":103,"y":276,"r":1,"color":"black"},],"lines":[{"x1":109,"y1":286,"x2":108,"y2":285,"strokeWidth":"2","strokeColor":"black"},{"x1":108,"y1":285,"x2":106,"y2":282,"strokeWidth":"2","strokeColor":"black"},{"x1":106,"y1":282,"x2":103,"y2":276,"strokeWidth":"2","strokeColor":"black"}]} Data-2 {"points":[{"x":524,"y":343,"r":1,"color":"black"},{"x":523,"y":342,"r":1,"color":"black"},{"x":521,"y":339,"r":1,"color":"black"},{"x":520,"y":334,"r":1,"color":"black"},{"x":514,"y":319,"r":1,"color":"black"}],"lines":[{"x1":524,"y1":343,"x2":523,"y2":342,"strokeWidth":"2","strokeColor":"black"},{"x1":523,"y1":342,"x2":521,"y2":339,"strokeWidth":"2","strokeColor":"black"},{"x1":521,"y1":339,"x2":520,"y2":334,"strokeWidth":"2","strokeColor":"black"},{"x1":520,"y1":334,"x2":514,"y2":319,"strokeWidth":"2","strokeColor":"black"}]} I need to form a new array by union of these two and diplay on canvas at present i am filtering the data by a single id as follows javascript to parse the data if (document.getElementById('JSONLoadData') != null) { // Parsing the loaded drawing from server to a JSON Object var loadedData = JSON.parse(JSONLoadData.value) // Iterating through all the points in the loaded drawing for(let i = 0; i < loadedData['points'].length; i++) { // Saving the point and drawing the same in the svg canvas const point = svg.append('circle') .attr('cx', loadedData['points'][i]['x']) .attr('cy', loadedData['points'][i]['y']) .attr('r', loadedData['points'][i]['r']) .style('fill', loadedData['points'][i]['color']); // Pushing the point inside points array points.push(point); } // Iterating through all the lines in the loaded drawing for(let i = 0; i < loadedData['lines'].length; i++) { // Saving the line and … -
Django rest framework + multiple database + POST data
I'm preparing API and I'm using multiple database ("oracle" and "sqlserver"). I want to POST data (json) into sqlserver. Here is part of my code. models.py (every table is in sqlserver database) class QtOfferParam(models.Model): ext_id = models.IntegerField(primary_key=True) dealer_code = models.CharField(max_length=10, db_column="dealer_code") dealer_name = models.CharField(max_length=30, db_column="dealer_name") dealer_user = models.CharField(max_length=30, db_column="dealer_user") class Meta: db_table = 'ZZ_QT_OFFER_PARAM' class QtParameterValues(models.Model): ext_id = models.ForeignKey(QtOfferParam, to_field="ext_id", db_column="ext_id", on_delete=models.PROTECT, related_name="parameterValues", primary_key=True) parameter = models.CharField(max_length=200, null=True, db_column="parameter") value_p = models.CharField(max_length=10, null=True, db_column="value_p") class Meta: db_table = 'ZZ_QT_PARAMETER_VALUE' class QtOptions(models.Model): ext_id = models.ForeignKey(QtOfferParam, to_field="ext_id", db_column="ext_id", on_delete=models.PROTECT, related_name="options", primary_key=True) f_amount = models.FloatField(db_column="FINANCED_AMOUNT") installment_amount = models.FloatField(db_column="INSTALLMENT_AMOUNT") total_amount = models.FloatField(db_column="TOTAL_AMOUNT") total_amount_in_percentage = models.FloatField(db_column="TOTAL_AMOUNT_IN_PERCENTAGE") class Meta: db_table = 'ZZ_QT_OPTIONS' serializers.py (i added " using='sqlserver' ") class ReqSerializer(serializers.HyperlinkedModelSerializer): dealer = DealerField(source='*') parameterValues = ParametersSgSerializer(many=True) options = OptionsSgSerializer(many=True) class Meta: model = QtOfferParam fields = ['ext_id', 'dealer', 'parameterValues', 'options'] def create(self, validated_data): parameters_data = validated_data.pop('parameterValues') options_data = validated_data.pop('options') req_id = QtOfferParam.objects.using('sqlserver').create(**validated_data) for parameters_data in parameters_data: parameters_data['ext_id'] = req_id QtParameterValues.objects.using('sqlserver').create(**parameters_data) for options_data in options_data: options_data['ext_id'] = req_id QtOptions.objects.using('sqlserver').create(**options_data) return req_id views.py class testView(viewsets.ModelViewSet): queryset = QtOfferParam.objects.using('sqlserver').all() serializer_class = ReqSerializer when I GET data everything is OK. The data are from sql server, but if I try POST new json i get error from oracle database: ORA-00942: … -
Django: can't login after editing user details
I'm trying to find a solution for 2 days now... can't figure out why login does not work for me once I have changed any user details. Normal flow works fine for me: user registers, logs in and out without a problem. But I thought it would be good to have profile change option where a user can change username, password or email. I did implement this, but after a user changes anything (even email), the login form does not admit him. Here is my views.py: class ProfileView(UpdateView): template_name = 'boat_app/edit_profile.html' form_class = UserChangeForm success_url = reverse_lazy('anchored') def get_object(self): return self.request.user class LoginView(TemplateView): template_name = 'boat_app/login.html' success_url = reverse_lazy('category_home') def post(self, request): print(request) user = authenticate(request, username=request.POST.get('username'), password=request.POST.get('password')) if user is not None: print('user not none') login(request, user) return HttpResponseRedirect(reverse('anchored')) else: print('user none') messages.info(request, 'Username OR password is incorrect') return HttpResponseRedirect(reverse('login')) And forms.py class EditUserForm(forms.ModelForm): class Meta: model = User fields = ('username', 'email') After changing a user I see this change in admin interface, so it does work. But I can't see a reason why the system does not see this relation. Any way to debug what exactly is going on there?