Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Enable a function when validation from another user are met
I have a Django project that have a send SMS function but the SMS distribution needed to be only available when needed or permission granted. I have 2 users, Admin Staff Staff handles the system, and Admin handles the permissions. Now to enable Send SMS, staff needs permission to the Admin to enable the button which is disabled by default. I'm thinking like, Admin's end have a function into a button, that when the admin clicks that button, it will enable the other button on staff's end. How am I gonna do this? please help! Thanks! -
How to stop having a value error on django?
I am trying to add a follow sistem to my django project my when running my code, I am getting a The QuerySet value for an exact lookup must be limited to one result using slicing. error, It is saying that the wrong part is on this line of code of the views.py file following_obj = Following.objects.get(user=user). views.py def profile(request, username=None): profile, created = Profile.objects.get_or_create(user=request.user) if username: post_owner = get_object_or_404(User, username=username) user_posts = Profile.objects.filter(user_id=post_owner) user = User.objects.filter(username=username) is_following = Following.objects.filter(user=request.user, followed=user) following_obj = Following.objects.get(user=user) follower, following = following_obj.follower.count(), following_obj.followed.count() else: post_owner = request.user user_posts = Profile.objects.filter(user=request.user) args1 = { 'post_owner': post_owner, 'user_posts': user_posts, 'connection': is_following, 'follower': follower, 'following': following, } return render(request, 'profile.html', args1) def follow(request, username): main_user = request.user to_follow = User.objects.get(username=username) following = Following.objects.filter(user = main_user, followed = to_follow) is_following = True if following else False if is_following: Following.unfollow(main_user, to_follow) is_following = False else: Following.follow(main_user, to_follow) is_following = True resp = { 'following': is_following, } response = json.dumps(resp) return HttpResponse(response, content_type="application/json") models.py class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) profile_pic = models.ImageField(upload_to='profile_pics', null=True, blank=True, default='default.png') bio = models.CharField(max_length=400, default=1, null=True) follower = models.IntegerField(default=0) following = models.IntegerField(default=0) def __str__(self): return f'{self.user.username} Profile' class Following(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) followed = … -
Django how to know if a method is instance method or class method
How do I know if a method in Django is an instance method or a class method, so that when overriding, I will know to put in "self". For example: the method get_object(self, QuerySet=None) is an instance method because there is "self". However, in Django official doc, they do not explicitly write out "self" (Please see the link to the picture.) Thus, I do not know if get_object() is an instance method. link to the pic I work on VScode, and VScode doesn't have good autocompletion to show the template of get_object(self, QuerySet=None). So then again, there is no way for me to find out get_object() is an instance method. I appreciate any help! -
How to create a model that inherits from another model that inherits from Django-User model using Django generic.CreateView
I have a model named 'Category' that inherits from "django.contrib.auth.models.User" . I also have a model named 'Content' that inherits from the 'Category' model. Its like: A user can have several categories and each category can have several contents. I'm trying to create a front-end for users to create contents using "django.contrib.views.generic.CreateView" class. Do you have any ideas how might possibly that happen? tell me if you have any other ways than generic-views as well please. -
I have problem to deploy my django project with docker nginx and gunicorn
If I have running my containers on the server side and everything is okay,for accessing route on the browser should I put ip of nginx container with domain in etc/host or it have to work without that? my nginx.config server { listen 80; server_name my_domain; root /code/; error_log /var/log/nginx/new_error.log debug; location / { proxy_pass http://web:8000/; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /staticfiles/ { alias /code/staticfiles/; } location /mediafiles/ { alias /code/mediafiles/; } } where web is my docker-container with gunicorn running -
empty_form in inline formset django
i try to make an inlineformset to submit multiple forms at the same time depend on empty_form, but when i submit the form it will only save first one this is the entire snippet <form method="POST">{% csrf_token %} <div class="col-12 p-0 border-top text-center border-light row info mx-auto"> <div class="row col-12 mt-1 mx-auto"> <div class="col-6 inp text-center"> {{form.title | add_class:'col-12'}} </div> <div class="col-6 inp text-center "> {{form.logo | add_class:'col-12 d-inline'}} </div> </div> </div> <!-- order --> <div class="col-12 p-0 border-top border-light "> <table class="customeTable col-12 table-responsive-sm info text-center table1 mx-auto mb-2 "> <thead> <tr > <th>name</th> <th>year</th> <th>note</th> </tr> </thead> <tbody class="tbody tb1 "> <tr class="p-0 col-12" id="form_set"> {{formset.management_form}} {% for info in formset.forms %} <td class=""> <div class="col-12 p-0 mt-3 inp"> {{info.name | add_class:'col-12'}} </div> </td> <td class=""> <div class="col-12 p-0 mt-3 inp"> {{info.year | add_class:'col-12'}} </div> </td> <td class=""> <div class="col-12 p-0 mt-3 inp"> {{info.note | add_class:'col-12'}} </div> </td> </tr> </tbody> {% endfor %} <tfoot> <tr style="background-color: #5dbcd3;color: #ffffff;"> <th colspan="2" > <label for="">date</label> {{form.date | add_class:'col-12'}} </th> </tr> </tfoot> </table> <input type="button" value="submit"> </div> </form> <div id="empty_form" style="display: none;"> <tr class="p-0 col-12"> <td class=""> <div class="col-12 p-0 mt-3 inp"> <input class="col-12 qarz" type="number" name="" placeholder="qarz"> </div> </td> <td … -
Django / Python - Convert image from AWS S3 bucket to Base64?
I'm trying to convert each image instance to base64. All images are stored in my amazon-s3 bucket. Unfortunately, my generated encryption is not displaying the image at my recipe_plain.html template. Any help is appreciated. views.py ... import base64 class RecipePlainView(DetailView): model = Recipe template_name = 'recipes/recipe_plain.html' def get_context_data(self, **kwargs): context = super(RecipePlainView, self).get_context_data(**kwargs) image = self.object.image image.open(mode='rb') context['recipe_image_base64'] = base64.b64encode(image.read()) image.close() return context recipe_plain.html <img src="data:image;base64,{{ recipe_image_base64 }}" alt="{{ recipe.image.name }}"> Here is one of the images for the testing purposes: baketoom-recipes-files.s3.amazonaws.com/default.jpg... When run by the RecipePlainView(), context['recipe_image_base64'] returns the following string found in the snippet: copyText = document.getElementsByTagName('textarea')[0]; document.getElementsByTagName('button')[0].onclick = function() { copyText.select(); document.execCommand('copy'); console.log('Copied') } document.getElementsByTagName('span')[0].innerHTML=copyText.innerHTML.length+' Characters in total.' <textarea style="width: 100%; min-height: 50px"> b'/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwhMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL/wAARCAEsASwDASIAAhEBAxEB/8QAHwAAA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C4tL+5012JtSPNXP8LZwR+P8ASgD6GopkMgljDDvT6ACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKq6jqNppOnzX9/OkFtCu55GPAH+PtQAmp6nZ6Pp09/fzrDbQrud2/z1r5j8f+P7zxpqO1d0Glwt+4t89f9tvU/wAqf8QfiDd+M9Q8uPfBpULfuIM8t/tv7+3auKoAKKKsWVlPf3S28C7nb8gPU0AFlZT6hdLbwLl26nso9TXrfg7QBYOkdupZiQZJCOWNVvDPhlbdFggXc7f6yTHLH/CvXtB0KOxhVmUbqANixQx2qK3XFWaAMDAooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiq9/f2umWM17ezpBbQqWeRzgAUAJqGoWmlWE19fTpDbQrud2PAFfMvxC+IV34zvzDCXg0mFv3MOeXP99vf27U/4ifES68ZXxt7cvBpELfuoTwZD/ff39B2rhqACiip7S0mvrlLeBNzt+g9TQAWdnNf3SW8C7nb8gPU16j4Z8MrbosMK7pGx5kmOWP8AhSeGPDC2yrFEu+Rv9ZJjr/8AWr1/QNBjsoVZlG6gBdB0GOyhVmUbq6EAAYFAAAwKWgAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKgvLy30+zlu7uZIbeJS7yOcBQKAEvb2206ymvLyZIbeFS0kjnAUV80/EX4iXPjG9Nral4dHhb93GeDKf77f0HanfEf4jT+MLz7HZl4dHhbMaHgzEfxt/Qdvr04KgAooqa1tZr24SCBC8jHgD+dABaWk17cpBAhaRv09zXp/hjwwtsqxRLvlf8A1kmOvt9KTwx4YFqqxxrvmf8A1kmOvsPavYPD+gR2cKu6jdQAugaBHZQqzKN1dGAAMCgAKMCloAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAoqteahZafEZLy7ht0HOZXC/zri9X+MHhHS9yx3j30g/htU3A/8AAjgfrQB3tFeH33x9nlcx6ToILH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yODgqwwRQA2iiigAooooAKKKKACiiigAooooAKKKKACiirunaRfarKI7O3eT1bGFH1NAFKtzQfC2oa9KvlRmO3zzKw6/T1rvPDHws3Ok2ofvn67MfIP8a9g0jw1b2Ma/IOBwMUAcr4Q8A2ulwLtiwTyzt95vrXotvbR28YVFAxUiIqLhRgU6gAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigCKa3jmUh1BrkfEPw+0jXEJuLVGfs4GGH412dFAHzxrnwbvbVmfTLnevaOYc/mK4PUfDGtaWxF1p8yqP41XcP0r7AeNHHzKDWdd6baSqd0QNAHx10JHcUV9K6x4R0O73GfT4XPqVGfzritR+HugZPlwzQn/YlP9c0AeP0V1Gs+G7PT2kEMk529N7A/0rmyg3Ec8UAR0U5VBqzZWqXMwRywHtQBUorvtL8GaZdRCSWS5b23gD+VdVp/gjQIyD9iDn1kYt/OgDxuGCa4fZBE8jeiKTXQ6b4F1vUWGbfyEPeTr+Qr3bS9A02JVWO3VQOygCups9NtIwNsQoA8e0H4SQqyyXm+4b0bhfyr03SfCNpYxooiRVXoqjAFdMkaIPlUCn0AQw20UC4RQKmoooAKKKKACiiigAooooAKKKKAP//Z' </textarea> <br> <span></span> <br><br> <button>Copy All</button> : -
Access values from joined table in django
I have 2 tables linked together by a foreign key (Category, Activity). I'm trying to access the values in the category table from my query using the activity object. Model class: class Category(models.Model): name = models.CharField(max_length=100) weekly_goal = models.IntegerField(blank=True, null=True) metacat_fk = models.ForeignKey(MetaCategory, models.DO_NOTHING, db_column='metacat_fk') class Meta: managed = False db_table = 'category' class Activity(models.Model): name = models.CharField(unique=True, max_length=100) distance = models.FloatField(blank=True, null=True) duration = models.TimeField(blank=True, null=True) date = models.DateField(blank=True, null=True) note = models.CharField(max_length=100, blank=True, null=True) category = models.ForeignKey(Category, models.DO_NOTHING, db_column='category_fk') class Meta: managed = False db_table = 'activity' Trying to access the values in Category: activity = Activity.objects.select_related('category') frequency_df = pd.DataFrame(list(activity.values())) logging.warning(activity.query) logging.warning(frequency_df.head()) Output: SELECT "activity"."id", "activity"."name", "activity"."distance", "activity"."duration", "activity"."date", "activity"."note", "activity"."category_fk", "category"."id", "category"."name", "category"."weekly_goal", "category"."metacat_fk" FROM "activity" INNER JOIN "category" ON ("activity"."category_fk" = "category"."id") id name distance duration date note category_id 0 1382 Yoga - Wednesday June 19 2019 None None 2019-06-19 Yoga 3 1 1385 Yoga - Wednesday September 18 2019 None None 2019-09-18 Yoga 3 2 1388 Yoga - Tuesday October 08 2019 None None 2019-10-08 Yoga 3 3 1391 Yoga - Tuesday October 15 2019 None None 2019-10-15 Yoga 3 4 1394 Yoga - Saturday October 26 2019 None None 2019-10-26 Yoga 3 According to … -
how to update django databsae from html?
I want to only update the brand. So I want to see if I can get the post from the input. print(request.POST.get('brand')) didn't print anything, but I can get print(request.POST.get('url')). Does anyone know why? Here is my base.html code. <form action="{% url 'script' %}" method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="form-group w-75"> <input type="text" name="url" id="url" class="form-control"> </br> <button type="submit" class="btn btn-success btn-lg btn-block">submit</button> </div> </br> {% if alldata %} <table class="table table-striped table-sm" id=""> <thead> <tr> <th>Price</th> <th>Asin</th> <th>Rank</th> <th>Brand</th> <th>CPU</th> <th>Update</th> </tr> </thead> <tbody> {% for data in alldata %} <tr> <td>{{ data.price }}</td> <td> <a href="{{ data.link }}">{{ data.asin }}</a> </td> <td>{{ data.rank }}</td> <td> <div> {{ data.brand }} <input type="text" name="brand" id="brand" value="{{data.brand}}"> <button type="submit">Update</button> </div> </td> <td>cpu</td> <td><button type="submit">Update</button></td> </tr> {% endfor %} </tbody> </table> {% endif %} </form> -
I want to show the Default pic to the user profile whenever a new user is registered using Signals without doing it manually from Django admin
I want to load the default pic of the user, whenever a new user is created using signals. But its not loading the default pic. I don't want to do this manually from Django admin, I want this to be done whenever a new user is created in the app. models.py from django.db import models from django.contrib.auth.models import User class userprofile(models.Model): user = models.OneToOneField(User,on_delete = models.CASCADE) profilepic = models.ImageField(default='pp.png',upload_to='profile_pic',blank = True) forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from .models import userprofile class ProfileUpdateForm(forms.ModelForm): class Meta: model = userprofile fields = ['profilepic',] views.py @login_required def profile(request): if request.method == 'POST': p_form = ProfileUpdateForm(request.POST,request.FILES,instance=request.user.userprofile) if p_form.is_valid(): p_form.save() return render(request,'profile.html') else: p_form = ProfileUpdateForm(instance=request.user.user) context = { 'p_form': p_form } return render(request,'profile.html',context) profile.html <form method ="POST" class="sm:w-1/3 text-center sm:pr-8 sm:py-8" enctype="multipart/form-data" > {% csrf_token %} <img id="profile_pic" alt="team" class="flex-shrink-0 rounded-lg w-full h-56 object-cover object-center mb-4" src="{{user.userprofile.profilepic.url}}"> {{ p_form|crispy }} <br> <input id="file-input" style="padding: 8px 93px;" class="text-white bg-green-500 border-0 py-2 px-8 focus:outline-none hover:bg-green-700 rounded text-lg" type="submit" value="Upload"> </form> signalspy from django.db.models.signals import post_save from django.contrib.auth.models import User from django.dispatch import receiver from .models import userprofile @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: userprofile.objects.create(user=instance) @receiver(post_save, sender=User) … -
Django Google Analytics API / Get age and gender information
Is there a way to pull demographic information from Google to my Django website via API method? For example, I need to write 2 extra information in a post, gender and age. Is there a way for me to print this information to my own database via google analytics? like this; read this article 41% male and 59% female. -
Django MPTT how to create children for loop and remove standard li formatting in browser
I am trying to create a small form under each child that lets you create a subchild to that child. But when i run a standard django for loop it returns a strange result in the browser. This is what works, but as said i want to create a custom form for each child. {% load mptt_tags %} <ul> {% recursetree goal %} <li> {{ node.title }} {% if not node.is_leaf_node %} <ul class="children"> {{children}} </ul> {% endif %} </li> {% endrecursetree %} </ul> So this is what i tried which doesn't work {% load mptt_tags %} <ul> {% recursetree goal %} <li> {{ node.title }} {% if not node.is_leaf_node %} <ul class="children"> {% for child in children %} {{child}} #add subchild to child form here {% endfor %} </ul> {% endif %} </li> {% endrecursetree %} </ul> Also, how do a return only the title of each node without having MPPT creating it in a list format for me? Advice greatly appreciated! -
Can't authenticate Tag Manager API through OAuth in Django when deployed on Google App Engine
I have a Django app that access data from Google Tag Manager using its API. It works fine locally, but when it is deployed and I try to authenticate, I get this message: UserWarning: Cannot access tagmanager.dat: No such file or directory Your browser has been opened to visit: https://accounts.google.com/o/oauth2/auth?scope=https%3A%2F%2Fwww.googleapis.com%........... If your browser is on a different machine then exit and re-run this application with the command-line parameter --noauth_local_webserver And the browser doesn't open a new window for authentication which leads to a timeout error. views.py import argparse import sys import os import httplib2 from apiclient.discovery import build from oauth2client import client from oauth2client import file from oauth2client import tools import pandas as pd def GetService(api_name, api_version, scope, client_secrets_path): parser = argparse.ArgumentParser( formatter_class=argparse.RawDescriptionHelpFormatter, parents=[tools.argparser]) flags = parser.parse_args([]) credentials = run_flow(flow, storage, args) flow = client.flow_from_clientsecrets( client_secrets_path, scope=scope, message=tools.message_if_missing(client_secrets_path)) storage = file.Storage(api_name + '.dat') credentials = storage.get() if credentials is None or credentials.invalid: credentials = tools.run_flow(flow, storage, flags) http = credentials.authorize(http=httplib2.Http()) service = build(api_name, api_version, http=credentials.authorize(http=httplib2.Http())) return service I have also tried to add flags.noauth_local_webserver = True as suggested here, but no luck. My API configuration is as follows: Client ID for Web Application Authorised JavaScript origins URI: https://myapp.appspot.com Authorised redirect … -
AttributeError: 'WSGIRequest' object has no attribute 'site' - wagtail, wagalytics
I'm trying to implement wagalytics within my new wagtail site (https://github.com/tomdyson/wagalytics). I'm my error pops up at line 138 of views.py site = Site.objects.get(hostname=request.site.hostname) AttributeError: 'WSGIRequest' object has no attribute 'site' When I change this to something like try: site = Site.objects.get(hostname=request.site.hostname) except: site = '127.0.0.1' It works - or at least gets me onto the next problem. Obviously I don't want to go chopping in a try/except block into the code in production - and I'd be better off for an understanding of what's happening here and how to resolve it. -
How to fix ProfileNotFoundError in Django
Basically, I'm creating an app and currently I'm testing out an "Edit Profile" feature. For me (the admin) I manually added myself to the Profile model using the admin page. However, when I tried it on my test account, it didn't work. I know what the problem is (I didn't add him to the model) but I was wondering how I could fix it. Here's my model: class Profile(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE) image = models.ImageField(default = 'default.jpg', upload_to = 'profile_pics') def __str__(self): return f'{self.user.username} Profile' def save(self): super().save() Here's my views.py: @login_required def profile(request): user_form = UpdateUser() profile_form = UpdateProfile() if request.method == 'POST': user_form = UpdateUser(request.POST, instance = request.user) profile_form = UpdateProfile(request.POST, request.FILES, instance = request.user.profile) if user_form.is_valid() and profile_form.is_valid(): user_form.save() profile_form.save() return redirect('profile') else: user_form = UpdateUser(instance = request.user) profile_form = UpdateProfile(instance = request.user.profile) context = { 'user_form' : user_form, 'profile_form' : profile_form } My signals.py: from django.db.models.signals import post_save from django.contrib.auth.models import User from django.dispatch import receiver from .models import Profile @receiver(post_save, sender = User) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user = instance) @receiver(post_save, sender=User) def save_profile(sender, instance, **kwargs): instance.profile.save() And finally, my apps.py: from django.apps import AppConfig class UsersConfig(AppConfig): name = … -
Django adding fields in a form statically
Good day, I am trying to make a Django form where I could add fields statically (the concept is described in the figure below). I want to have a form that would have a button "new". The button "new" should redirect to another page where I could fill the data such as from, to, and amount. Once I press submit it should go back to the form where the filled data should be visible in the form (as amount 1, amount 2 and etc.). Could somebody lead me on the right path how to start? P.S. I cannot use javascript -
from an id, how to get a path for different pages in django
I am creating a web page,it is for a restaurant. there is an image slide show. all the thing of slide show dynamic..load from the database. My problem is.. there is a button of the each slid to go to different pages. as an example one slide for wine section another is for menu another for special plates. another for another page so on...my html template is this [enter link description here][1] [1]: https://colorlib.com/wp/template/eatery/ how can i give the path to the each different pages. my urls.py urlpatterns = [ path('', home, name='home' ), ] my views.py def home(request): image_gallery = Gallery.objects.all() context = {'galleries':image_gallery} return render(request, 'restaurant/index.html', context) my html template with for loop <section class="home-slider owl-carousel"> {% for gallery in galleries %} <div class="slider-item" style="background-image:url('{{gallery.image.url}}')"> <div class="container"> <div class="row slider-text align-items-center justify-content-center"> <div class="col-md-8 text-center col-sm-12 element-animate"> <h1>{{gallery.image_title}}</h1> <p class="mb-5"> {{gallery.image_description}} </p> <p> <a href="{% url'' id= gallery.id %}" class="btn btn-white btn-outline-white">{{gallery.image_button}}</a> </p> </div> </div> </div> </div> {% endfor %} </section> My models.py class Gallery(models.Model): image = models.ImageField(null=True, blank=True, ) image_title = models.CharField(blank=True, null=True, max_length=200) image_description = models.TextField() image_button = models.CharField(blank=True, null=True, max_length=20) -
How to stop python development server from terminal?
I am writing a my_migration_script.py in the root directory of my django project to remove all the migration files from different apps of my django project. It is like this: import os import shutil migration_folders_names = [ '/app1/migrations/', '/app2/migrations/', '/app3/migrations/', '/app4/migrations/', '/app5/migrations/', '/app6/migrations/', '/app7/migrations/', ] cwd = os.getcwd() migration_folder_paths = [cwd + migration_folder_name for migration_folder_name in migration_folders_names] [shutil.rmtree(migration_folder_path, ignore_errors=False, onerror=None) for migration_folder_path in migration_folder_paths] [os.mkdir(migration_folder_path) for migration_folder_path in migration_folder_paths] [open(migration_folder_path + "0001_initial.py", "x") for migration_folder_path in migration_folder_paths] It works fine. I then want to do the following: 1) Stop runserver: I have a tab for running python manage.py runserver in my Pycharm IDE. What I normally do is that I go to the abovementioned terminal tab and hit Ctrl+C . However, I now want to automate it by adding a piece of code to my_migration_script.py . What should I add to my_migration_script.py ? 2) I have a tab for running python manage.py shell in my Pycharm IDE. What I normally do is that I go to the abovementioned terminal tab type and enter exit() . However, I now want to automate it by adding a piece of code to my_migration_script.py . What should I add to my_migration_script.py ? 3) I … -
How to insert data into a database every time I click Send from HTML button
I have an SMS function on my Django app, but I want to happen is record the message and timestamp each time I send a message. I need to store the value inside sms_message on another table every time I click send sms. The entry on the other table will be like this: id: 1 Description: As of {z.timestamp}, the Rainfall Warning is now at {z.level}. Please prepare for evacuation Timestamp: XXXXX Help, how to do it? Thanks! @views.py def send_sms(request): aws_access_key_id = "XXXXXXXXXXXX" aws_secret_access_key = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" aws_region_name = "us-east-1" z = Rainfall.objects.latest('timestamp', 'level') sender_id = "Test" sms_message = f'As of {z.timestamp}, the Rainfall Warning is now at {z.level}. Please prepare for evacuation' client = boto3.client( "sns", aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key, region_name=aws_region_name ) topic = client.create_topic(Name="notifications") topic_arn = topic['TopicArn'] # get its Amazon Resource Name numbers = Mobile.objects.all() for i in numbers: client.subscribe( TopicArn=topic_arn, Protocol='sms', Endpoint=i.mobile_number ) response = client.publish( Message=sms_message, TopicArn=topic_arn, MessageAttributes={ 'string': { 'DataType': 'String', 'StringValue': 'String', }, 'AWS.SNS.SMS.SenderID': { 'DataType': 'String', 'StringValue': sender_id } } ) messages.info(request, 'SMS sent successfully!') return HttpResponseRedirect('/advisory/') @sendsms.html {% block content %} {% if messages %} {% for message in messages %} {% if message.tags %} <script>alert("{{ message }}")</script> {% endif %} {% endfor … -
DRF , invalid model refrence
I'm restructuring my API and I've made a models folder inside the app. now when I'm trying to fix the AUTH_USER_MODEL I get the following error: ValueError: Invalid model reference 'api.models.user'. String model references must be of the form 'app_label.ModelName'. my structure: ├── api │ ├── admin.py │ ├── apps.py │ ├── migrations │ ├── models │ │ ├── __init__.py │ │ ├── messages.py │ │ └── user.py # rest of app and my settings: AUTH_USER_MODEL = 'api.models.user' -
using django messages while redirecting by javascript function
The project has two standart title and entry models. The deletion of entries is handled by ajax. Ajax: function ajax_delete(id){ $.ajax({ url: '/ajax/delete/', type: "get", data: { 'id': id, }, dataType: 'json', success: function (data) { if(data.nono){ window.location.replace("http://192.168.1.22:8000/mainpage/"); } else{ $("#overlay3").css("display","none"); $( "#article" + id ).remove(); $('body').css('overflow', 'scroll'); }}, error: function (result) { alert('nope'); } }); }; View: def delete(request): id= request.GET.get('id', None) if Entry.objects.filter(id= id).exists(): entry= Entry.objects.get(id= id) if entry.user == request.user or request.user.is_staff: entry.delete() if not Entry.objects.filter(title=entry.title).count(): Title.objects.get(title=entry.title).delete() data={"nono":1} return JsonResponse(data) data={"success":True} else: data={"success":False} else: data={"success":False} return JsonResponse(data) The function also deletes the entry if the title has no other entries. In that case, to prevent users from seeing an empty page the users are redirecting to the mainpage by ajax success. When that happens I want to inform the users about the deletion of the title by flashing a custom django info message (I have a badass fadeout animation for django info messages). So I wonder if there is any way of using djago messages after redirecting by ajax. -
How to make a filtered summary in django template involving two models linked with foreign key?
I am currently learning django and below is the current setup: models.py class Customer(models.Model): name = models.CharField(max_length=200, null=True) phone = models.CharField(max_length=200, null=True) def __str__(self): return self.name class Order(models.Model): STATUS = ( ('Pending', 'Pending'), ('Delivered', 'Delivered'), ) customer = models.ForeignKey(Customer, null=True, on_delete=models.SET_NULL) status = models.CharField(max_length=200, null=True, choices=STATUS, default="Pending") def __str__(self): return self.product.name views.py def home(request): orders = Order.objects.all().order_by('-date_created') customers = Customer.objects.all() c_pending = orders.filter(status='Pending').all() context = { 'orders': orders, 'customers': customers, 'c_pending': c_pending, } return render(request, 'home.html', context) home.html {% for customer in customers %} <tr> <td>{{customer.name}}</td> <td>{{customer.phone}}</td> <td>{{customer.order_set.count}}</td> <td>{{c_pending.count}}</td> </tr> {% endfor %} One to third column work flawlessly, except fourth column. The problem is I wish to display in fourth column the no. of orders which is under pending status for each customer but it indeed shows up the total no. of pending orders as a whole. What steps I am missing in order for django template properly extract the no. of orders for each customer under pending status. Any help is highly appreciated. Thanks. -
Passing user input from one template to multiple other templates
I am learning Django and looking to build out a site that would take input from a user one page1. Then it will pass that information over to page2. Then both page1 and page2 user input would get passed to page3 and processing will happen. Very similar to like a sign up form. The first page is some information, then the second page is some more information, then the third page will complete the signup. Right now I return data from one page to another like this: return render(request, 'per/per.html', context) And then on that page I have access to all the data in the context variable. But wanted to know how to move it to another page. -
MySQL handling large queries
I'm using MySQL + Django and I'm downloading and updating data in my database. I have a few large queries which they sometimes fail -> "MySQL server has gone away" The query is such SELECT * FROM XYZ_table WHERE id IN (list with about 10-40K values) What are my possibilities here? Should I split the query and then concatenate the separate lists? Or is there a MySQL config value I can increase? I have max_packet_size set at 512M -
Django doesn't recive pre save signal
I'm writing DRF appliaction and I have problem which I can't understand. I'm trying to send request when my model changes. Here is my model: class Sensors(models.Model): CATEGORIES = [ ('temperature', 'temperature'), ('humidity', 'humidity'), ] id = models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID') name = models.CharField(max_length=30, unique=True) category = models.CharField(max_length=15, choices=CATEGORIES) battery_level = models.IntegerField(blank=True, null=True) notifications = models.BooleanField(default=True) is_active = models.BooleanField(default=True) frequency = models.IntegerField(default=300) ip_address = models.GenericIPAddressField(blank=True, null=True) class Meta: verbose_name = "Sensor" verbose_name_plural = "Sensors" def __str__(self): return str(self.id) And here is my signal.py: from django.db.models.signals import pre_save from django.dispatch import receiver from sensors.models import Sensors import requests @receiver(pre_save, sender=Sensors) def do_something_if_changed(sender, instance, **kwargs): try: sensor = Sensors.objects.get(pk=instance.pk) except Sensors.DoesNotExist: pass # Object is new, so field hasn't technically changed, but you may want to do something else here. else: if not sensor.frequency == instance.frequency: # Field has changed # do something data_for_sensor = { 'id': sensor.id, 'frequency': instance.frequency } response = requests.post('http://192.168.1.21:8000/receive', data=data_for_sensor) response.raise_for_status() Generally post is not sending and I cannot find why