Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cuckoo Web TemplateSyntaxError when checking behavioral analysis
I'm having problems with cuckoo web when attempting to check the behavioral analysis results. Whenever I try to click on the link the following error is displayed: Any ideas on the cause? -
django prefetch within a prefetch - must be a Model, Manager, or QuerySet, not 'QuerySet'
Im trying to do a prefetch within a prefetch in django but am getting the below error: First argument to get_object_or_404() must be a Model, Manager, or QuerySet, not 'QuerySet'. this is the query: site = get_object_or_404(SiteData.objects.prefetch_related( Prefetch( 'sitesubnets_set', queryset=SiteSubnets.objects.filter(site_ip=True), ), Prefetch( 'circuits_set', queryset=Circuits.objects.exclude(decommissioned=True).prefetch_related('servicecontacts_set'), ) ), pk=site_id ) if I remove the below, the query works successfully, so I know its related to chaining the prefetches im just not sure why or how to rectify this? .prefetch_related('servicecontacts_set') -
Getting a new ValueError when using manage.py to run a server from cmd
I'm fairly new to Python and I am using a video tutorial on Lynda to help me build the frameworks for a Social WebApp. I'm trying to run the server from the cmd using manage.py, however, I keep running into this error message. CMD PROMPT ERROR Traceback (most recent call last): File "C:\Users\Kelechi\AppData\Roaming\Python\Python35\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\Kelechi\AppData\Roaming\Python\Python35\site-packages\django\core\management\commands\runserver.py", line 121, in inner_run self.check(display_num_errors=True) File "C:\Users\Kelechi\AppData\Roaming\Python\Python35\site-packages\django\core\management\base.py", line 364, in check include_deployment_checks=include_deployment_checks, File "C:\Users\Kelechi\AppData\Roaming\Python\Python35\site-packages\django\core\management\base.py", line 351, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\Kelechi\AppData\Roaming\Python\Python35\site-packages\django\core\checks\registry.py", line 73, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\Kelechi\AppData\Roaming\Python\Python35\site-packages\django\core\checks\urls.py", line 40, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) File "C:\Users\Kelechi\AppData\Roaming\Python\Python35\site-packages\django\core\checks\urls.py", line 57, in _load_all_namespaces url_patterns = getattr(resolver, 'url_patterns', []) File "C:\Users\Kelechi\AppData\Roaming\Python\Python35\site-packages\django\utils\functional.py", line 36, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Kelechi\AppData\Roaming\Python\Python35\site-packages\django\urls\resolvers.py", line 536, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\Kelechi\AppData\Roaming\Python\Python35\site-packages\django\utils\functional.py", line 36, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Kelechi\AppData\Roaming\Python\Python35\site-packages\django\urls\resolvers.py", line 529, in urlconf_module return import_module(self.urlconf_name) File "C:\Users\Kelechi\AppData\Local\Programs\Python\Python35\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 665, in exec_module File "<frozen importlib._bootstrap>", line … -
XML Parsing error: no root element found (empty content) Django
I am using ajax to connect to a view in my web application. $.ajax({ url: url, type: 'PATCH', success: function() { var d = new Date(); img = e.target.parentElement.parentElement.getElementsByTagName('img')[0]; if (img.src.includes("?")){ img.src = img.src.split("?")[0] + '?' + d.getTime(); } else { img.src = img.src + '?' + d.getTime(); } }, }); When I click on the button that triggers this, everything works, but I get an XML Parsing error. According to the other questions on stack exchange, this might be beacuse of an empty content. When I use the firefox developer tools, the content of the reverse of the concerned view is indeed empty, because of which, I think, firefox interprets it as an xml. My problem is, that I do not know how to fill the content. In my view, I changed return Response(status=200) to return Response(status=200, content_type='image/jpeg'), because the view does something to an image. But still the content seems to stay empty and I still get the error. I don't know how else to alter the content type than by specifying it in the response. I only get this error in firefox, not in chrome. -
Django: How can you index images from an object_list in a django template
So basically I wanted to know how you can index images in a django template using a for loop. The idea is to create a slide show using the first three images that you user has adds to the model model.py class Product(models.Model): Name=models.CharField(max_length=120,null=True,blank=True) Category=models.CharField(max_length=80,null=True,blank=True) Image=models.ImageField(null=True,upload_to='Image') Description=models.TextField(null=True,blank=True) Price=models.DecimalField(default=0.00,max_digits=10,decimal_places=2) Delivery_date=models.DateTimeField(null=True,blank=True) Delivered=models.BooleanField(default=False) This is the template but the obj.image.url tag is incomplete as i want only the first three items and not in a loop but listed out {% for obj in object_list%} {%if obj.Image%} <ul class="pgwSlider"> <li><img src="{{obj.Image.url}} "></li> <li><img src="" a></li> <li> <img src='"> <span>Shanghai, China</span> </li> <li> </ul> -
Django: Serializer automatically parse json field and add to common fields
I call serializer: serializer = MySerializer(qs, many=True) when qs - QuerySets for myModel from rest_framework.serializers import Serializer class MySerializer(Serializer): param1 = CharField() param2 = IntegerField(required=False) custom_fields = JSONField() class Meta: pass Next, I just use the custom_fields and get the values manually. Is it possible at this stage to get the fields inside this custom_fields and return them through the serializer? custom_fields contains: { 'custom_value1': 3, 'custom_value2': 5 } -
Celery under supervisor refuse to acknowledge PYTHONPATH. Errors with AttributeError no attribute celery.
I've started to use Celery 4.x after years of using v3.x (Django project). When running locally everything is fine. However on the server when running under supervisor, celerybeat starts ok, but the worker process receives: AttributeError: module 'project' has no attribute 'app' followed by: AttributeError: module 'project' has no attribute 'celery' I believe this is a PYTHONPATH issue and have tried setting the PYTHONPATH in the shell, in the supervisor process config, in supervisord's config, and even in the code itself. Nothing seems to resolve it. I could replicate the issue on the server by running /path/to/venv/bin/celery worker -A project outside of the project directory without PYTHONPATH being set and having it work when it is, but this doesn't seem to work with supervisor. This already shaved hours off my time. - project-dir - project - __init__.py - celery.py - celeryconfig.py - settings.py - otherapp - ... -- # celery.py from __future__ import absolute_import import os from celery import Celery from django.conf import settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings') app = Celery('project') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() -- # __init__.py from __future__ import absolute_import from .celery import app as celery_app __all__ = ['celery_app'] -- `celeryconfig.py` contains the celery and queue configs etc. -- [program:myprogram] process_name=fw%(process_num)s … -
Django in real service, Do I have to set these if else statements to prevent abuse?
EXAMPLE1: def example(request): if request.method=="POST": if request.is_ajax(): #do something EXAMPLE2: def example(request): if request.method=="POST": if request.is_ajax(): #do something else: #do something else: #do something If django project has that above EXAMPLE1 code, even it doesn't have any else: statement like EXAMPLE2, is it okay to run real service? I wonder absense of else: statement will be chance of being abused or some bad things. In real service, Do I have to consider statement almost case of request? -
Data passing from HTML text input to python script
I am creating a web scrapping application, using Django, which scraps the imdb website and lists the movie names based on what users types in the text field[suppose if user types 'b', it lists all the movie names starting with letter 'b'] I have a html text input and a button. <body> <h1>The IMDB Scrapper</h1> <form method="POST" action=""> <input type="text" name="name" placeholder="Iron Man.."> <input type="submit" value="Search"> </form> </body> I also have a python script which scraps the data from the website, using the hardcoded keyword. I want to send the text input data to this python script when the button is pressed and process this data and send send the result hack to the same HTML page for display. -
Django deployment Google App Engine (Flexible)
Google provide a guide how to do this. They have a section on how to run the application locally, together with the Cloud SQL Proxy. Super neat really. So you apply your migrations onto the database hosted on your GCP. Then there is another section how to deploy your application to the cloud. They don't say production, they just say Google App Engine Flexible Which leads me to the question. How do I handle a production environment. I cant seem to find any articles on the topic. Because they can't meen that your suppose to run migrations locally with 'Google SQL Proxy' and then run gcloud app deploy onto a production environment? -
Obtain a client's location coordinates through the browser's geolocation API, or resolve through IP address from the server?
I'm wondering which method to go with for fairly accurate locationing, + scalability and speed. It seems Django's Geoip has a limited number of addresses. And IPs are some times redirected to the ISP generated address. The advantage of using GeoIP would be that I don't have to fiddle around client-side. Would using IP, and relying on Maxmind be a practical hinderance? On the other hand, using the browser's Geolocation API, I believe I can obtain a much more accurate location, but only if it's first "Allow[ed]" by the client. It would then involve sending the coordinates to the backend for further processing using something like Geodjango to resolve the coordinates. What am I missing? Can someone shed some light on the differences? Does it not matter much? -
Mysql: OperationalError at / (1054, "Unknown column '' in 'field list'")
I have made all of my migrations with these commands successfully. python manage.py makemigrations senty python manage.py migrate I end up with this error: django.db.utils.OperationalError: (1054, "Unknown column 'senty_score.points' in 'field list'") To me, it looks like "points" is right there in the class, and it migrated successfully. The most updated pycache has the correct version of the class as well, which was an error before. I wasn't getting an error on this until I changed points from a different function call. Pretty inexperienced to mysql so this is a tough one. Do I have to manually add the column somehow? models.py from django.db import models from datetime import datetime from decimal import Decimal class score(models.Model): ticker = models.CharField(max_length=10) points = models.DecimalField(max_digits=4, decimal_places=1) created_at = models.DateTimeField(default=datetime.now, blank=True) -
How do I extract informations from the user using his/her facebook access token ?
I am doing a Django web app where the user can login using facebook. When the user login, I get a token. I want to use the token to extract and print out the informations the user grants my app without having to paste it in the facebook graph api explorer. How can I do this and integrate it in my django project ? Thanks -
Python / django.db: How to create a generic class without hardcoded Meta.db_table?
I have a class using django.db as follows: from django.db import models class myClass(models.Model): "My class" class Meta: db_table = 'my_table' field1 = models.CharField() # more fields here def some_function(self): return "hello" I'd like to turn this into a generic class that does not have "my_table" hardcoded, so that I can use it in some way such as: class GenericClass(models.Model): class Meta: db_table = None # genericClass properties and methods here class myClass(GenericClass): id = models.CharField(max_length=20) def __init__(self, *args, **kwargs): super(self.__class__, self).Meta.db_table = 'my_table' super(self.__class__, self).__init__(*args, **kwargs) However, this gives me the following error (using Python 2.7 / Django 1.11): Local field u'id' in class 'myClass' clashes with field of similar name from base class 'GenericClass' Is there any way to create a generic class that extends django.db.models.Model, that supports a non-default database table name without hardcoding Meta.db_table? -
steps to configure prometheus metrices with django application
HiI am working on how I can configure Prometheus metrices in my Django-webapplication.I have a script which works fine if i add metrices and scrape it into prometheus but I want to do the same thing in my web-application with Django.Can anyone please guide me -
Django translations - translate days of week
I'm making multilingual website and have a problem in translating days of week So: var day = moment().startOf("week").format('dddd') This is short version. I've tried to use ugettext_lazy (_) - var one = _(moment().startOf("week").format('dddd')) But it doesn't work. full: var days = data.buckets.map(e => moment().startOf('week').day(1 + e.key).format('dddd')) This is d3/c3 format. I'm using days in x-axis in vertical bar chart(maybe it is important:)) I need to translate all day's names. -
Loading templates in Django doesn't work
I have a project that has 3 apps: app1, app2 and app3. In the first two apps I had different templates: app1/templates/app1/page.html app2/templates/app2/anotherpage.html And I load them like this: return render(request, "app1/page.html") It worked perfectly, but now I added app3, and I tried to do the same: app3/templates/app3/config.html but when I return "app3/config.html" I get the error TemplateDoesNotExist I simply created the app doing python manage.py startapp app3 and copy the files to the folder. However, this works: app1/templates/app3/config.html app2/templates/app3/config.html Why it's not working now? -
Basic http authentication asks login credentials for each request in chrome
I am implementing Basic http authentication with Nginx. My website is Django powered website. I am using Django auth as well for user authentication. My default behaviour for website it's checks user is logged in or not. If not returns the 401 status. Now i am trying to implement the http basic auth, it's working but for each request it's asking for login credentials. I am facing this issue in chrome. In firefox it's works fine. satisfy any; auth_basic "Restricted Area"; auth_basic_user_file htpasswd-docdoc; # Allowed IP Address List allow 127.0.0.1; deny all; I don't what wrong i am doing. -
How should I manage url versioning in Django
I have a doubt about the optimal structure of my files. Right now, I have all my urls in a file api.py. The endpoints for a new version of the app are being located in a new api_v2.py file, only the urls that require a new version, is that ok? Also, if a new functionality is added to the app, should I put the new urls directly on api_v2.py? or maybe on the base api.py and keep the api_v2.py for the urls that have a "new version" of themselves? Any advice will help. -
Deploying two different Django Applications on Windows Server in IIS
I am deploying two different Django applications on Windows 2012 in IIS. My first application is running but I can't seem to run my second application. My question is how do I configure my FastCGI Settings if I have two PYTHONPATH and two DJANGO_SETTINGS_MODULE? Do I put a semicolon every after values? For example: NAME: DJANGO_SETTINGS_MODULE VALUE: mysettings.settings;myothersettings.settings NAME: PYTHONPATH VALUE: C:\PythonApps\firstapp;C:\PythonApps\secondapp -
How to get apps url from inside the app's views or templates
I'm working on a FOSS app that the users can assign any url to in their project's urls.py But the problem is the app is setup in such a way that JS need to call the apps root url. The user might have set up any URL like ^forum/?. I need to know this url. Thanks. -
How to pass ID parameter to views.py in CreateView in Django?
I am doing a webapp containing products with a Rating (1-5) functionality. I created an app called rating and I want people to click on a button "rate" on single.html which will direct you to a rating page where people will be rating. The issue here is that I do not know how to pass the product ID to the Rating(CreateList) in views.py. so far Ive done: urls.py urlpatterns = [ url(r'^product/(?P<product_id>\d+)/rating/$', views.RatingView.as_view, name = 'rating'),] models.py class Rating(models.Model): RATING_CHOICES = ( (1, 'Poor'), (2, 'Average'), (3, 'Good'), (4, 'Very Good'), (5, 'Excellent') ) productID = models.ForeignKey(Product, on_delete=models.CASCADE) indRating = models.IntegerField(choices=RATING_CHOICES) def __str__(self): return self.productID views.py class RatingView(CreateView): model = Rating fields = ['productID', 'indRating'] def get_context_data(self, **kwargs): context = super(RatingView, self).get_context_data(**kwargs) context['product_id'] = self.kwargs['product_id'] return context -
How to run a xml file using django localhost
Actually I am learning xml and I want to test my xml file by running it on a localhost . I want to run it on my django localhost server kindly help me in this regard -
Reading from xlsx limited to 65535 rows: openpyxl
When I read from an xlsx file containing more than half million entries. pyopenxl reads only 65535 rows. wb = load_workbook(filename=import_file, read_only=True) ws = wb['Sheetname'] rows = ws.rows # yields upto 65K rows What is confusing is, I have used the same package for the writing operation. I was able to write a million entries to an xlsx file. wb = openpyxl.Workbook() ws = wb.get_active_sheet() ws.cell # Write operations here wb.save(filename=file_path) It will be great if I was able to use the same package for reading and writing. -
Login not working in Django
I'm trying to login but Django is not allowing the navigation to the profile.html This is what I have so far views.py def login(request): if request.method == 'POST': form = UserLoginForm(request.POST) if form.is_valid(): userObj = form.cleaned_data print(userObj) username = userObj['username'] password = userObj['password'] user = authenticate(username=username, password=password) if user is not None: print("in login") login(request) return render(request, 'profiles.html', {'form': form}) else: return render(request, 'login_form.html', {'form': form}) else: return render(request, 'login_form.html') forms.py class UserLoginForm(forms.Form): username = forms.CharField( required=True, label='Username', max_length=32 ) password = forms.CharField( required=True, label='Password', max_length=32, widget=forms.PasswordInput() )