Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why won't os.environ.get return the new value set in bash profile?
I have a django application and I recently changed a password on an email that uses the google smtp. I've updated the password in the bash profile, but when I run settings.py the os.environ.get returns the previous password in the bash profile. old password: ABC new password: XYZ EMAILS_HOST_PASSWORD = os.environ.get("EMAIL_PASS") print(EMAILS_HOST_PASSWORD) still returns ABC instead of XYZ -
How to Use Django Management Command For One Time Tasks
I want to schedule one time tasks with Django Management Command. I tried following this tutorial but couldn't figure out how to NOT do a recurring task. Let's say I want something to run on January 25th, 5:00 PM UTC 2021 ONCE. How could I do this? Thanks! -
Django3.0: Images from database not showing-up after debug=False
After debug=False in my settings. Images from database not showing up otherwise they were. Static files are showing up real good. Even my media files were showing up before debug=False. Database has correct addresses of files but covers not showing up. Following is the code, how I am accessing cover images. <div class="product-top"> <img src="{{ product.cover.url }}" alt="book-image"> <h5>{{ product.title }}</h5> </div> my settings.py related code: import os import django_heroku # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) TEMP_DIR = os.path.join(BASE_DIR, 'templates') # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'abc' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['*'] EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'abc@gmail.com' EMAIL_HOST_PASSWORD = 'xyz' EMAIL_PORT = 25 EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = 'abc@gmail.com' EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' BASE_URL = '127.0.0.1:8000' MANAGERS = ( ('abc', "abc@gmail.com"), ) ADMINS = MANAGERS # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'debug_toolbar', 'crispy_forms', # myapps 'myapp', ] AUTH_USER_MODEL = 'accounts.User' STRIPE_SECRET_KEY = 'abc' STRIPE_PUB_KEY = 'abc' MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'debug_toolbar.middleware.DebugToolbarMiddleware', # Simplified static file serving. 'whitenoise.middleware.WhiteNoiseMiddleware', ] ROOT_URLCONF = 'project.urls' TEMPLATES … -
How do I retrieve the name of superuser in Django?
users = User.objects.all() post.author = users.name Considering that 'User' is where superuser's info is stored in the database. It throws an error as: 'Query Set' object has no attribute 'name' -
Django + S3 Signature expiration
Should my django-storage instance be storing the S3 signature in the database along with the image name? If so how do you regenerate a new key on each request assuming the old request expiration is already past? models.py def user_directory_path(self, filename): return 'profile/user_{0}/images/profile/{1}'.format(self.user.id, filename) ... ... user_image = models.ImageField(upload_to=user_directory_path, storage=PrivateMediaStorage(), blank=True) storage_backends.py class PrivateMediaStorage(S3Boto3Storage): location = 'private' default_acl = 'private' file_overwrite = False custom_domain = False Sorry new to Django, want to make sure my logic is correct. -
'<frozen importlib._bootstrap>' django error
I have been receiving the error below, whenever I wish to run the server (python manage.py runserver) However as of late, I have been getting the error below. The last thing that I did was carry out tests for my project over a week ago. Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Python38\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Python38\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Python38\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Python38\lib\site-packages\django\core\management\commands\runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "C:\Python38\lib\site-packages\django\utils\autoreload.py", line 76, in raise_last_exception raise _exception[1] File "C:\Python38\lib\site-packages\django\core\management\__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "C:\Python38\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Python38\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Python38\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Python38\lib\site-packages\django\apps\config.py", line 90, in create module = import_module(entry) File "C:\Python38\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'django_filters' Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Python38\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Python38\lib\site-packages\django\core\management\__init__.py", line 395, in execute … -
could not concatenate string with int inside action method of url inf form tag in python Django
todo_item.id is an int and rest of addres is string so it is not concatinating . Please tell me how to concatenate it. I search a lot but found nothing -
Django-Filters - ListApiView
I am following this documentation on how to implement django-filter: https://django-filter.readthedocs.io/en/stable/guide/rest_framework.html#using-the-filterset-fields-shortcut import django_filters from django_filters import rest_framework as filters class PostApiView(ListAPIView): filter_backends = (filters.DjangoFilterBackend,) filterset_fields = ('category', 'location') def get(self, request, format=None): post_qs = Post.objects.all() po_serializer = PostSerializer(post_qs, many=True) po_data = po_serializer.data data = { 'post_data': [{ 'title': po['title'], 'content': po['content'], 'category': po['category'], 'location': po['location'], 'author': po['author'], 'date_posted': po['date_posted'], 'author_image': po['author_image'], 'post_pk': po['post_pk'], 'author_desc': po['author_desc'], 'contact': po['contact'] } for po in po_data], } <form class="filter_form" action="" method="get"> {{ filter.form.as_p }} <button class="filter_form_btn" type="submit">Suche</button> </form> The form does not render Thank you for any suggestions -
What does the underscore before the label value in Django forms mean
I have came through the UserCreationForm in the django source code here. Here is the question, if you look at both password fields you will see an underscore before the label value, I wonder what's the purpose of it, because it's not written in the documentation since I searched for it. class UserCreationForm(forms.ModelForm): """ A form that creates a user, with no privileges, from the given username and password. """ error_messages = { 'password_mismatch': _('The two password fields didn’t match.'), } password1 = forms.CharField( label=_("Password"), strip=False, widget=forms.PasswordInput(attrs={'autocomplete': 'new-password'}), help_text=password_validation.password_validators_help_text_html(), ) password2 = forms.CharField( label=_("Password confirmation"), widget=forms.PasswordInput(attrs={'autocomplete': 'new-password'}), strip=False, help_text=_("Enter the same password as before, for verification."), ) -
Improve performance of processing API created using Django-rest-framework
I want the above API "story": { "pranay": [ 9, 2 ], "eeee": [ 8, 6, 4, 3, 1 ], "pranay56n": [ 5 ] } And I am getting it using the method below. But there is a problem it is okay to have the method if my objects are less but if there are 100000 objects than it will lower the performance. class Follow(models.Model): user = models.OneToOneField(User, verbose_name=_("User"),related_name="user" ,on_delete=models.CASCADE) following = models.ManyToManyField(User, verbose_name=_("Following"),related_name='is_follower',blank=True) class StorySerializer(ModelSerializer): story = SerializerMethodField() class Meta: model = Stories fields = ('story',) def get_story(self,request): user = self.context.get("request").user follower_ids = [x.pk for x in user.user.following.all()] qs = Stories.objects.filter(user__id__in=follower_ids, active=True).order_by('-date_created').values_list('user__username',flat=True) data = {} for obj_user in qs: data[obj_user]=Stories.objects.filter(user__username__exact=obj_user, active=True).order_by('-date_created').values_list('pk',flat=True) return data Is there any way that will increase its performance? -
Which method is the most efficient and fast for Tag functionality, using content types or using manytomany field for diff apps in a django project?
Hello guys I have a doubt regarding having to implement Tag functionality. I have 3 apps, I need to add tags to the models in all those apps. Are there performance issues in using content types when the database gets populated ? or is it better to use manytomanyfield for every model in terms of performance and speed? Thanks -
How do I create dynamic detail pagea for my products in my Django e-commerce website?
I am in the process of creating an e-commerce website. My goal is to have individual detail pages for all the products listed on my website. Ideally, I want to do this dynamically using a slug field, which I have already migrated. I am relatively new to Django and would really appreciate it if someone could assist me. -
Bitbucket cloning into Linux server
I have read: BitBucket: Host key verification failed and Jenkins Host key verification failed and several other links provided. I seem to find myself in an odd situation. I want to clone my django repo into a digital ocean droplet. I am following the steps of this document. https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-18-04 . Everything seems to have gone well, until the step where I need to create the django project. I already have a django project and thus don't want to create a new project on the server. I only need to clone it onto the server. I ran : root@ubuntu-s-1vcpu-2gb-xxx:~#rsync --archive --chown=llewellyn:llewellyn ~/.ssh /home/llewellyn My bitbucket has the id_rsa SSH key uploaded and it all worked in the past, no new SSH has been generated. And the repo is set to public. When running: (myprojectenv) llewellyn@ubuntu-s-1vcpu-2gb-xxx:~/myprojectdir$ git clone git@bitbucket.org:LlewellynHattinghLH/repo.git Cloning into 'repo'... Warning: Permanently added the RSA host key for IP address '18.205.xx.x' to the list of known hosts. git@bitbucket.org: Permission denied (publickey). fatal: Could not read from remote repository. Please make sure you have the correct access rights and the repository exists. I have tried several articles, but most only tell me how to create a new SSH. Any help would … -
Django Adding User details to a UserPost List View
I have a UserPost List View which is a view for a specific user's posts. I am looping the posts of this specific user but I want to add this user's profile details like profile image and other details like email. So, I am not sure on how to add the user details of the user's post names as designer not the logged-in user. I can add the user/designer details in every looped post but I don't want it to be repeated with every post I just want it to appear once just like {{ view.kwargs.username }} as this page is realted only to this user/designer Here is the models.py class Post(models.Model): designer = models.ForeignKey(User, on_delete=models.CASCADE, related_name="post") title = models.CharField(max_length=100, unique=True) here is the profile model related to every user class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') class UserRegisterForm(UserCreationForm): email = forms.EmailField() first_name = forms.CharField() last_name = forms.CharField() class Meta: model = User fields = ['username', 'first_name', 'last_name', 'email'] here is the views for the userpostlist which is filtered by a specific user/designer not the logged in user class UserPostListView(ListView): model = Post template_name = "user_posts.html" context_object_name = 'posts' queryset = Post.objects.filter(admin_approved=True) paginate_by = 6 def get_queryset(self): … -
Why does Django template block/include include external <table> tag?
Consider the below code: <table id='table1'> {% if model_name == 'TransactionsTable' %} {% block transactions_create %} {% include "snippets/transactions_create_and_update.html" with form=form %} {% endblock transactions_create %} {% endif %} </table> I have another <table>, 'table2', within transactions_create_and_update.html. Table2 was appearing outside of it's parent element. So after some testing I tried closing table1 early (first line): <table id='table1'></table> {% if model_name == 'TransactionsTable' %} {% block transactions_create %} {% include "snippets/transactions_create_and_update.html" with form=form %} {% endblock transactions_create %} {% endif %} Then table2 behaves as expected. So table1 is kind of included in the include/block inheritance - but the template doesn't seem to know that I close it after. From the docs - think this is part of the answer but I don't know what to do with it: The include tag should be considered as an implementation of “render this subtemplate and include the HTML”, not as “parse this subtemplate and include its contents as if it were part of the parent”. This means that there is no shared state between included templates – each include is a completely independent rendering process. Blocks are evaluated before they are included. This means that a template that includes blocks from another … -
How to get the values of a div by pressing a button in django
good afternoon, I come to ask a question. I have an online ordering website, I have all my products displayed on the web next to a button to add product (to the basket) The point is, I don't know how to get the data after clicking the button. Models.py (Cart): from django.db import models # Create your models here. class Cart(models.Model): titulo = models.CharField(max_length=100) precio = models.FloatField(default=0) unidades = models.IntegerField(default=0) imagen = models.ImageField(default="null", blank=True) slug_cart = models.CharField(verbose_name="Vinculo", max_length=100) usuario = models.CharField(max_length=99) creado_el = models.DateField(auto_now_add=True) actualizado_el = models.DateField(auto_now=True) class Meta: verbose_name = "Cesta" verbose_name_plural = "Cestas" def __str__(self): return self.titulo Models.py(Food): from django.db import models from ckeditor.fields import RichTextField # Create your models here. class Food(models.Model): titulo = models.CharField(max_length=100) descripcion = RichTextField() precio = models.FloatField(default=0) unidades = models.IntegerField(default=0, blank=True) publico = models.BooleanField(verbose_name="¿Publico?") imagen = models.ImageField(default="null", upload_to="foods") slug_food = models.CharField(verbose_name="Vinculo", max_length=100) creado_el = models.DateField(auto_now_add=True) actualizado_el = models.DateField(auto_now=True) class Meta: verbose_name = "Comida" verbose_name_plural = "Comidas" def __str__(self): return self.titulo views.py (Cart-app): def anadir_cesta(request): username=None if request.user.is_authenticated: username = request.user.username cesta = Cart( titulo = titulo, precio = precio, unidades = unidades, imagen = imagen ) cesta.save() HTML pages with Food: {% extends 'layouts/layout.html' %} {% block titulo %} {{page.titulo}} {% endblock titulo … -
Django compute score of matches (workaround to annotate a query after a union)
I need to compute the ranking of athletes during boxing tournaments. In my models, I track the result of each match and the points to be attributed for each outcome to each athlete. class Member(models.Model): surname = models.CharField(max_length=200) last_name = models.CharField(max_length=200) class Tournament(models.Model): name = models.CharField(max_length=200) class TrophyRule(models.Model): win = models.IntegerField() loose = models.IntegerField() draw = models.IntegerField() class Ring(models.Model): code = models.CharFieldmax_length=1) tournament = models.ForeignKey(Tournament, on_delete=models.CASCADE) class Match(models.Model): ring = models.ForeignKey(Ring, null=True, on_delete=models.SET_NULL) winner = models.CharField(max_length=20, null=True, blank=True) trophy_rule = models.ForeignKey(TrophyRule, on_delete=models.SET_NULL, null=True) red_member = models.ForeignKey(Member, related_name='reds', on_delete=models.SET_NULL, null=True) red_count_ranking = models.BooleanField(default=True) blue_member = models.ForeignKey(Member, related_name='blues', on_delete=models.SET_NULL, null=True) blue_count_ranking = models.BooleanField(default=True) Based on this model, I need to sum the points acquired when the athlete was in the red corner with the points acquired when the athlete was in the blue corner. The result should be a queryset with all members and their total number of points. In order to achieve this, I started with the computation of the points acquired by the athletes in the red corner: from apps.members.models import Member from django.db.models import Case, Sum, When, Q red = Member.objects.filter(reds__ring__tournament_id=11402).annotate( points=Case( When(Q(reds__winner='red') & Q(reds__red_count_ranking=True), then='reds__trophy_rule__win'), When(Q(reds__winner='draw') & Q(reds__red_count_ranking=True), then='reds__trophy_rule__draw'), When(Q(reds__winner='blue') & Q(reds__red_count_ranking=True), then='reds__trophy_rule__loose'), ), ) I also did … -
Django - Retrieve a field for split operation from sorted chain list
How can I access or retrieve a field for a split operation from a sorted chain in Django? Assuming the following example where each of the mentioned models has a field called "tag"? def post_list(request): list_posts = sorted( chain( Model1.objects.all(), Model2.objects.all(), Model3.objects.all(), ), key=attrgetter('published_date'), reverse=True ) tags = list_posts.tag.split(", ") [-> Cannot retrieve .tag here] .... args = {'posts': posts, 'tags': tags } return render(request, 'post_list.html', args) Each tag field is basically just a CharField / Single String where words are separated using ", " and now its required to split this up to show tags at my template, any idea? Kind regards -
how to serialize time with timezone in django-rest-framework's serializer?
I have a Django model: class Clinic(models.Model): NAME_MAX_LENGTH = 150 name = models.CharField(max_length=NAME_MAX_LENGTH,blank=False,null=False) start_at = models.DateTimeField(blank=False,default=timezone.now) the client sends the start_at field as a time field with timezone like { start_at : "12:40:10+04:30" } I want to convert this time field into the DateTimeField with the current date as the date and then save it into the database as a timezone-aware DateTimeField. I want to serialize this field and extract timezone info from the input and then create my DateTimeField object. How can I do this in rest_framework serializer? -
Add function when getting queryset django
In my view I get the popular articles by this variable: popular_article_list = Article.objects.order_by('-votes')[:5] Now in my model I have a was_published_recently function that looks like this: def was_published_recently(self): now = timezone.now() return now - datetime.timedelta(days=1) <= self.pub_date <= now So how do I combine the two to get the most popular articles in the last 24 hours? -
Accessing Twilio Usage API response in Django and Python
I am trying to access the Twilio usage records API (https://www.twilio.com/docs/usage/api/usage-record) using the below: account_sid = "" auth_token = "" client = Client(account_sid, auth_token) # A list of record objects with the properties described above records = client.usage.records.daily.list( category="sms", start_date="2020-08-22", end_date="2020-08-22" ) I can't seem to me able to reference the data. If I return the above to a Django template I get the following: [<Twilio.Api.V2010.DailyInstance>] How would I actually access the data in the response e.g. "price" -
if statmen not working well in django please help me
I'm trying to print specific output if the data equal to 1 but it's not working! it's printing the picture in the other if -
Django, Jinja -- Dynamically Reference Static Images from using an object attribute (slug)
Forgive my asking of what might be the wrong question, it's my second day of Django. I've got a model in the database, and the model has the following attributes: 'title': 'Entity title for Entity A', 'slug': 'entity-a', '...': '...' In my .html Jinja template, I want to load multiple entities using a loop. Which works. However, I want to reference some static loaded logo using the entity.slug. Like so... {% for entity in entities %} {{ entity.slug }} <img src="{% static 'logos/{{entity.slug}}_50x50.png' %}" alt="" class="mr-2 img-thumbnail" width="50"> {% endfor %} See inside IMG tags. Where I have {{entity.slug}}. How can I put it in so the static images will load dynamically? Atm, it's rendering the {{}} see here -
Relationship between models in models.py?
I want to make a Django ecommerce website, in models.py. I have 6 models: Order,OrderItem,Item,ShippingAddress,Payment and Coupon but i don't know which relationship to use between these models. -
How to pass a user variable saved in forms to a button link in Django
I'm trying to get a user to enter the IP address, and then return the user this IP address with port attached as a button that can be clicked by this user and take him to given website ( a part of bigger project ). I have the IP address saved, but when I'm trying to pass it, I'm getting errors. views.py: @login_required def home(request): if request.method == 'POST': form = ConnectionForm(request.POST) if form.is_valid(): form.save() home.ip = form.cleaned_data['ip'] home.username = form.cleaned_data['username'] home.password = form.cleaned_data['password'] return redirect('deploy_honeypot') else: form = ConnectionForm() return render(request, 'home.html', {'form': form}) and in template: <td><a href="{{ url 'home.ip' }}">Your Website</a></td>