Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
python newspaper - cannot extract article if URL is not in english language
I am trying to get the content of a news article with python newspaper module. I can find the body of a news item with the following code. The code parses the feed URL in feed_url variable with feedparser and then tries to find the news body and publishing date with newspaper module. import newspaper from newspaper import Article import feedparser count = 0 feed_url="https://www.extremetech.com/feed" #feed_url="http://www.prothomalo.com/feed/" d = feedparser.parse(feed_url) for post in d.entries: count+=1 if count == 2: break post_link = post.link print("count= ",count," url = ",post_link,end="\n ") try: content = Article(post_link) content.download() content.parse() print(" content = ", end=" ") print(content.text[0:50]) print(" content.publish_date = {}".format(content.publish_date)) except Exception as e: print(e) I mentioned 2 different values for the variable feed_url in the code - one is from extremetch site and another one is from prothomalo website . Let us say for example, extremetech has a news item with URL as https://www.extremetech.com/computing/263951-mit-announces-new-neural-network-processor-cuts-power-consumption-95. And I can easily get the news body text and publishing date for this URL. But prothomalo for example has a news item with the URL as http://www.prothomalo.com/sports/article/1432086/%E0%A6%B8%E0%A6%B0%E0%A7%8D%E0%A6%AC%E0%A7%8B%E0%A6%9A%E0%A7%8D%E0%A6%9A-%E0%A6%B8%E0%A7%8D%E0%A6%95%E0%A7%8B%E0%A6%B0-%E0%A6%97%E0%A7%9C%E0%A7%87%E0%A6%93-%E0%A6%B9%E0%A6%BE%E0%A6%B0 . The reason behind such URL is that the URL has some parts that are in Bengali language. The content here is … -
Rendering blank ImageFields in Django template
I am trying to render an instance of this model in my template: class Candidate(models.Model): UserID = models.ForeignKey(User, on_delete=models.CASCADE) ElectionID = models.ForeignKey(Election, on_delete=models.CASCADE) Bio = models.CharField(max_length=500, blank=True) Poster = models.ImageField(upload_to="profilepics/", null=True, blank=True) I am having trouble with rendering the Poster attribute which, as you can see, has the option of being blank. When I try to render the following html in the template: <h1>{{candidate.UserID.first_name}} {{candidate.UserID.last_name}} ({{candidate.UserID.username}})</h1> <h2>{{candidate.ElectionID}}</h2> <img src="{{candidate.Poster.url}}" width=240><br> I get an error if Poster is blank. ValueError: The 'Poster' attribute has no file associated with it. How do I prevent this error? I want to show nothing if Poster is blank and obviously show the image if it isn't. -
Django foreign key and self.text errors
So I'm working on the model.py in django and get 2 pylint errors E1120:No value for argument 'on_delete' in constructor call E1136:Value 'self.text' is unsubscriptable The first is on line 19, in Entry topic = models.ForeignKey(Topic) The second is on line 24 self.text[:50] If I remove the entry class the code works from django.db import models # Create your models here. class Topic(models.Model): """A topic the user is learning about""" text = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): """Return a string representation of the model.""" return self.text class Entry(models.Model): """Something specific learned about a topic""" topic = models.ForeignKey(Topic) text = models.TextField() date_added = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural = "entries" def __str__(self): """Return a string representation of the model.""" return self.text[:50] + "..." -
unable to Retrieve data from JSON file using Angular js
enter image description hereI am not able Retrieve data from Json file using Angular Js. Am trying to get the Json data from URL using click function in angular Js and also when click the button add empty tr td in table. <!doctype html> <html lang="en" ng-app="sampleapp"> <head> {% load staticfiles %} <meta charset="utf-8"> <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css"> <script src="{% static 'bootstrap/js/angular.min.js'%}"></script> <script type="text/javascript" src="{% static 'bootstrap/js/jquery.min.js'%}"></script> <script src="{% static 'bootstrap/js/bootstrap.min.js'%}" type="text/javascript"></script> <script type="text/javascript" src="{% static '/bootstrap/js/app_ang.js'%}"></script> </head> <body > <div class="col-sm-12" ng-controller="tablejsonCtrl"> <button class="clickbutton" ng-click="jsonclick();">Show-json</button> <table rule="all" class="table table-bordered table-hover "> <tr> <th>Name</th> <th>Price</th> <th>Description</th> <th>Calories</th> <th>isbest</th> </tr> <tr ng-repeat="value in students.breakfast_menu.food"> <td>{{value.name}}</td> <td>{{value.price}}</td> <td>{{value.description}}</td> <td>{{value.calories}}</td> <td>{{value.isbest}}</td> </tr> </table> </div> </body> </html> var app =angular.module('sampleapp', []) app.controller("tablejsonCtrl", function ($scope, $http) { $scope.jsonclick = function () { var url = "http://127.0.0.1:8000/static/waste/test.json"; $http.get(url).then(function(response) { $scope.students = response.data; }); } }); -
UpdateView with AJAX
I have a realized message wall (multilevel). The form is used only one, it is cloned. Adding messages works as an AJAX well. I cannot implement message editing. Here I delete the message when I click and put in its place the form obtained by cloning: $('.edit').on('click', function(e) { e.preventDefault(); $(this).next().remove(); var action = $(this).attr('href'), clone = $('.comment_form').clone().attr('action', action).css('display', 'block'); $(this).after(clone); clone.addClass('add_comment_form').removeClass('comment_form'); clone.attr('onclick', comment()); }); The comment () function calls AJAX when the form is submitted, uses the URL received in the action (update). My UpdateView: class EditComment(UpdateView): model = Comment form_class = AddCommentForm template_name = 'wall/wall-msg.html' And I need it to work in the main template. Help please, how to me to receive the form with initial data and all it correctly to implement as a whole. Thank you! -
'str' object has no attribute 'GET' when requesting to django script
i have been working with django to make an interactive web page. But when i try to make a Http request to a django view. It throws that error, even though i have the exact same code above and that works just fine. Here is my Python code: def test(request): default = {"Error" : "Could not make request"} name = request.GET.get('showname') token = getToken() showJs = searchShowId(name, token) if showJs.get('Error'): try: token = refreshToken(token) showJs = searchShowId(name, token) return JsonResponse(showJs) except KeyError as error: token = login() showJs = searchShowId(name, token) return JsonResponse(showJs) else: return JsonResponse(showJs) def image(request): default = {"Error" : "Could not make request"} id = request.GET.get('id') return JsonResponse(image(id)) this is the full error: Traceback: File "C:\Users\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\exception.py" in inner 35. response = get_response(request) File "C:\Users\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\base.py" in _get_response 128. response = self.process_exception_by_middleware(e, request) File "C:\Users\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\base.py" in _get_response 126. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "E:\Documentos\Programming\DjangoProjects\mediaD\mediaDe\views.py" in image 33. return JsonResponse(image(id)) File "E:\Documentos\Programming\DjangoProjects\mediaD\mediaDe\views.py" in image 32. id = request.GET.get('id') Exception Type: AttributeError at /image/ Exception Value: 'str' object has no attribute 'GET' Javascript Code: function search() { console.log('Function Called') var showName = document.getElementById('showName'); console.log(showName.value); var name = stringToPost(showName.value); $.ajax({ type: "GET", url: "/request/", data: { showname: showName.value }, success: function … -
Using "CKEditor" with Django "Machina Forums?"
This is a more-general question – just hoping to find someone who already knows. ("To save my forehead," y'know.) ;-) I want to use CKEditor in conjunction with Machina forums, and I specifically want to be able to "drag and drop" images. I've found the right CKEditor feature to do that, but I'm getting "Incorrect Server Response" messages from CKEditor when I try to accomplish the drop. (This also happens on my development box.) (Note that my concern is quite-particular to Django ("django-ckeditor"), and to the Machina forum software ("django-machina"). I need answers that are very tightly focused upon this use-case.) So is there anyone out there who might say – "oh yeah, that happened to me, too, and the way to fix it is ...?" -
Django: which url does the LocaleMiddleware check?
Our company provides both a API and a small number of widgets that are embedded in clients websites through Iframes. Now we have a Belgian customer who wishes to use our widgets. As you know Belgium is bi-lingual, so we are making liberal use of both the LocaleMiddleware and the {% trans 'string' %} tags. Now as I understand correctly the middleware checks the URL to see which language to use. When you first visit our clients website you get a large pop-up where you choose your language. After this popup your url changes to this format: www.clientorg.be/fr_BE/rest-of-the-url, so that should (hopefully) work just fine. However, our widget is served through an Iframe. (src = s2.oururl.com) which contains no language value. So my question is: Will Django be able to detect the language of the user? Or will it only be able to check 'our' s2.url, meaning we need to contact our client and provide him with 2 urls to paste in the iframe, depending on the language the user chooses. -
Generate HTML Report after running django unit testing testcases
I am newbie to djnago and python, I want to generate the report of testcases run by djnago and send in mail to team. Please help me -
Django search not showing results
So I was trying to set up the search view for a model. But I think I am doing something wrong. Maybe I pass arguments wrong ? def search(request): query = request.GET.get('q') if query: results = Course.objects.filter(Q(name__icontains=query)) else: results = Course.objects.all() context = { 'results': results, } return render(request, 'courses/index.html', context) -
Django - redirect to non-www version
Is in Django a simple way to redirect everything from domain with www to version without it? I mean from http://www.example.com to http://example.com. like PREPEND_WWW only vice versa -
django_cron config when .ebextensions is not in root directory
There are a few solutions to configuring .ebextension container commands for cronjobs but none of them are working for me. I am concerned that the reason they aren't working is because .ebextensions is not in the root directory. This messy code was handed over to me and I've tried to move .ebextensions to where it needs to be but that seems to break everything else. This app is a streaming video application currently in production and I can't afford to break it so I ended up just leaving it where it is. Can someone tell if I am doing this right and I just need to find a way to move .ebextensions or is the problem in my cronjob configuration? app1/.ebextensions/02_python.config container_commands: ... cronjob: command: "echo .ebextensions/cronjobs.txt > /etc/cron.d/cronjobs && 644 /etc/cron.d/cronjobs" leader_only: true ... app1/.ebextensions/cronjobs.txt ***** root source /opt/python/run/venv/bin/activate && python3 manage.py runcrons > /var/log/cronjobs.log app1/settings.py INSTALLED_APPS = [ ... 'django_cron', ... ] CRON_CLASSES = [ 'app2.crons.MyCronJob', ] app2/crons from django_cron import CronJobBase, Schedule class MyCronJob(CronJobBase): RUN_EVERY_MINS = 1 schedule = Schedule(run_every_mins=RUN_EVERY_MINS) def do(self): # calculate stuff # update variables This deploys to AWS elastic beanstalk without error and logs show it's run but the work doesn't get done … -
QR code generate django-admin
how to print the qr code with the data above the button after pressing "Print qr code"? enter image description here -
Include templates; pass variables to 'with' as keys (strings) and retrieve them as objects
I have multiple formsets where the code is very similar, so I want to use a base template, and include with variables, as the obj and the field {{ form.obj.management_form }} .... {% for obj_form in form.obj %} {{obj_form.field.errors}} {% include 'base.html' with obj='doc' field='doc_a' %} My issue is that what I can transfer is the name of the obj, or field and not the real Object behind. To ge the real obj I have to loop, which doesn't server the purpose of DRY. So how I can pass in template the variable/object name and get/call the real Object in the base template. -
How to get the old values of django model field while updating without using signals in django rest framework?
I am using django-rest-framework. I have a case in which I need to update the field of other model once instance of first model is created or updated. here is my models.py: class FirstModel(models.Model): first_model_item = models.ForeignKey(Item) quantity = models.IntegerField() class SecondModel(models.Model): second_model_item = models.ForeignKey(FirstModel) quantity = models.IntegerField() Here is my views.py: class CreateSecondModelView(generics.CreateAPIView): permission_classes = () queryset = SecondModel.objects.all() serializer_class = SecondModeSerializer def perform_create(self, serializer): instance = serializer.save() first_model_item = instance.item first_model_item.quantity -= instance.quantity first_model_item.save() class UpdateSecondModelView(generics.RetrieveUpdateAPIView): permission_classes = () queryset = SecondModel.objects.all() serializer_class = SecondModeSerializer def perform_update(self, serializer): instance = serializer.save() #here i want old value of quantity before updating. -
DRF : Custom permission denied message
How to change the default DRF-Permission Denied message from {"detail":"You do not have permission to perform this action."} to something like this, {"status": False, "message": "You do not have permission to perform this action."} I found this SO Answer, but it doesn't help to change the Key for the message -
Sort merged QuerySets by created_at field
I try to sorted two merged QuerySets by created_at field and DESC (from max to min): # app/views.py class AccountIndexView(View): template_name = 'accounts/accounts_index.html' def get(self, request): # Get TVS object obj_1 = ModelOne.objects.filter(user=request.user) obj_2 = ModelTwo.objects.filter(user=request.user) # Make orders object orders = sorted( chain(obj_1, obj_2), key=attrgetter('created_at') ) return render(request, self.template_name, {'orders': orders}) But this way not working: QuerySet still sorting by ID and ASC (from min to max). How to solve that with my case? -
No ProcessListView endpoint and ArchiveListView variable
I created simple workflow based on cookbook/custom-ui example. My process is working, but I wanted to add list of all processes(using process_list.html in example) and after checking available endpoints with show_urls command i noticed i don't have ProcessListView endpoint listed there. So i tried with archive (which was listed along queue and tasks). But no matter what variable i use in {% for task in archive %} the list is empty. So first question is what should i do to see endpoint or get the list of all processes with custom_ui. And second what variable should i use to get list of archived processes and when process is archived (when it's finished or later on) Also if answers for my questions are in some documentation please give me a link, because i cannot find them Thank you for your help -
Possible jQuery messing up pagination in Django
I have trouble setting up my pagination right. I have a Course model which holds courses and a Faculty model which holds faculties, to whom specific courses belong to. I am switching between all courses display and all courses that belong to a specific faculty by simple click and no other page, just by using a jQuery to hide/show items on page. Now I tried to set up pagination for courses that belong to a specific faculty, and every time I try to change page, it redirects me to the main page which contains all courses. Also, for my first faculty I have only 2 courses, but pagination will show that a 3rd page is available for some reason. I think it's either my view, either my jQuery. https://imgur.com/7Br1a0o <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <script> $(document).ready(function () { $('.btnClick').on('click', function () { $('.col-md-9').find('[id^="dep"]').hide(); var faculty_id = $(this).attr('id'); $('#' + faculty_id + '_tab').show().siblings('div').hide(); }); $('.btnClick2').on('click', function () { $('.col-md-9').find('[id^="std"]').hide(); var study_id = $(this).attr('id'); $('#' + study_id + '_tab').show().siblings('div').hide(); }); $('.btnClick3').on('click', function () { var a = $('.col-md-9'); a.find('[id^="fac"]').hide(); a.find('[id^="std"]').hide(); a.find('[id^="crs"]').show(); }); }); </script> <div class="row"> <div class="col-md-3"> <div class="jumbotron"> <h4>Search courses</h4> <hr> <br> <p onClick="window.location.reload()" class="btnClick3">Show all courses</p> <br> <ul> {% for faculty in … -
related_name='hourlys' corresponds to empty list
I have three Django models namely User, Project and Hourly. User model: which represents a standard Django user, which can start a new project. Project model: Represents a project, containing project specifc constants such as Time Zone, site latitude, site longitude, etc… Hourly model: Which represents all the hourly values (clock-time, solar time, solar hour angle, etc…) for a certain project. To simplify the problem the Hourly model has only two fields, namely project and clock_time. Eventually I would like to use fields to store all the hourly values (declination, solar hour angle, etc…) to the database. In addition I override the Project.objects.create(….) method using the ProjectManager() class. Whenever a new project is created, there will be 8760 new hourly value instances also created which stores all the hourly values for declination, solar hour angle. The Project and Hourly models and ProjectManager are defined as follows: User = settings.AUTH_USER_MODEL class ProjectManager(models.Manager): """""" def create(self, owner, project_name, TMZ, lat, lon): project = super().create(owner=owner, project_name=project_name, TMZ=TMZ, lat=lat, lon=lon) project.save() hourlys = Hourly.objects.filter(project=project) hourlys.delete() hourlys = [] for i in range(0, 8760): clock_time=i*3600 hourlys.append(Hourly(project=project, clock_time=clock_time)) Hourly.objects.bulk_create(hourlys) return project class Project(models.Model): objects = ProjectManager() owner = models.ForeignKey('auth.User', related_name='projects', on_delete=models.CASCADE) project_name = models.CharField(max_length=200) TMZ = … -
Django taggit, tags owned by users
By default django-taggit adds tags to objects, visible by any user. I want user to add tags and these tags to belong to that user. Only visible and modified by owner user. Same tag maybe used by different users. There are 2 things to be done , saving tags belong to user and filtering tags per user. I don't know what is the correct way to do that. -
Getting Permissions issue on sending the authenticated request to OAuth2.0 Django rest Framwork
I Have integrated the OAuth2.0 with django-rest-framework. When I send the authenticated request to my class based view I got this { "detail": "You do not have permission to perform this action." } settings.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'oauth2_provider.contrib.rest_framework.OAuth2Authentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ) } views.py from rest_framework import permissions from oauth2_provider.contrib.rest_framework import TokenHasReadWriteScope class LogoutView(APIView): """ This will help in logout of user. """ authentication_classes = () permission_classes = (permissions.IsAuthenticated, TokenHasReadWriteScope) def get(self, request): return Response({'s': 'd'}) urls.py from django.urls import path, re_path from accounts.views import SignUpView, LoginView, LogoutView urlpatterns = [ path('signup/', SignUpView.as_view()), path('login/', LoginView.as_view()), path('logout/', LogoutView.as_view()), ] And this is what my headers look like Content-Type:application/json Authorization:Bearer 4A7qGgmHpbEWlJn5w4wCwxJ9jWfTZ5 This is the access token that I generated. -
How add columns from a list?
(This is my first post on StackOverFlow and it's a great ressource and community <3) I develop a website and i use django_tables2 to display my result. My problem is that i have my table model here (very simple)... class myTable(TableReport, ColumnShiftTable): column_default_show = ['select']; class Meta: attrs = {'class': 'table table-bordered table-striped table-condensed'}; and i want to display dynamically a set of columns... data = []; #Tuples of data listColumnsName = ['columnsName1', 'columnsName2',......]; table = myTable(data=data) ; ...but i dont know how adding the columns because the list of columns is not stable. I hope that i have been understable. -
Django ORM - Get N random records, and then split them in 2 groups
I have a Post model: class Post(models.Model): headline = models.CharField(max_length=255) ... What I am, unsuccessfully, trying to achieve, is to get two random groups of 5 posts each, where the 2nd group records that the 1st group does NOT have. Now I know how to do this using Python, but I was wondering if there is a more elegant, ORM-like solution. I have tried the following: posts = Post.objects.all().order_by('?') first_group = posts[:5] second_group = posts[5:] But this will, sometimes, return the same posts in both groups. I have also tried to trick the system doing the following: posts = Post.objects.all().order_by('?') first_group = posts[:5] second_group = Post.objects.exclude(id__in=posts) But again no luck. Can someone give me a few pointers so I don't have to loop over the records in pure Python? -
How to change the config file in TravisCI to run Django?
I am new to TravisCI and have written the following text in .travis.yml: language: python python: - 3.6 env: - DJANGO=2.0.2 script: - python manage.py test I am trying to run a build for a Django-project. The build runs, but for some reason it fails because TravisCI thinks it is a Ruby-project. This is not strange as, when I press "view config", I see that it is written for Ruby (also see screenshot below): { "language": "ruby", "group": "stable", "dist": "trusty", "os": "linux" } Does anyone know how to change this config-file to fit for Django? So that my .travis.yml file can run correctly?