Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django oauth2 authentication with client_id and client_Secret hardcded
I implement Oauth2 in django and my refresh token is under o/token/ url, I want to define another url like this: path('api/v1/login',Login.as_view()), and inside my login view I want to have something like this: class login(APIView): def post(self,request): client_id = "123" client_Secret = "123" username = request.query_params.get('username') .... *problem is here* I want to define those parameters inside login class and then pass it to o/token/ url and get the token as a result. In fact, when the user enters www.example.com/api/v1/login address, it enters just username and password and previously inside my code I said to OAuth what my client info is and then the token will generate. -
Django, The current path, blog/, didn't match any of these
Please help with this enter image description here -
Django is putting empty string by default while excepting it to be null
I am using postgresql version 10.6 with my Django 2.1 application. The problem is that when I am using null=True in my model field it is translating to empty string ('') in database column as default where I am trying default it as null. In my following code sample image column should be null: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(upload_to='profile_pics', null=True, blank=True) And I am calling this class from a signal like this: @receiver(post_save, sender=User) def create_profile(sender, **kwargs): if kwargs.get('created') is True: Profile.objects.create(user=kwargs.get('instance')) In this snapshot you can see that image column is inserting as empty string instead of null I have also tried to use default value for my model field as: image = models.ImageField(default=None, upload_to='profile_pics', null=True, blank=True) but it doesn't work either. -
problem with setting & accessing a variable value in django template
I want to set a variable err for errors in the form fields (using django 2.1.3): {% for field in form %} {% if field.errors %} {% with field.errors as err %}{% endwith %} {% endif %} {% endfor %} {% if err %} <div class="alert alert-danger fade show"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> {{ err }} </div> {% endif %} But, while rendering to html the value of the variable has no output. Though, there are errors, which I've raised using forms.ValidationError. Also, try this like ... {% for field in form %} {% if field.errors %} <div ... > ... ... {{ field.errors }} </div> {% endif %} {% endfor %} In this case, output or the errors are showing, but with multiple <div> elements & n no. of times. I know that, it can be done by another way in the views.py: using 'django.contrib.messages'. Then sending errors to messages.error(), inside form.is_valid(), then ... {% if messages %} {% for message in messages %} {{ message }} {% endfor %} {% endif %} But, I want to manipulate it from forms.py file. So, how do I do it? 🙄️😕️🤔️🤨️ Thanks in advance!! -
Django CKEditor 404 image not found
On my Django admin panel, I can upload an image using CKEditor. However, the image doesn't apear and it return a 404 not found on the image file path. Actually, my image files are available on a dedicated url : media.mysite.com But, CKEditor is trying to GET the file from mywebsite.com/media/uploads/..., so this is normal that I get a 404 error. What is the good parameter to do for telling to CKEditor to use media.mysite.com to get any images ? Settings.py MEDIA_ROOT = "/var/www/media/mysite/" MEDIA_URL = "/media/" CKEDITOR_BASEPATH = "/static/ckeditor/ckeditor/" CKEDITOR_JQUERY_URL = 'https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js' CKEDITOR_UPLOAD_PATH = 'uploads/' CKEDITOR_IMAGE_BACKEND = "pillow" CKEDITOR_CONFIGS = { 'default': { 'toolbar': 'full', 'height': 300, 'width': '100%', }, } I visited many topics, but I found no answer. Thank you. -
Django Google api client library oauth2client - Unresolved reference FlowField
In google api client documentation, an example is provided for using the api-client-library in django here I attempt to use the snippet provided as is: from django.contrib.auth.models import User from django.db import models from oauth2client.contrib.django_orm import FlowField class FlowModel(models.Model): id = models.ForeignKey(User, primary_key=True) flow = FlowField() Importing from oauth2client.contrib.django_orm import FlowField however produces an error: Unresolved reference FlowField What am I doing wrong? (I have already installed the requirements with pip and have a running django application) -
django2 migrations ProgrammingError
Since I moved from django 1.8 to 2.1 I frequently get db migration errors. It doesn't occur during the migration directly, but when manage.py is called: django.db.utils.ProgrammingError: relation "obj1_obj2" does not exist LINE 1: .... Migration doesn't even start but it defines the relation or any model changes that cause the errors. When working locally I usually rollback code and then make migrations, but on cloud providers it is useless solution. I work on python 3.6 -
ImageField error in a admin side(after registration)
i enter image description hereused an ImageField in one of my apps model, but i can't add an image in a admin side(after registration) ------------------------------------------- from django.db import models from datetime import datetime ------------------------------------ class Realtor(models.Model): name = models.CharField(max_length=200) photo = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True) description = models.TextField(blank=True) phone = models.CharField(max_length=20) email = models.EmailField(max_length=50) is_mvp = models.BooleanField(default=False) hire_date = models.DateTimeField(default=datetime.now, blank=True) def __str__(self): return self.name -------------------------------------------- -
Error: (GET Request) http://my_ip_address/image_path/image.png 404 (Not Found)
I have a django project hosted on ec2 instance.I am trying to implement this thing http://bug7a.github.io/iconselect.js/ in my app.I have copied and pasted the code from this url in static directory of an app named 'dashboard' in my project.These are the files at this(/home/dashboard/static/dashboard/) location.:- css js lib images In images folder there is an image named 'arrow.png'. Path to arrow.png is dashboard/static/dashboard/images/control/icon-select/arrow.png I need to know how should i assign path to IconSelect.COMPONENT_ICON_FILE_PATH variable so that the function can get to arrow.png file In original code present at http://bug7a.github.io/iconselect.js/ code is written as follows Original iconselect.js ----Existing code----- IconSelect.DEFAULT = {}; IconSelect.COMPONENT_ICON_FILE_PATH = "images/control/icon-select/arrow.png"; -----Existing lines of code------ function IconSelect($$elementID, $$parameters) { ------Existing lines of code----- var componentIconImgElement = document.createElement('img'); componentIconImgElement.setAttribute('src', IconSelect.COMPONENT_ICON_FILE_PATH ); componentIconElement.appendChild(componentIconImgElement); -----------Exiting lines of code------ }; Now how should i assign path to IconSelect.COMPONENT_ICON_FILE_PATH variable IconSelect.COMPONENT_ICON_FILE_PATH = "Need your help here" I know how to do this in html document.For example if i want the 'src' to point at iconselect.js file present at dashboard/static/dashboard/lib/control/icon-select.js ,I would do like this: <script type="text/javascript" src="{% static "dashboard/lib/control/iconselect.js" %}"></script> But how should i do this in javascript(i.e iconselect.js) file? Error that i got in console is as follows: GET http://my_ip_address/testPage/images/control/icon-select/arrow.png … -
How to send key and check its value in html/django?
i want to input a key value from user and send to other url which checks if its right or wrong. right being value as "secretkey" wrong being any other value. My form in html file is:- <form action="/signup/mentor/checkkey" method="GET"> Key: <input type="text" name="mkey"><br> <input type="submit" value="Submit"> </form> and in urls.py path('signup/mentor/checkkey/<mkey>', views.signup_checkkey, name='signup_checkkey'), and in views.py def signup_checkkey(request,mkey): if request.user.is_authenticated: messages.warning(request, 'You are already registered as a valid user') return redirect(reverse('home')) if(mkey == 'secretkey'): return render(request=request, template_name='signup/mentor/user.html') else : messages.warning(request,'Wrong key to register as mentor') but this isn't working correctly. What am I doing wrong? I get Page not found error... -
authentication from mobile to backend django
Good day everyone. I am stumped at the moment and would appreciate some guidance. I feel like I am a great googler to usually find my answers or resources but for the life of me I can't seem to find any good learning material on JSON requests and responses. So I took a course that builds a 3 part app. Web app with Django, and 2 mobile apps that make API calls to it. The instructor uses Facebook authentication from the mobile apps and I am trying to set up the apps for username and login and a registration page as well. I have django models setup and and can make users from the web app but I can't seem to wrap my head around how to make JSON calls from app to Django. When I search for possible terms like authenticate django I get results that talk about only django usage. Does anyone have some tips or links to resources that would help me understand the login process better. I realize that almost every app has a login which is why I'm surprised that I can't find any good learning material on how its done. Or I'm just searching … -
Django: TypeError: int() argument must be a string, a bytes-like object or a number, not 'property'
I have done this in my view: model = company paginate_by = 10 def get_queryset(self): return company.objects.filter(User=self.request.user).order_by('id') def get_context_data(self, **kwargs): context = super(companyListView, self).get_context_data(**kwargs) context['selectdates'] = selectdatefield.objects.filter(User=self.request.user) groupcach = group1.objects.filter(User=self.request.user, Company=company.pk,Master__group_Name__icontains='Capital A/c') groupcacb = groupcach.annotate( closing = Coalesce(Sum('ledgergroups__Closing_balance'), 0)) groupcstcb = groupcacb.aggregate(the_sum=Coalesce(Sum('closing'), Value(0)))['the_sum'] ledcah = ledger1.objects.filter(User=self.request.user, group1_Name__group_Name__icontains='Capital A/c') ledcacb = ledcah.aggregate(the_sum=Coalesce(Sum('Closing_balance'), Value(0)))['the_sum'] total_cacb = groupcstcb + ledcacb context['capital'] = total_cacb return context But getting this error: TypeError: int() argument must be a string, a bytes-like object or a number, not 'property' I just cannot understand what this error mean. I just want to display the capital amount for all companies... The error is in this line of code: groupcach = group1.objects.filter(User=self.request.user, Company=company.pk,Master__group_Name__icontains='Capital A/c') Do anyone have any idea what I am doing wrong in my code? -
Static site with netlify + Django on the same url
Let's assume I own the domain: foobar.com/ I want to use Netlify for my static pages like foobar.com/features/ foobar.com/pricing/ foobar.com/imprint/ etc. But I also have a Django application on a seperate server on AWS that has nothing to do with the static sites served my Netlify. My Django has urls like foobar.com/login/ foobar.com/dashboard/ etc. Is it possible to use Netlify for a few static pages and my Django application for other pages? I don't know how start or if this is event possible. -
Django rest framework, How can I convert this query to django ORM
SELECT SUM(r.consultant_rate)/count(c1.consultant_id) avgf, count(c1.consultant_id) nofcon,c2.first_name,c2.category,c2.username,c2.email,c2.status,c2.about_me,c2.gender from consultations_consultation c1 RIGHT JOIN authentications_member c2 ON c1.consultant_id = c2.id RIGHT JOIN consultations_review r ON r.consultation_id = c1.id GROUP BY c2.first_name,c2.category,c2.username,c2.email,c2.status,c2.about_me,c2.gender -
Order SearchQuerySet according to matching term
I have been using elasticsearch for the search and for the items to show using haystack library. Everything is working fine except one thing. I want the SearchQuerySet to be sorted so that the items with term matches exactly, should come first and the partial matches later.Here is the code. sqs = SearchQuerySet().order_by('-created_at') q = self.request.GET.get('q', '') if q: q = escape(q).replace('&amp;', '&') q = q.replace('&#39;', "'") q = q.replace('&quot;', '"') print(q) sqs1 = sqs.filter(search_exact1__exact=q, global_search=True, is_active=True) sqs2 = sqs.filter(search_param1=q, global_search=True, is_active=True).exclude(search_exact1__exact=q) sqs = sqs1 | sqs2 return sqs Where search_exact1 is default CharField of Haystack and search_param1 is EdgeNGram. q is the term which is passed. -
How to create custom page inside Django 2 admin?
I need create a custom page inside Django 2.1.4 admin with admin styles, breadcrumbs e.t. support. urls.py urlpatterns = [ path('admin/', include([ path('', admin.site.urls), path('test/', TemplateView.as_view(template_name="admin/test.html"), name="admin-test"), ])), ... ] templates/admin/base.html {% extends "admin/base.html" %} {% block welcome-msg %} <a href="{% url 'admin-test' %}">admin test page</a> {{ block.super }} {% endblock %} templates/admin/test.html {% extends "admin/base.html" %} {% block content %} <h1>admin/test.html</h1> {% endblock %} My page looks like this: Page is created, but header content is diapered: no user-tools, no branding info. I've tried to add {{ block.super }} inside block content but no effect. Will be very appreciate for any tips how to make my template correctly inherit form base. -
Python Web Applicaiton
I was working on web application with PHP and developed a MVC model by myself. Now due to some reason we are shifting to python. I have some experience with Django framework. But Now with my new web application I want to develop it in python and I will design my own MVC model in it. I am not sure that I will be able to do it python So, can you guys help me with some knowledge. Can I use python to create my own MVC model without Django and Flask? Will it be feasible and good option to create my own MVC and not using Django or Flask? -
File picker in django-filer not picking file
I have Orderdetail model in django. i want to attach multiple file with with each instance. I have following code. class OrderDetail(models.Model): company_name = models.CharField(max_length=100, blank=True, null=True) created = models.DateTimeField(auto_now_add=True) file = FilerFileField(on_delete=models.CASCADE, null=True, blank=True, related_name='sample_file') and for admin.py @admin.register(OrderDetail) class OrderDetailAdmin(admin.ModelAdmin): fieldsets = ( ('OrderDetail', {'fields': (company_name','created', 'file')}), ) my file pick window pop up but does not pick file. Any one can help please. -
Django: Retrieve user data from a django sqlite database to show all the information and markers on google map
I'm trying to build a webpage where users can drop a pin on a location / input their GPS location into a form, along with the user's own message. It's something like the Waze app where users can report events at each marker location. The message will subsequently appear on a map with the message marker. I am trying to implement this with Django and Google Maps. The first step I am trying to solve is - how do I retrieve user data from a django sqlite database to show all the information and markers on the map, with javascript on the frontend? I am having difficulty finding information/example on how to implement this. Would truly appreciate any help and examples:) I found the an example to do this but for MYSQL and PHP. google maps -
Lazy Pagination gives error 'odict_items' object is not subscriptable
I have a nested ordered dictionary for displaying RSS Feeds in a template. I want to implement pagination, and I have used django-el-pagination library, and it gives error "odict_items is not subscriptable" template file: <section> <div class="container"> <div class="row effect-2" id="grid"> {% load el_pagination_tags %} {% lazy_paginate data.items as obj %} {% for key, value in data.items %} <div class="col-md-4 col-xs-12 col-sm-6"> {% if value.image %} <div class="hover ehover1"> <a href="{{value.link}}" target="_blank" title="{{key}}"> <img src="{{value.image}}" class="img-responsive"> </a> </div> {% endif %} <div class="underItem"> <a href="{{value.link}}" title="{{key}}" target="_blank">{{key}}</a> <p>{{value.description}}</p> <b class="pull-right">{{value.pub_date}} - {{value.source}}</b> <div class="clearfix"></div> </div> </div> {% endfor %} {% show_more %} </div> </div> views file: def rss_feed_parser(request): sorted_result={} data = {} rss_feeds_bloomberg = "https://www.bloombergquint.com/stories.rss" feeds = feedparser.parse(rss_feeds_bloomberg) for entry in feeds.entries: epoch = int(time.mktime(time.strptime(entry.published, '%a, %d %b %Y %H:%M:%S %z'))) pdate = pretty_date(epoch) feed_data = { entry.title: { 'title': entry.title, 'link': entry.link, 'image': "", 'pub_date': pdate, 'time': epoch, 'description': entry.description, 'source': "BloombergQuint" } } data.update(feed_data) sorted_result = OrderedDict(sorted(data.items(), key=lambda i: i[1]['time'], reverse=True)) return render(request, "rss_feeds.html", {'data' : sorted_result}) What is missing? Is there anyother way I could implement pagination? -
Django + nginx +wsgi: can see only default nginx page
I deploy my django apps on pythonanywhere usually, but now i have a project that should be deployed on scaleway. Im using nginx as a webserver, and wsgi to run my app. I use this guide as an example, but got a problems on step with nginx configuration. Im running uwsgi --ini uwsgi.ini but on web page can see only default nginx page. here is my config file nginx.conf: upstream django { server unix:///var/www/sjimalka/main.sock; # взаимодействие с uwsgi через Unix-сокет #server 51.15.215.60:8001; # взаимодействие с uwsgi через веб-порт } # конфигурация веб-сервера server { listen 80; # порт, который будет слушать веб-сервер в ожидании запросов от пользователей server_name 51.15.215.60; # доменное имя charset utf-8; #кодировка utf-8 client_max_body_size 75M; # максимальный размер загружаемых на сервер данных # обслуживание медиа файлов и статики location /media { alias /var/www/sjimalka/media; # расположение медиафайлов } location /static { alias /var/www/sjimalka/static; # расположение статики } # Остальные запросы перенаправляются в Django приложение location / { uwsgi_pass django; include /var/www/sjimalka/uwsgi_params; # файл uwsgi_params } } uwsgi_params: uwsgi_param QUERY_STRING $query_string; uwsgi_param REQUEST_METHOD $request_method; uwsgi_param CONTENT_TYPE $content_type; uwsgi_param CONTENT_LENGTH $content_length; uwsgi_param REQUEST_URI $request_uri; uwsgi_param PATH_INFO $document_uri; uwsgi_param DOCUMENT_ROOT $document_root; uwsgi_param SERVER_PROTOCOL $server_protocol; uwsgi_param REQUEST_SCHEME $scheme; uwsgi_param HTTPS $https if_not_empty; … -
Django admin add form show object fields from related model
I have following model: class Company(models.Model): company_name = models.CharField(verbose_name="Company", max_length=200) class Department(models.Model): name = models.CharField(verbose_name="Department", max_length=255) company = models.ForeignKey(Klijent, on_delete=models.CASCADE) class Employee(models.Model): external_id = models.CharField(max_length=50, null=True, blank=True) name = models.CharField(max_length=100) department = models.ForeignKey(Department, on_delete=models.CASCADE) I am trying to have my Add employee admin form have besides Department, related selection for Company. So when i select Company i get choice of its departments. Currently i get choice of all the departments. App is heavily admin focused so it would be good to have this functionality. -
How to mark post as liked with django Generic Relation
I would like to use GenericRelation in my app to implement "like" feature. I have already these models: class Activity(models.Model): LIKE = 'L' ACTIVITY_TYPES = ( (LIKE, 'Like'), ) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) activity_type = models.CharField(max_length=1, choices=ACTIVITY_TYPES) date = models.DateTimeField(auto_now_add=True) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey() def __str__(self): return str(self.user) class Post(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=200) text = RichTextUploadingField() likes = GenericRelation(Activity, related_query_name='posts') created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return self.title I my views.py file I have line like this: activity = Activity.objects.get(content_type=ContentType.objects.get_for_model(obj), object_id=obj.id, user=request.user) My problem is, how I can get info that this user is already liking this post? -
Django upload zip file and save .zip and extracted file to different location in same model
In Django I want be able to upload a .zip file. The zip file contains a scl file (basically plain text) I want read and process. The .zip and the .scl I want to save locally. The problem is that I am unable to save the locally extracted .scl file to the model via the upload_to method. As the .zip is uploaded and the scl file is extracted it appears in the root of the project. My current solutio is the following, here the zip is extracted and then moved but these paths are hard coded and raise an error if two files have the same name. The upload_to method renames the files if it finds similar named files and saves the renamed file path to the database. models.py class Default_software(models.Model): version = models.CharField(max_length=10, help_text='AISA_V2-Q') zip_location = models.FileField(upload_to='default_software') #docfile scl_location = models.FileField(upload_to='default_scl') created_at = models.DateTimeField(auto_now_add=True) def __str__(self): """String for representing the Model object""" return self.name views.py from django.views.decorators.csrf import csrf_exempt from django.template import RequestContext from django.http import HttpResponseRedirect from django.urls import reverse from myapp.models import Default_software from myapp.forms import DocumentForm # import aboslute URL for files processing from django.conf import settings # file handling and saving from shutil import move … -
Django CreateView Foreign key
I need some help. I'm writing an app with Django 2.1 and python 3.7 I am trying to add a new Comment that it is associated to an Article through foreign key. The url of the screen to add a new comment is http://127.0.0.1:8000/articles/1/comment/new/ so the url has the foreign key. When I try a save the comment it returns the error below: IntegrityError at /articles/1/comment/new/ NOT NULL constraint failed: articles_comment.article_id Request Method: POST Request URL: http://127.0.0.1:8000/articles/1/comment/new/ Django Version: 2.0.6 Exception Type: IntegrityError Exception Value: NOT NULL constraint failed: articles_comment.article_id Exception Location: /Users/fabiodesimoni/.local/share/virtualenvs/news-s2R6SLTq/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py in execute, line 303 Python Executable: /Users/fabiodesimoni/.local/share/virtualenvs/news-s2R6SLTq/bin/python Python Version: 3.7.1 Python Path: ['/Users/fabiodesimoni/Development/Python/Django/news', '/Users/fabiodesimoni/.local/share/virtualenvs/news-s2R6SLTq/lib/python37.zip', '/Users/fabiodesimoni/.local/share/virtualenvs/news-s2R6SLTq/lib/python3.7', '/Users/fabiodesimoni/.local/share/virtualenvs/news-s2R6SLTq/lib/python3.7/lib-dynload', '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7', '/Users/fabiodesimoni/.local/share/virtualenvs/news-s2R6SLTq/lib/python3.7/site-packages'] Server time: Tue, 18 Dec 2018 10:05:07 +0000 If I add the field Article into the Comment screen, I am able to select the Article and the insert works as expected, but I want to do it automatically because I have the article id in the url. I hope all information are here and in case it needed the code the source code is https://github.com/fabiofilz/newspaper_app Model.py: from django.contrib.auth.models import User from django.conf import settings from django.contrib.auth import get_user_model from django.db import models from django.urls import reverse class Article(models.Model): title …