Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Push to heroku: no module named 'channels'
I am facing this error when I add 'channels' into INSTALLED_APPS Writing objects: 100% (4/4), 351 bytes | 0 bytes/s, done. Total 4 (delta 3), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Python app detected remote: -----> Installing requirements with latest Pipenv… remote: Installing dependencies from Pipfile.lock (36121f)… remote: -----> $ python manage.py collectstatic --noinput remote: Traceback (most recent call last): remote: File "manage.py", line 10, in <module> remote: execute_from_command_line(sys.argv) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line remote: utility.execute() remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 337, in execute remote: django.setup() remote: File "/app/.heroku/python/lib/python3.6/site- packages/django/__init__.py", line 27, in setup remote: apps.populate(settings.INSTALLED_APPS) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/apps/registry.py", line 85, in populate remote: app_config = AppConfig.create(entry) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/apps/config.py", line 94, in create remote: module = import_module(entry) remote: File "/app/.heroku/python/lib/python3.6/importlib/__init__.py", line 126, in import_module remote: return _bootstrap._gcd_import(name[level:], package, level) remote: File "<frozen importlib._bootstrap>", line 978, in _gcd_import remote: File "<frozen importlib._bootstrap>", line 961, in _find_and_load remote: File "<frozen importlib._bootstrap>", line 948, in _find_and_load_unlocked remote: ModuleNotFoundError: No module named 'channels' remote: remote: ! Error while running '$ python manage.py collectstatic --noinput'. remote: See traceback above for details. remote: remote: You may need to update application code to resolve this error. … -
mod_wsgi-express: error: no such option: --url-alias
I'm deploying an application with mod_wsgi-express, and I've a new error when launching the service : oct. 12 09:15:29 Angara mod_wsgi-express[12284]: Usage: mod_wsgi-express start-server script [options] oct. 12 09:15:29 Angara mod_wsgi-express[12284]: mod_wsgi-express: error: no such option: --url-alias /static /var/www/agenda-v3.example.tld/static --url-alias /media /var/www/agenda-v3.example.tld/media The mod_wsgi-express application fails to launch... I've added the --log-directory directive to route logs to the ${SERVER_PATH}/log, which works great (I can read the log files now), I've checked the /var/www/agenda-v3.example.tld/media and /var/www/agenda-v3.example.tld/static directories, they exist for now. Service file: https://gist.github.com/frague59/a7701073d50e77e4b5492c72157ebfab Service environment file: https://gist.github.com/frague59/2992e3b02e5d40a1b5a6f0a508a73f4a Have you any idea ? It worked before... Thanks for your help ! -
Django test: how to compare result of resolve() with view function when login_required is specified for that view
In urls.py i have my view detail annotated with login_required to forward unauthorised users to login page: url(r'^(?P<id>[0-9]+)/$', login_required(views.detail), name = 'detail') And i'm trying to write a test to check which view are selected on querying target url. I've a class to log in before tests start off: class LoggedInTestCase(TestCase): def setUp(self): user = User.objects.create_user('test', 'test@example.com', 'test') self.client.login(username='test', password='test') class ProductDetailTest(LoggedInTestCase): def setUp(self): super(ProductDetailTest, self).setUp() def test_product_detail_url_resolves_product_detail_view(self): view = resolve('/products/1/') self.assertEquals(view.func, detail) and when i run tests i got: FAIL: test_product_detail_url_resolves_product_detail_view (products.tests.ProductDetailTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "D:\heroku\django\products\tests.py", line 46, in test_product_detail_url_resolves_product_detail_view self.assertEquals(view.func, detail) AssertionError: <function detail at 0x05CC3780> != <function detail at 0x053B38A0> ---------------------------------------------------------------------- When i remove login_required all tests pass well. -
Use the template of another django app in an another app
I have two django apps. One which belongs to core code and one contrib app. What I need to do is to display a template in my contrib app, which actually exists already in the core app. This is more or less the folder structure: django project core app templates ... contrib app templates -template_from_core_app The template renders data from views and forms which exist in the core app. I am wondering what is the best way to do something like this. -
Connect to remote ElasticSearch Server using Haystack
I am using to django-Haystack to connect to remote elasticsearch, but the haystack is looking for local installation of the elastic-server. How to use haystack with remote elastic server These are my config HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'haystack.backends.elasticsearch2_backend.Elasticsearch2SearchEngine', 'URL': 'http://xx.xx.xx.xx:9200', 'INDEX_NAME': 'my-index', } } -
how to pass {% csrf_token %} in javascript which is returning a html form
function GetDynamicTextBox(value){ return '<form id="addtextbox" name="addtextbox" method="post">'+ '<div class="col-xs-4">'+ '<label for="ex3">Enter Alertname</label>'+ '<input class="form-control" id="userInput" type="text" name="alertname1" placeholder="Enter the alerts..">'+ '<br>'+ '<i class="fa fa-cloud" aria-hidden= "true"></i>'+ ' <input type="submit" class="btn btn-success" value="Save">'+ '</div>'+ '</form>' } It is throwing an error csrf token missing but even I include ''+'{% csrf_token %}' it is throwning an error.Please guide me in this -
python django restful api - can't always catch a specific post request
I am using python Django restful api framework. I am trying to catch all the userPreference post requests in views.py. For some reason I can catch all the post request with my code. Here is my views.py class aUserViewSet(aAPIViewSet): def get_queryset(self): ''' This function limits the queryset to User's data ''' queryset = super(aUserViewSet, self).get_queryset() qs1 = queryset.filter(user=self.request.user) if qs1.exists(): if "userpreference" in qs1.model._meta.db_table: tp = self.ws_userPreference(qs1, self.request.user.username) else : print("no handle needed") else : print("qs1 not exist") return queryset.filter(user=self.request.user) def ws_userPreference(self, qs1, username): if self.request.method == 'POST': print("get userPreference post") else : print("get userPreference non post request") return 0 class UserPreferenceViewSet(aUserViewSet): queryset = UserPreference.objects.all() print "In userPreference viewset" serializer_class = UserPreferenceSerializer filter_fields = ('activationResponse','startTimeForDecisionChoice', 'endTimeForDecisionChoice', 'valueScale1', 'valueScale2', 'valueScale3', 'valueScale4', 'decisionPreference', 'waypointsCompleted', 'numberOfSessionsToDecisionChoice','created', ) filter_backends = (URLFilter, ) ordering_fields = ('activationResponse','startTimeForDecisionChoice', 'endTimeForDecisionChoice', 'valueScale1', 'valueScale2', 'valueScale3', 'valueScale4', 'decisionPreference', 'waypointsCompleted', 'numberOfSessionsToDecisionChoice','created', ) -
upstream prematurely closed while reading response header from upstream, reques: "GET / HTTP/1.1", upstream: "uwsgi://unix:///tmp/web.sock:"
upstream prematurely closed connection while reading response header from upstream, client: xxx.xx.xx.xx, server: website.com, request: "GET / HTTP/1.1", upstream: "uwsgi://unix:///tmp/web.sock:", host: "website.com" How to solve this? -
Error Setting Up Frontend Login in django marcador tutorial
I am a newbie using django 1.11.5 installed.This a tutorial from macador app project.I have already created the view in thhe project main template.my login and logout is not working.When i run the runserver command,I get the following error. terminal Performing system checks... Unhandled exception in thread started by <function wrapper at 0x7f087adf5aa0> Traceback (most recent call last): File "/root/Desktop/bookmarksmanager/myenv/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/root/Desktop/bookmarksmanager/myenv/local/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run self.check(display_num_errors=True) File "/root/Desktop/bookmarksmanager/myenv/local/lib/python2.7/site-packages/django/core/management/base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "/root/Desktop/bookmarksmanager/myenv/local/lib/python2.7/site-packages/django/core/management/base.py", line 346, in _run_checks return checks.run_checks(**kwargs) File "/root/Desktop/bookmarksmanager/myenv/local/lib/python2.7/site-packages/django/core/checks/registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "/root/Desktop/bookmarksmanager/myenv/local/lib/python2.7/site-packages/django/core/checks/urls.py", line 16, in check_url_config return check_resolver(resolver) File "/root/Desktop/bookmarksmanager/myenv/local/lib/python2.7/site-packages/django/core/checks/urls.py", line 26, in check_resolver return check_method() File "/root/Desktop/bookmarksmanager/myenv/local/lib/python2.7/site-packages/django/urls/resolvers.py", line 254, in check for pattern in self.url_patterns: File "/root/Desktop/bookmarksmanager/myenv/local/lib/python2.7/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/root/Desktop/bookmarksmanager/myenv/local/lib/python2.7/site-packages/django/urls/resolvers.py", line 405, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/root/Desktop/bookmarksmanager/myenv/local/lib/python2.7/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/root/Desktop/bookmarksmanager/myenv/local/lib/python2.7/site-packages/django/urls/resolvers.py", line 398, in urlconf_module return import_module(self.urlconf_name) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/root/Desktop/bookmarksmanager/myenv/src/mysite/urls.py", line 27, in <module> name='mysite_login'), File "/root/Desktop/bookmarksmanager/myenv/local/lib/python2.7/site-packages/django/conf/urls/__init__.py", line 85, in url raise TypeError('view must be a callable or a list/tuple in the case of include().') TypeError: view … -
save google autocomplete places data in a model which has foreign key
I have a form in django where there is a field called address where I am using https://github.com/ubilabs/geocomplete/ plugin so which when submitted should store address in fields like country, city, postal_code etc instead of giving user to fill all those fields in restaurant object along with other data. This one is working well class Restaurant(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, related_name='restaurant' ) name = models.CharField(max_length=500) country = models.CharField(max_length=7) city = models.CharField(max_length=7) postal_code = models.CharField(max_length=7) class RestaurantForm(forms.ModelForm): class Meta: model = Restaurant widgets=({country: forms.HiddenInput(attrs={'id': country}), city: forms.HiddenInput(attrs={'id': locality}), postal_code: forms.HiddenInput(attrs={'id': postal_code})}) fields = ( "logo", "name", "cuisine", "country", "city", "postal_code", "address", "phone" ) def restaurant_sign_up(request): user_form = UserForm() restaurant_form = RestaurantForm() if request.user.is_authenticated(): if request.method == "POST": restaurant_form = RestaurantForm(request.POST, request.FILES) if restaurant_form.is_valid(): new_restaurant = restaurant_form.save(commit=False) new_restaurant.user = request.user new_restaurant.save() return redirect(restaurant_order) else: if request.method == "POST": user_form = MemberForm(request.POST) restaurant_form = RestaurantForm(request.POST, request.FILES) if user_form.is_valid() and restaurant_form.is_valid(): new_user = User.objects.create_user(**user_form.cleaned_data) new_restaurant = restaurant_form.save(commit=False) new_restaurant.user = new_user new_restaurant.save() login(request, authenticate( username=user_form.cleaned_data["username"], password=user_form.cleaned_data["password"] )) return redirect(restaurant_order) return render(request, "restaurant/sign_up.html", { "user_form": user_form, "restaurant_form": restaurant_form }) <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {% if user.is_anonymous %} {% bootstrap_form user_form %} {% bootstrap_form restaurant_form %} {% else %} Hello, {{ request.user.username }} <br>Please … -
Add filter by year in Django admin
I have a Django model with DateTimeField field as "created_at", now I want to add a filter for that field in Django admin but I need only the year field instead of default fields as (today, past 7 days, this month, this year). Here's my model: In models.py class TaggedArticle(models.Model): user = models.ForeignKey(User, related_name='tagging') email = models.EmailField(max_length=255) category_fit = models.CharField(choices=choices, max_length=255) article = models.ForeignKey(Article, related_name='articles') link = models.URLField(max_length=255,) relevant_feedback = models.TextField(blank=True) category = models.CharField(max_length=255,) created_at = models.DateTimeField(default=timezone.now, editable=False) I have tried to override created_at field in admin.py as: class TaggedArticle(admin.ModelAdmin): fields = ['category_fit', 'article', 'link', 'relevant_feedback', 'category', 'user', 'email', 'created_at'] list_display = ['article_id', 'link', 'user', 'created_at'] list_filter = ['user', 'email', 'created_at'] model = Tagged def created_at(self, obj): return self.Tagged.created_at.year admin.site.register(Tagged, TaggedArticle) But it doesn't work. How can I achieve that? Help me, please! Thanks in advance! -
How to Make an Non-Database Auto-Attribute to a Django Model Instance
Sometimes, we save some fields that change a lot to Redis or other backends. But in that way, we could lose the convenience of getting a value from an instance by article.count. We usually set a property function to a model, which performs the logic of querying the memory based database. class WhatEver(models.Model): @property def some_field(self): return redis.hget('what-ever-%s' % self.id) def set_some_field(self, value): return redis.hset('what-ever-%s' % self.id, value) Ugly, but useful. But, it doesn't work all the time, as it's an intrusive way to bring us the ability. Say, we want to get a user's visits, We actually want to call user.visits, But it's not good for a submodule to overwrite the base module, so we can only wrap it as a function get_user_visits(user) and again, not elegant. Do we have a way to do this kind of tricks automatically and non-intrusively? -
How to do database migration using python script?
is it possible to do migration from python script? I am trying to use django on Heliohost where there is no shell but I can use python script. something like from django import shell shell.main(['mysite/manage.py', 'migrate']) -
Foreign Key "automatic column lookup" in Django
Consider the following models: class Book(models.Model): id = models.AutoField(primary_key=True) title = models.CharField(max_length=255) publisher = models.ForeignKey('Publisher') class Publisher(models.Model): id = models.AutoField(primary_key=True) publisher_name = models.CharField(max_length=255) I would like to call Book.objects.filter(id=123), but the output for this should be: { 'id':123, 'title':'ABC', 'publisher':1 } for admin users, and { 'id': 123, 'title':'ABC', 'publisher':'XYZ Books' } for normal users. My question is, can this be done with select_related() or changing the models.ForeignKey() parameters only? -
Using ModelFormMixin without the 'fields' attribute is prohibited
I'm using Django 1.11 I have created a Form and using Class based view to create a record and save to database. Business/models.py class BusinessType(models.Model): title = models.CharField(max_length=100) created = models.DateTimeField('date created', auto_now_add=True) modified = models.DateTimeField('last modified', auto_now=True) class Meta: db_table = 'business_types' def __str__(self): return self.title class Business(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=200) business_type = models.ForeignKey(BusinessType, on_delete=models.CASCADE) created = models.DateTimeField('date created', auto_now_add=True) modified = models.DateTimeField('last modified', auto_now=True) class Meta: verbose_name = 'business' verbose_name_plural = 'businesses' db_table = 'businesses' def __str__(self): return self.name Business/Forms.py class BusinessForm(ModelForm): class Meta: model = Business fields = ['user'] Business/views.py class BusinessCreate(LoginRequiredMixin, CreateView): model = Business form = BusinessForm def form_valid(self, form): messages.success(self.request, 'form is valid') form.instance.user = self.request.user form.save() def get_success_url(self): messages.success(self.request, 'Business Added Successfully') return reverse('business:list') On loading template of BusinessCreate it gives error as Using ModelFormMixin (base class of BusinessCreate) without the 'fields' attribute is prohibited. My Trials After moving fields to views class, it is working fine. But I don't want to do so, as I may be using this form on multiple views and thus will require changes on multiple pages in future if needed. -
Django CMS placeholder content not showing up on page when i log out from the admin
i'm having trouble with placeholders Django-CMS.I have used placeholders all over my templates of my existing project and they seem to work just fine when i'm logged in, i can add and edit plugins but when i log out all the edits don't show up on the templates anymore.what might be causing this?considering i have followed the placeholder creation procedure and published all my changes? Considering the following scenario where i have {% placeholder "feature" %} on my template, the plugin is visible on the page and editable but the content only shows up on the website page when i'm logged in. -
Django Book tree base model
I'd like to know if is possible to do a book base model. Every category has many subcategories with the same name. For ex: Book 1 has seccion 1, seccion 2, etc. Every seccion chapter 1, chapter 2 and so on. wich is the best way to do the structure? -
Django Models - Lists vs One-to-Many
I have two models, Audience and Reports, that I want to relate. The Audience model has one set of ids that reference a particular instance of an audience while the reports have a separate set of codes that relate to a particular instance of an audience. On top of that each report is associated with multiple Audience. Am still pretty new to Django but just ashamedly rusty with setting up database models. In my current solution I create a third model AudienceReportMapping which just relates the audience_id to the report_code. I have a class method on Reports which uses the intermediate mapping table to get me the appropriate audience ids for the codes associated with each report. Everything relevant is set up like so: from django.db import models from django_mysql import ListTestField class Audience(models.Model): ... id = models.IntegerField() class AudienceReportMapping(models.Model): audience = models.ForeignKey(Audience) report_code = models.IntegerField() class Reports(models.Model): ... report_id = models.IntegerField() codes = ListTextField( base_field=models.IntegerField() ) @classmethod def audience_ids(cls, report_id): report = Reports.objects.filter(report_id=report_id).first() codes = report.codes audience_ids = [] for code in codes: audience = AudienceReportMapping.objects.filter(report_code=code).first().audience audiences_ids.append(audience.id) return audience_ids This feels like a pretty inelegant solution to something thats been solved before, just have trouble getting my head around … -
Adding functionality dynamically to Django app
I have a requirement to be able to extend a Django app dynamically. For example, the app should be able to list all .py files in a particular directory, and using a well-defined interface, call any of the functions in any of these .py files. Another requirement is that power users should be able to just drop a new .py file in the specified directory, and it should become visible to all users. I looked here, here and here, but none of the approaches allows me to load an arbitrary file - perhaps because I am using Python 3.6 (Django 1.11) and these approaches are deprecated. The following code is working fine: def show_modules(request): listOfNames = os.listdir( os.path.dirname( os.path.dirname(os.path.abspath(__file__)) + OPS_DIR)) where OPS_DIR is defined in settings.py as a relative path to the project (but could be a shared folder elsewhere). The variable listOfNames does get populated with the list of files in the particular directory. An example of the type of files would be: def do_operation(one, two): return one + two def description(): return "This just adds a couple of numbers. Provide two parameters." I want to be able to (a) list all the .py files available in the … -
save address from google autocomplete to an object
I have a form in django where there is a field like address, country, city, postal_code etc. I want to use this https://github.com/ubilabs/geocomplete/ plugin so which when submitted should store address in fields like country, city, postal_code etc instead of giving user to fill all those fields in restaurant object along with other data. Here is what I have tried class Restaurant(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, related_name='restaurant' ) name = models.CharField(max_length=500) country = models.ForeignKey(Country, related_name='restaurant_country') city = models.ForeignKey(City, related_name='restaurant_city') postal_code = models.CharField(max_length=7) address = models.CharField(max_length=500) class RestaurantForm(forms.ModelForm): class Meta: model = Restaurant # fields = ( # "logo", "name", "cuisine", "country", "city", "postal_code", # "address", "phone" # ) #instead of above i switched to this fields = ( "logo", "name", "cuisine", "phone" ) views.py def restaurant_sign_up(request): user_form = UserForm() restaurant_form = RestaurantForm() if request.user.is_authenticated(): if request.method == "POST": restaurant_form = RestaurantForm(request.POST, request.FILES) if restaurant_form.is_valid(): new_restaurant = restaurant_form.save(commit=False) new_restaurant.user = request.user new_restaurant.save() return redirect(restaurant_order) else: if request.method == "POST": user_form = MemberForm(request.POST) restaurant_form = RestaurantForm(request.POST, request.FILES) if user_form.is_valid() and restaurant_form.is_valid(): new_user = User.objects.create_user(**user_form.cleaned_data) new_restaurant = restaurant_form.save(commit=False) new_restaurant.user = new_user new_restaurant.save() login(request, authenticate( username=user_form.cleaned_data["username"], password=user_form.cleaned_data["password"] )) return redirect(restaurant_order) return render(request, "restaurant/sign_up.html", { "user_form": user_form, "restaurant_form": restaurant_form }) template <form method="POST" enctype="multipart/form-data"> … -
ImportError: cannot import name 'BlobService' when using Azure Backend
I followed these instructions to set up Azure as my backend service: http://django-storages.readthedocs.io/en/latest/backends/azure.html Also added additional packages per this document: https://docs.microsoft.com/en-us/azure/storage/blobs/storage-python-how-to-use-blob-storage Getting this error: Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/storages/backends/azure_storage.py", line 23, in <module> from azure.storage.blob.blobservice import BlobService ModuleNotFoundError: No module named 'azure.storage.blob.blobservice' .... File "/usr/local/Cellar/python3/3.6.2/Frameworks/Python.framework/Versions/3.6/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 978, in _gcd_import File "<frozen importlib._bootstrap>", line 961, in _find_and_load File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 655, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed File "/usr/local/lib/python3.6/site-packages/storages/backends/azure_storage.py", line 26, in <module> from azure.storage import BlobService ImportError: cannot import name 'BlobService' [12/Oct/2017 01:38:00] "POST /upload HTTP/1.1" 500 18034 My pip3 freeze looks like so: (venv) Mikes-MacBook:drhazelapp mikebz$ pip3 freeze | grep azure azure==2.0.0 azure-batch==3.0.0 azure-common==1.1.8 azure-datalake-store==0.0.17 azure-graphrbac==0.30.0 azure-keyvault==0.3.7 azure-mgmt==1.0.0 azure-mgmt-authorization==0.30.0 azure-mgmt-batch==4.0.0 azure-mgmt-cdn==0.30.3 azure-mgmt-cognitiveservices==1.0.0 azure-mgmt-compute==1.0.0 azure-mgmt-containerregistry==0.2.1 azure-mgmt-datalake-analytics==0.1.6 azure-mgmt-datalake-nspkg==2.0.0 azure-mgmt-datalake-store==0.1.6 azure-mgmt-devtestlabs==2.0.0 azure-mgmt-dns==1.0.1 azure-mgmt-documentdb==0.1.3 azure-mgmt-iothub==0.2.2 azure-mgmt-keyvault==0.31.0 azure-mgmt-logic==2.1.0 azure-mgmt-monitor==0.2.1 azure-mgmt-network==1.0.0 azure-mgmt-nspkg==2.0.0 azure-mgmt-rdbms==0.1.0 azure-mgmt-redis==4.1.0 azure-mgmt-resource==1.1.0 azure-mgmt-scheduler==1.1.3 azure-mgmt-sql==0.5.3 azure-mgmt-storage==1.0.0 azure-mgmt-trafficmanager==0.30.0 azure-mgmt-web==0.32.0 azure-nspkg==2.0.0 azure-servicebus==0.21.1 azure-servicefabric==5.6.130 azure-servicemanagement-legacy==0.20.6 azure-storage==0.34.3 azure-storage-blob==0.37.0 azure-storage-common==0.37.0 azure-storage-file==0.37.0 azure-storage-nspkg==2.0.0 msrestazure==0.4.14 -
Django Forms (File Upload)
I have a form in my Django project that lets users upload images only if they Png, jpeg of gif but if any other file is uploaded it wont accept the file but neither will it give an error saying wrong file uploaded. Is there any function that can be used to perform this? -
Image which is made by using matplotib is cracked
Image which is made by using matplotib is cracked. I wanna show graph's image which is made by using matplotib in index.html. I wrote in views.py def view_plot(request): left = np.array([1, 2, 3, 4, 5]) height = np.array([100, 200, 300, 400, 500]) plt.bar(left, height) response = HttpResponse(content_type="image/png") image.save(response, "PNG") return response def index(request): return render(request, 'index.html') in index.html(accounts is app name) <body> <header> <h1>WEB SITE</h1> </header> <img src='/accounts/view_plot' width=300 height=300> </body> index.html is shown in browser,but image is creacked like Why does this happen?I think url directory is wrong but I cannot think another url. How should I fix this?By using Google console,500 error happens.Is this way which use matplotlib in views.py and make image wrong? -
Django Hello World web app on a Windows Server VM
Good Evening, I am trying to setup hello world app on azure cloud. I am following the tutorial Django hello world web app on windows server vm After doing all the set up when I navigate to the http://localhost/ I get following error Error occurred while reading WSGI handler: Traceback (most recent call last): File "c:\users\compUser\appdata\local\programs\python\python36\lib\site-packages\wfastcgi.py", line 791, in main env, handler = read_wsgi_handler(response.physical_path) File "c:\users\compUser\appdata\local\programs\python\python36\lib\site-packages\wfastcgi.py", line 633, in read_wsgi_handler handler = get_wsgi_handler(os.getenv("WSGI_HANDLER")) File "c:\users\compUser\appdata\local\programs\python\python36\lib\site-packages\wfastcgi.py", line 605, in get_wsgi_handler handler = handler() File "c:\users\compUser\appdata\local\programs\python\python36\lib\site-packages\django\core\handlers\wsgi.py", line 151, in init self.load_middleware() File "c:\users\compUser\appdata\local\programs\python\python36\lib\site-packages\django\core\handlers\base.py", line 81, in load_middleware middleware = import_string(middleware_path) File "c:\users\compUser\appdata\local\programs\python\python36\lib\site-packages\django\utils\module_loading.py", line 20, in import_string module = import_module(module_path) File "c:\users\compUser\appdata\local\programs\python\python36\lib\importlib__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 994, in _gcd_import File "", line 971, in _find_and_load File "", line 955, in _find_and_load_unlocked File "", line 665, in _load_unlocked File "", line 678, in exec_module File "", line 219, in _call_with_frames_removed File "c:\users\compUser\appdata\local\programs\python\python36\lib\site-packages\django\contrib\auth\middleware.py", line 4, in from django.contrib.auth.backends import RemoteUserBackend File "c:\users\compUser\appdata\local\programs\python\python36\lib\site-packages\django\contrib\auth\backends.py", line 4, in from django.contrib.auth.models import Permission File "c:\users\compUser\appdata\local\programs\python\python36\lib\site-packages\django\contrib\auth\models.py", line 4, in from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "c:\users\compUser\appdata\local\programs\python\python36\lib\site-packages\django\contrib\auth\base_user.py", line 52, in class AbstractBaseUser(models.Model): File "c:\users\compUser\appdata\local\programs\python\python36\lib\site-packages\django\db\models\base.py", line 110, in new app_config = apps.get_containing_app_config(module) File "c:\users\compUser\appdata\local\programs\python\python36\lib\site-packages\django\apps\registry.py", line … -
Querying related data from a Django model with 2 or more degrees of separation
Suppose I have the following Django models: class Client(models.Model): name = models.CharField(max_length=250) class Staff(models.Model): name = models.CharField(max_length=250) class Agent(models.Model): staff = models.ForeignKey(Staff, on_delete=models.CASCADE) class Writer(models.Model): staff = models.ForeignKey(Staff, on_delete=models.CASCADE) class Order(models.Model): client = models.ForeignKey(Client, on_delete=models.CASCADE) agent = models.ForeignKey(Agent, on_delete=models.CASCADE) writer = models.ForeignKey(Writer, on_delete=models.CASCADE) The relationship between the models have the following conditions: Each order may only have one client Each order may only have one agent Each order may only have one writer A client may have multiple orders An agent may have multiple orders A writer may have written multiple orders Given these models and parameters, how can I get a list of all agents or all writers who have worked with a specific client in the past? I somehow need to query from [Client] > [All Orders] > [Agent per Order] using Python/Django.