Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Call python function with Django
I've recently started learning how to use Django and I was wondering whether or not you could create a button in HTML that can directly call a python function without changing the URL. I was told this was possible with JS but I wanted to know if you could do that in Python. Thanks for your time reading this! -
Flash popup from within decorator function on Flask Route
I would like to create a flash popup from within a decorator function applied to a Flask view. When I generate a flash from within my view, everything works perfectly fine. I would like to be able to also generate flash messages from a wrapper function acting on the view; the form I have tried is: from flask import Flask, render_template from functools import wraps def my_wrapper_function(_f): @wraps(_f) def _decorated_function(*args, **kwargs): ... flash(removed_article.get('name', 'expansion')) ... return _f(*args, **kwargs) return _decorated_function @app.route('/my_view/<int:_id>', methods=['GET']) @my_wrapper_function def my_view(_id): ... return render_template('my_template.jinja2') This does not appear to work however, no flash message appears. N.B: As opposed to generating flash messages within my view, which does work. The following template is included below for completeness; I would imagine the solution lies in the python code. # my_template.jinja2 {% with messages = get_flashed_messages(with_categories=true) %} {% if messages %} {% for category, message in messages %} {% if category == 'message' %} <div class="alert alert-success text-center" role="alert"> {% else %} <div class="alert alert-{{ category }} text-center" role="alert"> {% endif %} {{ message }} </div> {% endfor %} {% endif %} {% endwith %} Since I'm fairly new at both decorators and Flask in general, I thought I'd … -
Django-Python: Grabbing Alias Outlook Email in the form of JSON
0 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-v3-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. I tried doing: print(events) print(get_user(token)) print(get_calendar(token)) print(get_calendar_group(token)) But none of those are showing me the alias email addresses it is only showing me the main account information. How do I see the alias account information? -
Getting TypeError: __init__() got an unexpected keyword argument 'upload_to' in Django Project?
I have just started learning Django frame work and got stuck after getting an unexpected error as below:-(I have tried to post all information, which i find necessary to be here) TypeError: __init__() got an unexpected keyword argument 'upload_to' I got this error while running command python manage.py makemigrations My project contains only one Model class Products My Model Class:- from django.db import models # Create your models here. class Products(models.Model): name = models.CharField(max_length=25) price = models.IntegerField() description = models.CharField(max_length=50) pic = models.DateTimeField(upload_to="myimages") I am added my app in INSTALLED_APPS fields in setting.py Thanks in advance. Hope to here from you soon. -
Django: Change default parameter appended in the URL in forms
I have a form like this: <form method="get"> <button name="load" type="submit" value="{{game.game_id}}|{{game.champion}}">Show user's stats</button> </form> When the user submits the form, the parameter will automatically be appended into the URL like this www.example.com/?load=5293733926|99 However, I want to add manually another parameter to the URL making the URL look like this: www.example.com/?load=5293733926|99&page=2 If I manually type this to the URL, it goes to where I want. How should I do this? I tried adding: action="./?load={{game.game_id}}|{{game.champion}}&page={{game.page}}" and multiple other variants. But it doesn't work, it redirects to www.example.com/?load=5293733926|99. Context: I have a huge list of dictionaries and if I show them all at the same time and process them, it takes a lot of time. I divided the list with Django's paginator. The forms act as a load more. By default, I show some data from the dictionary and when the user clicks the form button, some extra information is showed. However, if someone clicks the form button in page 2 www.example.com/?page=2, Django would redirect the user to the first page after processing the data. In order to redirect the user to the submitted button's page, I would need to redirect the user to www.example.com/?load=5293733926|99&page=2 It's my first time asking a question … -
How to use Login View in django?
I decided to customize the login form and make authentication with email. I can login with super user account but can't do it with the simple user. Here's the models.py file. I created custom user manager and redifened the creation logic def create_superuser(self, email, user_name, first_name, last_name, password, **other_fields): other_fields.setdefault('is_staff', True) other_fields.setdefault('is_superuser', True) other_fields.setdefault('is_active', True) if other_fields.get('is_staff') is not True: raise ValueError('Staff must be True') if other_fields.get('is_superuser') is not True: raise ValueError('Superuser must be True') if other_fields.get('is_active') is not True: raise ValueError('Is active must be True') return self.create_user(email, user_name, first_name, last_name, password, **other_fields) def create_user(self, email, user_name, first_name, last_name, password, **other_fields): if not email: raise ValueError('You must provide an email') email = self.normalize_email(email) user = self.model(email = email, user_name = user_name, first_name=first_name, last_name = last_name, **other_fields) user.set_password(password) user.save() return user class UserProfile(AbstractBaseUser, PermissionsMixin): email = models.EmailField(('email address'), unique=True) user_name = models.CharField(max_length=150, unique=True) first_name = models.CharField(max_length=150) last_name = models.CharField(max_length=150) start_date = models.DateTimeField(default=timezone.now) department = models.CharField(max_length=150) company = models.CharField(max_length=150) head = models.CharField(max_length=150, blank=True) is_staff = models.BooleanField(default=False, blank=True) is_active = models.BooleanField(default=False, blank=True) is_admin = models.BooleanField(default=False, blank=True) dashmodel = models.CharField(max_length=150, blank=True) role = models.CharField(max_length=150, blank=True) objects = CustomAccountManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['user_name','first_name','last_name'] def __str__(self): return self.user_name ``` I change the logic of … -
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.