Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How top automaticly generate pages in Django?
I am try to make an internet shop with Django but i have a problem. I made a template to show products from certain category for now that looks like : {% for item in products %} .............. .............. {% endfor %} That works until i have only few products. But when it will be the hundreds of products how can i automatically generate pages for products ? For example for 10 products in a page? And in the bottom numbers for pages [1][2][3]...[100]. -
does overriding an abstract base class attribute affect other child class?
If I change the attribute of a abstract base classes field using , Classname._meta.get_field(fieldname).attribute = 'value' will it affect the other child classes fields too? -
Only able to login ONCE with Selenium and Django Testing
I'm testing using Django's tests and Selenium so I can run tests with a live browser. But it won't let me log in more then once. I am using Django's StaticLiveServerTestCase to access both static and media files live. I login by going to the page. I've tried putting the login code both in setUpClass to run once at the beginning and setUp to run each time. Both only let me log in once. Here's the code: from django.contrib.staticfiles.testing import StaticLiveServerTestCase from django.contrib.auth.models import User from selenium import webdriver @override_settings(DEBUG=True) class LoginTest(StaticLiveServerTestCase): @classmethod def setUpClass(cls): super().setUpClass() # create user cls.user = User.objects.create_user( 'Testing User', 'somewhere@wherever.com', 'pwd') # initalize webdriver cls.driver = webdriver.Chrome() # doesn't work on FireFox either cls.driver.set_window_size(1280,800) cls.driver.implicitly_wait(5) # login - send username and password to login page cls.driver.get(cls.live_server_url+'/accounts/login/') cls.driver.implicitly_wait(10) username = cls.driver.find_element_by_name('login') username.clear() username.send_keys(cls.user.username) password = cls.driver.find_element_by_name('password') password.clear() password.send_keys("pwd") password.submit() # eubmits form @classmethod def tearDownClass(cls): cls.driver.quit() # quit after tests have run super().tearDownClass() def test_login_one(self): # this test PASSES self.driver.get(self.live_server_url) # go to home page login_menu = self.driver.find_element_by_id('login_menu') self.assertTrue( # if logged in username is in text of #login_menu self.user.username in login_menu.text ) def test_login_two(self): # this test FAILS self.driver.get(self.live_server_url) # go to home page login_menu … -
Django-el-pagination not working, pagination not showing up
So I tried installing django-el-pagination, but apparently, it doesn't want to load on my web page. Every package is installed but it won't show. Here is what I did: def index(request): course_list = Course.objects.all() page = request.GET.get('page', 1) paginator = Paginator(course_list, 1) try: courses1 = paginator.page(page) except PageNotAnInteger: courses1 = paginator.page(1) except EmptyPage: courses1 = paginator.page(paginator.num_pages) context = { 'courses1': courses1, 'courses': Course.objects.all(), 'faculties': Faculty.objects.all(), 'departments': Department.objects.all(), 'studies': StudyProgramme.objects.all(), 'teachers': Teacher.objects.all() } return render(request, 'courses/index.html', context) <div id="crs"> <h3>All courses</h3> <ul> {% paginate courses1 %} {% for course in courses1 %} <li><a href={{ course.slug }}>{{ course.name }}</a></li> {% endfor %} {% show_pages %} </ul> </div> -
Django Populate the admin model fields with the data
This is my model.py. I have registered this model with the admin panel. I want to populate my model with data. That data will come from another model and I will perform some calculations on it and put that data in this model. Any help guys. class Sectorcapitalratios(models.Model): sectorserialnum = models.IntegerField(db_column='SectorSerialNum', primary_key=True) # Field name made lowercase. sectorname = models.CharField(db_column='SectorName', max_length=50, blank=True, null=True) # Field name made lowercase. years = models.CharField(db_column='Years', max_length=15) # Field name made lowercase. debttoequityratio = models.FloatField(db_column='DebtToEquityRatio', blank=True, null=True) # Field name made lowercase. debttocapital = models.FloatField(db_column='DebtToCapital', blank=True, null=True) # Field name made lowercase. debttototalassets = models.FloatField(db_column='DebtToTotalAssets', blank=True, null=True) # Field name made lowercase. timestamp =models.DateTimeField(auto_now_add = True) #This will create the time class Meta: db_table = 'sectorcapitalratios' unique_together = (('sectorserialnum', 'years'),) #def __str__(self): # return self.sectorserialnum Admin.py class CapitalratiosResource(resources.ModelResource): class Meta: model = Capitalratios skip_unchanged = True report_skipped = False import_id_fields = ('ticker','years') class CapitalratiosAdmin(ImportExportModelAdmin,admin.ModelAdmin): resource_class = CapitalratiosResource list_display = ('ticker','years','debttoequityratio','debttocapital','debttototalassets') #Register the Capital Ratios model and admin with the admin admin.site.register(Capitalratios, CapitalratiosAdmin) -
Django relation "myapp_mymodel" does not exist error
I initially attempted to change the name of the CharField "NewsItem.markdown" to "NewsItem.name" and change its max length. I made migrations and migrated as per usual, however this led to an error telling me that "main_NewsItem.markdown" does not exist. After struggling with this (flushing database, dropping database and recreating it etc. with no change in the error message) I decided to delete that model all together and create a new one named "News_item". I again made migrations and migrated as per usual. This resulted in the following error: Environment: Request Method: GET Request URL: http://46.101.55.192/admin/main/newsitem/ Django Version: 2.0.2 Python Version: 3.5.2 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'main'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "/home/koan/koansite/koansiteenv/lib/python3.5/site- packages/django/db/backends/utils.py" in _execute 85. return self.cursor.execute(sql, params) The above exception (relation "main_newsitem" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "main_newsitem" ^ ) was the direct cause of the following exception: File "/home/koan/koansite/koansiteenv/lib/python3.5/site- packages/django/core/handlers/exception.py" in inner 35. response = get_response(request) File "/home/koan/koansite/koansiteenv/lib/python3.5/site- packages/django/core/handlers/base.py" in _get_response 128. response = self.process_exception_by_middleware(e, request) File "/home/koan/koansite/koansiteenv/lib/python3.5/site- packages/django/core/handlers/base.py" in _get_response 126. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/koan/koansite/koansiteenv/lib/python3.5/site- packages/django/contrib/admin/options.py" in wrapper 574. return self.admin_site.admin_view(view)(*args, **kwargs) File "/home/koan/koansite/koansiteenv/lib/python3.5/site- packages/django/utils/decorators.py" in _wrapped_view 142. … -
Error in db with modeltranslation in django
I want to add internationalization to a project, so I use django-modeltranslation app. However, after following all the steps of configuration and running migrations, when I enter in my admin the model is registered, but when I click on it: "Something's wrong with your database installation. Make sure the appropriate database tables have been created, and make sure the database is readable by the appropriate user." Here's the code (note I have put it all in a file for clarity): INSTALLED_APPS = [ 'modeltranslation', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'nuggets', ] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'Trans', 'USER': 'postgres', 'PASSWORD': 'c1l2a3u4', 'HOST': '127.0.0.1', 'PORT': '5432', } } LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True gettext = lambda s: s LANGUAGES = ( ('en', gettext('English')), ('es', gettext('Spanish')), ) #Models code from django.db import models class News(models.Model): title = models.CharField(max_length=255) text = models.TextField() #Admin code from django.contrib import admin from .models import News from modeltranslation.admin import TranslationAdmin class NewsAdmin(TranslationAdmin): pass admin.site.register(News, NewsAdmin) #translation.py code from modeltranslation.translator import translator, TranslationOptions from .models import News class NewsTranslationOptions(TranslationOptions): fields = ('title', 'text',) translator.register(News, NewsTranslationOptions) ]2]2 I have tried before createing the models, after, … -
Django: Loop over 2 objects in same loop in template
I have two models that are related, and I need to create a table that takes from both objects. In my models: class Chamber(models.Model): chamber_name = models.CharField(max_length=100) chamber_type = models.CharField(max_length=50) customer = models.ForeignKey(Customer, on_delete=models.CASCADE) class ChamberProperties(models.Model): chamber = models.ForeignKey(Chamber, on_delete=models.CASCADE) property_name = models.CharField(max_length=20) property_value = models.CharField(max_length=100) The structure is strange, but it's too late to just add properties and values to the chamber model. I'll have to live with the fact that they are two separate models. In my table I need the following structure: chamber_name(obj A) - property_value(obj B) - customer(obj A again) I tried zipped lists, but I don't seem to be able to unpack it: class ChambersView(generic.DetailView): template_name = 'pages/chambers.html' def get(self, request): user = User.objects.get(username=request.user) customer = Customer.objects.get(user=user) chambers_list = list(Chamber.objects.filter(customer=customer)) chamber_properties = list(ChamberProperties.objects.filter(chamber__in=chambers_list).order_by('id')) objects_list = zip(chamber_properties, chambers_list) form = ChambersFilterForm(request=request) return render(request, self.template_name, {'filter_form':form, 'objects_list': objects_list}) If I unpack it in python it works: for properties, chambers in objects_list: print("-----------------------------------------------------------") print("Property is: ", properties.property_value, "and the chamber is:", chambers.chamber_name) print("-----------------------------------------------------------") But when I go to my HTML template: <div class="card-body p-1"> <table class="table table-hover"> <tr class="table-active"> <th>Chamber</th> <th>Property Value</th> <th>Customer</th> </tr> {% for properties, chambers in objects_list %} <tr> <td><a href="{% url 'chamber' chamber.id %}">{{chambers.chamber_name}}</a></td> … -
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?