Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to filter GTE, LTE on Float or Decimal via Django ORM
I'm trying to filter GPS coordinate points (not using Geodjango) on my app. I need to filter a range, but the float values of the GPS coordinates give me this error django.core.exceptions.FieldError: Unsupported lookup '_lte' for DecimalField or join on the field not permitted. [03/Feb/2019 14:51:14] "GET /api-v1/location-within/10.0/10.0/10 HTTP/1.1" 500 136144 I tried both float and decimal Any insight? Thanks! :) -
How to get current admin that has logged in?
I want to get the current logged in admin to show its posts in admin panel i know that i should 'request.user' but it doesn't work for me in my definition in admin.py what is wrong in here? from django.contrib.admin import AdminSite from rest import models from django.contrib.auth.models import User from django.contrib import admin class BlogAdmin(admin.ModelAdmin): list_display = ('post_title', 'post_author', ) search_fields = ['post_title', 'post_content', ] list_filter = ('post_category', ) def authenticated_admin(request): current_user = request.user admin_posts = models.BlogPost.objects. get(post_author=current_user, post_privacy='public') return admin_posts admin_site.register(models.BlogPost, BlogAdmin) in 'request.user' it shows the 'Unresolved attribute reference 'user' for class 'BlogAdmin' ' Error -
memory leak in django shell, django rest framework serilizer and cassandra
I have a django cassandra model like this: class Milad(DjangoCassandraModel): name = columns.Text(primary_key=True) bulkid = columns.BigInt(primary_key=True) f1 = columns.UUID() f2 = columns.UUID() f3 = columns.UUID() f4 = columns.UUID() f5 = columns.UUID() f6 = columns.UUID() f7 = columns.UUID() f8 = columns.UUID() f9 = columns.UUID() f10 = columns.UUID() class Meta: get_pk_field = "bulkid" and following serializer: from rest_framework import serializers class BulkidSerializer(serializers.Serializer): bulkid = serializers.IntegerField() def to_representation(self, instance): return instance.bulkid I have 220200 records in my table. when i open the django shell with command python3 manage.py shell a do the following operations my memory usage from 8.8GB goes to 10.8GB. operations: records = Milad.objects.all().limit(None) data = BulkidSerializer(records, many=True).data after the operation when i use sys.getsizeof(data) the size of the object is about 2MB but my memory is still 10.8 when no operation is running and no data with that size is in my memory. what's the problem? -
How to correctly serve static files in django? on heroku
My static files work in DEBUG=True condition but in DEBUG=False it does not My settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'mysite/static') ] command I try python manage.py collectstatic It create a folder but can not render the data home.html <!DOCTYPE html> {% load staticfiles %} # I try {% load static %} also <html> <head> <link rel="stylesheet" type="text/css" href="{% static 'app1css/home.css' %}"> <title></title> </head> <body> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do .</p> </body> </html> This is my project structure C:. ├───app1 │ ├───migrations │ │ └───__pycache__ │ └───__pycache__ ├───mysite │ ├───static │ │ └───app1css │ └───__pycache__ ├───static │ ├───admin │ │ ├───css │ │ │ └───vendor │ │ │ └───select2 │ │ ├───fonts │ │ ├───img │ │ │ └───gis │ │ └───js │ │ ├───admin │ │ └───vendor │ │ ├───jquery │ │ ├───select2 │ │ │ └───i18n │ │ └───xregexp │ └───app1css └───templates └───app I have read many questions related to this but can not solve my problem. I have uploaded my blog to heroku with this setting(static files) but it give me SERVERERROR 500(debug=False). I have try to change {% load static %} to {% load staticfiles … -
JQuery conflict with Django base .js file
I have a base template in Django in which i am using app.js. This app.js is used in theme. Now i want to have modal popup by ajax and for which i need to call Jquery function. The page on which the button for popup modal is present is extending the base.html. Thus, when i try to call the page i get the following error. Error in console However, when i don't extend base.html on my page i don't get any error and am able to have the popup modal. Here the code of my page new.page {% extends 'base.html' %} {% load static %} {% include "devices/_modal.html" %} {% block content %} <div class="container mt-3"> <div class="row"> <div class="col-12 mb-3"> <button class="create-book btn btn-primary" type="button" name="button"> <span class="fa fa-plus mr-2"></span>Create book</button> </div> </div> </div> {% endblock %} {% block extra_js %} <script type="text/javascript" charset="utf8" src="{% static "user/js/jQuery-3.3.1.js"%}"></script> <script type="text/javascript" src="{% static "user/js/bootstrap.min.js" %}"></script> <script type="text/javascript" charset="utf8" src="{% static "user/js/jquery.bootstrap.modal.forms.min.js"%}"></script> <script type="text/javascript"> $(function () { $(".create-book").modalForm({formURL: "{% url 'addLocation' %}"}); }); </script> {% endblock extra_js %} My base.html is <!DOCTYPE html> {% load user_tags %} {% load static %} <html lang="en"> <head> {% block extra_head %}{% endblock %} <meta charset="utf-8"> … -
Filter data for given a given day (timezone aware) from postgres directly
I want to filter all data for the following day (which is timezone aware). Assumptions: server data is in a specific timezone client query is coming from different timezone My current approach is: date = received_date_timezone_aware # any time of that day lower = date.replace(hour=0,minute=0,second=0) upper = lower + datetime.timedelta(day=1) data = Model.objects.filter(date__gte=lower, date__lt=upper) Question Is there a direct solution to this using django orm or raw query? -
I am trying to update profile and status if its their own profile and status. But the user is able to update others profile and status
Thank you guys all in advance. Hoping for a soon response. permission.py class UpdateRegister(permissions.BasePermission): """ Allow user to edit their own profile. """ def has_object_permissions(self, request, view, obj): """ Check user is trying to edit their own profile. """ if request.method in permissions.SAFE_METHODS: return True return obj.id == request.user.id class PostOwnStatus(permissions.BasePermission): """ Allow user to update their own status. """ def has_object_permissions(self, request, view, obj): """ Check user is trying to update their own status. """ if request.method in permissions.SAFE_METHODS: return True return obj.user_profile.id == request.user.id This is the permission.py file where users are allow to edit or update their own profile and status. **view.py* class UserViewSet(viewsets.ModelViewSet): """ API endpoint that allows users to be viewed or edited. """ serializer_class = UserSerializer queryset = UserRegister.objects.all() authentication_classes = (TokenAuthentication,) permission_classes = (permissions.UpdateRegister,) class ProfileFeedViewSet(viewsets.ModelViewSet): """ Handles creating reading and updating profile feed. """ serializer_class = ProfileFeedSerializer queryset = ProfileFeed.objects.all() authentication_classes = (TokenAuthentication,) permission_classes = (permissions.PostOwnStatus, IsAuthenticatedOrReadOnly) def perform_create(self, serializer): """Sets the user profile to the logged in user.""" serializer.save(user_profile=self.request.user) This is view.py file. Here i have got user view set and profile feed view set serializer.py class UserSerializer(serializers.ModelSerializer): class Meta: model = UserRegister fields = ('id', 'name', 'email', 'password') extra_kwargs = … -
How can i add a disqus comment system using python in a github project?
Here is the web page to which I want to add the comment system:https://archana9693.pythonanywhere.com/ListResponses/response/1 Here is the link for the github project:https://github.com/arc9693/IntReview/issues/7 -
Construct an URL with data of login to redirect to another app with parametter
When a user finish to login, i'd like to redirect to another app(app_2). At the end of the url i'd like that the URL be .../app_2/username. And not .../app_2 Her's my code: app_2/views.py from django.shortcuts import render # Create your views here. def index(request,user_name)): return render(request,'app_2/index.html',{'user_key':user_name}) app_2/urls.py from django.urls import path from . import views urlpatterns =[ path('<user_name>', views.index), ] In another app, i made a test. app_1/views.py if Authentification(request,username,password): request.session['username_key'] = username return redirect('/app_2/',{'key_app_1':username}) -
how can I remove an item from local storage when it gets deleted from data base using javascript
I have a website for ads. I made a favorite list stored in local storage. User can add and remove favorite ad by clicking on favorite icon (star-icon). Now, the ads older than 45 days is removed from data base. Hence, I want when I load data from local storage to be compared with data loaded from data base (data loaded to the page using Django). Thus, any data not available will be removed from local storage. I made the whole code using pure javascript. The only problem with the code is that when the code did not find the ads in the data loaded from the data base, it does not remove that ads from the local storage. using following line: else{ localStorage.removeItem(stored_fav[i]); console.log('item number'+stored_fav[i]+'removed') } Please follow the code to understand the whole process <!-- setting favorite ads list --> <script type="text/javascript"> function currentAddFav(item_id){ if (localStorage.getItem('SL_favourites')) { // If there are favourites var storage = JSON.parse(localStorage['SL_favourites']); if (storage.indexOf(item_id) == -1) { // not found storage.push(item_id); localStorage.setItem('SL_favourites', JSON.stringify(storage)); console.log('item has been added to favorites') cc="favouriteBtn_"+item_id console.log(cc) var fav_solid = document.getElementById(cc); if (fav_solid){ fav_solid.classList.remove("fa-star-o"); fav_solid.classList.add("fa-star");} document.getElementById("fav-num").innerHTML =storage.length; } else { // found storage.splice(storage.indexOf(item_id),1) localStorage.setItem('SL_favourites', JSON.stringify(storage)); console.log('item has been removed') cc="favouriteBtn_"+item_id … -
Django: Checkbox not showing up in HTML
This form has multiple choices to select from. However the check boxes don't show up in HTML! I'm using Materialise CSS. Please help. forms.py: FAVORITE_COLORS_CHOICES = ( ('blue', 'Blue'), ('green', 'Green'), ('black', 'Black'), ) class StudentForm(forms.ModelForm): favorite_colors = forms.MultipleChoiceField( required=False, widget=forms.CheckboxSelectMultiple, choices=FAVORITE_COLORS_CHOICES, ) form.html: <div class="container"> <form> {{ form.as_p }} <input type='submit' value='Save' /> </form> HTML page in browser: -
How i got User Full IP Address like (2405:204:e68c:5415:3599:9ec7:c5c:3f40)
i have create a methord for get user ip address and i use this this is my view def get_ip(request): x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[0] else: ip = request.META.get('REMOTE_ADDR') return HttpResponse(ip) it gives me my ip 10.0.0.53 but my real ip is 2405:204:e68c:5415:3599:9ec7:c5c:3f40 how i got this real ip please tell me -
How to create such a table with checkbox in django?
I want to have a table with a checkbox on each row with Django as shown in the image. My Django view.py, models.py and HTML file are mentioned below. How this can be done? Is there any built-in function in Django or what? Table with check box I have models file as: class AppsDescription(db.Model): aws_response = aws_list_conf_api_call() CHOICES = [("yes", "YES"), ("no", "NO")] OPTIONS = list() for apps in aws_response: OPTIONS.append(('{name1}'.format(name1=apps.lower()), '{name2}'.format(name2=apps)), ) name = db.CharField(max_length=256) description = db.TextField() plan_to_migrate = db.CharField(choices=CHOICES, max_length=256) # app_names = MultiSelectField(choices=OPTIONS) def __str__(self): return self.name My views.py as def createapp(request): # import ipdb; ipdb.set_trace() form = DashboardForm() if request.method == "POST": form = DashboardForm(request.POST) list_of_inputs = request.POST.getlist("inputs") if form.is_valid: form.save(commit=True) return HttpResponseRedirect(reverse("aws:createapp")) server = aws_server_list_conf() return render(request, "createapp.html", {'server':server, 'form': form}) My html file as <form method="POST"> {{form.as_p}} <table> <tr> <th>Select</th> <th>Agent ID</th> <th>Configuration ID</th> <th>Host Name</th> <th>OS Name</th> <th>OS Version</th> <th>Source</th> <th>Time of Creation</th> <th>Type</th> </tr> {% for apps in server %} <tr> <td><input type="checkbox" name="" value=""></td> {% for k,v in apps.items %} <td>{{ v }}</td> {% endfor %} </tr> {% endfor %} </table> {% csrf_token %} <input type="submit" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal" name="" value="submit"> <div class="modal fade" id="myModal" role="dialog"> <div class="modal-dialog"> … -
Can anyone suggest me some Useful Learning Resources for Django?
I want to learn Django web framework. From basic to advance, I want to learn about this. How can I set my learning goals? -
Django stop clean() on errors
I have two forms, one validating OTP and one changing password. There are OTP input, current password input, and password to change input, and password to change verification input. The problem is when OTP validation fails, current password validation shouldn't happen. Otherwise attackers can guess the password by brute force. What I'm trying to do is to stop clean() when OTP verification fails. # OTP side clean() def clean(self): # Validation except OTPFail: raise ValidationError('example error') return cleaned_form # Password side clean() def clean(self): if not self['otp'].errors: # Validate password Currently I am using this code but the problem is that I have to do if not self['otp'].errors: every time. Is there a better way to stop clean() from validating when predecessor fails? -
Django: cannot access Object in Admin Panel
When clicking the Object Cart or CartItem in the AdminPanel I'm getting: Error during template rendering In template D:\virtual_envs\stickers_gallito\lib\site-packages\django\contrib\admin\templates\admin\base.html, error at line 0 __str__ returned non-string (type int) When quering these objects in Shell, I'm getting: >>> carts = Cart.objects.all() >>> carts Traceback (most recent call last): File "<console>", line 1, in <module> File "D:\virtual_envs\stickers_gallito\lib\site-packages\django\db\models\query.py", line 247, in __repr__ return '<%s %r>' % (self.__class__.__name__, data) File "D:\virtual_envs\stickers_gallito\lib\site-packages\django\db\models\base.py", line 503, in __repr__ return '<%s: %s>' % (self.__class__.__name__, self) TypeError: __str__ returned non-string (type int) models.py: class Cart(models.Model): cart_id = models.CharField(max_length=100) date_added = models.DateField(auto_now_add=True) class Meta: db_table = 'Cart' ordering = ['date_added'] def __str__(self): return self.id What can be wrong? -
How would i create a side panel that opens and displays marker info when clicked in google maps (Django)
So im using google maps to display django object locations as markers, i was wondering how i would make a side panel open when the marker is clicked displaying that marker info. -
Django collectstatic giving no errors. But staticfiles not showing on website. Files on S3. project on Lambda with Zappa
Intro: I have made my application in Django I am trying to get my static and media files hosted in aws s3. My Django project is on AWS Lambda and AWS Api gateway using Zappa. below is my settings.py AWS_DEFAULT_ACL = None STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] DEFAULT_FILE_STORAGE = 'aws_storage_classes.MediaStorage' AWS_ACCESS_KEY_ID = os.getenv("ACCESS_KEY") AWS_SECRET_ACCESS_KEY = os.getenv("ACCESS_SECRET_KEY") AWS_STORAGE_BUCKET_NAME = os.getenv("AWS_STORAGE_BUCKET_NAME") STATICFILES_STORAGE = 'aws_storage_classes.StaticStorage' AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_S3_DOMAIN = "%s.s3.amazonaws.com" % AWS_STORAGE_BUCKET_NAME STATIC_URL = 'https://%s.static/' % AWS_S3_DOMAIN MEDIA_URL = 'https://%s.media/' % AWS_S3_DOMAIN STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') MEDIA_ROOT = os.path.join(BASE_DIR, 'media') I then created a file in my project folder the same as my manage.py called aws_storage_classes.py Below are the contents of my file aws_storage_classes.py from storages.backends.s3boto3 import S3Boto3Storage class StaticStorage(S3Boto3Storage): location = 'static' class MediaStorage(S3Boto3Storage): location = 'media' When I do python manage.py collectstatic all the staticfiles are downloaded and I don't get any errors. But when go on admin page the static files are not uploaded. See images below Below is the image of my S3 bucket Below is what is inside the static folder Static files not showing -
Accessing variable within def clean() from def __init__()
I've established a variable inside my def init function inside my form that I want to be able to access within def clean() in that same form. def __init__(self, *args, **kwargs): super(UserOrderForm, self).__init__(*args, **kwargs) car = 'BMW' def clean(self): cleaned_data = super(UserOrderForm, self).clean() print(car) When I print car, I'm told that name 'car' is not defined Is there a way to do this? Thanks! -
Django Wizard - AJAX call to next step
I'm setting up Django Wizard and all is woking fine if I try to post data on my Database by loading for every step a new page with his form containing few inputs (I've red this documentation). But right now I'm trying to use AJAX to load each step and I've some troubles. I've a button and clicking on it I load the first step with AJAX and all is fine, but when i submit (with e.preventDefault() on submit) my page reload anyway without showing the next step. Is this the right way to achieve this? Am I forgetting something? Or I can't just do that and I've to find another way? var link = "link/to/wizard"; // First call to show first step $('.btn').on('click', function(event){ event.preventDefault(); $.ajax({ url : link, type : 'GET', dataType:'html', success : function(data) { $wizardContainer.empty().html(data); }, error : function(request,error) {} }); }); // After first ajax call $('#next').on('submit', '#creation-form' , function(e){ e.preventDefault(); $.ajax({ url: link, type: "get", success: function(data){ $wizardContainer.empty().html(data); }, processData: false, contentType: false }); }); -
Django messages, count number of messages between two users
Im using django-postman as user to user messaging system. now i want to show in the template how many messages were sent between 2 users in models.py sender = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='+', null=True, blank=True, verbose_name=_("sender")) recipient = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='+', null=True, blank=True, verbose_name=_("recipient")) how can i count how many messages were written between two users? -
Django: Reverse for '' not found. '' is not a valid view function or pattern name
I am doing an entry-level project and I met this problem. urls.py of project: urlpatterns = [ path('', TemplateView.as_view(template_name='welcome.html'), name='welcome'), path('accounts/', include('login.urls')), path('accounts/', include('django.contrib.auth.urls')), # use auth app path('ride_sharing/', include('ride.urls')), path('admin/', admin.site.urls), ] urls.py of ride app: app_name = 'ride' urlpatterns = [ path('', views.home, name='home'), path('requests/', views.view_requests, name='view_requests'), path('new-request/', views.request_new, name='request_new'), path('driver/', views.driver_home, name='driver_home'), path('new-share-request/', views.sharer_request_new, name='sharer_request_new'), ] views.py of ride app, just incomplete codes: def home(request): return render(request,'ride/home.html') def view_requests(request): return render(request, 'ride/home.html') def request_new(request): return render(request, 'ride/home.html') def driver_home(request): return render(request, 'ride/home.html') def sharer_request_new(request): return render(request, 'ride/home.html') And home.html: <!-- ride/templates/ride/home.html --> {% extends 'ride/base.html' %} {% block title %}HOmeeeeeeeeeee {% endblock %} {% block content %} {% if user.is_authenticated %} Hi {{ user.username }} <p><a href="{% url 'ride:view_requests' %}">View My Requests</a></p> <p><a href="{% url 'ride:request_new' %}">Request a Ride</a></p> <p><a href="{% url 'ride:driver_home' %}">Driver Entrance</a></p> <p><a href="{% url 'ride:sharer_request_new' %}"></a></p> <p><a href="{% url 'logout' %}">Logout</a></p> {% else %} <p>Welcome to CJ & XY's Ride Sharing Service!</p> <a href="{% url 'login' %}">login</a> | <a href="{% url 'login:signup' %}">signup</a> {% endif %} {% endblock %} But after I login (I make LOGIN_REDIRECT_URL = 'home'), I get: NoReverseMatch at /ride_sharing/ Reverse for 'view_requests' not found. 'view_requests' is not a valid … -
Django secret key generation
I am making a boiler plate for a Django backend and I need to be able to make it to where the next person who downloads it won't have access to my secrot key obviously, or have a different one. I have been researching some options and have become experimental in this process. I have tried the following: from django.core.management.utils import get_random_secret_key SECRET_KEY = get_random_secret_key() This appears to be working. I am assume it generates a new key everytime I run python manage.py runserver. Is this going to be a problem for a production environment? This is really for a heroku deploy, is there a better way I should be doing this with a public repo? I imagine what I am doing now is going to break something. -
Custom template filter: replace HTML element with regex filtered text (Django 2.1)
I am building a search engine, which needs a custom filter that displays the text surrounding a keyword, like the excerpts on Google results page. I am using regex to identify the surrounding words. Here is my code for the filter: @register.filter(needs_autoescape=True) @stringfilter def show_excerpt (value, search_term, autoescape=True): # make the keyword put into the search engine case insensitive # keywords = re.compile(re.escape(search_term), re.IGNORECASE) # make excerpt return 300 characters before and after keyword # excerpt_text = '.{300}' + str(keywords) + '.{300}' # replace the original text with excerpt # excerpt = value.sub(excerpt_text, value) return mark_safe(excerpt) Code for the search engine in view.py: def query_search(request): articles = cross_currents.objects.all() search_term = '' if 'keyword' in request.GET: search_term = request.GET['keyword'] articles = articles.annotate(similarity=Greatest(TrigramSimilarity('Title', search_term), TrigramSimilarity('Content', search_term))).filter(similarity__gte=0.03).order_by('-similarity') context = {'articles': articles, 'search_term': search_term} return render(request, 'query_search.html', context) HTML template (it includes a custom highlight filter that highlights the keyword put into search engine): <ul> {% for article in articles %} <li><a href="{% url 'search:article_detail' article.ArticleID %}">{{ article|highlight:search_term }}</a></li> <p> {{ article.Content|highlight:search_term|show_excerpt:search_term }} </p> {% endfor %} </ul> Error message: 'SafeText' object has no attribute 'sub' I think I am doing .sub wrong. I just need the excerpt to replace the entire original text … -
Celery interval schedule doesn't executes on given interval
I found that IntervalSchedule function of celery doesn't execute the tasks if the task interval is greater than 24 Hours. The interval scheduler django_celery_beat.models.IntervalSchedule runs at a specifically given interval. from django_celery_beat.models import PeriodicTask, IntervalSchedule #should executes every 26 hours. >>> schedule, created = IntervalSchedule.objects.get_or_create( ... every=26, ... period=IntervalSchedule.HOURS, ... ) https://django-celery-beat.readthedocs.io/en/latest/ I Noticed that this above 26 hour task never executes, where as tasks which are under 24 Hours of period gets executed every day ######## CELERY : CONFIG CELERY_BROKER_URL = 'redis://localhost:6379' CELERY_RESULT_BACKEND = 'redis://localhost:6379' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = "Asia/Kolkata" CELERYBEAT_SCHEDULER = 'django_celery_beat.schedulers:DatabaseScheduler' Versions : celery (4.2.1) django-celery (3.2.2) django-celery-beat (1.3.0)