Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Formset new entry fails validation
I am trying to create a formset where I can 1) show all entries +1 (for new entry) 2) update existing entries 3) add new entries. Currently I can successfully complete 1 & 2. When it comes to adding a new entry the formset fails .is_valid() check. This is because I have a hidden input for the entry_id. The id is necessary for bulk_update() to update existing entries, but causes the is_valid() function to fail on the new entry. If I use bulk_create(), I do not need the id but it will duplicate all existing entries. Is there a way to pass the .is_valid() check when attempting to add a new entry? views.py def CustomerView(request): template = "accounts/customers.html" # Create the formset, specifying the form and formset we want to use. CustomerFormSet = formset_factory(CustomerForm, formset=BaseFormSet) # Get our existing data for this user. customer_list = Customers.objects.all().order_by("cust_name") customers = [{'customer_id': c.id, 'customer_name': c.cust_name} for c in customer_list] if request.method == 'POST': customer_formset = CustomerFormSet(request.POST) # print(customer_formset.errors) if customer_formset.is_valid(): # Now save the data for each form in the formset customer = [] for customer_form in customer_formset: customer_id = customer_form.cleaned_data.get('customer_id') customer_name = customer_form.cleaned_data.get('customer_name') if customer_id and customer_name: customer.append(Customers(id=customer_id, cust_name=customer_name)) try: with transaction.atomic(): … -
Get Return from a dynamic form from javascript to view in django imagefileds
I want to get dynamic image upload data from a javascript to my view.py in django my dynamic scrpit <script> $(document).ready(function(){ var id = 1; $("#add_more").click(function(){ var showId = ++id; if(showId <=5) { $(".input-files").append('<input type="file" name="file_upload-'+showId+'">'); } }); }); </script> and my view and model img_dokans = ArrayField(models.URLField(max_length=200), blank=True, null=True) Suggest me my view from a html form how can i integrate script to django so i can get the files which later i ll upload to S3 -
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte while calling the function
while calling the investors_data function ,getting the error "UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte" views.py owners_with_pp=['Q5UrH4bPgggmroA8g8p5sJ', 'qpA8kptiYUGFCFYN2Tg4oR', 'e6dQwGi2ehgLaK6qYJr8KA', 'YZovJ23LamzMWpKaPsgrsk', 'YZovJ23LamzMWpKaPsgrsk'] owners_without_pp = ['9jeJ8YNJtF9N9tjibtpdZG'] if owners_with_pp: stock_data['investors_with_pp'] = utils.investors_data(owners_with_pp,friends,'with') if owners_without_pp: stock_data['investors_without_pp']= utils.investors_data(owners_without_pp,friends,'without') utils.py def investors_data(user_data,friends,flag): inv_data = User.objects.filter(id__in=user_data).order_by('-user_name') F = False profile_pic = None for investor in inv_data: if investor.id in friends: F = True if investor.profile_pic: profile_pic = investor.profile_pic investors_details = {'id': investor.id, "user_name": investor.user_name, "profile_pic": profile_pic, "is-friend": F} return investors_details but it works when i comment out # if owners_with_pp: # stock_data['investors_with_pp'] = utils.investors_data(owners_with_pp,friends,'with') -
Best practise Django-Rest-Framework external library testing
i'm developing an API that has both a lot of external libraries such as django-polymorphic and django-cors-headers. And I have lots of 3rd party integration such as AWS for deployement and i was wondering when i run python manage.py test does it run the tests in these external libraries ? Or do i have to include them? If i have to include them whats the best way to do it ? -
Image not saving to media or creating media folder (Python, Django)
I have been struggling with this for the past days i have done everything right and i dont know what am missing exactly. when i try to upload the image from the admin page it uploads succesfully creates the media folder if not exist already. but when i try to get the image from url the image is saved in the url field of my model but never get create to the image field of my model whis is image = image = models.ImageField below is my code models class Image(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, related_name="user_images", on_delete=models.CASCADE ) users_like = models.ManyToManyField( settings.AUTH_USER_MODEL, related_name="images_liked", blank=True ) title = models.CharField(max_length=200) slug = models.SlugField(max_length=200, blank=True) url = models.URLField() image = models.ImageField(upload_to="images/%Y/%m/%d/") description = models.TextField(blank=True) created = models.DateField( auto_now_add=True, db_index=True ) forms save method def save(self, force_insert=False, force_update=False, commit=True): image = super().save(commit=False) image_url = self.cleaned_data["url"] name = slugify(image.title) extension = image_url.rsplit(".", 1)[1].lower() image_name = f"{name}.{extension}" # download image from the given URL response = request.urlopen(image_url) image.image.save(image_name, ContentFile(response.read()), save=False) if commit: image.save() return image -
How can I modify models.py in external app in Django CMS
I am trying to modify existing model(In Django CMS Blog application). There is a Post class, I can modify it in models.py that located inside the Django CMS Blog project, like so: media = PlaceholderField("media", related_name="media") post_title = PlaceholderField("post_title", related_name="post_title") # My code content = PlaceholderField("post_content", related_name="post_content") liveblog = PlaceholderField("live_blog", related_name="live_blog") And after the migration the DB looks like this. As you can see, the field is added. But how can I do that from my local project files? I don't want to add this code inside 3d party app models, because it will lead to problems with updating this 3d party app. -
Django: change column headers in Admin ListView without losing sortability
I just want to change the column header in Django' Admin ListView. There is already an answer: Django admin listview Customize Column Name, but this solution (define a function and set .short_description on it) comes at the cost of no longer being able to sort by the column in question. I cannot find any other solution. It seems to simple a wish that I cannot believe it cannot be done. -
Please help me with Django model object validation
I'm very new to Django and programming in general. I'm trying to do some Django admin model object validations. I'm implementing bid system. User must be able to bid straight from admin page. The code may be far from perfect... Here's models.py: class User(AbstractUser): pass class category(models.Model): category = models.CharField(max_length=50, default='Enter new category') def __str__(self): return f"{self.category}" class bid(models.Model): listing = models.ForeignKey('listing', on_delete=models.CASCADE) user = models.ForeignKey(User, null=True, on_delete=models.CASCADE) bid = models.DecimalField(max_digits=6, null=True, decimal_places=2) def clean(self): if self.bid <= self.listing.Price: raise ValidationError('Please place a bid higher than starting price') if self.bid <= ??? #How should I code this? raise ValidationError('Please place a bid higher than the current highest bid') def __str__(self): return f"{self.user}, {self.listing} {self.bid}" class listing(models.Model): user = models.ForeignKey(User, null=True, on_delete=models.CASCADE) Title = models.CharField(max_length=50) Description = models.CharField(max_length=300) Price = models.DecimalField(max_digits=6, decimal_places=2) category = models.ForeignKey(category, on_delete=models.CASCADE, related_name="categories") def __str__(self): return f"{self.Title}" -
Getting list indices must be integers in Django views
I'm scraping some data inside Django views.py and append them to a dictionary that looks like this: movie_data = { 'movie_details': [], 'actor_details' : [], 'dir_details': [], } and then append to it like below: movie_data['movie_details'].append({'title': title, 'summary': summary}) I defined a variable title = movie_data['movie_details'][0]['title'] to create objects from it but I get the error below when I try to do so: list indices must be integers or slices, not str Which already is an integer, and I've tried my code outside of Django and tried to print the data using print(movie_data['movie_details'][0]['title']) and it worked. Can anyone help me find where the error comes from? Thanks in advance. -
How to create a HomeConfig modell
I'm learning Django and I have a problem because I don't know how to put my intention a model. On my public page I would like to be able to dynamically change the content of my homepage. However, I don't want to create a PageModel - I want only a HomeConfig model with which I can define different texts, images, etc. My problem is that this model could only have one entry but a model isn't made for just one entry. -
Django, PostGreSQL; django.db.utils.IntegrityError: insertion or update in the table violates the foreign key
Out of the box git repo doesn't work. The error occurs after running pytest. django.db.utils.IntegrityError: insertion or update in the table "product_product" violates the foreign key "product_product_polymorphic_ctype_id_44f73554_fk_django_co" Here are the things I've figured out already: DETAIL: The key (polymorphic_ctype_id)=(503) is not present in the table "django_content_type". and in psql: payments=# \d+ django_content_type Tabla «public.django_content_type» Columna | Tipo | Ordenamiento | Nulable | Por omisión | Almacenamiento | Estadísticas | Descripción -----------+------------------------+--------------+----------+-------------------------------------------------+----------------+--------------+------------- id | integer | | not null | nextval('django_content_type_id_seq'::regclass) | plain | | app_label | character varying(100) | | not null | | extended | | model | character varying(100) | | not null | | extended | | Índices: "django_content_type_pkey" PRIMARY KEY, btree (id) "django_content_type_app_label_model_76bd3d3b_uniq" UNIQUE CONSTRAINT, btree (app_label, model) Referenciada por: TABLE "auth_permission" CONSTRAINT "auth_permission_content_type_id_2f476e4b_fk_django_co" FOREIGN KEY (content_type_id) REFERENCES django_content_type(id) DEFERRABLE INITIALLY DEFERRED TABLE "django_admin_log" CONSTRAINT "django_admin_log_content_type_id_c4bce8eb_fk_django_co" FOREIGN KEY (content_type_id) REFERENCES django_content_type(id) DEFERRABLE INITIALLY DEFERRED TABLE "product_product" CONSTRAINT "product_product_polymorphic_ctype_id_44f73554_fk_django_co" FOREIGN KEY (polymorphic_ctype_id) REFERENCES django_content_type(id) DEFERRABLE INITIALLY DEFERRED Método de acceso: heap payments=# table django_content_type; id | app_label | model ----+--------------+------------- 1 | admin | logentry 2 | auth | permission 3 | auth | group 4 | auth | user 5 | contenttypes | contenttype 6 | … -
Django queryset return the newest of field choices
I would like the return a queryset that is comprised of the newest (date) objects for each choice of a field name. I can do it by iterating over an ordered queryset and then progressively removing older objects with exclude(). I'm wondering if this could be done using latest(). I don't know how to run latest with each unique value of name. I don't have a lot of experience with django, I'm worried that my working code below would be slow/expensive. It groups the dogs by name, then orders it by date, then systematically removes older dates. class Dog(models.Model): # names = husky, poodle, lab, etc name = models.CharField(max_length=20) age = models.IntegerField() datemade = models.DateField(default=date.today) views.py ad = Dog.objects.all().order_by('name', 'datemade') n=0 while n < (len(ad)-1): if ad[n].name==ad[n+1].name and ad[n].datemade<=ad[n+1].datemade: ad = ad.exclude(id=ad[n].id) print(ad) n=n-1 n=n+1 -
How to fetch user selected model fields in django
I wanted to fetch the data from database according to the data selected by user input. I'am using model_name.objects.all which fetches all the data from that model. from django.db import models from django.contrib.auth.models import User from django.conf import settings class quiztitle(models.Model): Quiz_id = models.AutoField(primary_key=True) Quiz_title = models.CharField(max_length=600) User = settings.AUTH_USER_MODEL User_id= models.ForeignKey(User, on_delete=models.CASCADE) no_of_ques = models.IntegerField(default=10) def __str__(self): return self.Quiz_title class question(models.Model): Qid = models.AutoField(primary_key=True) User = settings.AUTH_USER_MODEL User_id = models.ForeignKey(User,on_delete=models.CASCADE) Quiz_id = models.ForeignKey(quiztitle,on_delete=models.CASCADE) Qques = models.TextField() Qoption1 = models.TextField() Qoption2 = models.TextField() Qoption3 = models.TextField() Qoption4 = models.TextField() QAnswer = models.TextField() def __str__(self): return self.Qques class answer(models.Model): Ansid = models.AutoField(primary_key=True) Qid = models.OneToOneField(question,on_delete=models.CASCADE) Quiz_id = models.ForeignKey(quiztitle, on_delete=models.CASCADE) User = settings.AUTH_USER_MODEL User_id = models.ForeignKey(User, on_delete=models.CASCADE) Answer = models.TextField() class result(models.Model): result = models.AutoField(primary_key=True) Quiz_id = models.OneToOneField(quiztitle, on_delete=models.CASCADE) User_id = models.OneToOneField(User, on_delete=models.CASCADE) score = models.FloatField() def __str__(self): return str(self.pk) here's html file from which user selects the quiz title to start the quiz. By clicking on the attempt quiz button user can attempt there choosen quiz . <div class="Question-container"> <div> {% for x in title %} <h1 class="title"><i class="fa fa-circle" id="quiz-icon" ></i>{{x.Quiz_title}}<button>Attempt Quiz</button></h1> {% endfor %} </div> </div> I want to fetch the data i.e question along with the option of … -
Django DRF - Axios POST
I am converting my app from jQuery/Ajax to ReactJs. Currently in the backend I am grabbing an array by doing request.data.getlist('something[]) With the same code when I am doing an axios POST i get an error. If I change the code to request.data['something'] then it works fine. What am I missing? How can I grab an array of string that working for both ajax and axios -
How to extract values from a list and insert into database
Am pretty new to Django, I have a use case where I have a list of data stored in a list, the data comes from a text area inputted by a user and stored on the variable scannedcode . Am trying to loop through and insert the values as individual records in a column but the whole list end up being inserted as ['7622210354822', '0071831003508'] . How can I have I extract and insert 7622210354822 and 0071831003508 on two different rows in SQL using Django? What I have tried so far with no luck def submit(request): scannedcode = request.POST.get('description') for code in scannedcode: print('testing data') print(code) scancodes = LabSigned(scannedcode=scannedcode) print('testing data') print(scancodes) scancodes.save() return render(request, 'detect_barcodes/detect.html') Whenever I try to print the data from the loop I get [ ' 7 6 2 2 2 1 0 3 5 4 8 2 2 ' , ' 0 0 7 1 8 3 1 0 0 3 5 0 8 ' ] instead of getting 0071831003508 7622210354822 Thank you in advance for any help -
What is the correct pathway for Django OTP body message?
I'm doing a Django project and I'm at where I want to have a custom OTP email to the users. I have tried everything I could think of to have the OTP email not just display the OTP code but also the HTML but it just displays the path of "text" I have read the docs but couldn't find much help. settings.py: text = './Templates/email.txt' html = './Templates/email.html' #OTP settings OTP_EMAIL_SENDER="" OTP_EMAIL_SUBJECT="Verification Code" OTP_EMAIL_TOKEN_TEMPLATE=text OTP_EMAIL_BODY_TEMPLATE=text OTP_EMAIL_BODY_TEMPLATE_PATH=html OTP_EMAIL_TOKEN_VALIDITY=300 email.html: <tr> <td bgcolor="#fdfbf0" style="padding:25px"> <p style="margin: 0;"> <!--the safe parameter allows us to generate html. always make sure you are passing valid html markup to the email body--> {{email_body|safe}} </p> </td> </tr> email.txt: {{email_body}} -
SQL query having two IN operator with comparison being performed index wise
I have a use case in which I have two lists which are my search criteria and I need to write a query which will result in such a way that the searching is done by taking each element from each of the list one by one and performing the query operation. Example: list1 = (1,2,3,4,5); list2 = (21,23,27,26,28); select * from table where column1 in list1 and column2 in list2; Query should work like: select * from table where column1=1 and column2=21; select * from table where column1=2 and column2=23; select * from table where column1=3 and column2=27; and so on..... Note: I have to make this query in Django, so Django's model query will also work in case SQL query doesn't fit here. -
Sort List of self referenced objects by date time : Django-RestFramework
I am new to django, I have table which store the comments, but each comment can have child comments and child comments can have another child comments. I am trying to sort them based on most recent date but only the first layer of comments are being sorted. [ { "id": 25, "reviewer": { "id": 2, "first_name": "", "last_name": "", "username": "sriram", "email": "123@gmail.com" }, "comment_category": "marketing", "comment": "Marketing 1", "x": 30.0, "y": 30.0, "children": [ { "id": 26, "reviewer": { "id": 2, "first_name": "", "last_name": "", "username": "sriram", "email": "abc@gmail.com" }, "comment": "Marketing", "children": [ { "id": 27, "reviewer": { "id": 3, "first_name": "Anusha", "last_name": "Savaram", "username": "Anu", "email": "abc@gmail.com" }, "comment": "Marketing 3", "children": [ { "id": 30, "reviewer": { "id": 3, "first_name": "Anusha", "last_name": "Savaram", "username": "Anu", "email": "xyz@gmail.com" }, "comment": "Marketing 5", "is_parent_comment_resolved": true } ], "is_parent_comment_resolved": false } ], "is_parent_comment_resolved": true }, { "id": 28, "reviewer": { "id": 2, "first_name": "", "last_name": "", "username": "sriram", "email": "abc12@gmail.com" }, "comment": "Technical4", "children": [ { "id": 29, "reviewer": { "id": 4, "first_name": "", "last_name": "", "username": "anusha", "email": "abc@gmail.com" }, "comment": "Tech5", "is_parent_comment_resolved": true } ], "is_parent_comment_resolved": true } ], "is_parent_comment_resolved": false, "comment_created": "1 hour ago" }, … -
Django-Python: How to Grab Alias Outlook Email in the form of JSON
I am trying to grab the alias email addresses created within the main account. How am I able to grab the JSON for all of the alias email addresses and then grab all the calendar events contents? Here is the layout of my code: https://github.com/reportex-development/Lobby-Menu/tree/main/Lobby-menu-v2-here I see that in the tutorial > graph_helper.py there is something that's trying to get_calendar_events but it seems like it is only for that one main account but I want to see all the events in the alias accounts. -
Is it possible to allow dependabot on GitHub to automatically "bump" software to new version?
Please help this learner out: I get frequent GitHub's dependabot alerts for "bumping" software versions to a more current one. My issue is I have to go into each (in my case, Django) app to pull or merge files. It tedious and time consuming to deal with my limited number of apps. How do professionals manage the process? Is there a way to allow GitHub just bump whatever needs to be bumped (assuming one doesn't mind apps being broken)? -
Django: convert DateField to string using DATE_FORMAT
I want to convert a Django DateField to a string according to the DATE_FORMAT as specified in settings.py, where I have a certain date format hard-coded. Can it be done without specifying a second (and at best superflous) date format for, e.g., strftime? -
Got an error creating the test database: database "DATABASE_NAME" already exists
I'm trying to run tests in my Django app and I suddenly started getting this error. When I go to run a test, it first tells me that the database already exists. Creating test database for alias 'default'... Got an error creating the test database: database "DATABASE_NAME" already exists Type 'yes' if you would like to try deleting the test database 'DATABASE_NAME', or 'no' to cancel: I type yes to delete the test database. At which point I get this error: Creating test database for alias 'default'... Traceback (most recent call last): File "/Users/x/Django/myapp/./manage.py", line 23, in <module> main() File "/Users/x/Django/myapp/./manage.py", line 19, in main execute_from_command_line(sys.argv) File "/Users/x/Django/myapp/venv/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/Users/x/Django/myapp/venv/lib/python3.9/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/x/Django/myapp/venv/lib/python3.9/site-packages/django/core/management/commands/test.py", line 23, in run_from_argv super().run_from_argv(argv) File "/Users/x/Django/myapp/venv/lib/python3.9/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/Users/x/Django/myapp/venv/lib/python3.9/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/Users/x/Django/myapp/venv/lib/python3.9/site-packages/django/core/management/commands/test.py", line 55, in handle failures = test_runner.run_tests(test_labels) File "/Users/x/Django/myapp/venv/lib/python3.9/site-packages/django/test/runner.py", line 725, in run_tests old_config = self.setup_databases(aliases=databases) File "/Users/x/Django/myapp/venv/lib/python3.9/site-packages/django/test/runner.py", line 643, in setup_databases return _setup_databases( File "/Users/x/Django/myapp/venv/lib/python3.9/site-packages/django/test/utils.py", line 179, in setup_databases connection.creation.create_test_db( File "/Users/x/Django/myapp/venv/lib/python3.9/site-packages/django/db/backends/base/creation.py", line 74, in create_test_db call_command( File "/Users/x/Django/myapp/venv/lib/python3.9/site-packages/django/core/management/__init__.py", line 181, in call_command return command.execute(*args, **defaults) File "/Users/x/Django/myapp/venv/lib/python3.9/site-packages/django/core/management/base.py", line 398, in execute … -
Nginx, Gunicorn, Django, Postgresql concurrency handle?
I have so many confusion on my mind about concurrency handling . I am new about this concurrency handle so everything is feels like overwhelming . First thing is suppose I can handle 10k concurrent requests with nginx . (1) can Gunicorn handle 10k concurrent requests? (2) If Gunicorn can handle 10k requests how will posgresql response to this. (3) Did Django App Create new database connection for every request(unique user) ? If this happend, How will Postgres handle 10k connection ? -
Won't able to zoom after including chartjszoom in chartjs
Failed to zoom after include the correct version of chartjs and chartjs-plugin-zoom. <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.bundle.js"></script> <script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-zoom@0.7.7/dist/chartjs-plugin-zoom.min.js"></script> This is my canvas tag <div class='chart-wrapper'> <div class="training-chart-area" style="width: 768px; height: 384px;"> <canvas id="trainingChart1"></canvas> </div> </div> My plugin option in my chart js function options: { plugins: { zoom: { zoom: { enabled: true, mode: 'y' }, pan: { enabled: true } } } I know I have the correct version because I tested it with another HTML file. I thought the problem may be chartjs-plugin-zoom won't work with multiple datasets within one chart, but test HTML worked perfectly fine. I have no idea where went wrong. -
How to filters field using django-filter
I need to create some filters for one table but cannot get it to work. When clicking on the Search button nothing happens. Ideally, I would like to get be able to select one or multiple category and get the results displayed with the number of objects counted. Did I missed anything in my code? Thank you models.py class Lead(models.Model): CATEGORY = ( (0, 'Education'), (1, 'Hotel'), (2, 'Construction'), (3, 'Residential'), (4, 'Facility Management'), ) businessname = models.CharField(max_length=150,blank=True, null=True) businesscategory = models.IntegerField(choices=CATEGORY, blank=True, null=True) filters.py import django_filters from .models import Lead class LeadFilter(django_filters.FilterSet): businessname = django_filters.CharFilter(lookup_expr='icontains') businesscategory = django_filters.CharFilter(lookup_expr='icontains') class Meta: model = Lead fields = ['businessname','businesscategory'] views.py @login_required(login_url="/login/") def index_leads(request): leads = Lead.objects.all() lead_filter = LeadFilter(request.GET, queryset=leads) context = { 'leads': leads, 'filter':lead_filter, } return render(request, 'analysis/index_leads.html', context) index_leads.html <form method="get"> <div class="container-fluid"> <h4 style="margin-top: 0"></h4> <div class="row"> <div class="form-group col-sm-3 col-md-3"> {{ filter.form.businesscategory.label_tag }} {% render_field filter.form.businesscategory class="form-control" %} </div> <div class="form-group col-sm-3 col-md-3"> {{ filter.form.businessname.label_tag }} {% render_field filter.form.businessname class="form-control" %} </div> </div> <button type="submit" class="btn btn-primary float-right"> <span class="glyphicon glyphicon-search"></span> Search </button> </div>