Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
onclick function is running only once
I am using an edit button to edit the posts but when I am clicking the button the onclick function executes and it works perfectly like it edits the post and updates the post content(not from backend). But the problem is when I click the edit button again the onclick function is not running. My HTML code :- <div class="post"> <b><a href="{% url 'profile' post.author.id %}">{{post.author}}</a></b> <input type="hidden" name="postid" value={{post.id}}> <!-- <br><br> --> <p>{{post.content}}</p> {% csrf_token %} <textarea name="edit_content" id="edit_content" cols="50" rows="5"></textarea> {% if user.is_authenticated %} {% if post.author == user %} <button class="edit" onclick="edit(this)">Edit</button> {% endif %} {% endif %} <p><small class="text-muted">{{post.created_on}}</small></p> Here textarea display is set to 'none'. My javascript code :- function edit(ele){ var parent = ele.parentNode; console.log(ele.parentNode); var post = parent.querySelector('p'); var textarea = parent.querySelector('textarea'); var id = parent.querySelector('input'); post.style.display = 'none'; textarea.style.display = 'block'; ele.innerHTML = "Save"; ele.id = "save"; ele.disabled = true; const csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value; textarea.onkeyup = () => { if( textarea.value.length > 0){ ele.disabled = false; } else{ ele.disabled = true; } } var save = document.getElementById('save'); save.onclick = () => { fetch("http://127.0.0.1:8000/edit", { method : "PUT", headers: {'X-CSRFToken': csrftoken}, body : JSON.stringify({ "postdata" : textarea.value, "id" : id.value }) }).then(() => … -
How do I call a function inside another function from different files in django and display its objects on the frontend?
Please, can anyone help me out. I am trying to call a function I defined in my views.py under food_app into another application in my project. after calling it, it works but I have a problem in reading out the function objects on my html template. it usually displays "₦<HttpResponse status_code=200, "text/html; charset=utf-8">" But the objects prints out on the terminal after when printed. This is the first function defined views.py #food_app def price_in_packs(request): total_price1 = "" total_price2 = "" total_price3 = "" total_price4 = "" total_price5 = "" total_price6 = "" total_price7 = "" total_price8 = "" total_price9 = "" total_price10 = "" total_price11 = "" total_price12 = "" price_pack_box1 = "" price_pack_box2 = "" price_pack_box3 = "" price_pack_box4 = "" price_pack_box5 = "" price_pack_box6 = "" price_pack_box7 = "" price_pack_box8 = "" price_pack_box9 = "" price_pack_box10 = "" price_pack_box11 = "" price_pack_box12 = "" food = "" food_price = "" #try and except is used here to avoid a null or empty value input by the user. A user can forget to input a price in pack value, which can break the code. if request.method == "POST": if request.POST["form"] == "form1": try: price_pack_box1 = int(request.POST.get("price1")) food = Food.objects.get(pk=1) … -
Is it possible to apply list_filters for parent's object's fields in django?
I want to display the timestamp stored in my parents model to be shown in my model. Also, I want to display it in german format. This is not the problem, but of course I want to be able to sort by this timestamp. One solution would be to create a new DateTimeField in model B, but then I would store redundant information. How can I do that with Django? For example: #models.py class A(models.Model): timestamp = models.DateTimeField(null=True) class B(models.Model): key_to_a = models.ForeignKey(DjangoPage, on_delete=models.CASCADE, null=True) ########## #admin.py class BAdmin(admin.ModelAdmin): def german_timestamp(self, B): return B.key_to_a.timestamp.strftime('%d-%m-%Y %H:%M:%S') german_timestamp.short_description = "timestamp" list_display = ("german_timestamp") list_filter = ("german_timestamp") #This breaks my code as there is no field called "german_timestamp" -
Computing difference between two datefields in Django Model
I have two datefields fields in a Django model, start_date and end_date. I want to calculate and store the total number of days between the two, which will be used alongside a daily fee to return total cost. models.py class Booking(models.Model): """Stores the bookings, for example when it was made, the booking date, and the car ID.""" # Unique ID for this booking. start_date = models.DateField(default=timezone.now) end_date = models.DateField(null=True) Most answers recommend extracting the days function (using start_date.day) but that doesn't work. If a booking starts on November 30, and ends on December 2, the function will return 28 days because it subtracts the integers alone. Using simple addition and subtraction: duration = end_date - start_date returns an error: TypeError: Unsupported Operand type(s) for -: 'DateField' and 'DateField' I've tried using a function nested within the model, which subtracts each day from end_date until it reaches start_date: def get_total_days(self): """Computes total number of days car will be rented from with a basic While loop.""" # Create separate instances of start and end day so as not to tamper with db values. start_day = self.start_date end_day = self.end_date days = 0 while end_day > start_day: days += 1 end_day -= 1 … -
How to add godot html5 game to my django website
I'm creating a website with django where users can play games, I already made the game on godot and exported to html5 but I don't know how to add the game to the website (I also don't know if its possible which I think it is). I am trying to achieve something where I can always add new games and their names through the admin panel. I not sure if I,m supposed to ask a question this short but I'm very new to python and django so I don't know what to do. -
Filter TreeNode children by parent
How i can order my queryset, by category_views field in treenode model I tried with ordering = ["category_stats__category_views"] (on settings "DEFAULT_FILTER_BACKENDS" configured with "rest_framework.filters.OrderingFilter") but it's, not working # category models.py from tree_queries.models import TreeNode class Category(TreeNode) foo = models.CharFiled() bar = models.CharField() class CategoryStats(models.Model) category = models.ForeingKey(Category, related_name="category_stats") category_views = models.IntegerField() # category views.py class CategoryViews(FrontEndListView): serializer_class = serializers.CategoryListSerializer # ordering = ["category_stats__category_views"] lookup_field = "id" def get_queryset(self): queryset = models.Category.objects.filter(parent_id=self.kwargs.get("id")) for item in queryset: return item.children.all()#.order_by("category_stats__category_views") -
Snowflake sample database tables are retrieved instead of my private database-Django-snowflake package
I have specified correct database config variable with all the required credentials of my local database that is hosted,but when I am trying to auto generate models for my tables from inspectdb command,I am receiving only SNOW_FLAKE_SAMPLE schema tables into my models file Please provide me a solution I tried using options key which is specified on django-snowflake package description but receiving same tables from snowflake_sample_database schema -
Random color selection from list in django
I have a list of colors in models like: COLOR_CODE = ( ('bg1', '#8AD7E0'), ('bg2', '#E0BD75'), ('bg3', '#EAC2AC'), ('bg4', '#C0AFDB'), ('bg5', '#96B2E0'), ('bg6', '#8BE0B0'), ('bg7', '#D2A1E0'), ('bg8', '#BCE080'), ) i need to use them in serializers, how can i do that? I am very new to django and i tried codes like ''.join([random.choice(chars) for c in range (10)]) the above was for random choice for passwords -
Django data was not brought to heroku
I have Django apps, which include users and posts models. The apps work perfectly at local following making migrations and migrating. I tried two different ways to deploy the apps to Heroku. First, using Heroku Git, the apps works on Heroku the same as at local. When using GitHub, however, all data were not brought to Heroku. I tried to run "python manage.py makemigrations" and "python manage.py migrate", but the data from local was not brought still. I would really appreciate it if you could please explain and help with the issue using GitHub. Thank you -
Javascript doesn't execute when the html is called by a hx-get
I have the following html's that i load in a Django app: pie_chart.html {% load i18n %} <div id="chartcontainer" > <div style= "width: 400px;" "height: 400px;"> <canvas id="pie-chart"></canvas> <b>Balance: </b> {{balance}}<br> </div> <div> <h5>Detail group: <select name="group" id="group" hx-get="groupdetail/" hx-trigger="click changed delay:1s" hx-target="#groupchart" hx-include="[name='year']" hx-swap="innerHTML" >} {% for l in labels %} {% if l == groupcode %} <option value={{l}} selected>{{l}}</option> {% else %} <option value={{l}}>{{l}}</option> {% endif %} {% endfor %} </select> </h5> </div> <div id=groupchart> {% include 'bar_chart.html' %} </div> </div> <script> var config_pie = { type: 'pie', data: { datasets: [{ data: {{ data|safe }}, backgroundColor: {{ backgroundcolor|safe }}, label: 'Amount_EUR', }], labels: {{ labels|safe }} }, options: { responsive: true } }; var ctx_pie = document.getElementById('pie-chart').getContext('2d'); window.myPie = new Chart(ctx_pie, config_pie); </script> bar_chart.html {% load i18n %} <div> <div style= "width: 400px;" "height: 400px;"> <canvas id="group-chart"></canvas> <b>Balance: </b> {{groupbalance|safe}} <br> <p id="data"> her should com the config_bar var</p> </div> </div> <script> var config_bar = { type: 'bar', data: { datasets: [{ data: {{ groupdata|safe }}, backgroundColor: {{ backgroundcolor|safe }}, label: 'Amount_EUR', }], labels: {{ grouplabels|safe }} }, options: { indexAxis: 'y', responsive: true } }; var ctx_bar = document.getElementById('group-chart').getContext('2d'); window.myBar = new Chart(ctx_bar, config_bar); document.getElementById("data").innerHTML = … -
How to generate an automatic incrementing custom id to created forms in django?
I'm working on a bug tracker system and I would like to generate automatic incrementing id for eg: BUG001, BUG002, BUG003 etc. Also I need to create IDs like this for the existing ones as well. How can I establish this mechanism? models.py file ` from django.db import models from phonenumber_field.modelfields import PhoneNumberField, formfields from django.utils import timezone from django.contrib.auth.models import User # Create your models here. status_choice = [("Pending","Pending"),("Fixed","Fixed"),("Not Fixed","Not Fixed")] class bug(models.Model): name = models.CharField(max_length=200, blank= False, null= False) info = models.TextField() status = models.CharField(max_length=25, choices=status_choice, default="Pending") fixed_by = models.CharField(verbose_name="Fixed by/Assigned to", max_length=30) phn_number = PhoneNumberField() user = models.ForeignKey(User, on_delete= models.CASCADE) created_at = models.DateTimeField(auto_now_add= True) updated_at = models.DateTimeField(auto_now= True) screeenshot = models.ImageField(upload_to='pics') forms.py file ` from django.forms import ModelForm from django import forms from .models import bug from phonenumber_field.modelfields import PhoneNumberField status_choice = [("Pending","Pending"),("Fixed","Fixed"),("Not Fixed","Not Fixed")] class UploadForm(ModelForm): name = forms.CharField(max_length=200) info = forms.TextInput() status = forms.ChoiceField(choices = status_choice, widget= forms.RadioSelect()) fixed_by = forms.CharField(max_length=30, label="Fixed by/Assigned to") phn_number = PhoneNumberField() #created_by = forms.CharField(max_length=30) #created_at = forms.DateTimeField() #updated_at = forms.DateTimeField() screeenshot = forms.ImageField() class Meta: model = bug fields = ['name', 'info', 'status', 'fixed_by', 'phn_number', 'screeenshot'] ` Generate automatic incrementing custom ids. -
How to persist data when uploading content to texbox?
Ok, I am really stuck with this. And I am searched a lot for it. But I can't figure out how to deal with the following issue. The situation is as follows: I have two submit buttons and two forms. And I want to upload a file independent of the other upload file. Because I have one upload for PDF and the other one for uploading a Excel file. But the problem now is when a user upload a PDF file and the content displays in a text box and the user choose for uploading a Excel file in the other textbox. The content of the PDF file will be erased. Because of refresh. So this is the template stuff: <form class="form-inline" role="form" action="/controlepunt140" method="POST" enctype="multipart/form-data" > <div class="form-group"> {% csrf_token %} {{ form }} <button type="submit" name="form_pdf" class="btn btn-warning"> Upload! </button> </div> <div class="form-outline"> <div class="form-group"> <textarea class="inline-txtarea form-control" id="content" cols="70" rows="25"> {{content}}</textarea> </div> </div> </form> </div> </span> <span class="form-inline" role="form"> <div class="inline-div"> <form class="form-inline" role="form" action="/controlepunt140" method="POST" enctype="multipart/form-data"> <div class="form-group"> {% csrf_token %} {{ form }} <button type="submit" name="form_excel" class="btn btn-warning"> Upload! </button> </div> <div class="form-outline"> <div class="form-group"> <textarea class="inline-txtarea form-control" id="" cols="65" rows="25"> {{content_excel}}</textarea> </div> </div> </form> … -
How to compare old and new field values in Django serialiazer?
Good afternoon! I have a Django model which has a many to many field. When adding or changing a record in this table, I need to perform certain actions. Because the table contains a many to many field, I can't perform model-level validation using the save method.(Correct me if I am wrong, but when i add or remove many to many field then save method on main table is not called) So I'm trying to override the save method on the serializer. def save(self, **kwargs): obj = super(PlanningExchangeRateSerializer, self).save(**kwargs) return obj Can you please tell me how to determine whether any field values have changed? -
Stripe implementation in django not redirecting to success page
I was trying to implement stripe in django and everything worked fine until i tried to redirect the user to a success page after the payment. Can anybody have a look at my code and tell me what I am doing wrong? Any help would be appriaceted views.py @csrf_exempt def create_checkout_session(request, id): request_data = json.loads(request.body) gig = get_object_or_404(Gig, pk=id) stripe.api_key = settings.STRIPE_SECRET_KEY checkout_session = stripe.checkout.Session.create( customer_email=request_data['email'], payment_method_types=['card'], line_items=[ { 'price_data': { 'currency': 'eur', 'product_data': { 'name': gig.seller, }, 'unit_amount': int(gig.price * 100), }, 'quantity': 1, } ], mode='payment', success_url='http://127.0.0.1:8000/checkout/success?session_id={CHECKOUT_SESSION_ID}', cancel_url='http://127.0.0.1:8000/checkout/failed/', ) order = OrderDetail() order.customer_email = request_data['email'] order.gig = gig order.stripe_payment_intent = checkout_session.payment_intent order.amount = int(gig.price * 100) order.save() # return JsonResponse({'data': checkout_session}) return JsonResponse({'sessionId': checkout_session.id}) class PaymentSuccessView(TemplateView): template_name = "checkout/payment_success.html" def get(self, request, *args, **kwargs): session_id = request.GET.get('session_id') if session_id is None: return HttpResponse("failed") stripe.api_key = settings.STRIPE_SECRET_KEY session = stripe.checkout.Session.retrieve(session_id) order = get_object_or_404(OrderDetail, stripe_payment_intent=session.payment_intent) order.has_paid = True order.save() return render(request, self.template_name) models.py from django.db import models from django.core import validators class OrderDetail(models.Model): id = models.BigAutoField( primary_key=True ) # You can change as a Foreign Key to the user model customer_email = models.EmailField( verbose_name='Customer Email' ) gig = models.ForeignKey( to=Gig, verbose_name='Product', on_delete=models.PROTECT ) amount = models.IntegerField( verbose_name='Amount' ) stripe_payment_intent = … -
redirect not happening despite the request being announced in the console
I have an increment function in views.py that sends and receives data. At each data reception it increments a value and when this value reaches a threshold it redirects to a page, page2.html I have the request indicating that it accesses page2 but nothing happens. I always stay on page 1 "POST incremente HTTP/1.1" 302 0 "GET page2 HTTP/1.1" 200 1395 views.py from django.http import JsonResponse def page1(request): # load and init data request.session["nb"] = 0 return render(request, 'page1.html', context:{"nb": 0) def incremente(request): request.session["nb"] = request.session.get("nb") +1 if(request.session.get("nb") < 5): return JsonResponse({"nb": request.session.get("nb")}) else: print("goToScore") redirect("p2") def page2(request): return render(request, "page2.html") page1.html <body> <h1 id="title"> </h1> <form id="myForm" method="POST"> {% csrf_token %} <button id="submit" type="submit">Valider</button> </form> <script type="text/javascript"> document.getElementById("titre").textContent = "{{nb}}" const form = document.getElementById('myForm') form.addEventListener('submit', sendData); function sendData(event){ event.preventDefault(); const csrf = $('input[name="csrfmiddlewaretoken"]').val() $.ajax({ type: "POST", url: 'incremente', // data: { csrfmiddlewaretoken : csrf, "result": "data" }, dataType: "json", success: function (data) { document.getElementById("title").textContent = data["nb"] }, failure: function () {alert("failure");} }) } </script> </body> urls.py from django.urls import path, re_path from . import views urlpatterns = [ path('page1', views.initQuiz, name="p1"), re_path(r'^incremente$', views.incremente), path('page2',views.page2,name="p2"), ] -
I'm Trying to create a superuser model and i'm getting the error below
from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager Create your models here. class MyUserManager(BaseUserManager): # create user def create_user(self, email, phone, password=None): if not email: raise ValueError('----------EMAIL REQUIRED----------') if not phone: raise ValueError('----------PHONE NUMBER REQUIRED----------') user = self.model( email = self.normalize_email(email), phone = phone ) user.set_password(password) user.save(using=self._db) return user # create super user def create_superuser(self, email, phone, password=None): if not email: raise ValueError('----------EMAIL REQUIRED----------') if not phone: raise ValueError('----------PHONE NUMBER REQUIRED----------') user = self.create_user( email = email, phone = phone, password = password ) user.is_admin = True user.is_staff = True user.is_supersuser = True user.save(using=self._db) return user my user class model class MyUser(AbstractBaseUser): email = models.EmailField(verbose_name='email', max_length=50, unique=True) phone = models.CharField(verbose_name='phone', max_length=50) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['phone'] objects = MyUserManager() def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_lable): return True Project setthing AUTH_MODEL_USER = serivce.MyUser /* I'm tried to create an admin user login with the command python manage.py createsuperuser the email I used : coded@gmail.com the error i'm getting: Error: Enter a valid email address. */ -
Replace some special characters from username in django
how i can set django username as telegram username characters example testuser_user testuser_user_5 jQuery(function($) { $("#id_username").on("keyup blur", function() { $(this).val($(this).val().replace(/[^a-z0-9]/ig, '')); }); }); -
Is there a way to order Wagtail Blocks in the Admin Panel
Currently I have all blocks split out into different groups for the page editors to easily navigate through the different block options. However, from reading the documentation I cannot see any way to specifically order the groups. It would be great to be able to customise this so that I could have the text editor group at the top, the image group/carousel block next to each other etc. -
path in FileField django
I prepared my model to create PDF filled by all the fields it includes and I try to to link generated file to the pdf = models.FileField(). However the path to the file seems to be ok I can't reach the file through the view. models.py: class Lesson(models.Model): # fields # ... pdf = models.FileField(upload_to = 'pdfs/', default = None, blank = True) def render_template(self, request): #some magic BASE_DIR = str(Path(__file__).resolve().parent.parent) file_name = 'myfile' os.system(f"pdflatex -halt-on-error --output-directory={BASE_DIR}/media/pdfs {BASE_DIR}/media/tex/rendered/{file_name}") os.system(f"rm {BASE_DIR}/media/tex/rendered/{file_name}.tex") os.system(f"rm {BASE_DIR}/media/pdfs/{file_name}.aux") os.system(f"rm {BASE_DIR}/media/pdfs/{file_name}.log") return f"{BASE_DIR}/media/pdfs/{file_name}.pdf" views.py: def create_lesson(request): lesson = Lesson() lesson.pdf = lesson.render_template(request) lesson.save() message = { 'tag' : 'success', 'body' : "Successfully added new lesson!" } return JsonResponse({'message' : message}) But when putting <a href="{{ lesson.pdf }}">CLICK TO VIEW FILE</a> the link directs to: http://localhost:8000/docs/lessons/media/pdfs/myfile.pdf What path should be set to pdf field to direct to media/pdf/myfile.pdf in models.py? -
Django: How to add created_at with nulls for old records?
I'm trying to add created_at field to a table with millions of records, and I don't want to add value to the previous records. I have tried the following: created_at = models.DateTimeField(auto_now_add=True) OR created_at = models.DateTimeField(auto_now_add=True, null=True) Still, it set the value to all records, not only to new ones. How can I keep the old with nulls? My database is postgresql -
celery in django project unable to connect to dockerized RabbitMQ in local development
everything runs on mac - i have an django project with celery running. I configured (as always) RabbitMQ as Broker and Redis as Result Backend. When i start the worker i get [2022-11-18 11:53:56,256: ERROR/MainProcess] consumer: Cannot connect to amqp://guest:**@127.0.0.1:5672//: Server unexpectedly closed connection. Trying again in 18.00 seconds... (9/100) celery settings CELERY_TIMEZONE = TIME_ZONE CELERY_RESULT_BACKEND = "redis://localhost" CELERY_BROKER_URL = "amqp://localhost" docker-compose.yaml version: "3.8" services: db: image: postgres:14 ports: - "5432:5432" environment: - POSTGRES_DB=local - POSTGRES_USER=test_user - POSTGRES_PASSWORD=test_test1! volumes: - db-data:/var/lib/postgresql/data redis: image: redis ports: - "6379:6379" volumes: - redis-data:/data rabbitmq: image: rabbitmq:management ports: - "5672:5762" - "15672:15672" volumes: db-data: redis-data: Connecting to the Management panel with base guest:guest works fine, but celery can't connect. Expecting that celery can connect to rabbitmq and no connection gets closed -
Passing variable to href django template
I have some problem and maybe I can give an example of two views below what I want to achieve. class SomeViewOne(TemplateView): model = None template_name = 'app/template1.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) # The downloads view contains a list of countries eg France, Poland, Germany # This returns to context and lists these countries in template1 class ItemDetail(TemplateView): model = None template_name = 'app/template2.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) countries_name = kwargs.get('str') The view should get the passed "x" with the name of the country where I described it below. Then on the page I have a list of these countries. After clicking on the selected country, a new tab should open and show a list of cities in the selected country. So I am using in loop template1.html as below {% for x in list_countries %} <li> <a href="{% url 'some-name-url' '{{x}}' %}" class="target='_blank'">{{ x }}</a><br> </li> {% endfor %} I can't pass "x" this way. Why? The url for the next view looks like this path('some/countries/<str:x>/',views.ItemDetail.as_view(), name='some-name-url'), And I can't get that 'x' given in the template in the href -
How to add trix.css when it is removed after pruning?
After pruning with the command "docker system prune -a" nodejs wont build anymore beacuse trix.css is missing. I am assuming this was probably deleted while pruning. How can I resolve this error (see the error below)? Why is it not created again while building the container again since the file is in the docker file. Required path doesn't exist: /code/bower_components/trix/dist/trix.css trix [13:57:39] 'vendorcss' errored after 1.63 ms [13:57:39] Error: Promise rejected without Error at Domain.onError (/usr/local/lib/node_modules/gulp/node_modules/async-done/index.js:49:15) at Object.onceWrapper (events.js:315:30) at emitOne (events.js:116:13) at Domain.emit (events.js:211:7) at Domain._errorHandler (domain.js:134:21) at process._fatalException (bootstrap_node.js:375:33) [13:57:39] 'staging' errored after 41 ms ERROR: Service 'nodejs' failed to build: The command '/bin/sh -c gulp staging' returned a non- zero code: 1 Usually I use this command : "sudo docker-compose -f docker-compose-staging.yml build nodejs" when I want to build the container again. I am very new to this and would be greatfull for some help. -
Error: Apps aren't loaded yet. when fork subprocess in django views
I want to fork subprocess in django view def subprocess_setup(): if not settings.configured: settings.configure() django.setup() class ABView(CustomModelViewSet): def _query_facebook_balance(self, query_record_id): ... @action(methods=['get'], url_path='account-balance', detail=True) def query_account_balance(self, request, *args, **kwargs): with ProcessPoolExecutor(max_workers=3, initializer=subprocess_setup) as pe: process_list = [] future = pe.submit(VSSign()._query_facebook_balance, query_record_id) process_list.append(future) for future in as_completed(process_list): future.result() ... return Response(self.response_no_http_error(data=ret)) but it always failed like below. Process SpawnProcess-1: Traceback (most recent call last): File "/usr/local/Cellar/python@3.9/3.9.13_3/Frameworks/Python.framework/Versions/3.9/lib/python3.9/multiprocessing/process.py", line 315, in _bootstrap self.run() File "/usr/local/Cellar/python@3.9/3.9.13_3/Frameworks/Python.framework/Versions/3.9/lib/python3.9/multiprocessing/process.py", line 108, in run self._target(*self._args, **self._kwargs) File "/usr/local/Cellar/python@3.9/3.9.13_3/Frameworks/Python.framework/Versions/3.9/lib/python3.9/concurrent/futures/process.py", line 240, in _process_worker call_item = call_queue.get(block=True) File "/usr/local/Cellar/python@3.9/3.9.13_3/Frameworks/Python.framework/Versions/3.9/lib/python3.9/multiprocessing/queues.py", line 122, in get return _ForkingPickler.loads(res) File "/Users/apple/Develop/bv_crm/api/sign/views.py", line 19, in <module> from rest_framework.decorators import action File "/Users/apple/Develop/bv_crm/venv3.9/lib/python3.9/site-packages/rest_framework/decorators.py", line 13, in <module> from rest_framework.views import APIView File "/Users/apple/Develop/bv_crm/venv3.9/lib/python3.9/site-packages/rest_framework/views.py", line 17, in <module> from rest_framework.schemas import DefaultSchema File "/Users/apple/Develop/bv_crm/venv3.9/lib/python3.9/site-packages/rest_framework/schemas/__init__.py", line 33, in <module> authentication_classes=api_settings.DEFAULT_AUTHENTICATION_CLASSES, File "/Users/apple/Develop/bv_crm/venv3.9/lib/python3.9/site-packages/rest_framework/settings.py", line 220, in __getattr__ val = perform_import(val, attr) File "/Users/apple/Develop/bv_crm/venv3.9/lib/python3.9/site-packages/rest_framework/settings.py", line 168, in perform_import return [import_from_string(item, setting_name) for item in val] File "/Users/apple/Develop/bv_crm/venv3.9/lib/python3.9/site-packages/rest_framework/settings.py", line 168, in <listcomp> return [import_from_string(item, setting_name) for item in val] File "/Users/apple/Develop/bv_crm/venv3.9/lib/python3.9/site-packages/rest_framework/settings.py", line 177, in import_from_string return import_string(val) File "/Users/apple/Develop/bv_crm/venv3.9/lib/python3.9/site-packages/django/utils/module_loading.py", line 17, in import_string module = import_module(module_path) File "/usr/local/Cellar/python@3.9/3.9.13_3/Frameworks/Python.framework/Versions/3.9/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "/Users/apple/Develop/bv_crm/utils/middleware.py", line 10, in … -
is it possble to split saving data automatically?
i have created 2 table, A and B. is it possible to split the data by choice? I mean like while creating data when i pick a from load_type it auto save my data to table A or if i pick b it save to table B.and while i was in B when i change the load_type to a it moves my data to A. is it possible? models.py ` class LoadType(models.Model): load = [ ('a','typeA'), ('b','typeB') ] load_type = models.CharField(max_length=10,choices=load) class A(models.Model): code = models.AutoField(primary_key=True) load_type = models.ForeignKey(LoadType,on_delete=models.DO_NOTHING) load_no = models.CharField(max_length=255,blank=True,null=True) material_no = models.CharField(max_length=255,blank=True,null=True) quantity = models.IntegerField() move_type = models.CharField(max_length=255,blank=True,null=True) start_area = models.CharField(max_length=255,blank=True,null=True) start_point = models.CharField(max_length=255,blank=True,null=True) end_area = models.CharField(max_length=255,blank=True,null=True) end_point = models.CharField(max_length=255,blank=True,null=True) priority = models.IntegerField() created_at = models.DateTimeField(auto_now_add=True) class B(models.Model): code = models.AutoField(primary_key=True) load_type = models.ForeignKey(LoadType,on_delete=models.DO_NOTHING) load_no = models.CharField(max_length=255,blank=True,null=True) material_no = models.CharField(max_length=255,blank=True,null=True) quantity = models.IntegerField() move_type = models.CharField(max_length=255,blank=True,null=True) start_area = models.CharField(max_length=255,blank=True,null=True) start_point = models.CharField(max_length=255,blank=True,null=True) swap_area = models.CharField(max_length=255,blank=True,null=True) swap_point = models.CharField(max_length=255,blank=True,null=True) end_area = models.CharField(max_length=255,blank=True,null=True) end_point = models.CharField(max_length=255,blank=True,null=True) priority = models.IntegerField() created_at = models.DateTimeField(auto_now_add=True) ` Not sure if i need to add a new form or add some function ?