Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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!! -
How to divide a huge model and group it with subdomains and keep a single modelForm
I am starting to do a project with Django and I have a very big Model that I would like to divide into sub-model it seems to me that it is possible according to the doc with models.ForeignKey but I don't know how to put them together in the same form This is my actual model and ModelForm class Device(models.Model): phone_regex = RegexValidator(regex=r'^[0-9]{10}$', message="Error: Format 0611223344") device_regex = RegexValidator(regex='^[a-zA-Z1-9]{3}$', message='Format de l\'identifiant invalide.') name = models.CharField(max_length=16) place = models.CharField(max_length=16) start_at = models.DateTimeField(default=datetime.datetime.now) end_at = models.DateTimeField(default=datetime.datetime.now) ChiefGo_function = models.CharField(max_length=16) ChiefGo_indicative = models.CharField(max_length=16) ChiefGo_phone = models.CharField(validators=[phone_regex], max_length=10) DChiefGo_function = models.CharField(max_length=10, blank=True) DChiefGo_indicative = models.CharField(max_length=10, blank=True) DChiefGo_phone = models.CharField(validators=[phone_regex], max_length=10) DSO_function = models.CharField(max_length=10, blank=True) DSO_indicative = models.CharField(max_length=10, blank=True) DSO_phone = models.CharField(validators=[phone_regex], max_length=10) device_id = models.CharField(max_length=3, validators=[device_regex], default=random_id) status = models.BooleanField(default=True) class DeviceForm(ModelForm): class Meta: ordering = ('end_at',) model = Device fields = ['name', 'place', 'start_at', 'end_at', 'ChiefGo_function', 'ChiefGo_indicative', 'ChiefGo_phone', 'DChiefGo_function', 'DChiefGo_indicative', 'DChiefGo_phone', 'DSO_function', 'DSO_indicative', 'DSO_phone', 'device_id', 'status'] widgets = { 'name': django.forms.TextInput(attrs={'placeholder': 'sairir le nom de l\'évenement'}), 'place': django.forms.TextInput(attrs={'placeholder': 'commune'}), 'start_at': django.forms.TextInput(attrs={'placeholder': 'date du début'}), 'end_at': django.forms.TextInput(attrs={'placeholder': 'date de fin'}), 'ChiefGo_function': django.forms.TextInput(attrs={'placeholder': 'fonction'}), 'ChiefGo_indicative': django.forms.TextInput(attrs={'placeholder': 'indivatif'}), 'ChiefGo_phone': django.forms.TextInput(attrs={'placeholder': '06 12 34 56 78'}), 'DChiefGo_function': django.forms.TextInput(attrs={'placeholder': 'fonction'}), 'DChiefGo_indicative': django.forms.TextInput(attrs={'placeholder': 'indivatif'}), 'DChiefGo_phone': django.forms.TextInput(attrs={'placeholder': '06 12 … -
How to concatenate text from multiple rows in to single record string Django
I'm doing some JOINS to get the data from the DB, but due to one column, my records are getting duplicated because of that column's unique values rest all other column values are the same. Below is an example of a sample record that I'm trying to achieve here: id name product_name 1 100 Cory Trimmer 2 100 Cory Steamer Now, I want the above record something like below: id name product_name 1 100 Cory Trimmer,Steamer Is there any way to achieve this kind of result as I have tried and exhausted all the links on the internet? Code which I'm using to get the records. products = ( customer.customerproduct_set.prefetch_related("product") .annotate( grade_code=F("product__grade__name"), package_type=F("product__packaging_type__packaging_type"), container_type=F("product__packaging_type__container_type"), product_name=F("product__name"), # this line is creating multiple rows ) .all() ) I know there is no such function available in Django to get this output. If anybody knows how to tame this kind of situation please suggest or highlight if I'm doing something wrong here. Any kind of help would be much appreciated. Thanks in advance! -
How to link two django models in a view
I am trying to design a app where some patient details are entered, an algorithm processes these, and directs to the appropriate treatment page I have managed to get it so patient details are entered and the user is the redirected to a view of that patient instance using the below code But I am not sure how to in TreatmentDetailView to instead present the details of the relevant treatment rather than that patient instance. models.py: class Patient(TimeStampedModel): # get a unique id for each patient - could perhaps use this as slug if needed patient_id = models.UUIDField(primary_key=True, unique=True, default=uuid.uuid4, editable=False) name = models.CharField("Patient Name", max_length=255) age = models.IntegerField("Age", default=0) class Treatment(TimeStampedModel): name = models.CharField("Treatment Name", max_length=255) views.py: class PatientCreateView(LoginRequiredMixin, CreateView): model = Patient fields = ['name', 'sex', 'age'] def form_valid(self, form): form.instance.creator = self.request.user return super().form_valid(form) def get_success_url(self): return reverse('patient:detail', kwargs={"slug": self.object.patient_id}) class TreatmentDetailView(DetailView): model = Patient slug_field = “patient_id” def find_treatment(Patient): treatment_instance = runalgorithm(Patient) return treatment_instance urls.py urlpatterns = [ path( route='add/', view=views.PatientCreateView.as_view(), name='add'), path( route='<slug:slug>/', view=views.TreatmentDetailView.as_view(), name='detail'), ] -
How to not allow user to enter previous datetime in wagtail form?
I am working on a wagtail project (CMS based on Django). I have a DateTime field in one of the model page. from django.db import models from wagtail.core.models import Page class ArticlePage(Page): publish_at = models.DateTimeField() This field is shown on the Page edit screen. I want to add validations in the DateTime picker, which should not allow the user to pick past DateTime. Something like shown in the screenshot below: How can I achieve similar restriction? Is there a built in widget in django or wagtail, where I can add this validation? -
Django app gives an application error when deployed to Heroku
After deploying my django app to heroku while launching it I got an application error. "An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details." The application was working fine on localhost. Heroku logs showed the following: 2021-08-16T08:22:10.383324+00:00 app[web.1]: Traceback (most recent call last): 2021-08-16T08:22:10.383335+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/sit e-packages/gunicorn/arbiter.py", line 589, in spawn_worker 2021-08-16T08:22:10.383336+00:00 app[web.1]: worker.init_process() 2021-08-16T08:22:10.383336+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/sit e-packages/gunicorn/workers/base.py", line 134, in init_process 2021-08-16T08:22:10.383336+00:00 app[web.1]: self.load_wsgi() 2021-08-16T08:22:10.383336+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/sit e-packages/gunicorn/workers/base.py", line 146, in load_wsgi 2021-08-16T08:22:10.383336+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2021-08-16T08:22:10.383337+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/sit e-packages/gunicorn/app/base.py", line 67, in wsgi 2021-08-16T08:22:10.383337+00:00 app[web.1]: self.callable = self.load() 2021-08-16T08:22:10.383337+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/sit e-packages/gunicorn/app/wsgiapp.py", line 58, in load 2021-08-16T08:22:10.383337+00:00 app[web.1]: return self.load_wsgiapp() 2021-08-16T08:22:10.383338+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/sit e-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp 2021-08-16T08:22:10.383338+00:00 app[web.1]: return util.import_app(self.app_uri) 2021-08-16T08:22:10.383338+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/sit e-packages/gunicorn/util.py", line 359, in import_app 2021-08-16T08:22:10.383338+00:00 app[web.1]: mod = importlib.import_module(module) 2021-08-16T08:22:10.383339+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/imp ortlib/__init__.py", line 127, in import_module 2021-08-16T08:22:10.383339+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2021-08-16T08:22:10.383339+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1030, in _gcd_import 2021-08-16T08:22:10.383340+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1007, in _find_and_load 2021-08-16T08:22:10.383340+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 972, in _find_and_load_unlocked 2021-08-16T08:22:10.383340+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 228, in … -
Django ORM joining two models without primary key/foreign key relationships
I have been programming APIs with Django Rest Framework for a little while but have yet to need to invoke more complex joins than those made by default with the convenient PK/FK relationship building Django handles. One issue I seem to have is creating multi-level joins between models where the models do not have a primary-foreign key relationship. It is also impossible for the related fields themselves to be unique between the Customers and the source. from django.db import models class Customers(models.Model): address_key = models.CharField(db_column='address_key', max_length=40) lastname_key = models.CharField(db_column='lastname_key', max_length=5) firstname_key = models.CharField(db_column='firstname_key', max_length=4) fname = models.CharField(db_column='fname', max_length=255) lname = models.CharField(db_column='lname', max_length=255) address = models.CharField(db_column='address', max_length=255) city = models.CharField(db_column='city', max_length=255) state = models.CharField(db_column='state', max_length=255) zip = models.CharField(db_column='zip', max_length=255) class Meta: constraints = [ models.UniqueConstraint(fields=['address_key', 'lastname_key', 'firstname_key'], name='unique customer') ] class Attributes(models.Model): address_key = models.CharField(db_column='address_key', max_length=40) lastname_key = models.CharField(db_column='lastname_key', max_length=5) firstname_key = models.CharField(db_column='firstname_key', max_length=4) attr_1 = models.CharField(db_column='attr_1', max_length=255) attr_2 = models.CharField(db_column='attr_2', max_length=255) attr_3 = models.CharField(db_column='attr_3', max_length=255) An example of the SQL join I am interested in achieving using Django's ORMs is below. SELECT attr_1, attr_2, attr_3 FROM Attributes a JOIN Customers c ON c.address_key = a.address_key AND c.lastname_key = a.lastname_key AND c.firstname_key = a.firstname_key I've learned through the documentation and a … -
Formulate conditional Q on Unique Constraint for exception handling
Django doesn't throw a ValidationError because of a missing conditional in UniqueConstraint, and I don't know how to formulate a correct one. One of my models contains a unique constraint including a Foreign Key: class Entry(models.Model): """ Entry on a List """ name= models.CharField() expiration_date = models.DateField() list = models.ForeignKey(List, related_name="entries", on_delete=models.CASCADE) ... class Meta: constraints = [ UniqueConstraint(fields=['list', 'name'], name='unique_entry') # Each entry_name may only occur once per list. ] When submitting a new Entry which violates this constraint, the database rejects the query and Django throws an unhandled exception IntegrityError. According to the Django documentation this is intended behaviour: Validation of Constraints In general constraints are not checked during full_clean(), and do not raise ValidationErrors. Rather you’ll get a database integrity error on save(). UniqueConstraints without a condition (i.e. non-partial unique constraints) are different in this regard, in that they leverage the existing validate_unique() logic, and thus enable two-stage validation. In addition to IntegrityError on save(), ValidationError is also raised during model validation when the UniqueConstraint is violated. I would like your help with formulating a conditional, or other suggested solutions to fix this behaviour. The goal is to treat the UniqueConstraint like any other field that won't … -
There's an error in using filter to search company ,getting type errror can only concatenate str(Not nonetype) to str online compsearchobj in views.py
I'm using this definition to define the search and filter page using a database that is joined and saved. I have added views.py and models.py code for the same. views.py def multiplesearchcomp(request): if request.method=="POST": citycode=request.POST.get("citycode") statecode=request.POST.get("statecode") countrycode=request.POST.get("countrycode") revenue=request.POST.get("revenue") noofemployees=request.POST.get("noofemployees") domaincode=request.POST.get("domain_id") compsearchobj=DisplayCompanyDomain.objects.raw('select * from enquire_automation_app_displaycompanydomain where citycode="'+citycode+'" and statecode="'+statecode+'" and countrycode="'+countrycode+'" and domain_id="'+domaincode+'" and revenue="'+revenue+'" and noofemployees="'+noofemployees+'"') return render(request,'filtercompany.html',{"DisplayCompanyDomain":compsearchobj,"countries": Country_master.objects.all(), 'states': State_master.objects.all(), "cities": City_master.objects.all(), "domains": Domain_master.objects.all()}) else: compobj=DisplayCompanyDomain.objects.raw('select * from enquire_automation_app_displaycompanydomain') return render(request,'filtercompany.html',{"DisplayCompanyDomain":compobj, "countries": Country_master.objects.all(), 'states': State_master.objects.all(), "cities": City_master.objects.all(), "domains": Domain_master.objects.all()}) models.py class DisplayCompanyDomain(models.Model): companyname = models.CharField(max_length=100) address = models.CharField(max_length=200) citycode = models.CharField(max_length=20) statecode = models.CharField(max_length=20) countrycode = models.CharField(max_length=20) foundedin = models.CharField(max_length=20) revenue = models.CharField(max_length=100) noofemployees = models.CharField(max_length=20) domesticprojects = models.IntegerField(default=0) globalprojects = models.IntegerField(default=0) website = models.CharField(max_length=50) domain_id=models.CharField(max_length=20) no_of_projects=models.IntegerField() -
celery doesn't run task when I'm using Tweepy in Django
When I wanna use tweepy with celery tasks It doesn't run and it just give me failure 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=clean_count,lang=clean_lang).items(int(clean_count)): tweet.retweet() views.py class Retweet(FormView): form_class = RetweetForm template_name = 'retweet.html' success_url = reverse_lazy('tweet:done') def form_valid(self, form): user = self.request.user 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) error: The full contents of the message body was: b'\x80\x04\x95B\x01\x00\x00\x00\x00\x00\x00(\x8c\x19crR6CW6AB9MpsLkFsGLu4i1du\x94\x8c2cMEZk1z8zlSPnKlYZKTgpBXEqeZ4EMpf4HGSIe7j1adYAAwf5w\x94\x8c21157597880-a3cBcPLXFNaaeT3DYbajBdznpdGid1llqqmxEE0\x94\x8c-LBmrhuR6MWIvJ1YhLpR9DDUIxlqBwumfbsMxlmZagZtC1\x94\x8cE\xd9\x87\xd9\x88\xd8\xb4 \xd9\x85\xd8\xb5\xd9\x86\xd9\x88\xd8\xb9\xdb\x8c OR \xd8\xa8\xd8\xb1\xd9\x86\xd8\xa7\xd9\x85\xd9\x87 \xd9\x86\xd9\x88\xdb\x8c\xd8\xb3\xdb\x8c OR \xd8\xa7\xdb\x8c\xd9\x84\xd8\xa7\xd9\x86 \xd9\x85\xd8\xa7\xd8\xb3\xda\xa9\x94\x8c\x013\x94\x8c\x02fa\x94\x8c\x016\x94t\x94}\x94}\x94(\x8c\tcallbacks\x94N\x8c\x08errbacks\x94N\x8c\x05chain\x94N\x8c\x05chord\x94Nu\x87\x94.' (333b) Traceback (most recent call last): File "/Users/User/PycharmProjects/twitterTest/venv/lib/python3.9/site-packages/celery/worker/consumer/consumer.py", line 581, in on_task_received strategy = strategies[type_] KeyError: 'tweet.tasks.retweet' -
save() missing 1 required positional argument: 'tran'
My save() method is throwing the error: save() missing 1 required positional argument: 'tran'. I overrode the save() method in the model “Transactions” as follows: def save(self,D,tran): self.DATE=D self.TYPE=tran.SERVICE_CODE self.SUCCESS=tran['Success'] self.TECHNICAL_DECLINES=tran['Technical_declines'] self.BUSINESS_DECLINES=tran['Business_declines'] self.TOTAL=self.SUCCESS+self.TECHNICAL_DECLINES+self.BUSINESS_DECLINES self.PERCENTAGE_TECH_DEC=((T/(self.TOTAL))*100) super(Transactions,self).save() where tran argument in the save() is a dictionary object passed on from views. Please note that I have also tried super(Transactions,self).save(D,tran) in the last line of save(). views.py def fetch(): DATE=datetime.datetime.now() print(DATE) status=Transactions.objects obj=wf() for tran in obj: print(tran) Transactions.save(DATE,tran) return Transactions.objects.all() Here wf() is a function retrieve database object from a model. From the output of print(tran) it is clear that the db_object is being fetched without any issue. output of print(): {'SERVICE_CODE': 'APY', 'Success': 1, 'Technical_declines': 0, 'Business_declines': 0} I don't understand where the argument tran is being missed. -
How to send custom JSON headers with requests in drf_spectacular (django)?
Can I create an custom description of JSON headers in drf_spectacular without using serializers class in @extend_schema decorator? -
how to load multiple images from json data - django
im trying to show multiple images in my template using ajax request every post has multiple images , but it takes some time to load images! class Document(models.Model): booking =models.ForeignKey(Booking,on_delete=models.PROTECT) docs = models.ImageField(upload_to=upload_docs) class Booking(models.Model): admin = models.ForeignKey(User,on_delete=models.CASCADE) title = models.CharField(max_length=40) my views.py def booking_detail_lists(request,id): obj = get_object_or_404(Booking,id=id) doc = Document.objects.filter(booking=obj) documents = [] for i in doc: documents.append({ 'source':i.docs.url }) data = { 'title':obj.title, 'admin':obj.admin.username, 'images':documents return JsonResponse({'data':data}) this is my script to load images , but its too slow to load images ! $.ajax({ type:'GET', url:"{%url 'booking:booking_detail_lists' id=2222 %}".replace(/2222/,{{obj.id}}), success:function(data){ if(data.data){ let images = data.data.images imgs = '' for(i=0;i<images.length;i++){ imgs +=` <img src="${images[i]['source']}" class="w-full" alt=""> ` console.log(images[i]['source']) } document.getElementById('images').innerHTML = imgs } } }) <div class="w-full md:w-6/12 mx-auto rounded-lg " id="images"> </div> and this is my url path('ajax/booking/<int:id>',booking_detail_lists , name='booking_detail_lists'), it load too slow ! is there a better way to load image data through ajax please ?! ` -
Django timezone models.DateTimeField does not have seconds via DRF
I have model which has DateTimeField class Genre(models.Model): pub_date = models.DateTimeField('date published',default=timezone.now) in database it has the Datetime with seconds 2021-07-27 07:51:18.87329 However when returning this in Django-Restful-Framework, it doesn't have seconds. like class GenreViewSet(viewsets.ModelViewSet): queryset = Genre.objects.all() serializer_class = GenreSerializer def list(self,request,*args,**kwargs): objs = Genre.objects.all() custom_data = { 'items': GenreSerializer(objs, many=True).data } return Response(custom_data) class GenreSerializer(serializers.ModelSerializer): class Meta: model = Genre fields = ('id','pub_date') Somehow it shows like "pub_date": "07/27/2021 07:51P" Why seconds are omitted?? -
password authentication failed for user in django when using postgress
i have been trying to use the python-dotenvlibrary to work with my env variables. for other variables its working but when i came to use PostgreSQL in Django i am getting an error. This is what i am getting, conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError: FATAL: password authentication failed for user "brian" FATAL: password authentication failed for user "brian" Here is the code i am using if DEBUG: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } else: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.environ.get('NAME'), 'USER': os.environ.get('USER'), 'PASSWORD': os.environ.get('PASSWORD'), 'HOST': os.environ.get('HOST'), 'PORT': os.environ.get('PORT'), } } any ideas -
Django Choicefield from a list
i have a small question about forms. So how i would usually create a choice form would be this way: Metric_name_CHOICES = [ ('Transfer', 'Transfer'), ('RFI/RFD', 'RFI/RFD'), ('...', '...') ] Metric_name = forms.ChoiceField(choices=correct_associate_action_CHOICES, widget=forms.Select) Which is a great method, but what if I wanted the list of choices to come from a list in a model? I guess something like: Metric_name = forms.ChoiceField(choices=dv_model.objects.get(Metric_name_dv), widget=forms.Select) So to take all the fields inside a column in a model, and display them as a drop down field. -
Using jQuery UI autocomplete input field in Django
I'm trying to create an autocomplete text input field in a ModelForm class, so I found jQuery UI library to do the autocomplete part of the input field, and this is what i did so far but it didn't work with me, so could you please check it and help me out? This is my model.py file: class Frequency(models.Model): EN_frequency = models.CharField(max_length=100, null=True) def __str__(self): return self.EN_frequency class MedicinePrescription(models.Model): medicine = models.ForeignKey(Medicine, null=True, on_delete=CASCADE) prescription = models.ForeignKey( Prescription, null=True, on_delete=SET_NULL) frequency = models.ForeignKey(Frequency, null=True, on_delete=CASCADE) This is my urls.py file: path('CreatePatientPrescriptionForm/<int:pk>/', views.CreatePatientPrescriptionFormView.as_view(), name='CreatePatientPrescriptionForm'), This is my views.py file: class CreatePatientPrescriptionFormView(CreateView): template_name = 'MedCareApp/patientPrescription-form.html' model = Prescription form_class = PatientPrescriptionForm def get_frequency_list(request): if 'term ' in request.GET: queryset = Frequency.objects.filter( EN_frequency__istartswith=request.GET.get('term')) titles = list() for frequency in queryset: titles.append(frequency.EN_frequency) return JsonResponse(titles, safe=False) return request def get_form_kwargs(self): kwargs = super().get_form_kwargs() random_user = User.objects.get(id=1) kwargs.update({ 'medicine_choices': get_medicine_list(random_user), 'frequency': self.get_frequency_list() }) return kwargs This is my template.html file: <script> $( function() { $( "#id_frequency" ).autocomplete({ source: '{% url '+CreatePatientPrescriptionForm+' %}' }); } ); </script> This is my forms.py file: class PatientPrescriptionForm (ModelForm): frequency = forms.CharField() class Meta: model = MedicinePrescription fields = ['frequency'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['frequency'].widget.attrs.update( {'class': 'text-field small w-input', … -
How to show the first true element after if condition in for loop in django template?
I have a for loop in Django template. After that, I check for coincidences. But in some cases, there are might be 3 coincidences. I need to show only the first coincidence. Now, my code returns the name for 3 times, because, there are 3 coincidences {% for ip in ips %} {% if d.name == ip.name %} <strong>{{ d.name}} </strong> {% endif %} {% endfor %}