Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Channels wss not connecting received 404 Error
I am attempting to move my server off my local subnet and to a domain. The main webpages are working and I have them behind an SSL. Apache does a rewrite of the url from any HTTP connection to an HTTPS. However when I attempt to connect with javascript from in browser with: new WebSocket("wss://" + window.location.host); I receive the following error: WebSocket connection to 'wss://{MY_WEBSITE}.com/message_route/' failed: Error during WebSocket handshake: Unexpected response code: 404 My config for the settings.py is as follows: "default": { "BACKEND": "asgi_redis.RedisChannelLayer", "ROUTING": "my_app.routing.channel_routing", "Config": { "hosts": [os.environ.get('REDIS_URL', 'redis://127.0.0.0:6379')], } }, I also have a worker running, a redis server set up, and daphne running as well. Please let me know if you can think of any possible solutions to this problem -
Django F field iteration
I created a simple Django model to explore F field but could iterate over the field. class PostgreSQLModel(models.Model): class Meta: abstract = True required_db_vendor = 'postgresql' class NullableIntegerArrayModel(PostgreSQLModel): field = ArrayField(models.IntegerField(), blank=True, null=True) Now, from my django shell I created a F object as below.Not sure what this object contains. Does it contain all the ids? How can I iterate over the result? >>> a=F('id') >>> a F(id) >>> dir(a) ['ADD', 'BITAND', 'BITOR', 'DIV', 'MOD', 'MUL', 'POW', 'SUB', '__add__', '__and__', '__class__', '__delattr__', '__dict__', '__dir__', '__div__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__mod__', '__module__', '__mul__', '__ne__', '__new__', '__or__', '__pow__', '__radd__', '__rand__', '__rdiv__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__ror__', '__rpow__', '__rsub__', '__rtruediv__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__weakref__', '_combine', 'asc', 'bitand', 'bitor', 'desc', 'name', 'resolve_expression'] -
How to modify Django Rest Framework incoming request?
I am building a web app using Django that is pretty much only serving as the API server. I have a single-page application that connects to it as well as an Android client. I have a need to modify some of the incoming POST requests that are coming through. My two use cases: If during the registration process the user does not select an avatar image to upload (which is a simple TextField that is the URL to the image), I should be able to insert the default avatar URL. So something like if request.data["avatar"] is None: <use default> The incoming "timestamp" requests from the Android client are all unix timestamps. I would like to convert this to Django's datetime on the fly - so, current request comes in with date_time = 1473387225, I'd like to convert that to a DateTime object. Now, I'm already doing something similar for certain POST parameters. The way I do it right now is in the post() function of my generic ListCreateApiView I would directly modify the request object and then call the self.create() with that new request object. Is this the right way, or is there a much better way to do it? … -
I use crispy-forms work in django,render failures after the first click the submit button,the second time click the submit button has no response
I am ready to use crispy-froms to my django projection,but in the test,there happen a question,I do not know where happened mistakes.So I post the code here. If someone can point out the mistake,I will appreciate it. forms: class TestForm(forms.ModelForm): name = forms.CharField(widget=forms.TextInput(),label='Name',max_length=100,) def __init__(self,*args,**kwargs): super(TestForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.add_input(Button('save', 'save')) self.helper.form_class = 'form-horizontal' self.helper.label_class = 'col-lg-3' self.helper.field_class = 'col-lg-8' self.helper.form_id = 'pkg-form' class Meta: model = PkgList fields = ( 'id','name', ) urls.py: url(r'^testform/$',test_form,name='test_form') the views in my code: @json_view def test_form(request): if request.method == 'POST'and request.is_ajax(): form = TestForm(request.POST) if form.is_valid(): return {'success': True} else: form_html = render_crispy_form(form) return {'success': False, 'form_html': form_html} else: if request.method == 'GET': form = TestForm() return render(request,'man/pkg_form.html',{'form':form}) templetes: <div class="modal-dialog" xmlns="http://www.w3.org/1999/html"> <div class="modal-content message_align"> <div class="modal-body" align="center"> <span class="section">Pkg Info</span> {% crispy form form.helper%} </div> <div> </div> $('#button-id-save').on('click', function(event){ event.preventDefault(); var form = '#pkg-form'; $.ajax({ url: "{% url 'pkg_view' %}", type: "POST", data: $(form).serialize(), success: function(data) { if (!(data['success'])) { $(form).replaceWith(data['form_html']); }else { window.location.href = "{%url 'man/pkglist' %}"; } }, error: function () { $(form).find('.error-message').show() } }); return false; }); after the first ajax POST and return {'success': False, 'form_html': form_html} from the backend,click the button can not send ajax … -
Django - Click on link won't redirect me to the page unless i right click and open in new tab
I'm fairly new to django and I'm working on a project for some reason clicking on my links won't redirect me to the desired page, nothing happens, but i cant open it bu right click > open in new tab here is my template index.html: <ul class="list"> {% for movie in all_movies %} <li> <img src="{{ movie.poster }}" alt="" class="cover" /> <a href="{% url 'detail' movie.id %}"><p class="title">{{ movie.title }}</p></a> {% for genre in movie.genre.all %} <p class="genre">{{ genre.genre }} | </p> {% endfor %} </li> {% endfor %} </ul> views.py : def detail(request, movie_id): movie = get_object_or_404(Movie, pk=movie_id) return render(request, 'movies/detail.html', {'movie': movie}) urls.py : urlpatterns = [ # /movies/ url(r'^$', views.index, name='index'), # /movies/id/ url(r'^(?P<movie_id>[0-9]+)/$', views.detail, name='detail'), ] i can't find what's wrong with my code, any help would be appreciated! -
Django search as input is entered into form
I currently have a working search form in my project that passes through form data to the GET request. Pretty standard. What I'm wanting to do is search as data is entered into the search form, so that results will display in real time with search data. This is much like what Google does with the instant desktop results. Is this something that's possible with Django? Below is my current (simple) search #views.py def ProductView(request): title = 'Products' all_products = Product.objects.all().order_by("product_Name") query = request.GET.get("q") if query: products = all_products.filter( Q(product_Name__contains=query) | Q(manufacturer__contains=query) ).distinct() return render(request, 'mycollection/details.html', { 'all_products' : products }) - <!-- HTML --> <!-- SEARCH BAR --> <form class="navbar-form navbar-left" role="search" method="get" action="{% url 'mycollection:products' %}"> <div class="form-group"> <input type="text" class="form-control" name="q" value="{{ request.GET.q }}"> </div> <button type="submit" class="btn btn-default">Search</button> </form> -
Testing Django inline formset (getting duplicate items)
I have an inline formset (TranslationFormSet), which edits all the translations associated with a particular Sense. It seems to be working well, both when adding new translations and editing existing ones. However, my unittests[1] are failing, because there are two items where there should be one: i.e., the edited item is a new item, and the old item is still there. This is only happening in the the tests, the actual form on the website is behaving as expecting. So it must be something wrong with how I've written the tests, but I can't figure out what. I modeled it largely off the Django docs section on inline formsets. Here are the test and failure: def test_edit_sense_successfully_edits_translations(self): # set up required related objects e = Entry.objects.create(hw='فحص') p = PartOfSpeech.objects.create(pos=1, entry=e) s = Sense.objects.create(number=1, pos=p, entry=e) t = Translation.objects.create(tr='test') # submit edited data through the form self.client.post('/edit_sense/%d/%d/' % (p.id, s.id), { 'number': 2, 'pos': p, 'entry': e, 'translation_set-0-id': t.id, 'translation_set-0-tr': 'test1', 'translation_set-TOTAL_FORMS': '3', 'translation_set-INITIAL_FORMS': '1', }) sense = Sense.objects.first() self.assertEquals(sense.translation_set.count(), 1) # passes self.assertEquals(Translation.objects.count(), 1) # fails ====================================================================== FAIL: test_edit_sense_successfully_edits_translations (dict.tests.add_sense_tests.EditSensePageView) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/larapsodia/dict/dev/dict/tests/add_sense_tests.py", line 181, in test_edit_sense_successfully_edits_translations self.assertEquals(Translation.objects.count(), 1) AssertionError: 2 != 1 What am … -
How can I show realtime text analysis of a Django form Textarea (models.TextField)?
OK, so I have a model class Recipe and a form class AddRecipeForm that is based on Recipe (via forms.ModelForm). The form shows up in my html template and works, but I want to implement a special type of form validation. Basically, I want to do some text processing on some big text input fields. I have code that figures out where all the amounts (numbers) in the ingredient text are, and identifies and classifies all the units (e.g. 'lbs.', 'gr', etc...). --> I'd love to be able to basically have a text-box right by the side of the form in add_recipe.html that performs this text processing (via highlighting, bold, etc) in real time. However, I'm really not sure how to do it. I've been reading about doing real-time form validation via AJAX, jquery, or maybe just django's ModelForm.clean() method, but I'm not sure which would be best or where to start. Any pointers / suggestions would be awesome! Here's my (simplified) code: models.py class Recipe(models.Model): recipe_name = models.CharField(max_length=128, default='') description = models.CharField(max_length=1024) ingredients_text = models.TextField(max_length=2048*2) instructions_text = models.TextField(max_length=2048*4) forms.py class AddRecipeForm(forms.ModelForm): class Meta: model = Recipe fields = '__all__' add_recipe.py (html template) sidenote: I'm using the materialize framework, so … -
Maintain the queryset object through http requests
I have an use case that is completed in 3 screens. In the first screen, the user sees a list of objects and can apply some dynamic filters. He can add rules like: "phone_number contains 85" "phone_number doesn't contains 9" "name is equals to Fabio" After user clicks in apply filters button, i refresh the screen and show only the objects that match the rules. In the same screen i have actions like admin actions in django admin where i can update a list of objects. If the user selects 3 objects, i pass the 3 IDs to the second screen. But i would like to update 250k rows at once, so my idea is to pass the filters to the second screen to mount the queryset again. Is there an easy way to maintain the queryset object from one page to another ? If i could put the select of the queryset inside a html field to read it and create a django queryset object again it would be great. Any better ideas ? -
How do I authenticate users with Django REST framework and React.js frontend?
I am making a website with django rest in the backend and react.js in the frontend. This will be my first time using a front end framework with django. I am using django-allauth for social auth on the backend (facebook/twitter/google). Once the user is signed in through a web session (using allauth) via a 3rd party provider (facebook) how do I pass that data to my react app? Do I grab the facebook token, authenticate it, then generate an oauth2/jwt token and store that somehow? Is there some boilerplate/code that will save me time on this. I don't want to reinvent the wheel here. Many thanks! -
Show queryset fields in DJango template, where 'values' are used to make some joins
I have the next queryset: fotosslide=IndexHasFotografia.objects.filter(index_idindex=infoindex,ubicacion_fotografiaindex=0).values('fotografia_idfotografia__pk','fotografia_idfotografia__ruta_fotografia','fotografia_idfotografia__nombre_fotografia') And I'm trying to access to the values in the template in this way: <img src="{{ fotosslide.fotografia_idfotografia__ruta_fotografia }}"> But nothing shows, I have checked the database and all the data is there, I have checked the webpage code but the string isn't there. I don't know if when values are used, the fields must be called in other way in the template? I have displayed images in other templates, but using Django forms, or JSON, so that is not the problem, because I don't even get the image route. Also I have tried with pure strings, not with images, and nothing is shown too. -
Best Practices when using JSON to update DB
I am working on an API for my first web app, a scheduling system, with Django on the back end. Shifts are sent to the front end in a single JSON object (schedule), that contains shift objects. This object can then be modified by the front end and sent back to have the server update the database according to any changes in the JSON object. My question: is it better to use "marker" properties, such as {... "delete": true...} and {... "new": true...} within the shift objects to let the server know what has changed, or should the back end figure it out on its own by comparing the incoming data to existing data? The first option seems to me to allow for fewer database queries, while the second option seems more robust (i.e. it does not depend on the front end to properly tag its changes). Also, as this is my first attempt at web dev, any related recommendations or criticisms are encouraged. -
Django Admin Page Doesn't show CSS properly
My Admin page CSS of my Django project is not working properly. When I go to localhost:8000/admin I get this visual: The settings.py code: Static files (CSS, JavaScript, Images) https://docs.djangoproject.com/en/1.10/howto/static-files/ STATIC_URL = '/static/' STATICFILES_FINDERS = ( "django.contrib.staticfiles.finders.FileSystemFinder", #"django.contrib.staticfiles.finders.AppDirectoriesFinder" ) STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) When I run the command './manage.py collectstatic' I get this message: Traceback (most recent call last): File "./manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/guilhermenoronha/.local/lib/python2.7/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/home/guilhermenoronha/.local/lib/python2.7/site-packages/django/core/management/__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/guilhermenoronha/.local/lib/python2.7/site-packages/django/core/management/base.py", line 305, in run_from_argv self.execute(*args, **cmd_options) File "/home/guilhermenoronha/.local/lib/python2.7/site-packages/django/core/management/base.py", line 356, in execute output = self.handle(*args, **options) File "/home/guilhermenoronha/.local/lib/python2.7/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 193, in handle collected = self.collect() File "/home/guilhermenoronha/.local/lib/python2.7/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 124, in collect handler(path, prefixed_path, storage) File "/home/guilhermenoronha/.local/lib/python2.7/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 337, in copy_file if not self.delete_file(path, prefixed_path, source_storage): File "/home/guilhermenoronha/.local/lib/python2.7/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 255, in delete_file if self.storage.exists(prefixed_path): File "/home/guilhermenoronha/.local/lib/python2.7/site-packages/django/core/files/storage.py", line 394, in exists return os.path.exists(self.path(name)) File "/home/guilhermenoronha/.local/lib/python2.7/site-packages/django/contrib/staticfiles/storage.py", line 49, in path raise ImproperlyConfigured("You're using the staticfiles app " django.core.exceptions.ImproperlyConfigured: You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path. If I insert the variable STATIC_ROOT to my project I get this message: Traceback (most recent call last): File "./manage.py", line 22, in <module> execute_from_command_line(sys.argv) File … -
Can't set Select widget value from database Python
I have a form wizard that I have another URL that allows a user to edit the form, populating it with data in the database. It seems to work fine for all CharFields, but will the change the selected, (value) of the CharField with forms.Select() widget to reflect the value. All other form rows in the form set are populated correctly. output of the dict to be returned resources dict: [ { 'res_details': u'Sniper Rifle', 'res_justification': u'Shooting', 'res_task': <Task: Obtain Sniper Rifle>}, { 'res_details': u'Vantage Point', 'res_justification': u'Succeeding', 'res_task': <Task: Shoot her>}] Notice in the second row, the select box is not reflecting the respective 'res_task': <Task: Shoot her> and is instead just defaulting to the first index. models.py class Resources_Required_Form(forms.Form): res_details = forms.CharField(required=True) res_justification = forms.CharField(required=True,) res_task = forms.CharField( required=True, widget=forms.Select() ) wizard.py def get_form_initial(self, step): .. elif step == 'deliverable': project_id = self.kwargs['project_id'] project = Project.objects.get(pro_id=project_id) deli_dict = [{ 'deli_description': d.deli_description } for d in Deliverable.objects.filter(project=project)] print "deliverables dict:" pp.pprint(deli_dict) print "----" return deli_dict .. -
Angular JS convert 2 dim JSON in django
I have a 2 dimensional JSON which I want to translate to a html table. Something like this: http://www.bogotobogo.com/AngularJS/AngularJS_Tables.php I heard about serializing (ng-compile) but is that not a bit to much work for this? And how will it work? [{"model": "pricing.cashflow", "pk": 1, "fields": {"value": 4.0, "date": "2016-09-09"}}, {"model": "pricing.cashflow", "pk": 2, "fields": {"value": 3.0, "date": "2016-09-01"}}, {"model": "pricing.cashflow", "pk": 3, "fields": {"value": 3.0, "date": "2016-09-01"}}, {"model": "pricing.cashflow", "pk": 4, "fields": {"value": 3.0, "date": "2016-09-01"}}, {"model": "pricing.cashflow", "pk": 5, "fields": {"value": 3.0, "date": "2016-09-01"}}, {"model": "pricing.cashflow", "pk": 6, "fields": {"value": 5.0, "date": "2016-09-07"}}, {"model": "pricing.cashflow", "pk": 7, "fields": {"value": 3.0, "date": "2016-09-28"}}, {"model": "pricing.cashflow", "pk": 8, "fields": {"value": 3.0, "date": "2016-09-22"}}, {"model": "pricing.cashflow", "pk": 9, "fields": {"value": 5.0, "date": "2016-09-16"}}, {"model": "pricing.cashflow", "pk": 10, "fields": {"value": 5.0, "date": "2016-09-16"}}, {"model": "pricing.cashflow", "pk": 11, "fields": {"value": 4.0, "date": "2016-09-08"}}, {"model": "pricing.cashflow", "pk": 12, "fields": {"value": 8.0, "date": "2016-09-22"}}, {"model": "pricing.cashflow", "pk": 13, "fields": {"value": 3.0, "date": "2016-09-22"}}, {"model": "pricing.cashflow", "pk": 14, "fields": {"value": 5.0, "date": "2016-09-01"}}, {"model": "pricing.cashflow", "pk": 15, "fields": {"value": 8.0, "date": "2016-09-01"}}, {"model": "pricing.cashflow", "pk": 16, "fields": {"value": 4.0, "date": "2016-09-08"}}, {"model": "pricing.cashflow", "pk": 17, "fields": {"value": 5.0, "date": "2016-09-09"}}, {"model": "pricing.cashflow", "pk": 18, "fields": {"value": 5.0, … -
How to add comment to post on this same site?
i created blog and possibility to comment every post. But now i have it on two different sites. On page with post i have link to my comment form and there i create comment. Is that possible to add form to this post site? So i would like to have post_detail, form to add new comment and comments on one this same site. Now i have only post and comments. views.py: def comment_new(request, pk): post = get_object_or_404(Post, pk=pk) if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.save() return redirect(post_detail, pk=post.pk) else: form = CommentForm() return render(request, 'blog/post_detail.html', {'form': form}) template: post_detail.html (part with comment stuff): <a class="btn btn-default" href="{% url 'comment_new' pk=post.pk %}">Add comment</a> {% for comment in post.comments.all %} {{ comment.created_date }} <strong>{{ comment.author }}</strong> {{ comment.text }} {% endfor %} comment_new.html <form method="POST">{% csrf_token %} {{ form.as_p }} <button type="submit" class="save btn btn-default">Send</button> </form> urls.py: url(r'^post/(?P<pk>[0-9]+)/$', views.post_detail, name='post_detail'), url(r'^post/(?P<pk>[0-9]+)/comment/$', views.comment_new, name='comment_new'), -
Setting Django DateRangeField parameters
I need to track people in their current positions. So in my model I can do: tenure = models.DateRangeField(‘date of hire’, ‘date of termination’) but what about someone who is currently still employed? Can I do: tenure = models.DateRangeField(‘2006-10-10’, datetime.date.today()) or tenure = models.DateRangeField(‘2006-10-10’, [)) ? Then when this person terminates, I can change the value on the instance to a date certain, but will that cause a problem because the model field expects a function? Eventually I am going to have to query against this date range, which is why I was looking at the new DateRangeField, but maybe I'd be better off with two plain date fields, one for start and one for termination? -
Set foreign key constraint to IMMEDIATE in django model
I have a model with a ForeignKey to another table like so: class AModel(models.Model): created = models.DateTimeField(default=now) name = models.CharField(max_length=200, unique=True) category = models.ForeignKey('BModel', blank=True, null=True, to_field='category_id') class BModel(models.Model): category_id = models.IntegerField(unique=True) is_production = models.BooleanField(default=False) my intention for adding the ForeignKey to AModel was to ensure that one could not add a row of data to AModel unless the category_id was in BModel. But it does not appears to be working? My thought was it had somehting to do with the default constraint django adds: DEFERRABLE INITIALLY DEFERRED in which case how would I modify this in the AModel and is that actually the issue or have I just misunderstood the constraint set by django? -
get value of dinstinct object for select field in django form
I have the following 3 relationships: class Size(models.Model): amount = models.IntegerField(default=0) unit = models.CharField(max_length=64) created_at = models.DateTimeField(auto_now_add = True) updated_at = models.DateTimeField(auto_now = True) def __str__(self): return str(self.amount) + ' ' + self.unit + ' size' class Sku(models.Model): product = models.ForeignKey(Product) size = models.ForeignKey(Size) style = models.ForeignKey(Style) price = models.DecimalField(max_digits=8, decimal_places=2) created_at = models.DateTimeField(auto_now_add = True) updated_at = models.DateTimeField(auto_now = True) def __str__(self): return self.product.name class ProductImage(models.Model): product = models.ForeignKey(Product) title = models.CharField(max_length=128, blank=True, null=True) image = models.ImageField(upload_to='products', blank=True, null=True) created_at = models.DateTimeField(auto_now_add = True) updated_at = models.DateTimeField(auto_now = True) def __str__(self): return self.product.name I want to show all the sizes that are foreign keys of skus as choices in a model form. I tried this: class SkuForm(forms.ModelForm): def __init__(self, *args, **kwargs): product = kwargs.pop('product', None) super(SkuForm, self).__init__(*args, **kwargs) skus = product.sku_set.all() self.fields['size'].queryset = Size.objects.filter(sku__in=skus).values('amount', 'unit').distinct() quantity = forms.IntegerField() class Meta: model = Sku fields = ('size',) This puts the following values in my dropdown menu for "size": {'amount':5, 'size':'cups'} How can I have it show simply: "5 cups"? -
Prevent Django from appending domain to beginning of URLs in RSS feeds
I'm creating an RSS feed that contains application links for the URLs, but Django is prepending the domain name to any link that doesn't begin with http. So, URLs that should be appname:// are ending up as domain.nameappname... How do I prevent this from happening? -
Django form creates new instance instead updating a existing one
I've seen this question asked a lot of time here but I can't figure out why it doesn't work in my case. I have the following view code: def edit(request, coffee_id=None): coffee = get_object_or_404(Drink, pk=coffee_id) if coffee_id else Drink() if request.method == 'POST': form = CoffeeForm(request.POST, instance=coffee) if form.is_valid(): form.save() return HttpResponseRedirect(urlresolvers.reverse('coffee:index')) else: form = CoffeeForm(instance=coffee) return render(request, 'edit.html', {'coffee_form': form}) This is supposed to create a new instance of coffee or to update a new one if coffee_id given in argument exists in database. However even if coffee_id exists in database a new instance of coffee is always created. I also tried to save the coffee instance without saving the form but it does the same. Is there something that i'm doing wrong ? Should I set something special in the model to allow update ? -
django forms how to add attributes to individual form field in template
I'm trying to customise the rendering of a form: for a form with a field: {{ form.password1 }} how can I get that to become something like: <input id="signup-password" type="password" class="form-control login-password" placeholder="Password"> Note: I don't have control of the form (as it's a form in django allauth) -
Converting stdout stream to html (add <br> on linebreaks)
I'm trying to take some console output text and render it through django/js in a modal on my site. When printing the console output the line breaks work fine, but when rendered on the site it shows them all as one line. I tried replacing all the \n with < br> but it didn't seem to have any effect. Any thoughts on a better way to do this/why this isn't working in the first place? import sys from io import StringIO # Save the old stdout old_stdout = sys.stdout # Save the stdout to variable sys.stdout = mystdout = StringIO() ... # Do some processing that generates console text # Reset the to the old stdout sys.stdout = old_stdout # Get the stdout processing_std_out = mystdout.getvalue() # Replace all the linebreaks with <br> # This is the important part processing_std_out = processing_std_out.replace("\n","<br>") # return HttpResponse(json.dumps({'console_output':processing_std_out}), content_type="application/json") The js is this: input_modal.find('.modal-body').text('Analysis complete'+response.console_output) -
Django bulk_create a list of lists
As the title indicates, is there a way to bulk_create list of lists. Like right now I bulk_create it like - for i in range(len(x)) arr1 = [] for m in range(len(y)): arr1.append(DataModel(foundation=foundation, date=dates[m], price=price[m])) DataModel.objects.bulk_create(arr1) Now this will bulk create till the length of x. Can it be done like so - arr = [] for i in range(len(x)) arr1 = [] for m in range(len(y)): arr1.append(DataModel(foundation=foundation, date=dates[m], price=price[m])) arr.append(arr1) DataModel.objects.bulk_create(arr) If not, what else can be done to store data faster? -
In pycharm can I run every file for django?
I'm new to Django. My localhost site is running fine. Since I am using pycharm it is easy to run any file. I decided to run each file in my django project, and came across several errors, such as this one in my views.py: django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. Even though the site is running, what seems like properly, I'm seeing this message. What is causing this, and is it typical?