Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I show Subset from multiple model in Django Custom View with the UI same as other models?
I have created a Custom view in Admin Panel with this code in admin.py. I want the sometemplate.html template to have the information in the same UI format just like when I click on another model in the admin panel, and that information needs to be a combination of rows from multiple models. So, the data is displayed in this custom view will have all the entries from multiple models with valid = False How can I do that in my custom view of Django admin? class DummyModelAdmin(admin.ModelAdmin): model = DummyModel def my_custom_view(self,request): # return HttpResponse('Admin Custom View') context = dict( ) return TemplateResponse(request, "webapp/sometemplate.html", context) def get_urls(self): view_name = '{}_{}_changelist'.format( self.model._meta.app_label, self.model._meta.model_name) return [ path('my_admin_path/', self.my_custom_view, name=view_name), ] admin.site.register(DummyModel, DummyModelAdmin) sometemplate.html code: {% extends "admin/base_site.html" %} {% block content %} {% endblock %} -
Errors when get with axios in a django + vue app
I created an app with vue as front and django as back, now i try to make them communicate with axios, I've got this in my settings.py ... CORS_ORIGIN_ALLOW_ALL = True INSTALLED_APPS = [ ... 'rest_framework', 'corsheaders', ... ] MIDDLEWARE = [ ... 'django.middleware.common.CommonMiddleware', 'corsheaders.middleware.CorsMiddleware' ] if I go to localhost:8000/API/questions I can POST new data or GET. In frontend, i've got this in an API.js file import axios from 'axios' const api = axios.create({ baseURL: 'http://127.0.0.1:8000/API/', timeout: 1000, withCredentials: false, headers: { 'Access-Control-Allow-Origin' : '*', 'Access-Control-Allow-Methods':'GET,PUT,POST,DELETE,PATCH,OPTIONS', } }); export const getQuestions = async function() { const response = await api.get('questions/'); return response.data; } When I call my function, this error shows up Access to XMLHttpRequest at 'http://127.0.0.1:8000/API/questions/' from origin 'http://localhost:8080' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response. GET http://127.0.0.1:8000/API/questions/ net::ERR_FAILED Uncaught (in promise) Error: Network Error at createError (createError.js?2d83:16) at XMLHttpRequest.handleError (xhr.js?b50d:84) -
multi-selecting from dynamic dropdownlist in django
I come from MSAccess with extensive VBA. In a questionnaire I create dynamic dropdownlists. From the displayed list (1-15 items) users can select a number of items (kind of priority-sublist). The choices should be registered for later use in a couple of reports. How do I do this in Python/Django? -
How to send a simple data by Ajax jQuery to views.py in Django?
I want to send a simple data (a number) from home.html to a function in views.py by using Ajax jQuery. But it seems that the the function is not being called. home.html: I get the success response correctly. I see the tagID on the success notification. I want to see that in my views.py ... function GetInfo(e){ document.getElementById("test3").innerHTML = e.target.myCustomID; var tagID = e.target.myCustomID; $.ajax({ url: 'Ajax1', type: "POST", data: { 'tagID': tagID, 'csrfmiddlewaretoken': '{{ csrf_token }}', }, success: function (data) { alert ("Congrats! You sent some data: " + tagID);} , error: function() { alert ("Something went wrong"); } })}; views.py: I want to see that this function is called by the ajax. So if the command print ("AAAAAAAAAAAAA") works, I am happy! ... @csrf_exempt def Ajax1(request): print ("AAAAAAAAAAAAA") if request.is_ajax() and request.POST(): print("BBBBBBBBBBBBB") TagID = request.POST.get('tagID', None) else: raise Http404 my_app/urls.py urlpatterns = [ url(r'', views.home_map, name="home"), url(r'^ajax/$', views.Ajax1, name="Ajax") ] urls.py urlpatterns = [ path(r'', include('my_app.urls')), path('admin/', admin.site.urls), path(r'^ajax/$', Ajax1, name='Ajax') ] would you please let me know what I am missing? thanks -
djoser not sending activation email
im trying to get djoser or simple jwt(not sure which is supposed to send) to send an activation link after user registration but it doesnt seem to be doing anything. I registered my email account with an app password. Any help will be appreciated thanks. my settings.py: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ), } SIMPLE_JWT = { 'AUTH_HEADER_TYPES': ('JWT',), } EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'kingrafiki61@gmail.com' EMAIL_HOST_PASSWORD = '*********' EMAIL_USE_TLS = True DJOSER = { 'LOGIN_FIELD':'Email_Address', 'USER_CREATE_PASSWORD_RETYPE':True, 'USERNAME_CHANGED_EMAIL_CONFIRMATION':True, 'PASSWORD_CHANGED_EMAIL_CONFIRMATION':True, 'SEND_CONFIRMATION_EMAIL':True, 'SET_USERNAME_RETYPE':True, 'SET_PASSWORD_RETYPE':True, 'PASSWORD_RESET_CONFIRM_URL':'password/reset/confirm/{uid}/{token}', 'USERNAME_RESET_CONFIRM_URL':'password/reset/confirm/{uid}/{token}', 'ACTIVATION_URL':'activate/{uid}/{token}', 'SEND_ACTIVATION_EMAIL':True, 'SERIALIZERS': { 'user_create': 'nerve.serializers.UserCreateSerializer', 'user': 'nerve.serializers.UserCreateSerializer', 'user_delete': 'djoser.serializers.UserDeleteSerializer', } } -
Downloading files using checkboxes in Django?
I have created a model using Django & am displaying its contents in form of a table on a HTML page. Each row of this table has download links for different files. I have also added a checkbox to each row of this table. I want to create a download button which will download the files corresponding to those rows whose checkboxes have been ticked . Is it possible to do this using django alone or do I need to use something else like jquery? -
format string before passing it to another filter
I have a filter which accepts string, and i should format this string with another filter before passing it to first filter. I know that I can do it with help of "with block", but this code is around whole code base and i was looking for more neat solution. May be there is a way to control order of operations in django template language Here what i have: # html file {{ params|get:'route[{}][input_address]'|format_string:0 }} # filters @register.filter def format_string(text, fmt): return text.format(fmt) @register.filter def get_list(querydict, item): if isinstance(querydict, QueryDict): return querydict.getlist(item) return querydict.get(item) I have also tried to take that in brackets but there is syntax error -
Why is my custom django-admin command not running on Heroku?
I have created a custom django-admin command that finds the average price for an item with prices from various retailers. The average price is saved as an object in my PriceHistory model to form data points for product history charts. My Command python manage.py average works on my computer and it also works on the Heroku CLI, however, Heroku Scheduler is not running the command and no data is being saved, even though Heroku Scheduler works fine with my other Custom Commands. Useful Docs: https://devcenter.heroku.com/articles/scheduling-custom-django-management-commands average.py class Command(BaseCommand): def handle(self,*args,**options): try: products = Product.objects.all() for i in range(len(products)): total = 0 count = 0 self.stdout.write(self.style.SUCCESS(products[i]._id)) array = RetailerProduct.objects.filter(product=products[i]) for item in array: #print(item.price) if item.price != 0.00: total += item.price count += 1 try: mean = total/count except ZeroDivisionError: mean=0.00 self.stdout.write(self.style.SUCCESS(products[i].name+" : £"+str(mean))) save_mean = PriceHistory(price=round(float(mean),2),product=products[i]) save_mean.save() except: self.stdout.write(self.style.ERROR(error)) return self.stdout.write(self.style.SUCCESS('Successfully calculated all averages')) return Product Model: class Product(models.Model): name = models.CharField(max_length=30,null=True,blank=True) brand = models.CharField(max_length=20,null=True,blank=True) image = models.ImageField(null=True,blank=True) _id = models.AutoField(primary_key=True, editable=False) Retailer Product Model: class RetailerProduct(models.Model): url = models.CharField(max_length=300,null=True,blank=True) price = models.DecimalField(default=0.00,max_digits=8,decimal_places=2,null=True,blank=True) difference = models.DecimalField(default=0.00,max_digits=8,decimal_places=2,null=True,blank=True) retailer = models.ForeignKey(Retailer, on_delete=models.CASCADE) available = models.BooleanField(default=False) _id = models.AutoField(primary_key=True, editable=False) product = models.ForeignKey(Product, on_delete=models.CASCADE,related_name='sources') Price History Model: class PriceHistory(models.Model): price = models.DecimalField(default=0.00,max_digits=8,decimal_places=2) product … -
Django: How to create a mixin to set common attributes for every model?
I have a model mixin that sets created_at, created_by, updated_at and updated_by which I then inherit to most of the models in my project. This model mixin works fine. Obviously setting created_at and modified_at is very easy due to auto_now_add and auto_now. class Timestampable(models.Model): created_at = models.DateTimeField( auto_now_add=True, db_index=True, verbose_name=_('created at') ) created_by = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, related_name="created%(app_label)s_%(class)s_related", on_delete=models.SET_NULL) updated_at = models.DateTimeField( auto_now=True, db_index=True, verbose_name=_('updated at') ) updated_by = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, related_name="updated%(app_label)s_%(class)s_related", on_delete=models.SET_NULL) class Meta: abstract = True ordering = ['-created_at'] But, what I want is to also create a mixin (or maybe subclass) CreateView and UpdateView to set created_by and updated_by to be self.request.user everywhere those CBVs are used ( I would guess by modifying get_form() or form_valid()). I'll also need to create a similar admin mixin to modify save_model(). I have never created a custom mixin and the things I have found/tried aren't working. For example I got subclassing CreateView working by modifying get_form() but then, I couldn't further modify get_form() in the various class ModelXCreate(...) views I created. Does anybody know how I can achieve this? It'd be super useful to be able to have such a mixin and keep things DRY. -
Django Apache server error. no module named 'psycopg2._psycopg' [Dulicate, but duplicate answers didn't work :(]
I am running ubuntu-server 20 and I am trying to run django deplyments server on it with apache2 and libapache2-mod-wsgi-py3. I was having many errors but i somehow managed to fix them but I am stuck on this error: django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: No module named 'psycopg2._psycopg' psycopg2 and psycopg2-binary are installed in my env. Also I am using python version 3.9. Here are my apache server configs (if you need them) <VirtualHost *:80> ServerAdmin webmaster@localhost DocumentRoot /var/www/html ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined ServerName darkzone Alias /static /home/nika/HackerForum/staticfiles <Directory /home/nika/HackerForum/staticfiles> Require all granted </Directory> Alias /media /home/nika/HackerForum/media <Directory /home/nika/HackerForum/media> Require all granted </Directory> <Directory /home/nika/HackerForum/HackerForum> <Files wsgi.py> Require all granted </Files> </Directory> WSGIScriptAlias / /home/nika/HackerForum/HackerForum/wsgi.py WSGIDaemonProcess darkzone python-path=/home/nika/HackerForum python-home=/home/nika/HackerForum/venv WSGIProcessGroup darkzone </VirtualHost> WSGIPythonHome /home/nika/HackerForum/venv WSGIPythonPath /home/nika/HackerForum -
Get all object permissions of a group with Djano guardian
I am using Django Permission to have an object-level permission setting. I am finding it hard to display the permissions under a specific group. Group.objects.get_or_create(name="Admin") admin_group = Group.objects.get(name='Admin) task = Task.objects.get(id=1) assign_perm("view_task", admin_group, task) This will prompt: <GroupObjectPermission: Task1 | Admin | view_task> And I have to get the list of all the permissions under this Admin Group. I tried it this way: admin_group.permissions.all() # output is <QuerySet []> admin_group.permissions # output is auth.Permission.None Is there any way I can list out all the permissions under a specific group? -
How to set a fixed datetime.now() variable in Django using datetime.datetime
I want to have two record dates of a blog post, one is the date the post was created on, and the last time/date the post was updated. But the issues is the date_created variable reset every time I make any changes. ... from datetime import datetime class Post(models.Model): ... date_created = datetime.now() # how to not reset this variable everytime when I update changes to the post? last_edited_date = datetime.now() -
Django - foreign key to ManyToMany (through) fails with SystemCheckError
Using the following relations: class Author(models.Model): pass class Book(models.Model): authors = models.ManyToManyField(to=Author) class Contract(models.Model): work = models.ForeignKey(to=Book.authors.through, on_delete=models.CASCADE) we are trying to have a foreign key point at the through model without explicitly defining it (see also comment by Daniel Roseman in Django using a ManytoMany as a Foreign Key ) This fails with SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: Contract.work: (fields.E300) Field defines a relation with model 'Book_authors', which is either not installed, or is abstract. Book.authors.through is a model that is not abstract. Why does it not work anymore (django 3.2)? -
How do update last message date in Django model
I have two models where users create a post and comment on that post. When users comment this post I want updating last_message date on UserPost model. If there are no comments yet I want the default last_message date to be set to the date the post was created. Models: class UserPosts(models.Model): postTitle = models.CharField(max_length=100, verbose_name="Title") postContent = RichTextField(null=True, verbose_name="Content") created_at = models.DateTimeField( auto_now_add=True, verbose_name="Date of upload") last_message = ????????????????? def __str__(self): return self.postTitle class UserMessages(models.Model): postMessages = RichTextField(null=True, verbose_name="Message") post = models.ForeignKey( UserPosts, on_delete=models.CASCADE, verbose_name="Linked Post", null=True) created_at = models.DateTimeField(auto_now_add=True, verbose_name="Date of upload") I couldn't find anything relevant to this topic in the Django docs, Google, and other sources. -
Django - How to get User_Id from the username String in HTML Template?
I have this HTML form containing an DropDown with All username (Passed in context data like this: users_name = User.objects.values_list('username', flat=True)), when admin select one user, he submit the form (using javascript), and an backup will render a certain table ( All of this are implemented and worked) The form : <form name="searchForm" id="searchForm" method="get"> <div class="input-append"> <input class="span2" id="user" name="user" type="hidden"> <div class="btn-group"> <button class="btn dropdown-toggle" data-toggle="dropdown"> User List <span class="caret"></span> </button> <ul class="dropdown-menu" aria-labelledby="dropdownMenu1"> <li onclick="$('#user').val('All'); $('#searchForm').submit()" selected="selected" >All Users</li> {% for user_name in users_name %} <li onclick="$('#user').val('{{ user_name }}'); $('#searchForm').submit()">{{ user_name }}</li> {% endfor %} </ul> </div> </div> </form> What I need now is how can I get the ID of selected user, to use it on an link (a tag) the tag will be Like this : <a href="/CapDelKnowledge/export/{{formId}}/{{user}}/?type=XLS"> export</a> where {{user}} represent the ID of selected user, what can i do ? -
unable to rendered the object key,value using react js
I'm New to react js, Here, We have rendering the objects in table. first we will checking the keys, if it is available it will display the data.. Stored the objects in Claim_details using python and pass it to the frontend {Object.keys(this.state.claim_details).map((e)=>{ return (e != this.state.unique_field && e != "_id")? <tr className="text-center" key={e}> <td style={{lineHeight:"1.5", whiteSpace: "pre-line"}}>{e}</td> <td style={{lineHeight:"1.5", whiteSpace: "pre-line"}}>{convertISODateToApexon(this.state.claim_details[e])}</td> </tr> :"" })} -
How to Add class model data when condition is satisfied in Django
I am using django and have created 2 class models. class Student(models.Model): is_registered = models.CharField(max_length=50, blank=True, null=True) class Attribute(models.Model): student_id = models.ForeignKey(Student, on_deleted=models.SET_NULL, null=True, blank=True) statement = models.CharField(max_length=50, blank=True, null=True) I want to add 'end' to the statement field of the Attribute class model when off is added to the value of the is_registered field of the Studnet class. When you use the update statement, the existing value is changed. How do I add a new line of data? Please help. -
How to correct this django db error in production?
screenshot from my linux server But my settings.py is completely ok in testing environment...this only happens when I take this to production..but with sqlite3 production is also fine -
celery tasks is not doing for loop it just do first thing the finished the task
celery tasks is not doing for loop it just do first thing the finished the task it doesn't give any error but it just doing one thing it seems it doesn't completely do for loop tasks.py @shared_task(bind=True) def retweet(self, consumer_key, consumer_secret, access_token, access_token_secret, clean_text, clean_count, clean_lang, sleep_time): auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) api = tweepy.API(auth, wait_on_rate_limit=True) for tweet in tweepy.Cursor(api.search, q=(clean_text) + " -filter:mentions", count=int(clean_count),lang=clean_lang).items(int(clean_count)): tweet.retweet() sleep(int(sleep_time)) views.py class Retweet(FormView): form_class = RetweetForm template_name = 'retweet.html' success_url = reverse_lazy('tweet:done') # get the information from form in our template def form_valid(self, form): try: user = self.request.user tweepy_authenticate(user.consumer_key, user.consumer_secret, user.access_token, user.access_token_secret) query = form.cleaned_data.get('query') count = form.cleaned_data.get('count') time = form.cleaned_data.get('sleep_time') lang = form.cleaned_data.get('lang') clean_text = BeautifulSoup(query, "lxml").text clean_count = BeautifulSoup(count, 'lxml').text sleep_time = BeautifulSoup(time, 'lxml').text clean_lang = BeautifulSoup(lang, 'lxml').text retweet.delay(user.consumer_key, user.consumer_secret, user.access_token, user.access_token_secret, clean_text, clean_count, clean_lang, sleep_time) -
django's models.CASCADE in a Postgres database with db_constraint
Apparently, when I'm trying to delete a parent object, an integrity e is raised specifically IntegrityError at /admin/app/parent/(attempted to delete the parent object from admin & later shell) update or delete on table "app_parent" violates foreign key constraint "app_child_model_id_724b75c4_fk_app_parent_id" on table "app_child" DETAIL: Key (id)=(2) is still referenced from table "app_child" Upon googling and some stackoverflow answers, I decided to replace models.CASCADE with models.DO_NOTHING. One time, the deletion worked well, but later I'm encountering the same error. My code is just basic class Parent(models.Model): pass class Child(models.Model): parent = models.ForeignKey(Parent, on_delete=models.CASCADE) And, I saw this postgres specific documentation page https://docs.djangoproject.com/en/3.2/ref/contrib/postgres/constraints/ I cannot fully understand the technicalities here. It would be nice if someone could explain and probably demonstrate the proper code handling with say a model named Parent and a model named Child containing a foreign key field to Parent, for Postgres specifically. I am not good with DBs, so I need your help. Thanks !! Edit: Yes. I ran my migrations. And checking the relations in the psql shell, I see the foreignkey constraints existing at the db_level. Something like "app_child_parent_id_724b75c4_fk_app_parent_id" FOREIGN KEY (parent_id) REFERENCES app_parent(id) DEFERRABLE INITIALLY DEFERRED How do I overcome this clash between Django and Postgres? … -
Uncaught ReferenceError: load_posts is not defined at <anonymous>:1:1
I am stuck on a bug in my code. I am a beginner working on the CS50 web development project4 - Network. I am trying to get the All Posts section to display the existing posts from all users. My code so far is below (and incomplete - still working on it). It doesn't look to me like the load_posts() function is able to run. I want it to auto-run once DOM Content is loaded. Nothing happens automatically once DOM COntent is loaded, so I go into the console ot run load_posts()( manually and it gives me the error: Uncaught ReferenceError: load_posts is not defined at :1:1. models.py: from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): pass class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) followers = models.ManyToManyField(User, blank=True, related_name="followers") following = models.ManyToManyField(User, blank=True, related_name="following") def __str__(self): return f"User profile for {self.user}" class Post(models.Model): poster = models.ForeignKey(User, on_delete=models.CASCADE, related_name="poster") body = models.TextField(max_length=250) timestamp = models.DateTimeField(auto_now_add=True, blank=True) likes = models.ManyToManyField(Profile, blank=True, related_name="likes") def __str__(self): return f"{self.poster} posted '{self.body}' at {self.timestamp}. It has {self.likes} likes" def serialize(self): return { "id": self.id, "body": self.body, "timestamp": self.timestamp.strftime("%b %#d %Y, %#I:%M %p"), "likes": self.likes } urls.py: from django.urls import path from . import views urlpatterns … -
ValueError... "Contestant.contest" must be a "Contest" instance
I am trying to create a contestant through a model form, each contestant is a foreign key to a contest model, Whenever i try to submit a form to create a new contestant, i get a value error: Cannot assign "27": "Contestant.contest" must be a "Contest" instance. ``` I have two models, Contest and Contestant in my `models.py` ```class Contest(models.Model): contest_title = models.CharField(max_length=30) contest_post = models.CharField(max_length=100) class Contestant(models.Model): contest = models.ForeignKey(Contest, on_delete=models.CASCADE, related_name='participating_contest') contestant_name = models.CharField(max_length=10, blank=True, null=True) contestant_intro = models.CharField(max_length=30, blank=True, null=True) contestant_post = models.CharField(max_length=100, blank=True, null=True) in my urls.py i am trying to pass the Contest primary key (PK) to the form urls.py path('contestant/<int:pk>/new/', views.ContestantCreateView.as_view(), name='new-contestant'), i am using django's createview in my views.py and trying to pass in pk to the form's form_valid function. views.py class ContestantCreateView(CreateView): model = Contestant fields = ['contestant_name', 'contestant_intro', 'contestant_post'] def form_valid(self, form): form.instance.contest = self.kwargs.get('pk') return super().form_valid(form) I tried changing my views.py to class ContestantCreateView(CreateView): model = Contestant fields = ['contestant_name', 'contestant_intro', 'contestant_post'] def form_valid(self, form): contesting_contest = Contest.objects.get(participating_contest=pk) contesting_contest.contest = form.instance.contest return super().form_valid(form) but i got NameError at /contests/contestant/27/new/ name 'pk' is not defined -
Most efficient way to pull data from a sqlite3 database and display the result on HTML using Django?
I have a fairly large database named superstore.sqlite3 with 11MB in size. I'm trying to display a table named Merged in this database to a HTML table. Now, in my views.py,I call db.get_table() to get col names and rows. def index(request): table = db.get_table() c = { "cols": table["cols"], "rows": table["rows"] } return render(request, 'myapp/index.html', c) The get_table() function basically connects to my database and fetch related data: import sqlite3 def get_table(): c = sqlite3.connect("myapp/main/database/superstore.sqlite3") cur = c.cursor() cur.execute("SELECT * from Merged LIMIT 100") table = {} table["cols"] = list(map(lambda x: x[0], cur.description)) table["rows"] = cur.fetchall(); return table In my index.html, I have the following to display the table: <table> <tr> {% for col in cols %} <th>{{ col }}</th> {% endfor %} </tr> {%for row in rows%} <tr> {%for cell in row%} <td>{{ cell }} </td> {% endfor %} <tr> {% endfor %} </table> The Problem For now, as you can see, the data-pulling happens when users load the page. It's fine for now as I've limited the amount of data to 100 rows. But the whole table has over 100k rows, if I don't limit it in my cur.execute() method, the page will take a while to load. … -
An open stream object is being garbage collected; call
I am getting the below error trying to use djangochannelsrestframework Here is my model and serializer: class TestChannel(models.Model): text = models.TextField() user = models.ForeignKey(User, related_name="commentssss", on_delete=models.CASCADE) date = models.DateTimeField(auto_now=False, auto_now_add=True) class TestChannelSerializer(serializers.ModelSerializer): class Meta: model = TestChannel fields = ["id", "text", "user"] Is there any way to sort this out? TestChannel.objects.create(text="user 1 creates a new comment", user=user_1) TestChannel object (4) An open stream object is being garbage collected; call "stream.close()" explicitly. Traceback (most recent call last): File "", line 1, in File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/query.py", line 447, in create """ File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/base.py", line 753, in save ) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/base.py", line 801, in save_base # attname directly, bypassing the descriptor. Invalidate File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/dispatch/dispatcher.py", line 177, in send if not self.receivers or self.sender_receivers_cache.get(sender) is NO_RECEIVERS: File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/dispatch/dispatcher.py", line 178, in return [] File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/djangochannelsrestframework/observer/model_observer.py", line 108, in post_save_receiver self.database_event(instance, Action.CREATE) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/djangochannelsrestframework/observer/model_observer.py", line 127, in database_event connection.on_commit(partial(self.post_change_receiver, instance, action)) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/backends/base/base.py", line 643, in on_commit # No transaction in progress and in autocommit mode; execute File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/djangochannelsrestframework/observer/model_observer.py", line 155, in post_change_receiver self.send_messages( File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/djangochannelsrestframework/observer/model_observer.py", line 173, in send_messages async_to_sync(channel_layer.group_send)(group_name, message_to_send) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/asgiref/sync.py", line 147, in call SyncToAsync.threadlocal, "main_event_loop", None File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/concurrent/futures/_base.py", line 432, in … -
Update SQL table with an existing Pandas DataFrame in Django
I'm trying update my DataBase from one script in my Django project, I call this function from views.py before use the SQL information. I have a DataFrame with some calculateds values and I would like to update all values from column with this DataFrame like this: def update_db(df_precio, table_name): sql = "UPDATE "+table_name+" SET precio_usd = "+ df_precio['calc_usd'] cursor.execute(sql) I tried this but it obviously doesn't work, how could I do this? Would it be possible? Thanks!!