Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to make it such that the block system goes both ways?
I realised that there is a limitation in the blocking system. Basically based on the codes discussed, I have made it such that when I block a user, I will not be able to see his posts in the home feed, in the detail page. I won't be able to add comments or submit anything to his post. But then I realised that the users that we blocked are still able to see my post, my detail page, and add comments/submit things to my posts. This would kind of defeat the purpose of the blocking system. How do I make it such that from the perspective of the person that i blocked, he also cannot view my posts, comment on my post, or submit anything to my post too? models.py class Account(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) blocked_users = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, related_name='blocked_by_user') views.py where I tried to do the implement block functionality type_of_post = TypeofPostFilter(request.GET, queryset=BlogPost.objects.exclude((Q(author_id__in=request.user.blocked_users.all()) | Q(author = request.user))).order_by('date_updated')) if blog_post.author in user.blocked_users.all(): return redirect(reverse('HomeFeed:detail', kwargs={'slug': slug})) if comment.name in comment.post.author.blocked_users.all(): return redirect(reverse('HomeFeed:main')) views.py for block system: def block_user(request, pk): user = request.user user_to_block = Account.objects.get(pk=pk) user.blocked_users.add(user_to_block) if user_to_block == user: return HttpResponse("You can't block … -
Form in Django does not submit anything
I have an issue that is my form does not submit and because django thinks that it is not valid.... all the things in my html file is matching my forms.py and my model fields .. but I can`t figure out why it is not valid and do not create object. here`s my models.py file : class Profile(models.Model): name = models.CharField(max_length=100) email = models.CharField(max_length=100) phone = models.CharField(max_length=100) summary = models.TextField() degree = models.CharField(max_length=100) school = models.CharField(max_length=100) university = models.CharField(max_length=100) experience = models.TextField() skills = models.TextField() image = models.ImageField(upload_to='images/profile', blank=True, null=True) def __str__(self): return self.name here is my forms.py: from django import forms from .models import Profile class ProfileFormItem(forms.ModelForm): class Meta: model = Profile fields = '__all__' and also my html form: <div class="card-body"> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="form-row"> <div class="name">Full name</div> <div class="value"> <input class="input--style-6" type="text" name="name"> </div> </div> <div class="form-row"> <div class="name">Email address</div> <div class="value"> <div class="input-group"> <input class="input--style-6" type="email" name="email" placeholder="example@email.com"> </div> </div> </div> <div class="form-row"> <div class="name">Phone number</div> <div class="value"> <input class="input--style-6" type="text" name="phone"> </div> </div> <div class="form-row"> <div class="name">Degree</div> <div class="value"> <input class="input--style-6" type="text" name="degree"> </div> </div> <div class="form-row"> <div class="name">school</div> <div class="value"> <input class="input--style-6" type="text" name="school"> </div> </div> <div class="form-row"> <div class="name">University</div> … -
Django - MySQL Server has gone away
I'm using Django version 1.7 and quite a few times I see the error below: OperationalError: (2006, MySQL server has gone away) I've defined CONN_MAX_AGE = 200 in settings and wait_timeout = 300 in MySQL's config. Now as per my understanding from the doc, Django should drop the connection after 200 seconds and establish a new one, and therefore I should not get this error. I have seen a lot of discussion around this error but couldn't find an answer for why Django is not taking care of this. Am I missing something? -
Pycharm regex to replace Django's statics
I'm trying to use Pycharm's regex find and replace to turn all links such as <link rel="apple-touch-icon" sizes="180x180" href="assets/images/favicons/logo1.png"> into <link rel="apple-touch-icon" sizes="180x180" href="{% static 'assets/images/favicons/logo1.png' %}"> I tried the answer by Willem: \b(src|href)="([^"]*)"\b and as patttern to replace: $1="{% static '$2' %}" but it's not working EDIT: I'm using Pycharm version 2020.1 -
Why list data turned to str in form validator in Django?
I'm using FBV in django like below: def handle_recipient(request, pk): ... if request_method == "PATCH": recipient_data = request.json recipient = recipient_query.first() print(recipient_data['sale_name'], type(recipient_data['sale_name'])) # [12, 2333] <class 'list'> f = BaseMdRecipientForm(recipient_data) if f.is_valid(): ... And my forms defined as: def validate_char(char_value): print(char_value, type(char_value)) # [12, 2333] <class 'str'> if not isinstance(char_value, str): raise ValidationError( message="not a valid string value", code="invalid" ) class BaseMdRecipientForm(forms.Form): sale_name = forms.CharField(required=True, max_length=128,validators=[validate_char]) abbreviation = forms.CharField(max_length=64, required=True) My confusion is that the type of sale_name I submitted {"sale_name":[12,2333],"dsds":"" } as a format of application/json is always different in form validator. Can you help telling me where django make this transformation? -
Monkey patch all the request from Django to verify=false
I am making a request using sendgrid API but unfortunately internally sendgrid API use verify=True I want to monkey patch all the outgoing request from my Django application and set verify=False -
Django save method is not working as expected
I overrode Django save method. On saving new Discount item, print statements are executed but update_discount method is not called. I'm using Admin panel to save Discount items. I want to call same update_discount method on Django update method too. CODE: class Discount(models.Model): start_date = models.DateField(default=now) end_date = models.DateField() product = models.ForeignKey(Product, on_delete=models.CASCADE) disc_per = models.PositiveIntegerField(default=None) class Meta: unique_together = ('start_date', 'end_date', 'product') def __str__(self): return str(self.start_date) + '-' + str(self.end_date) + '-' + str(self.product) def save(self, *args, **kwargs): print('saved.') Discount.update_discount() print('updated discount.') super().save(*args, **kwargs) @staticmethod def update_discount(): discounts = Discount.get_all_discounts() products = Product.get_all_products() today = date.today() # Reset discounted prices of all products products.update(disc_price=None) # Apply discount on products if today is sale for discount in discounts: product = Product.get_product_by_id(discount.product.id) if (today >= discount.start_date) and (today <= discount.end_date): per = discount.disc_per price = discount.product.price disc_price = Discount.cal_disc_price(per, price) product.update(disc_price=disc_price) else: product.update(disc_price=None) OUTPUT: saved. updated discount. -
Django check array inside array and change template
i have array line this setime = ["00:00", "00:30", "01:00", "01:30", "02:00", "02:30", "03:00", "03:30", "04:00", "04:30", "05:00", "05:30", "06:00", "06:30", "07:00", "07:30", "08:00", "08:30", "09:00", "09:30", "10:00", "10:30", "11:00", "11:30", "12:00", "12:30", "13:00", "13:30", "14:00", "14:30", "15:00", "15:30", "16:00", "16:30", "17:00", "17:30", "18:00", "18:30", "19:00", "19:30", "20:00", "20:30", "21:00", "21:30", "22:00", "22:30", "23:00", "23:30"] and i want check in view myListTime= checkDateTime.objects.all().filter(Teacher_id = 1) i tried in template {% for i in setime %} <ul> {% for j in myListTime %} {% if j in i %} <li class="active">{{ i }}</li> {% else %} <li>{{ i }}</li> {% endif %} {% endfor %} </ul> {% endfor %} i need result like this matched li have active class -
Django template datatableview stopped working: datatableview is not defined, property assignment expected
I am upgrading a django app: Django==1.8.6 django-datatable-view==0.8.2 the app compiles and I can login into it but all tables are empty and in the console I can see the error: Uncaught ReferenceError: datatableview is not defined at (index):409 Here my code: the error on the console is generated by the following line in datatable_inint.html: datatableview.auto_initialize = false; From the picture you can see that there are also several compiler's warning. If I hover on the '{%' symbol I can see the javascript warning: Property assignment expected Any idea why my code stopped working? -
How to upload a file from local machine to a particular directory in aws EC2 instance?
I am developing a web app that takes csv files and stores them in my aws instance. I am using django to create my web app. I am having trouble connecting to aws instance from my django app. -
How can I automatically add the blogpost author into the member list?
Everytime a blogpost is added, a memberlist will be generated. How do I automatically make it such that the author of the post will be included in the member list? models.py class BlogPost(models.Model): chief_title = models.CharField(max_length=50, null=False, blank=False, unique=True) body = models.TextField(max_length=5000, null=False, blank=False) members = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, related_name="members") author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) class Account(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) views.py from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin class MemberListView( LoginRequiredMixin, UserPassesTestMixin, BlogPostMixin, DetailView ): login_url = 'must_authenticate' template_name = "HomeFeed/membersof_yourpost.html" def test_func(self): post = self.get_object() return self.request.user in post.members.all() -
Django Rosetta wont translate the whole page
I am using Django Rosetta to translate from en-us to Ar(Arabic), everything seems translated just some strings are missing but I cannot find what is wrong. The .po document generates in the beginning this lines with the fuzzy and the empty string # SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # FIRST AUTHOR <EMAIL@ADDRESS>, YEAR. # #, fuzzy msgid "" msgstr ""` After that start to appear the correlation of everything and just are missing those not translated obviously but neither appear the strings so I guess that not even try to translated because are not there. Those are the logs of the ones untranslated, and this is a section of the code .htm for the first form in the django Rosetta page taht is not translated {% extends "views/forms/base.htm" %} {% load i18n %} {% block form_content %} <!-- Resource Type CRUD Form --> <hr class="divider arches-RDM-divider"> <div id="site_ID-section"> <!-- Name CRUD Form --> <div class="row"> <div class="col-xs-12"> <div class="padding-left-10"> <dl> <!-- Title --> <dt> <h5 id="arches-names-form" class="section-headline">{% trans "National ID" %}</h5> </dt> <!-- Form --> <dd> <div class="row"> <div class="col-xs-12 hidden-xs"> … -
serializer.save is not update in django
I am using django rest frame work. I made a bulk create function, but it doesn't update automatically. just it create works. This is my code serializers.py from rest_framework import serializers from .models import Stock class StockSerializer(serializers.ModelSerializer): listedDate = serializers.DateTimeField(format="%Y-%m-%d",input_formats=['%Y%m%d']) class Meta: model = Stock fields = '__all__' model class Stock(models.Model): code = models.CharField(max_length=64, primary_key=True) name = models.CharField(max_length=128) cnt = models.BigIntegerField() construction = models.CharField(max_length=64) listedDate = models.DateTimeField() lastPrice = models.CharField(max_length=64) state = models.CharField(max_length=64) class Meta: db_table = 'stock' def __str__(self): return self.name viewsets.py from rest_framework.response import Response from rest_framework import viewsets, status from util import setEnvironment from . import models, serializers class StockViewset(viewsets.ModelViewSet): queryset = models.Stock.objects.all() serializer_class = serializers.StockSerializer def create(self, request, *args, **kwargs): stock_data = request.data.get("data") auth = request.META.get('HTTP_AUTHENTICATION') api_key = setEnvironment.get_secret("API_AUTH_KEY") if auth != api_key: return Response(status=status.HTTP_401_UNAUTHORIZED) serializer = self.get_serializer(data=stock_data, many=True) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) print(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) def perform_create(self, serializer): serializer.save() I think if you call perform_create in viewsets.py, you need to save or update it. As a result, i get an error saying that the same code value exists. Why doesn't the update automatically work even though I have a primary key in db? -
Best way to assign a list of integers to a key in redis using Django
I'm completely new to redis using django. All I want to do is store a list of IDs from DB into the redis server in the format: name@example.com : [100, 99, 98, 97, 96] The above key value pair should be accessible by any api in the same project. Can we use LPUSH methodologies of redis in django to achieve the above goal? I referred the below links and I'm still confused and stuck on the approach that I should take. https://realpython.com/caching-in-django-with-redis/ https://docs.djangoproject.com/en/3.1/topics/cache/ I've read somewhere that we cannot store array of integers in redis. They need to be strigified. What is the best way to achive the above goal? using StrictRedis inside utils.py or using the django's built in cache library? Please guide me through the best doable way. -
Dropdown menu is side navigation not working in React.js component
I'm trying to create a Side Navigation Component from a bootstrap template called Admindek. But it is not working when it comes in Dropdown Menu. Sample Dashboard with Side nav Here's my code: SideNavComp.js: require('../../config'); import React , { useState, useEffect } from "react"; import ReactDOM from "react-dom"; function SideNavMain(props){ return ( <nav className="pcoded-navbar"> <div className="nav-list"> <div className="pcoded-inner-navbar main-menu"> <ul className="pcoded-item pcoded-left-item"> <li className="pcoded-hasmenu"> <a href="#!" className="waves-effect waves-dark"> <span className="pcoded-micon"> <i className="feather icon-pie-chart"></i> </span> <span className="pcoded-mtext">Charts</span> </a> <ul className="pcoded-submenu"> <li> <a href="/" className="waves-effect waves-dark"> <span className="pcoded-mtext">Google Chart</span> </a> </li> <li> <a href="/" className="waves-effect waves-dark"> <span className="pcoded-mtext">ChartJs</span> </a> </li> </ul> </li> </ul> </div> </div> </nav> ); } ReactDOM.render(<SideNavMain/> , document.getElementById('side_nav')); config.js: // popper window.Popper = require('popper.js'); // jquery window.$ = window.jQuery = require('jquery/src/jquery'); // bootstrap require('bootstrap'); Base Html: <!DOCTYPE html> <html lang="en"> <meta http-equiv="content-type" content="text/html;charset=UTF-8" /> {% load static %} <head> <title>AFD PORTAL | Dashboard</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimal-ui"> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <link rel="icon" href="{% static 'images/sra_logo_old.png' %}" type="image/x-icon"> <link href="https://fonts.googleapis.com/css?family=Open+Sans:300,400,600,700,800" rel="stylesheet"> <link href="https://fonts.googleapis.com/css?family=Quicksand:500,700" rel="stylesheet"> <link rel="stylesheet" type="text/css" href="{% static 'admindek/css/bootstrap.min.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'admindek/css/waves.min.css' %}" media="all"> <link rel="stylesheet" type="text/css" href="{% static 'admindek/css/themify-icons.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'admindek/css/font-awesome.min.css' %}"> <link rel="stylesheet" … -
Error when trying to annotate a dict with Subquery
I have the following models: class Location(models.Model): system_key = models.CharField(max_length=20, unique=True) active = models.BooleanField(default=True) name = models.CharField(max_length=256) account = models.ForeignKey(Account,on_delete=models.CASCADE) ... class LocationScores(models.Model): location = models.ForeignKey(Location, on_delete=models.CASCADE,related_name=LOCATION_SCORES) date = models.DateField(default=now) first_score = models.PositiveSmallIntegerField(default=0) second_score = models.PositiveSmallIntegerField(default=0) third_score = models.PositiveSmallIntegerField(default=0) I'm looking for a way to annotate on a location a given list of scores from it's latest entry most efficiently (DB queries wise). Since a Prefetch Object can't filter the latest object I don't want to do the following: locations =Location.objects.filter(account=account).prefetch_related(Prefetch(lookup=LOCATION_SCORES, queryset=LocationScores.objects..order_by('-date'), to_attr='scores_by_date') )) this would maybe be an efficient query, but since each location might have thousands of records and the endpoint could serve a lot of locations it becomes very memory heavy. so I tried using Subquery, the closest I came is: class LocationScoresManager(models.QuerySet): def get_latest_location_scores(self, location_scores_names): scores_query = LocationScore.objects.filter(location=OuterRef('pk')).order_by('-date').values(*location_scores_names)[0] annotations = {score: Subquery(scores_query)[score] for score in location_scores} return self.annotate(**annotations) # adding it to the Location Model: class Location(models.Model): # same as before... scores = LocationScoresManager.as_manager() scores_list = ['first_score','third_score'] locations = Locations.scores.filter(account=account).get_latest_location_scores(scores_list) This raises: ValueError: This queryset contains a reference to an outer query and may only be used in a subquery. -
I have problem with django login view about auth lib
I have problem about auth system. It only work by username and password, but I need use email rather than username def login_view(request): if request.user.is_authenticated or request.user.is_staff or request.user.is_superuser: return redirect('/account/') elif request.method == "POST": email = request.POST['email'] password = request.POST['password'] user = authenticate(request, email=email, password=password) if not grecaptcha_verify(request): context = {'message_bad':'...'} if user is not None: login(request, user) return redirect('/account/') else: context = {'message_bad':'...'} else: context = {} return render(request, "login.html", context) Please help me or how can I change login() codes at auth lib . -
Custom Password Hash using MD5 and TripleDES
I know it may not be the best combination for password storing but how can I build a password hash using those two? -
Which pattern is implemented in Django Middleware? (Chain of responsibility or Decorator)
I'm trying to figure out what pattern is used in Django Middleware. Maybe there is combination of patterns? -
Linking a Vue file with Django template
I have a Django project contains multiple templates like this: <body> <div> <ul> <li> <a href="#"> customers </a> </li> </ul> </div> <script src="https://cdn.jsdelivr.net/npm/vue@2"></script> <!-- place project specific Javascript in this file --> <script src="{% static 'js/project.js' %}"></script> <script> {% include 'vue_dashboard.js' %} </script> </body> the vue_dashboard.js file is the following var app = new Vue({ el: '#vue_app', delimiters: ["{(", ")}"], data: function () { return { selected: 'group', } }, methods: { change_selected: function (type) { this.selected = type; }, } Now, I'm trying to use this vue method inside my <a> tag for example like this: <a href="#" onclick="change_selected(type='customers')"> customers </a> then inside some other div obtain the value of the selected variable in the data section: <div> {{selected}} </div> I've also tried: {% verbatim %} {{ selected }} {% endverbatim %} and few other things, I know I'm using it wrong, but what's the right way to do so? I'm not even sure if my template can communicate with the vue file like this -
Permission-Based Class Based Views Django
How do I make it such that you can only view the members list if you are part of the member list. I don't even know what the "permission required" in my MemberListView as this part was done by my expert friend, so I commented it out. (Hope someone can share what that is as well, super new to writing class based views) Basically for my current code, I tried to make it such that if the user that is currently logged in don't belong in the list, they will be redirected away. models.py class BlogPost(models.Model): chief_title = models.CharField(max_length=50, null=False, blank=False, unique=True) body = models.TextField(max_length=5000, null=False, blank=False) members = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, related_name="members") class Account(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) views.py class MemberListView(LoginRequiredMixin,BlogPostMixin, DetailView): login_url = 'must_authenticate' template_name = "HomeFeed/membersof_yourpost.html" #permission_required = ('blogpost.view_all_blogpost_members') def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) if self.request.user in object.members.all: return render('HomeFeed/membersof_yourpost.html', context) else: return render('HomeFeed/snippets/home.html', context) template: <ul> {% for member in object.members.all %} <li>{{member.username}}</li> {% endfor %} </ul> -
Build an FTP client in Django Project
I'm developping a Django App/Website with Python just locally, for myself, not for work or anything. For now, everything is perfect and all my features are functionals (LDAP authentication, store infos and pictures in database, etc..). I have an LDAP server, an FTP server and my "Django server". Now, I would like to build in my Django project a page which will be able to upload/download files on my FTP server. I've already built a Tkinter app to upload/download file throught an FTP server when I was learning Python. But now, I'm feeling lost because I really don't know how to put a such interface in Django MVT structure... Maybe is it possible in others languages (Java, PHP,.. ?) ? I really don't know so I'm asking to the community if anyone has an idea. Hope you understand evrything. -
Is there any django app for internal notification in the website?
I have created a simple blog and inside I need to add a notification system that user gets informed when: create a post, when his/her post get declined by admin, when his/her post receives any upvote/downvote and etc. I have found three choices: django-notification django-notification-system Create a model manually like this old tutorial in youtube If you have experience in this topic, can you please guid me, which one should II choose, or is there any easy(with a well written documentation) and better solution? -
How to solve the Identical URL Pattern Conflict in Django?
while practicing on Django I have faced the following problem of Identical URL Pattern. I have tried but fail to solve. My project has one apps and the models are class Category(models.Model): title = models.CharField(max_length=150) slug = models.SlugField(unique=True,blank=True, max_length=255) class Post(models.Model): title = models.CharField(max_length=200) cats = models.ForeignKey(Category, on_delete=models.CASCADE) slug = models.SlugField(unique=True,blank=True, max_length=255) My urls.py from django.contrib import admin from django.urls import path from post import views as apps urlpatterns = [ path('admin/', admin.site.urls), path('<slug:slug>/', apps.categoryView, name='category'), path('<slug:slug>/',apps.PostView, name='calc_detail'), ] Problem: When I Put '/' in the second line of the urlpattern for Category View, category View works but post View doesn't work (404). If remove '/' urlpattern for CategoryView , then post view Works but Category Views shows 404. How should I configure these urls. I am using function based views -
Fieldset values displaying in profile page but if another person registered it showing error in profile page -django
I have member table for registered persons.. I want to display that member table values of particular person in profile page who is logged in... i used Member.objects.get() data is displaying in the profile page of the person who is logged in. but if another person registered it showing error in profile page like.. MultipleObjectsReturned at /web/profile/ get() returned more than one Member -- it returned 2! this is views.py code def profile(request): member = Member.objects.get() print(member.Email) return render(request, 'web/profile.html',{'member':member} ) Thanking You in Advance. You will be highly appreciated, if you could suggest the implementation