Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Controller do download a static file
I have a controller in my web app like this: def all_trials(request): return HttpResponseRedirect(URL_TO_XML_IN_STATIC) How can I change my code to controller have the feature to download the and not open the file in my web browser? -
Uploading files on Elastic beanstalk using django
I have a django app and its migrated to the Elastic Beanstalk (AWS), But I cant see any media files on the server. I tried uploading my files using FileField and ImageField but the server doesnt render any of the images uploaded. -
Is it possible to manually render varying groups of forms per row without using Formset?
I'm trying to render a different number of forms per row, and I haven't been able to figure out if I can do that using Formset, but with normal forms it seems pretty simple. Is it possible to have a unique set of forms without using a Formset or is it possible to accomplish what I'm trying to do with Formset? -
ClassBased Views not Working properly i.e not showing(Django)
Thanks in advance. :) This is the code that is not shown on the browser, also no error is arising. Thanks once again :)! -
Django Wiki - URL Include Circular Reference Error
I have installed Django Wiki (https://github.com/django-wiki/django-wiki) via pip on Windows 10 Professional. The installed python version is 3.6.2. I am currently receiving the following error during server startup when running 'manage.py runserver': Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x000001BD23F6DE1A> Traceback (most recent call last): File "Documents\Projects\Documentation\venv\lib\site-packages\django\urls\resolvers.py", line 408, in url_patterns iter(patterns) TypeError: 'module' object is not iterable During handling of the above exception, another exception occurred: Traceback (most recent call last): File "Documents\Projects\Documentation\venv\lib\site-packages\django\utils\autoreload.py", line 229, in wrapper fn(*args, **kwargs) File "Documents\Projects\Documentation\venv\lib\site-packages\django\core\management\commands\runserver.py", line 125, in inner_run self.check(display_num_errors=True) File "Documents\Projects\Documentation\venv\lib\site-packages\django\core\management\base.py", line 360, in check include_deployment_checks=include_deployment_checks, File "Documents\Projects\Documentation\venv\lib\site-packages\django\core\management\base.py", line 347, in _run_checks return checks.run_checks(**kwargs) File "Documents\Projects\Documentation\venv\lib\site-packages\django\core\checks\registry.py", line 82, in run_checks new_errors = check(app_configs=app_configs) File "Documents\Projects\Documentation\venv\lib\site-packages\django\core\checks\urls.py", line 17, in check_url_config return check_resolver(resolver) File "Documents\Projects\Documentation\venv\lib\site-packages\django\core\checks\urls.py", line 27, in check_resolver return check_method() File "Documents\Projects\Documentation\venv\lib\site-packages\django\urls\resolvers.py", line 256, in check warnings.extend(check_resolver(pattern)) File "Documents\Projects\Documentation\venv\lib\site-packages\django\core\checks\urls.py", line 27, in check_resolver return check_method() File "Documents\Projects\Documentation\venv\lib\site-packages\django\urls\resolvers.py", line 255, in check for pattern in self.url_patterns: File "Documents\Projects\Documentation\venv\lib\site-packages\django\utils\functional.py", line 36, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "Documents\Projects\Documentation\venv\lib\site-packages\django\urls\resolvers.py", line 415, in url_patterns raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) django.core.exceptions.ImproperlyConfigured: The included URLconf '<module 'wiki.urls' from 'Documents\\Projects\\Documentation\\venv\\lib\\site-packages\\wiki\\urls.py'>' does not appear to have any patterns in it. If you see valid patterns in the file then the … -
CSV Parse + Upload Django ( Error: can't concat bytes to InMemoryUploadedFile)
I parse a CSV and when I try to save it, I get the error 'TypeError: can't concat bytes to InMemoryUploadedFile'. upload_obj = UploadField(csv=True) csv_upload = request.FILES.get('uploads', None) csv_parsed = csv.reader(codecs.iterdecode(csv_upload, 'utf-8'), delimiter=',') [parse loop then...] try: upload_obj.save(request=request, content_list=csv_upload) except Exception as e: print('Error:', e) I get the error when attempting to save. -
Import error - AppRegistryNotReady
I keep getting same error when I try to import User from django.contrib.auth.models, or any other model class from django. I installed Python 3.7, made new virtualenv and this is full traceback of the error: (trytest) C:\Users\User\Desktop\trytest\Scripts\trytest>python Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> from django.contrib.auth.models import User Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Users\Marin\Desktop\trytest\lib\site- packages\django\contrib\auth\models.py", line 2, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "C:\Users\Marin\Desktop\trytest\lib\site- packages\django\contrib\auth\base_user.py", line 47, in <module> class AbstractBaseUser(models.Model): File "C:\Users\Marin\Desktop\trytest\lib\site- packages\django\db\models\base.py", line 100, in __new__ app_config = apps.get_containing_app_config(module) File "C:\Users\Marin\Desktop\trytest\lib\site- packages\django\apps\registry.py", line 244, in get_containing_app_config self.check_apps_ready() File "C:\Users\Marin\Desktop\trytest\lib\site- packages\django\apps\registry.py", line 127, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. This is just test project i installed to see if I will have same problem with clean installation. Virtualenv is active. Is the problem with Python, or Django, I can't find anything useful online. -
TypeError: __init__() got an unexpected keyword argument 'many'
While trying to return a query-set using generic views, I get an error TypeError: init() got an unexpected keyword argument 'many' I am unable to understand the source of this error as it seems to be originating from internal libraries. I have no clue as to why this error originated as the create API works just fine. Complete StackTrace System check identified 1 issue (0 silenced). July 16, 2018 - 13:25:43 Django version 1.11.7, using settings 'BirthdayPostStash.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. <QuerySet [<Photos: 1>, <Photos: 2>, <Photos: 3>, <Photos: 4>, <Photos: 5>, <Photos: 6>, <Photos: 7>, <Photos: 8>, <Photos: 9>, <Photos: 10>, <Photos: 11>, <Photos: 12>]> Internal Server Error: /photos/list-photo/ Traceback (most recent call last): File "/home/t2b/env/bpstash/local/lib/python2.7/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/home/t2b/env/bpstash/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/t2b/env/bpstash/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/t2b/env/bpstash/local/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view return view_func(*args, **kwargs) File "/home/t2b/env/bpstash/local/lib/python2.7/site-packages/django/views/generic/base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "/home/t2b/env/bpstash/local/lib/python2.7/site-packages/rest_framework/views.py", line 489, in dispatch response = self.handle_exception(exc) File "/home/t2b/env/bpstash/local/lib/python2.7/site-packages/rest_framework/views.py", line 449, in handle_exception self.raise_uncaught_exception(exc) File "/home/t2b/env/bpstash/local/lib/python2.7/site-packages/rest_framework/views.py", line 486, in dispatch response = handler(request, *args, **kwargs) File "/home/t2b/env/bpstash/local/lib/python2.7/site-packages/rest_framework/generics.py", line … -
How to store an array of model objects in postgresql?
I tried to use the ArrayField from the django.contrib.postgres.fields to store an array of a model class that I created, as shown below: class Pricing(models.Model): begin = models.FloatField() end = models.FloatField() price_per_unit = models.FloatField() class Product(models.Model): name = models.CharField(max_length=200) unit = models.CharField(max_length=50) pricing = fields.ArrayField(Pricing) However, I'm getting this error AttributeError: type object 'Pricing' has no attribute 'set_attributes_from_name'. I consulted the doc page and it mentioned that the base_field must be a subclass of field. Does that mean I can't use ArrayField in my case? If so, what's the best way to store my product pricing info ? -
TypeError: 'NHKEasyNews' object does not support indexing Django
I don't really understand this error code. Python is showing me that it's happening on this line for items in data[0][dates]: , but I don't see anything wrong with this statement. In fact it works perfectly fine on python, and also when I comment out the following code and replace it with a print statement: data = NHKEasyNews(title=items['title'], title_with_ruby=items['title_with_ruby'], source_url=items['news_web_url']) data.save() The above code is making a new object in my database. It works for all the entries published on the same date, but as soon as it goes to the next date it gives me the above error code. I tried searching SO but the examples make me even more confused. If possible ELI5 please. Models.py class NHKEasyNews(models.Model): title = models.CharField(max_length=250) title_with_ruby = models.CharField(max_length=250) source_url = models.URLField(max_length=120, null=True, blank=True) def __str__(self): return self.title Views.py import json import requests def scrape_nhk_easy(request): r = requests.get('https://www3.nhk.or.jp/news/easy/news-list.json') data = json.loads(r.text) for dates in data[0]: for items in data[0][dates]: data = NHKEasyNews(title=items['title'], title_with_ruby=items['title_with_ruby'], source_url=items['news_web_url']) data.save() return HttpResponse("Finished") -
How to refresh a table in Django, without using Ajax/jQuery for that
I want to refresh a particular table of a HTML page in Django, but I don't want to use Ajax/jQuery for that. The data in table comes from database. In my case, Django application with SQLite database. The table need to be refreshed every 1hour. Is there any way I can achieve this? If yes, then how? -
Django Deployment on Heroku migration issue: Related model 'door.Product' cannot be resolved
I'm trying to deploy a Django app on heroku. Everything has worked perfectly until I ran the command heroku run python manage.py migrate. When I ran this command, I got an error saying: ValueError: Related model 'door.Product' cannot be resolved PS: When I run my server locally, everything works perfectly fine. Please help me if you know the answer to my problem! -
Django duplicate key exception on an empty table
I have these models: Account: class Account(models.Model): account_id = id_field.PrimaryIDField() name = models.CharField(max_length=100) created = models.DateTimeField(_("date joined"), auto_now_add=True, editable=False) modified = models.DateTimeField(_("date modified"), auto_now=True) User: class User(auth_models.AbstractBaseUser): user_id = id_field.PrimaryIDField() email = models.EmailField(_("email address"), unique=True, blank=False, db_index=True) created = models.DateTimeField(_("date joined"), auto_now_add=True, editable=False) modified = models.DateTimeField(_("date modified"), auto_now=True) class Meta: verbose_name = _("user") verbose_name_plural = _("users") AccountUser: I try to create a many to many relation between a user and an account with the following entity: class AccountUser(approve_delete_model.ApproveDeleteModel): account = models.ForeignKey(Account, on_delete=models.CASCADE) user = models.ForeignKey("User", on_delete=models.CASCADE) created = models.DateTimeField(_("date joined"), auto_now_add=True, editable=False) modified = models.DateTimeField(_("date modified"), auto_now=True) class Meta: verbose_name = _("account user") verbose_name_plural = _("account users") ordering = ["account", "user"] unique_together = (("user", "account"), ) When calling AccountUser.objects.all() the result is <QuerySet []> (which allegedly means the DB is empty) Then I picked the first user and first account as follows: account = Account.objects.all()[0] user = User.objects.all()[0] Both account and user are now populated with a valid value. I then try to create the relation between them as follows: AccountUser.objects.create(account=account, user=user) But then I get an integrity exception: duplicate key value violates unique constraint "app_accountuser_user_id_account_id_ase17b5v_uniq" DETAIL: Key (user_id, account_id)=(cc9d26c9-b6d7-4d0f-b68b-8f80178a64aa, 7978c6b3-9c40-458b-bcb2-8e4ad3092929) already exists. How is that possible to violate a … -
Print sql queries in jupyter notebook with django-extensions plugin
Is it possible to show SQL queries like in this command: python manage.py shell_plus --print-sql but in Jupyter Notebook? I tried this command python manage.py shell_plus --notebook --print-sql but it not worked. -
Routing error using Wagtail v2 with Django v1.11
Can't seem to find anything on this so far, I'm guessing I have something misconfigured somewhere. I have a pre-existing Django app and am trying to use Wagtail to add a blog in. I have installed as per the instructions and I can access the default landing page so it seems to be installed however I'm stuck with the below error when attempting to access the admin for it and am not sure how to proceed. Guessing its something to do with not defining namespaces somewhere, the Wagtail docs say that its compatible with Django v1.11 but their integration documentation is for Django v2 specifically and is using re_path etc. 'wagtailadmin_api_v1' is not a registered namespace My main project urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^blog/', include('blog.urls', namespace='blog')), url(r'^taggit_autosuggest/', include('taggit_autosuggest.urls')), url(r'^autocomplete/', include(ac_urls, namespace='ac')), url(r'^', include('website.urls', namespace='website')), ] My blog app's urls.py (which is fresh from a "python manage.py startapp blog") from django.conf.urls import url, include from wagtail.admin import urls as wagtailadmin_urls from wagtail.documents import urls as wagtaildocs_urls from wagtail.core import urls as wagtail_urls app_name = 'blog' urlpatterns = [ url(r'^cms/', include(wagtailadmin_urls)), url(r'^documents/', include(wagtaildocs_urls)), url(r'', include(wagtail_urls)), ] When I attempt to access localhost:8000/blog/ I get the default wagtail landing page, if … -
How can I pass a list of values from a django template to a django view function?
I have a django template viewreports.html which prints some results based on calculation done in a view function view_reports. But I have added a button to download csv to the template. Upon clicking the button I want to pass the result values from viewreports.html to another view function getcsvreport where the csv is generated. I'm unable to pass lists through the url. Can someone explain how I can pass multiple variables(some of them lists) from a template to a view function(through the url or any other method)?? -
Variable context between two blocks in Django templates?
I have two blocks that call the same method with same variables. I want to call the method only once, but the result is then outsite the scope of the block tags. I've tried calling this method in the parent template header.html and with a with tag, but nothing seems to work. This is the layout: {% extends "header.html" %} {% load navigation_tags %} {% block header %} {% get_section site=site as section %} {% include "foobar.html" with section=section %} {% endblock header %} {% block navigation %} <nav> <div class="container"> {% get_section site=site as section %} {% navigation section.slug %} </div> </nav> {% endblock navigation %} -
TypeError: 'str' object is not callable python3
def SaveRoles(request): if 'user_name' in request.session: if request.method == "POST": user_roles = request.POST['user_roles'] user_permission_level = request.POST['user_permission_level'] user_role_code = request.POST['user_role_code'] code = user_roles(user_roles=user_roles, user_permission_level=user_permission_level, user_role_code=user_role_code) print("qqqqqq", code) try: model_status = code.save() except Exception as e: print("exception occured", e) return render(request, 'administrator/add_role.html', {'message': 'Oops some error occured'}) if model_status == None: role = user_roles.objects.all() return HttpResponseRedirect('http://'+request.get_host()+'/admin/role-list/',{'message': 'Role added successfully','code': code}) else: return HttpResponseRedirect('http://'+request.get_host()+'/admin/role-list/') else: return HttpResponseRedirect('/admin/') When I am running this function I got the TypeError: 'str' object is not callable I searched all my code and I don't even use the word str anywhere in my project But I cant figure out the error -
Generate an auto-increment uniqueID number in the template
simpleMDE has an amazing function to autosave text, I use it to render the form when creating an new article, var simplemde = new SimpleMDE({ autosave: { enabled: true, uniqueId: "AutoSaveID", delay: 1000, }, }); It's uniqueID should be unique, I solved the problem by importing the numbers of articles from views, the extra querying is just for producing an number, #in the views, articles = Article.objects.all() render().... #in the template var uniqueID = {{ articles.count | add: 1}} All the cumbersome jobs is to generate a reasonable unique number. How could I generate an auto-increment number in template with javascript? -
django- store the request on each button click in a queue accessible by all the views
I would like to create a queue in django views.py that can be accessed by all the functions in views.py. The items to the queue are added by a function in views.py when a call(by a button click) is triggered by jquery to the url referred by this function. I have implemented a global list right now but that doesn't seem to be working. I am also not sure if the views.py gets loaded everytime one of the function is called inside because if that is the case, global variables won't work anyway. I have something like below right now in views.py- request_queue = [] def add_request(request, s): global request_queue if request.method == 'GET': request_queue.append(s) logger.info(request_queue) return JsonResponse({'request added': s}) any suggestions how I should approach? -
checkout after registration in saleor cms
Somebody can help me, actually i'm try to go on checkout page after registration but @saleor redirect on on the cart empty page. but i want my cart data to be added after registration. Flow of my process is: Add item in cart do registration redirect on shipping address page But instead of above it redirect me on cart empty page. Please help me i'm stuck at this stage. -
Ignore Where Clause if condition variable is null
I am using output of html into my django code, if it is null I want mysql query to ignore where clause and if it has value, use in query. below is my html: <form method="post" novalidate> {% csrf_token %} <input type="text" name="param1" placeholder="param1"> <input type="text" name="param2" placeholder="param"> <input type="text" name="param3" placeholder="param3"> <input type="submit" name="fetchdata" value="Fetch Data"> <br> </form> How it is possible in MySQL : def current_cfg(request): if request.POST.get("fetchdata"): param1=request.POST["param1"] param2=request.POST["param2"] <----aaaa from html as input param3=request.POST["param3"] else: RNC='RRRNCH02' MO='CORRMALGOSWITCH' parameterid='DRASWITCH_DRA_VOICE_SAVE_CE_SWITCH' conn=db.connect(host='localhost', user='update_db', passwd='1qaz!QAZ', db='rnc_parameters')c=conn.cursor() c=conn.cursor() c.execute("""select * from rnc_parameters.current_para where (if param1 is null ignore it else param1='aaaaa')""") current_stats=c.fetchall() conn.close() current_stats=list(current_stats) return render(request,'current.html',{'current_stats':current_stats, 'MO':MO}) can you help me with to correctly define below part : c.execute("""select * from rnc_parameters.current_para where (if param1 is null ignore it else param1='aaaaa')""") -
What is the best method to transfer data between a django server and a client app
Based on what I could find on the web, there are several ways to transfer data between server and client machines. my goal is to transfer data from the client (which is made using xamarin) to the server (Django) and then stored in a database and then sent back to the client and other client apps as well. my first decision was to use JSON to transfer data but then I read that the Django rest framework was a better option. I'm not entirely sure where to start and what sort of technologies will be fully supported on both sides. I would also like to be able to send and receive images so I want to use a technology that supports it. thanks in advance. -
postgis dont work with django
DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME':'agricom', 'USER':'postgres', 'HOST':'localhost', 'PASSWORD':'put', 'PORT':'5433', } } this error isn't an available database backend. Try using 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'sqlite3' -
How to expose Django-Constance settings via Django Rest Framework?
I am building a project in which I need to have a few custom settings that are editable by certain users which do not have access to the django admin panel, who access the application via an Angular frontend. I installed django-constance in order to have these custom settings editable, as it was the most recommended package I could find on the Django packages site. My problem now is that I do not know how to do to serve the settings on my API rest. I started with some customized view: class ConstanceSettingSerializer(serializers.Serializer): name = serializers.CharField() value = serializers.Field() defult_value = serializers.Field() modified = serializers.BooleanField(read_only=True) from constance import settings as constance_settings class ConstanceView(APIView): def get(self, request): settings = constance_settings.CONFIG.items() return Response(settings, status=status.HTTP_200_OK) But now I dont know how to pass those settings correctly to my serializer. I tried this without success: settings_serializer = ConstanceSettingSerializer(settings) return Response(settings_serializer.data, status=status.HTTP_200_OK) And I am only getting errors. Some idea how to do this properly? Thanks!