Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there any way to make any way to make a model abstract without loss of data?
Lets say I have 2 models such that: class Parent(models.Model): ... class Child(Parent): ... Is there any way to make parent abstract without loss of existing data, given that the parent class has never been directly used. Other answers have suggested using dumpdata and loaddata to preserve data but I was wondering if there was a better way to do so. -
Django, model filter and order by other foreignkey model
model1: class Tag(models.Model): text = models.CharField(max_length=255, null=True, blank=True, unique=True) model2: class TagConnect(models.Model): tag = models.ForeignKey("category.Tag", on_delete=models.CASCADE, null=True, blank=True) created = models.DateTimeField(auto_now_add=True) I want to get top 5 Tag object by count of TagConnect object that has created in recent 24 hours. The more TagConnect object exists, the tag is more likely on high priority. If tag "rabbit" has 2 TagConnect in 24 hours and "horse" has 10 TagConnect but those are not in 24 hours, "rabbit" has more high priority. Maybe it will be like.. Tag.objects.order_by(tag_connect_in_24hours)[:5] How to do this? -
Django Pagedown not rendering correctly in template
I am trying to implement django-pagedown and it works inside the django-admin, but it doesn't render correctly inside a template, this is what I have: new_post_form.py from django import forms from pagedown.widgets import PagedownWidget from .models import Post class NewPostForm(forms.ModelForm): description = forms.CharField(widget=PagedownWidget()) class Meta: model = Post fields = ["description"] views.py def home(request): context = {'post_form':NewPostForm} return render(request, 'pages/index.html', context) index.html <head> {{ post_form.media }} </head> postform.html <form> {{ post_form }} </form> This is what I get: <form> <div class="wmd-wrapper"> <div class="wmd-panel"> <div id="wmd-button-bar-id_description" class="wmd-button-bar"></div> <textarea name="description" cols="40" rows="10" class="wmd-input" required="" id="wmd-input-id_description"></textarea> </div> <div id="wmd-preview-id_description" class="wmd-preview"></div> </div> </form> Thank you for any suggestions -
Django rest framework get request on db with no related model
I am a bit confused. Let's say that we have a database with existing data, the data is updated from a bash script and there is no related model on Django for that. Which is the best way to create an endpoint on Django to be able to perform a GET request so to retrieve these data? What I mean is, that if there was a model we could use something like: class ModelList(generics.ListCreateAPIView): queryset = Model.objects.all() serializer_class = ModelSerializer The workaround that I tried was to create an APIView and inside that APIView to do something like this: class RetrieveData(APIView): def get(self, request): conn = None try: conn = psycopg2.connect(host=..., database=..., user=..., password=..., port=...) cur = conn.cursor() cur.execute(f'Select * from ....') fetched_data = cur.fetchone() cur.close() res_list = [x for x in fetched_data] json_res_data = {"id": res_list[0], "date": res_list[1], "data": res_list[2]} return Response({"data": json_res_data) except Exception as e: return Response({"error": 'Error'}) finally: if conn is not None: conn.close() Although I do not believe that this is a good solution, also is a bit slow ~ 2 sec per request. Apart from that, if for example, many Get requests are made at the same time isn't that gonna create a problem … -
Django models filter query not recognising field
I am working on a Django project, filter query function is not working as expected I imported the model, did migration I don't understand where the code is wrong, it is not able to recognize the field (rating) Model I created My code in views: ( object.all() is working properly but the filter is not working) My error : ( rating not defined) (basically I tried all fields it shows all not defined) Thank you for help -
How to add/exclude fields to a form that extends another form
Example forms.py: class UserCreationForm(forms.ModelForm): class Meta: model = User fields = ('email', 'role', 'first_name', 'last_name', 'is_staff') class AnotherUserCreationForm(UserCreationForm): #??? Example models.py: ROLE = [ ("NU", "Normal User"), ("AU", "Abnormal User"), ] class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), max_length=50, unique=True) first_name = models.CharField(_('first name'), max_length=50, blank=True) last_name = models.CharField(_('last name'), max_length=50, blank=True) is_active = models.BooleanField(_('active'), default=True) is_staff = models.BooleanField(_('staff status'), default=False) date_of_birth = models.DateField(blank=True) role = models.CharField(_('role'), max_length=2, choices=ROLE, blank=True) So I want to add date_of_birth to AnotherUserCreationForm and at the same time, I want to exclude role and is_staff in AnotherUserCreationForm. How do I manipulate it? Will it be done in the Meta class or do i manipulate it in the def __init__(self, *args, **kwargs) of AnotherUserCreationForm? -
Django sending email with TLS doesn't seem to be working
The emails I send are going through, but do not seem to be encrypted through TLS even though I have it configured to do so. I tried switching port and using SSL, but that also did not work. Settings.py #FOR EMAIL THING PRODUCTION EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = '587' EMAIL_HOST_USER = 'myemail@gmail.com' EMAIL_HOST_PASSWORD = '***************' EMAIL_USE_TLS = True admin.py (emails are sent in admin page) def send_email(self, request, queryset): updated = 0 for obj in queryset: updated +=1 #makes magic link from obj link = get_query_string(obj) subject, from_email, to = 'Pre-appointment Form', 'mail@myserver.com', [obj.email] html_message = render_to_string('mail_template.html', {'link': link}) plain_message = strip_tags(html_message) msg = EmailMultiAlternatives(subject, plain_message, from_email, to) msg.attach_alternative(html_message, "text/html") msg.send() # update message on how many emails were sent self.message_user(request, ngettext( '%d email was successfully sent.', '%d emails were successfully sent.', updated, ) % updated, messages.SUCCESS) -
Did you rename table_name.pid to table.id (a BigAutoField)? [y/N]
I have been running a Django app for last couple of weeks with no issues. However I started to see the above warning message out of no where when I tried to make migration (renaming invoice_date to order_date). When I closely look at the migration files, I see that the initial migration file auto created the pid column. But when I describe the tables in dev (sqlite3) the column name is in fact id. Just to confirm I did not attempt to rename the column name from pid to id. So I can't get my head around as to what is going on. If Django auto creates a column, it should manage the columns forever. Any intentional or unintentional changes to auto created columns should be blocked by Django. Below are the module verion I am using. Django==3.2.2 whitenoise==5.0 pandas==0.25.3 Detailed migration log: (venv) [prj(master)]$python manage.py makemigrations Did you rename packaging.pid to packaging.id (a BigAutoField)? [y/N] n Did you rename product.pid to product.id (a BigAutoField)? [y/N] n Did you rename purchase.pid to purchase.id (a BigAutoField)? [y/N] n Did you rename sale.pid to sale.id (a BigAutoField)? [y/N] n Did you rename saleschannel.pid to saleschannel.id (a BigAutoField)? [y/N] n Did you rename … -
django - Muliple choice filtering on multiple fields using defined choices
I am trying to filter through a model with the choices defined before the filter. store_choices = ( ('harveynichols', 'Harvey Nichols'), ('houseoffraser', 'House of Fraser'), ('selfridges', 'Selfridges'), ('lookfantastic', 'LOOKFANTASTIC'), ('superdrug', 'Superdrug'), ('boots', 'Boots'), ('allbeauty', 'allbeauty'), ('asos', 'asos'), ) class ProductFilter(django_filters.FilterSet): store = django_filters.MultipleChoiceFilter(choices=store_choices) brand = django_filters.MultipleChoiceFilter(choices=brand_choices) price = django_filters.RangeFilter() class Meta: model = Product fields = ['store', 'brand', 'price'] def store_checks(self, queryset, name, store_choices): return Product.objects.filter( Q(store__icontains=store_choices) | Q(storehn__icontains=store_choices) | Q(storehof__icontains=store_choices) | Q( storesf__icontains=store_choices) | Q(storelf__icontains=store_choices) | Q(storesd__icontains=store_choices) | Q(storeboots__icontains=store_choices) | Q(storeab__icontains=store_choices) | Q(storea__icontains=store_choices) ) This does not work and returns no products, I am not sure what variable to use instead of store_choices with the Q(XXX__icontains = ). Any help would be appreciated -
How to calculate percentage in python and django
Am writing a simple program to allow user to get in return 8 percent of any amount they invest in the period of ten days. The user balance in ten days will equal to Eight percent of any amount he/she invest and the percentage balance will be return into the user balance after ten days. Look at my code below and help me. Models.py class Profile(models.Model): user = models.ForeignKey(UserModel, on_delete=models.CASCADE) balance = models.DecimalField(default=Decimal(0),max_digits=24,decimal_places=4) class Investment(FieldValidationMixin, models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) amount = models.DecimalField(max_digits=5, decimal_places=2, null=True, blank=True) fixed_price = models.DecimalField(max_digits=7, decimal_places=2, nulll=True, blank=True) percentageee = models.DecimalField(max_digits=3, decimal_places=0, nulll=True, blank=True) profile = models.ForeignKey(Profile, on_delete=models.CASCADE) def __str__(self): return _("{0}: (#{1} {2}%, ${3})".format(self.__class__.__name__, self.amount, self.percentage, self.fixed_price) ) I want to fetch the percentage of the user investment amount here Views.py def get_percentage(self): pef_of_amount = Investment.objects.filter(amount=self.amount).annotate(percentageee=Sum('amount')) return '{:%}'.format(amount.percentageee / 8) def percentile(self, days=10): percent=Investment.objects.filter(self.amount*self.percentage)/100 in days return percentile #get the percentage balance of the amount invested after ten days def get_current_balance(self,percentile): total_expenses = Profile.objects.all().aggregate(Sum('balance')).annonate(percentile) return get_current_balance -
How to return multiple lists with a single get request?
I want to write a GET request for my Django app to get three lists. I want to apply a filter to my database and return them in different lists in one response. These are the three lists that I want, and I want to filter them with {"to do," "in progress," "Done"}. I don't know is there a way to return multiple lists in one response? or I should write different APIs for every one of them Many thanks. -
How to get Object resource URL after pre-signed post upload?
I am using python to create a pre-signed post URL to upload images into s3. After the upload, I need to save the Object resource URL into the database. def create_presigned_post(request): if request.method == 'POST': bucket_name = 'mybucket' object_name = request.data.get('file_name', 'TEST') fields = { "key": f'{uuid.uuid4()}_{object_name.replace(" ", "_")}' } # key = a918e6b8-b0f0-4067-95e4-82ade3b138c2_myfilename.jpg conditions = request.data.get('conditions', None) expiration = request.data.get('expiration', 3600) try: response = s3_client.generate_presigned_post(bucket_name, object_name, Fields=fields, Conditions=conditions, ExpiresIn=expiration) except ClientError as e: logging.error(e) return None return Response({"message": "Got some data!", "data": response}) return Response({"message": "Hello, world! If you need pre-signed POST URL, make a POST request."}) However, I was hoping the dictionary key in keys of fields dictionary will be the key. And I would be able to get the object URL. For example here: https://mybucket.s3-region.amazonaws.com/myfilename.jpg I thought the key (a918e6b8-b0f0-4067-95e4-82ade3b138c2_myfilename.jpg) that I specified in the fields key-value pairs would be used to construct the Object's resource URL. But instead it is the filename. Also, even in the response that I get from create_presigned_post, the key is the filename, instead of the actual key that I specified in the fields value. How would I get the Object's URL so that I can save it into the database? -
how join 3 table in Django Python
This is my first class class dot_bay(models.Model): ma_dot_bay = models.CharField(primary_key=True,max_length=255, default=uuid.uuid4, editable=False) ten_dot_bay = models.CharField(max_length=255, default="") ngay_bay = models.DateTimeField()``` This is my second class class video(models.Model): ma_video = models.CharField(primary_key=True, max_length=255, default=uuid.uuid4, editable=False) ma_dot_bay = models.ForeignKey(dot_bay, on_delete=models.CASCADE, related_name='dot_bay_video') video_path = models.TextField() detected_path = models.TextField() ngay_upload = models.TextField() And my third class class hinh_anh(models.Model): ma_hinh_anh = models.CharField(primary_key=True, max_length=255, default=uuid.uuid4, editable=False) ma_video = models.ForeignKey(video, on_delete=models.CASCADE, related_name='video_hinh_anh') image_base64 = models.TextField() I try this in my Serializer in my project to display result of 2 join table dot_bay and video like that class DotBayModelSerializer(serializers.ModelSerializer): class Meta: model = dot_bay fields = ("ma_dot_bay", "ten_dot_bay", "ngay_bay", "dot_bay_video") depth = 1 And get the result like that [ { "ma_dot_bay": "db0001", "ten_dot_bay": "Đợt bay", "ngay_bay": "2021-05-14T15:30:27Z", "dot_bay_video": [ { "ma_video": "vd0001", "video_path": "1", "detected_path": "1", "ngay_upload": "1", "ma_dot_bay": "db0001" }, { "ma_video": "vd0002", "video_path": "1", "detected_path": "1", "ngay_upload": "1", "ma_dot_bay": "db0001" } ] }, { "ma_dot_bay": "db0002", "ten_dot_bay": "Đợt bay", "ngay_bay": "2021-05-14T15:31:07Z", "dot_bay_video": [ { "ma_video": "vd0003", "video_path": "1", "detected_path": "1", "ngay_upload": "1", "ma_dot_bay": "db0002" }, { "ma_video": "vd0004", "video_path": "11", "detected_path": "1", "ngay_upload": "1", "ma_dot_bay": "db0002" } ] } ] that's what I expected But now I want to join 3 table, display like that, [ { … -
Django formset with multiple choicefields(select) which have same datasource
I need a design recommendation about Django formset with multiple choicefields(select) which have same datasource. in my project I have simply: ''' Models class Event(models.Model): name= models.Charfield() class Schedule(models.Model): day = models.CharField(max_length=10) hour = models.CharField(max_length=10) event = models.ForeignKey(Event, on_delete=models.DO_NOTHING, related_name="event") Forms class FormSchedule(forms.ModelForm): class Meta: model = Schedule fields = 'all' views def schedule(request): if request.method == 'POST': ..... else: event_queryset = Event.objects.all() choice = maketuple(event_queryset) form_size = 24 * 7 # weekly schedule formset_ = formset_factory( FormSchedule, extra=168) formset = formset_() for form in formset: form.fields['event'].choices = choice return render(request, 'core/schedule.html','formset': formset}) ''' it works in runitme without error. I have html page with 168 selects and each select has 50 options. the problem is It takes more than 15 seconds loading page. is there any way to optimize this process thanks a lot, -
React+Django deploy to heroku not reading Static files
my website works fine on local host but when i upload it to heroku i get The resource from “https://websitename.herokuapp.com/Static/js/main.js” was blocked due to MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff). on all static files both css and javascript index.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <link rel="icon" href="%PUBLIC_URL%/favicon.ico" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" /> <link rel="manifest" href="%PUBLIC_URL%/manifest.json" /> <!-- Google Font --> <link href="https://fonts.googleapis.com/css?family=Muli:300,400,500,600,700,800,900&display=swap" /> <link rel="stylesheet" href="./Static/css/slicknav.min.css" type="text/css" /> <link rel="stylesheet" href="./Static/css/style.css" type="text/css" /> <title>React App</title> </head> <body> <div id="root"></div> <script src="./Static/js/jquery.slicknav.js" type="text/javascript" ></script> <script src="./Static/js/main.js" type="text/javascript"></script> </body> </html> i had to remove some of them from my post so they could fit. -
Angular 11 Django Heroku Deployment
i trying to deploy my Angular + Django with Postgres project to Heroku, and i don't know how to start and what to do. Can someone help? -
unable to store utf8mb4 in mysql
I'm using django with mysql. I want to change my unicode utf8 to utf8mb4 for storing emojis. i did try and change some fields. here is the variables- mysql> SHOW VARIABLES WHERE Variable_name LIKE 'character\_set\_%' OR Variable_name LIKE 'collation%'; +--------------------------+--------------------+ | Variable_name | Value | +--------------------------+--------------------+ | character_set_client | utf8mb4 | | character_set_connection | utf8mb4 | | character_set_database | utf8mb4 | | character_set_filesystem | binary | | character_set_results | utf8mb4 | | character_set_server | utf8 | | character_set_server | utf8 | | character_set_system | utf8 | | collation_connection | utf8mb4_general_ci | | collation_database | utf8mb4_unicode_ci | | collation_server | utf8_general_ci | +--------------------------+--------------------+ 10 rows in set (0.00 sec) Right now when i'm trying to add an emoji its prints ? question mark. I also change my databse and my.cnf file- DATABASES = { ’default’: { ’ENGINE’: ’django.db.backends.mysql’, ’NAME’: ’example’, ’USER’: ’example’, ’PASSWORD’: ’example’, ’HOST’: ’’, ’PORT’: ’’, ’OPTIONS’: {’charset’: ’utf8mb4’}, } } and my.cnf- [client] default-character-set = utf8mb4 [mysql] default-character-set = utf8mb4 [mysqld] character-set-client-handshake = FALSE character-set-server = utf8mb4 collation-server = utf8mb4_unicode_ci somehow the collation server is still shows the utf8 encode and collation connection shows utf8mb4_general_ci -
How to create video conference in flutter and django?
I want create a app thats need to have video conference for multiple users(50 maybe), How can i create this in python django and flutter or react native (for mobile app) ? -
I need to print my username from app named users to in another app named board..It throws error (Cannot import username from users
Here is my code: users/views: from django.shortcuts import render,redirect from django.contrib import messages from django.contrib.auth.models import User,auth global username def login (request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = auth.authenticate(username=username,password=password) if user is not None: auth.login(request, user) return redirect("/") else: messages.info(request,'INVALID CREDENTIALS') return redirect('login') else: return render(request,'loogin.html') print(username) I need my username which is logged in on my board/view,But am not able to import and if am able to import i cant print and shows an error named NameError (username is not defined) Board/views: from django.http import JsonResponse from django.shortcuts import render from board.models import userboard from.utils import get_plot import pandas as pd from sqlalchemy import create_engine from users.views import username print(username) def graphview(request): qs = userboard.objects.all() x=[x.Month for x in qs] y=[y.Bp_Values for y in qs] chart = get_plot(x,y) return render(request, 'piechart.html' ,{'chart':chart}) def panddf(request): engine=create_engine('postgresql+psycopg2://postgres:#24May@2002@localhost/bhavesh') df = pd.read_sql_query('SELECT * FROM public."board_userboard"',con=engine) print(df) return render(request, 'abc.html') -
Django don't save the image from the form with ajax
I have an model with a bunch of fields class Guide(models.Model): image = models.ImageField(upload_to='users/%Y/%m/%d/', blank=True) user = models.ForeignKey( User, blank=True, null=True, default=None, on_delete=models.SET_NULL, help_text=_("User, author/owner of this trip"), related_name="guide", ) active = models.BooleanField( default=False, help_text=_("Display it in trips list / search results?") ) featured = models.BooleanField( default=False, help_text=_("Display it on main/index page?") ) ... Form like this class ChangeImageForm(ModelForm): class Meta: model = Guide fields = ['image'] def __init__(self, *args, **kwargs): super(ChangeImageForm, self).__init__(*args, **kwargs) self.fields['image'].widget = FileInput(attrs={ 'name':'image', 'class':'image', 'id':'upload_image', 'style':'display:none' }) view def change_photo(request): if request.user.is_authenticated and Guide.objects.filter(user = request.user).exists(): item = Guide.objects.get(user=request.user) if request.method == "POST": form = ChangeImageForm(request.POST or None, request.FILES or None, instance = item) if form.is_valid(): form.save(commit=False) form.save() return HttpResponseRedirect('/profile/') ajax $.ajax({ type: 'POST', url: imageForm.action, enctype: 'multipart/form-data', data: fd, success: function (response) { $modal.modal('hide'); $('#uploaded_image').attr('src', fd); }, error: function (error) { console.log('error', error) }, cache: false, contentType: false, processData: false, }) I am trying to do cropping photo with CropJs, and save it with ajax, and so my photos are not saving in database , but when i upload it in admin panel all good, i think it might be something with permisions, but i dont know what is it -
Django Abstract User - how to create/save a profile each time a user has been created/updated
I know I don't have the standard User model to rely on, I don't know how to refer to the instance below. Before changing to the Abstract User Model I would refer to (user=instance). With Abstract User model: UserProfile.objects.create(userprofile=instance) The error I'm getting is Exception Value:'UserProfile' object has no attribute 'userprofile' Exception Location: /workspace/Project-Saasy/profiles/models.py, line 48, in create_or_update_user_profile models.py from django.contrib.auth.models import AbstractUser from django.db.models.signals import post_save from django.conf import settings from django.dispatch import receiver class UserProfile(AbstractUser): """ A user profile model for maintaining default delivery information and order history """ is_volunteer = models.BooleanField(default=False) is_organisation = models.BooleanField(default=False) default_phone_number = models.CharField(max_length=20, null=True, blank=True) default_street_address1 = models.CharField(max_length=80, null=True, blank=True) default_street_address2 = models.CharField(max_length=80, null=True, blank=True) default_town_or_city = models.CharField(max_length=40, null=True, blank=True) default_county = models.CharField(max_length=80, null=True, blank=True) default_postcode = models.CharField(max_length=20, null=True, blank=True) class Volunteer(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=True) def __str__(self): return self.user.username class Organisation(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=True) def __str__(self): return self.user.username @receiver(post_save, sender=UserProfile) def create_or_update_user_profile(sender, instance, created, **kwargs): """ Create or update the user profile """ if created: UserProfile.objects.create(userprofile=instance) # Existing users: just save the profile instance.userprofile.save() ``` -
How can I connect my packages (to call functions from them) to the Django project?
I have a task-to develop a bot + make a web admin panel for it -> in the admin panel, I need to output data from the bot's database, and from the admin panel to call some functions from the bot's packages (for example, turn the bot on or off). A simple import sees PyCharm, but Django swears that it doesn't find it. The picture shows how I want to import the functions. enter image description here If I misunderstand the concept, please correct me, I will be very happy (third day studying Django ): ) -
Heroku celery worker crashed
I have written app for email automation using: Django==2.2.19, django-celery-beat==2.2.0, redis==3.5.3 The desired outcome is to set a specific cron schedule and according to it send email messages. Everything works fine when I have local redis server, local celery worker and local django app. In app I am creating PriodicTask object with a specific crontab and email task to run. Localy App works as well using Herokuredis. I did setup worker in my Procfile release: python3 manage.py migrate web: gunicorn auto_emails.wsgi --preload --log-file - worker: celery -A auto_emails worker --beat --scheduler django --loglevel=info -
How to AutoWrap Statements with Jinja tags inside html file
is there a way to select the statements and wrap it with jinja tags ({% %}) inside html files? For Example. Lets say we have long text to comment,what we usually do is select the entire text and hit CTRL + /, So im looking some what similar , If i have statement like, if a == b after selecting the statement hitting the shortcut i want it to be wrapped with {% if a == b %}, If its possible please let me know -
theblockcrypto's embedded iframe not loading
I am embedding a chart from theblockcrypto.com on my django website. It's a simple iframe tag within the html: <iframe width="100%" height="420" frameborder="0" src="https://embed.theblockcrypto.com/data/crypto-markets/futures/btc-annualized-basis-binance/embed" title="BTC Annualized Daily Basis (Binance)"></iframe> It works fine within my runserver at home, but as soon as I move the code to my VPS(using the same runserver command), the chart doesn't load. The iframe just shows a loading logo. I get the following error in the js console: TypeError: Cannot read property 'getRegistrations' of undefined at 643985e.js:1 at h (72e8ff3.js:1) at Generator._invoke (72e8ff3.js:1) at Generator.next (72e8ff3.js:1) at r (72e8ff3.js:1) at l (72e8ff3.js:1) at 72e8ff3.js:1 at new Promise (<anonymous>) at 72e8ff3.js:1 at 643985e.js:1 Any idea what's going on?