Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I want to add a iCal to my Djano site
I am building a website for a client for his vacation homes. He currently uses multiple vacation home sites to list his homes. Each site links to his iCalendar and if someone books a date it shows across all sites. What I want to know is the best approach to adding a iCal to my Django framework and linking it to a form so users can message him about available dates. Appreciate any direction. -
Exceptions in django stop the flow?
in my view I am executing this piece of code: try: activeterm = LeaseTerm.objects.get(lease=lease, is_active = True) except LeaseTenant.DoesNotExist: activeterm = None And I expected there will be no value in LeaseTerm I will get exception but I am getting an error: LeaseTerm matching query does not exist. But I expected that I have handled the exception and flow should continue. What is my miss understanding? -
How to match an url with argument type url -django
Example: url('ajax/(?P<url>w+)','views.ajax') but this is failing to match.please help me -
RelatedObjectDoesNotExist - in clean function of the model
I have model @with_author class Lease(CommonInfo): version = IntegerVersionField( ) is_renewed = models.BooleanField(default=False) unit = models.ForeignKey(Unit) is_terminated = models.BooleanField(default=False) def __unicode__(self): return u'%s %i %s ' % ("lease#", self.id, self.unit) def clean(self): model = self.__class__ if self.unit and (self.is_active == True) and model.objects.filter(unit=self.unit, is_terminated = False , is_active = True).count() == 1: raise ValidationError('Unit has active lease already, Terminate existing one prior to creation of new one or create a not active lease '.format(self.unit)) and I have a form class LeaseForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(LeaseForm, self).__init__(*args, **kwargs) self.fields['unit'].required = True class Meta: model = Lease fields = [ 'unit', 'is_active','is_renewed', 'description'] and each time a save this form without selecting value for unit I am getting error RelatedObjectDoesNotExist from my clean function in model since there is no self.unit but I am explicitly validating the unit field.(at least i believe so) what am I doing wrong? -
Can not import models.UUIDField and other Django methods in deployment
I'm deploying my Django 1.9.8 project on a debian server. I'm repeatedly facing errors because django can not import some methods and packages. For example first it could not import slugify by following expression: from django.utils.text import slugify but then I checked it in django shell, and I saw no errors. After changing that to: from django.utils import text I could use text.slugify in my views. Now I'm facing new issue, which tells me: "'module' object has no attribute 'UUIDField'" but again in shell I can define a variable using models.UUIDField with no errors. Any idea why this is happening? -
Using MariaDB with Django 1.10 and Python 3.5
I want to migrate my database from SQLite to MariaDB. Running Ubuntu 14.04, Django 1.10 and Python 3.5. Digital Ocean has a guide, but it silent assumes one is using Python 2.x, not 3.x. They use the default mySQL connector, MySQLdb. This does not work for python 3.x. According to Django docs, the preferred alternative is mysqlsclient: pip install mysqlclient But this gives: Collecting mysqlclient Using cached mysqlclient-1.3.9.tar.gz Building wheels for collected packages: mysqlclient Running setup.py bdist_wheel for mysqlclient ... error Complete output from command /django/env/bin/python3.5 -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-3_5btd8o/mysqlclient/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" bdist_wheel -d /tmp/tmp39x31avopip-wheel- --python-tag cp35: running bdist_wheel running build running build_py creating build creating build/lib.linux-x86_64-3.5 copying _mysql_exceptions.py -> build/lib.linux-x86_64-3.5 creating build/lib.linux-x86_64-3.5/MySQLdb copying MySQLdb/__init__.py -> build/lib.linux-x86_64-3.5/MySQLdb copying MySQLdb/compat.py -> build/lib.linux-x86_64-3.5/MySQLdb copying MySQLdb/converters.py -> build/lib.linux-x86_64-3.5/MySQLdb copying MySQLdb/connections.py -> build/lib.linux-x86_64-3.5/MySQLdb copying MySQLdb/cursors.py -> build/lib.linux-x86_64-3.5/MySQLdb copying MySQLdb/release.py -> build/lib.linux-x86_64-3.5/MySQLdb copying MySQLdb/times.py -> build/lib.linux-x86_64-3.5/MySQLdb creating build/lib.linux-x86_64-3.5/MySQLdb/constants copying MySQLdb/constants/__init__.py -> build/lib.linux-x86_64-3.5/MySQLdb/constants copying MySQLdb/constants/CR.py -> build/lib.linux-x86_64-3.5/MySQLdb/constants copying MySQLdb/constants/FIELD_TYPE.py -> build/lib.linux-x86_64-3.5/MySQLdb/constants copying MySQLdb/constants/ER.py -> build/lib.linux-x86_64-3.5/MySQLdb/constants copying MySQLdb/constants/FLAG.py -> build/lib.linux-x86_64-3.5/MySQLdb/constants copying MySQLdb/constants/REFRESH.py -> build/lib.linux-x86_64-3.5/MySQLdb/constants copying MySQLdb/constants/CLIENT.py -> build/lib.linux-x86_64-3.5/MySQLdb/constants running build_ext building '_mysql' extension creating build/temp.linux-x86_64-3.5 x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -g -fstack-protector --param=ssp-buffer-size=4 -Wformat -Werror=format-security -D_FORTIFY_SOURCE=2 -fPIC -Dversion_info=(1,3,9,'final',1) -D__version__=1.3.9 -I/usr/include/mysql … -
Django page not found 404, Raised by: blog.views.blog_postDetailView
sometimes when i want to open the about page, the contact, create or blog page this error comes: Raised by: blog.views.blog_postDetailView i donnt know why, but I think it has to do sth with my urlpattterns or the order of them . here my code. appreciate your help and improvements thanks a lot mainurl from django.conf.urls import url, include from django.contrib import admin from django.conf import settings from django.conf.urls.static import static from blog.views import AboutPageView, ContactPageView, blog_postCreateView urlpatterns = [ url(r'^about/', AboutPageView.as_view(), name='about'), url(r'^contact/', ContactPageView.as_view(), name='contact'), url(r'^create/', blog_postCreateView.as_view(), name='blog_post_create'), url(r'', include('blog.urls')), url(r'^blog/', include('blog.urls')), #admin and login url(r'^admin/', admin.site.urls), url(r'^accounts/', include('registration.backends.default.urls')), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) blog url from django.conf.urls import url from .views import blog_postListView, blog_postDetailView, blog_postCreateView urlpatterns = [ url(r'^$', blog_postListView.as_view(), name='blog_post_list'), url(r'^(?P<slug>[-\w]+)$', blog_postDetailView.as_view(), name='blog_post_detail'), ] base html, the nav part <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav"> <li> <a href="/">Home</a> </li> <li> <a href="{% url 'about' %}">About</a> </li> <li> <a href="{% url 'contact' %}">Contact</a> </li> <li> <a href="/blog">Blog</a> </li> <li> {% if request.user.is_authenticated %} <li><a href="{% url 'auth_logout' %}">Logout</a></li> {% else %} <li><a href="{% url 'auth_login' %}">Login</a></li> <li><a href="{% url 'registration_register' %}">Register</a></li> {% endif %} model rom __future__ import unicode_literals from django.conf … -
Is it possible to create steam trading bot in Python?
I'm building website in Django where i will definitely need to use a trading bot, unfortunately, i couldn't find any good libraries that would do a job. ( Smiley's SteamAPI didn't have that feature ). Now i am trying to build my custom one, and i still don't understand how could i possibly do some things, is it even possible to be done in Python? I did find some code, but did not understand it quite well. The normal explanation is big, so code example is way more easily explainable: # Note: This code is example, it doesn't work. import mechanize import cookielib import steamapi from multiprocessing import Process from time import sleep br = mechanize.Browser() cj = cookielib.CookieJar() br.set_cookiejar(cj) def Listener(): while True: sleep(15) br.open("https://steamcommunity.com/tradeoffer/") if "If new offer appears": return "Bot accepts it" # ( I will make protections later ) def Sender(): while True: sleep(10) if "User bought item": # ( I don't need help on this line. ) items = ["something", "something2"] return "Make a trade using SteamID or Profile name" + items # ( So basically i need to make trade offer and send users items). if __name__ = '__main__': p1 = Process(target=Listener) p2 = … -
Django log requests with status 200 to syslog
I am writing a Django Application and using basic URL Routing to views. I am trying to implement logging to syslog. I want to log all incoming requests to syslog. My LOGGING dict looks like this: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse', }, 'require_debug_true': { '()': 'django.utils.log.RequireDebugTrue', }, }, 'formatters': { 'verbose': { 'format': '%(process)-5d %(name)s:%(lineno)d %(levelname)s %(message)s' }, 'simple': { 'format': '[%(asctime)s] %(name)s %(levelname)s %(message)s', 'datefmt': '%d/%b/%Y %H:%M:%S' }, }, 'handlers': { 'console': { 'level': 'DEBUG', 'filters': ['require_debug_true'], 'class': 'logging.StreamHandler', 'formatter': 'simple' }, 'syslog': { 'level': 'DEBUG', 'class': 'logging.handlers.SysLogHandler', 'facility': 'local7', 'address': '/dev/log', 'formatter': 'verbose' }, }, 'loggers': { 'django.server': { 'handlers': ['console', 'syslog'], 'level': 'INFO', 'propagate': False }, 'my_project': { 'handlers': ['console', 'syslog'], 'level': 'INFO', 'propagate': False, }, # root logger '':{ 'handlers': ['console', 'syslog'], 'level': 'INFO', 'disabled': False }, }, } Whenever I hit any URL on the server, the following is logged into the console: [01/Oct/2016 18:30:34] "POST /api/v1/users/login/ HTTP/1.1" 200 73 But nothing in my log file. When I insert a logger.error('Something went wrong!') in my code, it gets logged in my log file. How do I get the requests log in my log file? TIA -
See if user in ManyToManyField
I am trying to see if the current user is in the collaborators m2m field, but keep getting an error saying: Cannot query "John Doe": Must be "Company" instance. Could someone help me out with the conditional statement please? models.py: class MyUser(): name = ... email = ... class Company(models.Model): user = models.ForeignKey(MyUser, null=True, related_name='company_owner', on_delete=models.SET_NULL) collaborators = models.ManyToManyField(MyUser, blank=True, related_name='company_collaborators') name = models.CharField(max_length=120) views.py: def company_dash(request, username): user = request.user company = get_object_or_404( Company, Q(is_active=True), username=username) # NEED HELP HERE PLEASE if company.user == user or company.collaborators.filter(company_collaborators=user).exists(): # do something -
Django: add filtering sidebar to a change list admin view
I have a back-end module showing a quite long items listing that looks like this: ID Label Type 1 Label 1 Type A 2 Label 2 Type B 3 Label 3 Type A 4 Label 4 Type D 5 Label 5 Type C 6 Label 6 Type D 7 Label 7 Type C What I want to do is quite simple: I want to add a "filter by" sidebox listing all available types, for example Available Types Type A Type B Type C Type D If clicked they should enable filtering by single type. For example, if I click on "Type A" only items belonging to that type will be shown. Sidebar's HTML should look like this <ul> <li><a href="?type=11">Type A</a></li> <li><a href="?type=12">Type B</a></li> <li><a href="?type=13">Type C</a></li> <li><a href="?type=14">Type D</a></li> </ul> How can I implement that? I'm quite confused right now... Thanx a lot! -
How to apply / unapply a Django migration programmatically?
I need to apply a Django migration programmatically, for example this one: class Migration(migrations.Migration): dependencies = [ ('some_app', '0001_initial'), ] operations = [ migrations.AlterIndexTogether( name='some_model', index_together=set([('some_field_one', 'some_field_two')]), ), ] Is there a way to do it? I tried to use apply method, but couldn't figure out how to make it work. -
How do I reverse a named Django URL to the urlpattern that defines it?
My Django app contains a couple of external references, e.g. to the application's blog, which is not part of the Django codebase and is hosted on a different subdomain. So far, links to these were spread all around the source code as direct absolute URLs. Now I was wondering if there was a way to use Django's excellent URL routing system for these external URLs as well. I thought I could define them like this: url(r'^permalink/blog/$', RedirectView.as_view(url='https://blog.example.com'), name='blog'), Then I could just reference them as {% url 'blog' %} in my templates. That works. Now I was wondering if there was a way to resolve these directly to the 'final' URL with a special (self-defined) template tag, so that they appear as https://blog.example.com to the user, as opposed to /permalink/blog/ (to the browser) or https://app.example.com/permalink/blog/ (to the user). I do already have a self-defined {% absolute_url %} template tag, which I use in templates that require absolute URLs, like transactional email. However, I couldn't find a way to reverse a named URL (like external:blog) to its urlpattern as opposed to its final relative URL. To do this myself, it seems like I'd have to duplicate all the code from URLNode.render(), … -
Django: file field validation in model
I have a model containing file field. I want to restrict it to pdf files. I have written clean method in model because I want to check for admin and shell level model creation also. But it is not working in model clean method. However form clean method is working. class mymodel(models.Model): myfile = models.FileField() def clean(): mime = magic.from_buffer(self.myfile.read(), mime=True) print mime if not mime == 'application/pdf': raise ValidationError('File must be a PDF document') class myform(forms.ModelForm): class Meta: model = mymodel fields = '__all__' def clean_myfile(self): file = self.cleaned_data.get('myfile') mime = magic.from_buffer(file.read(), mime=True) print mime if not mime == 'application/pdf': raise forms.ValidationError('File must be a PDF document') else: return file If I upload pdf, mime in form clean method is correctly validating (printing 'application/pdf'). But model clean method is not validating. It is printing mime as 'application/x-empty'. Where am I doing wrong ? -
search engine for full-text search in Django project
I'm developing full-text search function in Django project, and I'm confusing about search engine. I found haystack with elasticSearch, Whoosh, and Solr. I don't know which search engine is appropriate for my project. I'm developing st like shopping web, and I'm using postgreSql. Also, it's really nice if it can support language searching (For example: "banh my" and "bánh mỳ") -
Nginx, fastcgi, proxy_pass
Have 2 domains: main.domain.com and sub.domain.com So I need sub.domain.com proxy pass to main.domain.com/somepath, but now I'm catching that main.domain.com works and sub.domain.com: [error] 27961#27961: *14 upstream timed out (110: Connection timed out) while reading response header from upstream, client: ip.ip.ip.ip, server: sub.domain.com, request: "GET / HTTP/1.1", upstream: "http://127.0.0.1:8000/", host: "sub.domain.com" My nginx config looks like: server { listen 80; client_max_body_size 1000m; charset utf-8; server_name main.domain.com; location / { fastcgi_pass 127.0.0.1:8000; include fastcgi_params; fastcgi_param PATH_INFO $fastcgi_script_name; fastcgi_param REQUEST_METHOD $request_method; fastcgi_param QUERY_STRING $query_string; fastcgi_param CONTENT_TYPE $content_type; fastcgi_param CONTENT_LENGTH $content_length; fastcgi_pass_header Authorization; fastcgi_intercept_errors off; } } server{ listen 80; server_name sub.domain.com; location / { proxy_pass http://127.0.0.1:8000/somepath; proxy_set_header Host main.domain.com; } } -
Smoothstate.js and Django - Form POST only triggered on second click
Im currently trying to integrate Smooth.js into my Django Project. I'm using the js code snippet from the smoothstate.js github site. $(function(){ 'use strict'; var options = { prefetch: true, cacheLength: 2, onStart: { duration: 250, // Duration of our animation render: function ($container) { // Add your CSS animation reversing class $container.addClass('is-exiting'); // Restart your animation smoothState.restartCSSAnimations(); } }, onReady: { duration: 0, render: function ($container, $newContent) { // Remove your CSS animation reversing class $container.removeClass('is-exiting'); // Inject the new content $container.html($newContent); } } }, smoothState = $('#main').smoothState(options).data('smoothState'); }); My template looks like this (I simplified it for this question): <head> {% load static %} <script src="{% static 'js/vendor/jquery.js' %}"></script> <script src="{% static 'js/vendor/what-input.js' %}"></script> <script src="{% static 'js/vendor/foundation.js' %}"></script> <link rel="stylesheet" href="{% static 'css/foundation.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> </head> <body> <div id="main" class="m-scene"> <!--...--> <div class="row expanded collapse"> <div class="scene_element scene_element--fadeinright large-12 columns"> <a href="{% url 'transition' %}">test</a> <form action="{% url 'transition' %}" method='POST'> {% csrf_token %} {{form}} <input type="submit" class="button green" value="join"></input> </form> </div> </div> </div> <script src="{% static 'js/jquery.smoothState.js' %}"></script> <script src="{% static 'js/initSmoothState.js' %}"></script> </body> When I click on a link Smoothstate.js works like expected. … -
prevent creating related objects while adding objects to many to many fields in django rest framework
I have already referred to many posts like these and a bug on github repo of DRF. I am still unclear if this is bug still exists as the info i fetched so far is not from recent posts. I am trying to create an api using django rest framework. below given is my code. Serializers.py class MemberSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('username', 'email') class TeamSerializer(serializers.ModelSerializer): members = MemberSerializer(many=True) class Meta: model = Team fields = ('name', 'members') class TeamUpdateSerializer(serializers.ModelSerializer): class Meta: model = Team fields = ('name', 'description', 'members', 'team_type', 'created_by') Views.py class TeamViewSet(viewsets.ModelViewSet): queryset = Team.objects.all() serializer_class = TeamSerializer authentication_classes = (SessionAuthentication, BasicAuthentication) permission_classes = (IsAuthenticated,) def get_queryset(self): queryset = Team.objects.filter(created_by=self.request.user) return queryset members is a M2M relationship to django user model. I can create a new object, get the details but upon updating an existing Team model bby adding a new user to member field, it says a user with that username exists. I can override save() method or switch to another serializer in the update() method of my modelserializer to solve the issue. def update(self, request, *args, **kwargs): partial = kwargs.pop('partial', False) instance = self.get_object() members = request.data['members'] member_list = list() for member … -
Django: custom input + select search into admin items listing module
I am working to an admin items listing + search module and I need to apply a more complex search pattern than the one provided in basic templates. This is how my listing view looks like: ID Label Type 1 Label 1 Type A 2 Label 2 Type B 3 Label 3 Type A 4 Label 4 Type B This is how my search div should look like (#searchbar2 options are the result of a filter but I'm just simplifying) <label for="searchbar">Label:</label> <input type="text" size="40" name="{{ search_var }}" value="{{ cl.query }}" id="searchbar" autofocus /> <label for="searchbar2">Type:</label> <select name="{{ search_var2 }}" id="searchbar2"> <option value="A">Type A</option> <option value="B">Type B</option> </select> <input type="submit" value="{% trans 'Search' %}" /> What should I do do archieve that? Looks like I cannot obtain this by using default templates and search_fields array and so I'm quite confused on how to proceed. At first I'd say that I must implement my own search_form.html override but how can I make admin/change_list.html load my override? After that, How I'm supposed to handle submitted values into the admin.py class of the module? Thanx in advance for your precious help -
the ways to earn money by making Django apps [on hold]
i want to know all the ways to earn money by making Django apps like selling them as open source or renting them ... thanks for help. -
Can't change language in Django project
I'm struggling with changing the language in my Django project. I think that everything is set correctly but it still doesn't work. I've created messages and compiled them already. SETTINGS.PY # -*- coding: utf-8 -*- import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'admin_interface', 'flat', 'colorfield', 'django.contrib.admin', 'django.contrib.auth', # 'djcelery_email', 'django.contrib.sites', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'dolava_app', 'solo', 'django_extensions', 'django_tables2', 'django_countries', 'admin_stuff', 'ajax_stuff', ] MIDDLEWARE_CLASSES = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.locale.LocaleMiddleware', ] ROOT_URLCONF = 'dolava.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.core.context_processors.i18n', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.core.context_processors.media', ], }, }, ] WSGI_APPLICATION = 'dolava.wsgi.application' # Database # https://docs.djangoproject.com/en/1.9/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/1.9/topics/i18n/ gettext = lambda s: s LANGUAGES = [ ('en','English'), ('sk','Slovak'), ] LANGUAGE_CODE = 'sk' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, … -
Create local files from a Django web
I have written a Django web run under Linux server, the web is used to read a file path and generate some folders and files on the local machine which browse the web, not sure how to do that, currently it can only generate the files on the server runs the web locally. Does it need to use the python package paramiko? Thanks, Le -
Django: How to sort data using a common field in template, result given by view
I have a product model, which is linked with foreign key to sale, purchase, sale return and purchase return. I querying the total sale, purchase, sales_return and purchase_return. I have chained four querysets. In template i want to show for each product sale, purchase, returns in a single line. Howe django gives result of each product in a seperate line. My views.py: def inventorybalance(request): inventory_purchase=productmodel.objects.filter(company=request.user.company.entity) purchase=inventory_purchase.annotate(purchase=Sum('exproduct__Quantity')) sale = inventory_purchase.annotate(sale=Sum('serviceproduct__Quantity')) purchase_return = inventory_purchase.annotate(purchase_return=Sum('dnproduct__Quantity')) sales_return = inventory_purchase.annotate(sales_return=Sum('cnproduct__Quantity')) inventory_movement = sorted(chain(purchase,sale,purchase_return,sales_return),key=attrgetter('product_name')) return render(request,'account/inventorymovement.html',{'inventory_movement':inventory_movement}) Template.html: {% for invoices in inventory_movement %} <tr> <td>{{ invoices.product_name }}</td> <td>+{{ invoices.purchase|default:0 }} </td> <td>-{{ invoices.sale|default:0 }}</td> <td>+{{ invoices.sales_return|default:0 }}</td> <td>-{{ invoices.purchase_return|default:0 }}</td> <td>-</td> </tr> {% endfor %} Data rendered in html is as below: Product1 0 0 1 0 Product1 0 0 0 2 I want result like this: product1 0 0 1 2 Stuck with this, Any help will be appreciated. -
Django JS - downloading Django-generated file to client
I have a Django code that generates a file on server-side and then I want the user to be able to choose a local location on his computer (f.e., Destktop) and actually download the file. def my_view(request): # Generating content myfile.write(content.encode('cp1251')) response = HttpResponse(content_type='application/force-download') file_name = get_declaration_file_name(declaration_instance) response['Content-Disposition'] = 'attachment; filename=%s' % smart_str(file_name) response['X-Sendfile'] = smart_str(myfile) return response JS $.post ('/my_view/', data, function() { // DON'T KNOW WHAT TO DO WITH RESPONSE :((( } The issue is that after surfing the internet, I can't figure out what should be the JS code that receives the RESPONSE from Django (containing the target file). Previously, I easily developed code for uploading files, but having trouble now with downloading. -
Django: If model field has editable=False does it matter if blank is set to True or False?
From Django: As currently implemented, setting auto_now or auto_now_add to True will cause the field to have editable=False and blank=True set. Field.editable If False, the field will not be displayed in the admin or any other ModelForm. They are also skipped during model validation. Default is True. Field.blank If True, the field is allowed to be blank. Default is False.? Note that this is different than null. null is purely database-related, whereas blank is validation-related. If a field has blank=True, form validation will allow entry of an empty value. If a field has blank=False, the field will be required. Am I correct when I say blank=True won't be validated? Does it matter in this case if it was set to blank=False?