Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Join sql queries for Django
I have two related models: class Category(models.Model): pass class Entry(models.Model): category = models.ForeignKey(Category) is_published = models.BooleanField(default=True) I need to get categories with published entries. I ended up with two queries: published = Entry.objects.filter(is_published=True) categories = Category.objects.filter(entries__in=published) Can I do this in one query? -
installation fixture django-municipios
I am getting the following error when executing the command python manage.py loaddata municipios_geo_2013_4674.json.bz2. how to solve attribute error? Package and json in: https://github.com/znc-sistemas/django-municipios Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/Users/lidiane/Developer/django/integra-fundaj/.myvenv/lib/python3.5/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/Users/lidiane/Developer/django/integra-fundaj/.myvenv/lib/python3.5/site-packages/django/core/management/__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/lidiane/Developer/django/integra-fundaj/.myvenv/lib/python3.5/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/Users/lidiane/Developer/django/integra-fundaj/.myvenv/lib/python3.5/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/Users/lidiane/Developer/django/integra-fundaj/.myvenv/lib/python3.5/site-packages/django/core/management/commands/loaddata.py", line 69, in handle self.loaddata(fixture_labels) File "/Users/lidiane/Developer/django/integra-fundaj/.myvenv/lib/python3.5/site-packages/django/core/management/commands/loaddata.py", line 109, in loaddata self.load_label(fixture_label) File "/Users/lidiane/Developer/django/integra-fundaj/.myvenv/lib/python3.5/site-packages/django/core/management/commands/loaddata.py", line 175, in load_label obj.save(using=self.using) File "/Users/lidiane/Developer/django/integra-fundaj/.myvenv/lib/python3.5/site-packages/django/core/serializers/base.py", line 205, in save models.Model.save_base(self.object, using=using, raw=True, **kwargs) File "/Users/lidiane/Developer/django/integra-fundaj/.myvenv/lib/python3.5/site-packages/django/db/models/base.py", line 837, in save_base updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "/Users/lidiane/Developer/django/integra-fundaj/.myvenv/lib/python3.5/site-packages/django/db/models/base.py", line 904, in _save_table forced_update) File "/Users/lidiane/Developer/django/integra-fundaj/.myvenv/lib/python3.5/site-packages/django/db/models/base.py", line 954, in _do_update return filtered._update(values) > 0 File "/Users/lidiane/Developer/django/integra-fundaj/.myvenv/lib/python3.5/site-packages/django/db/models/query.py", line 664, in _update return query.get_compiler(self.db).execute_sql(CURSOR) File "/Users/lidiane/Developer/django/integra-fundaj/.myvenv/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 1191, in execute_sql cursor = super(SQLUpdateCompiler, self).execute_sql(result_type) File "/Users/lidiane/Developer/django/integra-fundaj/.myvenv/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 863, in execute_sql sql, params = self.as_sql() File "/Users/lidiane/Developer/django/integra-fundaj/.myvenv/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 1157, in as_sql val = field.get_db_prep_save(val, connection=self.connection) File "/Users/lidiane/Developer/django/integra-fundaj/.myvenv/lib/python3.5/site-packages/django/contrib/gis/db/models/fields.py", line 182, in get_db_prep_save return connection.ops.Adapter(self.get_prep_value(value)) AttributeError: Problem installing fixture '/Users/lidiane/Developer/django/integra-fundaj/municipios_geo_2013_4674.json': 'DatabaseOperations' object has no attribute 'Adapter' -
Recursion error calling a function using a post-save signal
I have a Category model, where the ForeignKey is to self. class Category(SEO, MetaData): parent = models.ForeignKey('self', blank=True, null=True, verbose_name='parent category', on_delete=models.CASCADE) path = ArrayField(models.IntegerField(), blank=True, null=True) I introduced the path field, to avoid recursion in widget, and do it model, because is not often done. I use a post_save signal to ssave the path: def _recurse_for_parent(cat_obj, path=None): # path at the beginning don't exist and need to be initialized if not path: path = [] if cat_obj.parent is not None: _recurse_for_parent(cat_obj.parent, path) return path def save_path(sender, instance, **kwargs): if instance.parent_id: instance.children = _recurse_for_parent(instance.parent) instance.save() post_save.connect(save_path, sender=Category) My issue is that I get the "maximum recursion depth error" and I don't see why, because I use the condition: cat_obj.parent is not None: -
Heroku app crashes upon first deployment attempt
I've been trying to deploy my workoutcalendar app on heroku. After a lot of progress I finally successfully pushed to heroku master and ran makemigrations and migrate. Unfortunately, when it was time to go to the page and see my beautiful website, I was instead greeted by this: As instructed by the message in my browser, I checked the logs in the hope of finding further information of the error. But all I found was this: 2018-01-15T12:22:54.915142+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=workoutcalendar.herokuapp.com request_id=46d30e9c-d76c-451b-bbb6-ccbfef5efa72 fwd="130.229.155.250" dyno= connect= service= status=503 bytes= protocol=https This doesn't tell me much. The only thing I wonder is why path=/favicon.ico. That's not a url that I've defined on my site. I don't know if that's the reason for the crash. In any case, I wonder if you could tell me how to solve this error, or how to find more information on how to solve it. PS: Some additional info... My requirements.txt: dj-database-url==0.4.2 Django==2.0.1 django-secure==1.0.1 djangorestframework==3.7.1 gunicorn==19.7.1 psycopg2==2.7.3.2 python2==1.2 pytz==2017.2 six==1.10.0 whitenoise==3.3.1 My Procfile: web: gunicorn workoutcalendar.wsgi --log-file - My runtime.txt: python-3.6.4 -
Django Taggit: add defaut tag to object
What's the best practice to add a default tag to an object? This is what I wish to do: class Exercise(Model): tags = TaggableManager(blank=True) class TrueOrFalseExercise(Exercise): def __init__(self, *args, **kwargs): super(Exercise, self ).__init__(*args, **kwargs) self.tags.add("true or false") //but this will not work because self doesn't exist yet It will give me error: objects need to have a primary key value before you can access their tags. Is there an elegant way to acheive this? If possible I prefer not to add it through my already messy tag widgets. -
Django json array in models
I have a model in my app which I used Django rest framework. I want to have an array of json objects like below: class AddOn(models.Model): name = models.CharField(max_length=128) plans = ArrayField(JSONField(default=dict)) now after migration and register this model in admin.py file when i go to Django admin to create a record in DB, following error throwing: column "plans" is of type jsonb[] but expression is of type text[] LINE 1: ..."paas_addon" ("name", "plans") VALUES ('mongodb', ARRAY['{"a... ^ HINT: You will need to rewrite or cast the expression. I guess model want to have a JSON object but it gets an array of string instead. how can fix this? should i overwrite save method -
Business logic validations in Django: Model or ModelForm?
Suppose I have the following model: class Location(models.Model): name = models.CharField(max_length=32) class Event(models.Model): start = models.DateTimeField() end = models.DateTimeField() location = models.ManyToManyField(Location) The Event model has two invariants: end can't be before start a Location can't have overlapping events What would be a better pattern in Django: validating this in your form (EventForm.clean_end()) or in your model (Event.clean())? According to the docs, when you define a clean() method in your model, it won't be automatically called when using save(), so when manipulating objects outside the Form API I can't really see the added value (unless you call full_clean() by yourself). Also, in my case, my application only has one EventModelForm which manipulates Event objects, so both options would be equally DRY. In short: should I put these kind of validations in my models or in my forms? -
How to specify Parent-Child relationship withing one Model?
For example I have following code: class FamilyMember(models.Model): user = models.OneToOneField(User) And I have following situations: a1 = FamilyMember.objects.get(id=1) a1.first_name = 'John' a1.last_name = 'Smith' (a1 is a parent of a2) a2 = FamilyMember.objects.get(id=2) a2.first_name = 'Mark' a2.last_name = 'Smith' (a2 is a child of a1 and parent of a3 in the same time) a3 = FamilyMember.objects.get(id=3) a3.first_name = 'Jason' a3.last_name = 'Smith' (a3 is a child of a2) How can i accomplish that kind of relationships within one model ? -
Send filepath as getURL parameter Django2
I want to send a file url as a get parameter: $.get("/django_route/"+ encodeURIComponent(fileUrl), function(res){ console.log(res) }) But it looks like Django is interpreting my encoded URI component as an actual URI... Is this kind of thing possible with Django? -
How to change manager for custom User model
I've defined a custom user model: class User(AbstractUser): REQUIRED_FIELDS = [] USERNAME_FIELD = 'email' email = models.EmailField( _('email address'), max_length=150, unique=True, help_text=_('Required. 150 characters or fewer. Must be a valid email address.'), error_messages={ 'unique':_("A user with that email address already exists."), }, ) The point of it being to use an email address instead of username. I've put this in settings: # custom user model AUTH_USER_MODEL = 'workoutcal.User' The user model works, but there's one problem. I can't create superusers: (workout) n155-p250:workout sahandzarrinkoub$ ./manage.py createsuperuser Email address: sahandz@kth.se Password: Password (again): Traceback (most recent call last): File "./manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/core/management/__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/core/management/base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 59, in execute return super().execute(*args, **options) File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/core/management/base.py", line 335, in execute output = self.handle(*args, **options) File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 179, in handle self.UserModel._default_manager.db_manager(database).create_superuser(**user_data) TypeError: create_superuser() missing 1 required positional argument: 'username' Seems like the create_superuser method used has username as a required argument. I've read in the docs that I need to implement my own CustomUserManager. I've already done so here: class CustomUserManager(BaseUserManager): def _create_user(self, email, password, is_staff, is_superuser, **extra_fields): now = … -
Django model attribute that updates when database is updated
I am a django beginner trying to set up a django project for data analysis. Data from a certain type of experiment is represented by two models "Dataset" and "GeneEntry", where each Dataset represents one experiment and every GeneEntry is one line from a dataset. Each dataset contains around 20000 entries. A gene with the same name can occur with the same gene symbol in multiple datasets. class Dataset(models.Model): dataset_name = models.CharField(max_length=200) def __str__(self): return self.dataset_name class GeneEntry(models.Model): dataset = models.ForeignKey(Dataset, on_delete=models.CASCADE) gene_symbol = models.CharField(max_length=200) Pval = models.FloatField(default=0) x = models.IntegerField(default=0) y = models.IntegerField(default=0) def __str__(self): return self.gene_symbol On my django project, users can select one of the datasets and plot x vs. y. The colors of the datapoints should be allocated according to a colorscale on a gene specific ratio r = a/b. b is the number of times this exact gene_symbol appears in the database (e.g. 8 out of 10 experiments have this gene -> a = 8) and a is the number how many of these entries have a Pval < 0.05. Currently, I am doing this by looping over a list with gene names and calling the following method for all of them: def outlier(self, gene): … -
Create a edit view in django to modify the existing issues
I have been trying to work out how to create a edit view in django but everything I try keeps on failing and not giving me the ability to edit the already saved objects.The issues get created fine and saved and displayed but I just cant load them for editing.The code is bellow any help or advice would be good. views.py class IssueListView(ListView): template_name = 'issuetracker/issue_list.html' def get_queryset(self): slug = self.kwargs.get("slug") if slug == 'open': queryset = Issue.objects.filter(status__iexact="assigned") else: queryset = Issue.objects.all() return queryset class StatView(View): def get(self,request): if Issue.objects.filter(status__iexact="c").exists(): closed_lst = [] seconds = [] idx = 0 count = 0 queryset = Issue.objects.filter(status__iexact="closed") queryset1 = Issue.objects.filter(status__iexact="c") for tkt in queryset1: count = count + 1 times1 = queryset1.order_by().values_list('updated').distinct() times = queryset1.order_by().values_list('opened').distinct() final = times1[idx][0] - times[idx][0] sec = final / timedelta(seconds=1) idx = idx + 1 seconds.append(sec) mx = max(seconds) mn = min(seconds) av = sum(seconds) / len(seconds) maximum = (str(mx * timedelta(seconds=1)).split('.')[0]) minimum = (str(mn * timedelta(seconds=1)).split('.')[0]) average = (str(av * timedelta(seconds=1)).split('.')[0]) all_docs = len(Issue.objects.all()) - count return render(request,"issuetracker/main.html",{ 'maximum':maximum, 'minimum':minimum, 'average':average, 'count':count, 'all_docs':all_docs }) else: return render(request, "issuetracker/main.html") class FormView(FormView): template_name = 'issuetracker/form.html' form_class = CreateIssueForm success_url = '/issue/' def form_valid(self, form): obj = Issue.objects.create( submitter=form.cleaned_data.get('submitter'), … -
How to set up a web server in LAN?
I looked for this answer a lot but I didn't find an answer that can help me. I developed a django application that allows admin to upload files by the default admin page. I want to allow users to download these files by clicking on a download link.I know that files can't be served with django itself because it's not a web server. The server has centOS. Which web server should i use and how to set up it? I just want to use my application in my house LAN. -
Financial budgeting and cash-flow management app like pulseapp or floatapp
I am new to the Stack Overflow site and for that manner new to coding in general. I am a financial consultant by trade but am starting to see real opportunities in learning how to code and develop simple webapps for my clients. My idea is to develop an web based application for budgeting and cash-flow management for small and medium size enterprises for our local market which has its own accounting standards and therefore the already made solutions do not come into play. Basically I would like to develop an app similar to pulseapp or floatapp. I already have the financial model done in excel but would really benefit from a fully developed webapp. I have already started to learn python as I researched that it was most appropriate coding language for such solutions. I also learned a bit of django. My question is am I on the right track regarding the development environment (django/python) and do you maybe know how the above mentioned app are designed (which language or technology is used). Additionally I would kindly ask you for any suggestions on how I would go about learning how to develop such a webapp (tutorials, resources, tips, ideas). … -
Any remaining kwargs must correspond to properties or virtual fields - what does it mean?
I was trying with different model relationships, when came across this exception (please write if you want to see the full traceback): File "C:\Users\1\vat\tpgen\tpgen\src\generator\views\wizard.py", line 172, in get_next_form return step, form_type(**kwargs) File "C:\Users\1\vat\tpgen\venv\lib\site-packages\django\db\models\base.py", line 495, in __init__ raise TypeError("'%s' is an invalid keyword argument for this function" % kwarg) TypeError: 'data' is an invalid keyword argument for this function As I understand, the exception was raised when Django tried to create a new instance with some kwargs. The traceback points to Models’ __init__ method in django.db.models.base if kwargs: property_names = opts._property_names for prop in tuple(kwargs): try: # Any remaining kwargs must correspond to properties or # virtual fields. if prop in property_names or opts.get_field(prop): if kwargs[prop] is not _DEFERRED: _setattr(self, prop, kwargs[prop]) del kwargs[prop] except (AttributeError, FieldDoesNotExist): pass for kwarg in kwargs: raise TypeError("'%s' is an invalid keyword argument for this function" % kwarg) The kwargs seems to be all right (printed from the line 171 of wizard.py): {'data': None, 'prefix': '2', 'initial': {'0': {'0-trans_type': ['13'], '0-end_of_tax_year': ['']}, '1': {'1-funct_title': ['14']}}} So the problem, as I understand it, lies in the model, which I admit is a bit overcomplicated, but as said before, I was experimenting with models relationships. The … -
Django ValueError sending forms to template
I have just added another form to send to my template and I have begun to have this error. It isn't very descriptive so I can't work out what I've done wrong. The error is ValueError: too many values to unpack (expected 2). views.py: def new_post(request): if request.method == 'POST': form = NewPostForm(request.POST) election_form = ElectionSuggestionForm(request.POST, request.user) if form.is_valid(): post = form.save(commit=False) post.author = Candidate.objects.get(UserID=request.user, ElectionID=election_form.PostElection) post.save() return redirect('/feed/') else: form = NewPostForm() election_form = ElectionSuggestionForm(request.user) return render(request, 'campaign/new_post.html', { "form": form, "election_form": election_form, }) I think the error comes from the last line - the "election_form" item in the dictionary - which is confusing since there are only 2 items passed in the dictionary, thus contradicting the error message. Here is the offending form (The view was working with only NewPostForm() so I haven't included this.): forms.py: def GetAvailableElections(user): candidates = Candidate.objects.all().filter(UserID=user) choices = [] for i in candidates: choices.append(i.ElectionID.Name) return choices class ElectionSuggestionForm(forms.Form): def __init__(self, user, *args, **kwargs): super(ElectionSuggestionForm, self).__init__(*args, **kwargs) self.fields['PostElection'] = forms.ChoiceField(choices=GetAvailableElections(user)) Thanks in advance. -
Why is there both a create_user and a _create_user method in django.contrib.auth.models.UserManager
In the source for django, there is a UserManager class whose job (as far as I understand) is to create users according to a number of received parameters and save them to the database. The class accomplishes this with the use of two methods. One method create_user and one method _create_user, the latter is called by the former. My question is, why the need for two methods? Why not simply have one that does the exact same thing? Like this: def create_user(self, username, email=None, password=None, **extra_fields): """ Creates and saves a User with the given username, email and password. """ now = timezone.now() if not username: raise ValueError('The given username must be set') email = self.normalize_email(email) user = self.model(username=username, email=email, is_staff=False, is_active=True, is_superuser=False, date_joined=now, **extra_fields) user.set_password(password) user.save(using=self._db) return user -
Django HttpResponse with application/zip type corrupt
When I log the request in my frontend, I see characters like this: PKS/L'�I�rrQUsers/my/local/dev_env/django_app/webapp/webapp/csvs/mailMagaOutput.csv会員id,e-mail,お名前(姓),お名前(名),購入回数 And the response logs the rest of the CSV files I am trying to log as the way they should look... Does this mean that I am not properly encrypting them? The response I am sending (from Django): zipped_file = zipfile.ZipFile("csvOutput.zip", 'w') zipped_file.write(sms_file_path) zipped_file.write(mail_maga_file_path) zipped_file.close() response_file = open('csvOutput.zip', 'rb') response = HttpResponse(response_file, content_type="application/zip") response['Content-Disposition'] = 'attachment; filename=csvOutput.zip"' If I try to unzip the file that python generates on the server, it works just fine. When I try to unzip it locally, I am getting: tar: Too-small extra data: Need at least 4 bytes, but only found 3 bytes -
Wagtail installation: Wagtail command not found
Simple question. Trying to install wagtail. As docs tells, installed wagtail pip package. tigran@tigran:~/projects/website$ pip install wagtail Collecting wagtail Using cached wagtail-1.13.1-py2.py3-none-any.whl Collecting html5lib<1,>=0.999 (from wagtail) Using cached html5lib-0.999999999-py2.py3-none-any.whl Collecting Django<1.12,>=1.8.1 (from wagtail) Using cached Django-1.11.9-py2.py3-none-any.whl Collecting djangorestframework<3.7,>=3.1.3 (from wagtail) Using cached djangorestframework-3.6.4-py2.py3-none-any.whl Collecting django-treebeard<5.0,>=3.0 (from wagtail) Collecting Pillow>=2.6.1 (from wagtail) Using cached Pillow-5.0.0-cp27-cp27mu-manylinux1_x86_64.whl Collecting Unidecode>=0.04.14 (from wagtail) Using cached Unidecode-1.0.22-py2.py3-none-any.whl Collecting django-taggit<1.0,>=0.20 (from wagtail) Using cached django_taggit-0.22.2-py2.py3-none-any.whl Collecting django-modelcluster<4.0,>=3.1 (from wagtail) Collecting Willow<1.1,>=1.0 (from wagtail) Using cached Willow-1.0-py2.py3-none-any.whl Collecting beautifulsoup4>=4.5.1 (from wagtail) Using cached beautifulsoup4-4.6.0-py2-none-any.whl Collecting requests<3.0,>=2.11.1 (from wagtail) Using cached requests-2.18.4-py2.py3-none-any.whl Collecting six (from html5lib<1,>=0.999->wagtail) Using cached six-1.11.0-py2.py3-none-any.whl Collecting webencodings (from html5lib<1,>=0.999->wagtail) Using cached webencodings-0.5.1-py2.py3-none-any.whl Collecting setuptools>=18.5 (from html5lib<1,>=0.999->wagtail) Using cached setuptools-38.4.0-py2.py3-none-any.whl Collecting pytz (from Django<1.12,>=1.8.1->wagtail) Using cached pytz-2017.3-py2.py3-none-any.whl Collecting idna<2.7,>=2.5 (from requests<3.0,>=2.11.1->wagtail) Using cached idna-2.6-py2.py3-none-any.whl Collecting urllib3<1.23,>=1.21.1 (from requests<3.0,>=2.11.1->wagtail) Using cached urllib3-1.22-py2.py3-none-any.whl Collecting certifi>=2017.4.17 (from requests<3.0,>=2.11.1->wagtail) Using cached certifi-2017.11.5-py2.py3-none-any.whl Collecting chardet<3.1.0,>=3.0.2 (from requests<3.0,>=2.11.1->wagtail) Using cached chardet-3.0.4-py2.py3-none-any.whl Installing collected packages: six, webencodings, setuptools, html5lib, pytz, Django, djangorestframework, django-treebeard, Pillow, Unidecode, django-taggit, django-modelcluster, Willow, beautifulsoup4, idna, urllib3, certifi, chardet, requests, wagtail Successfully installed Django-1.11.9 Pillow-5.0.0 Unidecode-1.0.22 Willow-1.0 beautifulsoup4-4.6.0 certifi-2017.11.5 chardet-3.0.4 django-modelcluster-3.1 django-taggit-0.22.2 django-treebeard-4.2.0 djangorestframework-3.6.4 html5lib-0.999999999 idna-2.6 pytz-2017.3 requests-2.18.4 setuptools-38.4.0 six-1.11.0 urllib3-1.22 wagtail-1.13.1 webencodings-0.5.1 Creating project tigran@tigran:~/projects/website$ wagtail start website … -
Google App Engine Flexible
I'm trying to use CodeShip and deploy to Google App Engine. Using this guide. I'm getting this error: appcfg does not support deploying to the Flexible environment Im wondering if I might have done something wrong or if its in CodeShip. Does CodeShip have support Google App Engine Flexible? -
Create SOAP requst by zeep
I'm working on WSDL. I need to create SOAP request using by zeep package. So I implemented the code that from zeep import Client service = Client('https://api.mindbodyonline.com/0_5_1/ClientService.asmx?wsdl') request = service.service.GetClientServices But I could not move on. Because I could not login through this request and pass parameters. I want to fill following all requirement through this request. could anyone tell me that how to pass all this parameters by this request. This is HTTP headers SOAPAction: "http://clients.mindbodyonline.com/api/0_5_1/GetClientServices" Content-Type: text/xml; charset="utf-8" -
Python3 Django ZipFile HttpResponse UnicodeDecodeError
I created a zip file like so: zipped_file = zipfile.ZipFile("csvOutput{}.zip".format(timestamp), 'w') zipped_file.write(sms_file_path) zipped_file.write(mail_maga_file_path) zipped_file.close() And want to send it, which I am currently using this code: response_file = open('csvOutput{}.zip'.format(timestamp)) response = HttpResponse(response_file, content_type="application/force-download") response['Content-Disposition'] = 'attachment; filename=csvOutput{}.zip"'.format(timestamp) return response raise Http404 But maybe something I am using is out of date? Python keeps crashing with a byte it can't decode in unicode: UnicodeDecodeError: 'utf-8' codec can't decode byte 0x94 in position 14: invalid start byte Says line 100 is throwing the error, which would be the line with HttpResponse() Edit: I've changed the content_type to application/zip and am getting a new error (that seems better?): caution: zipfile comment truncated error [output.zip]: missing 3232109644 bytes in zipfile (attempting to process anyway) error [output.zip]: attempt to seek before beginning of zipfile (please check that you have transferred or created the zipfile in the appropriate BINARY mode and that you have compiled UnZip properly) -
How do I get the existing value of the fields in a django form when going back in the browser?
I have a django form which has two select fields the second one being dynamic dependent on the value of the first. The values for the second select is loaded via ajax after the first one is selected. Although this works fine it breaks when going back in the browser. The value for the first select appear but nothing in the second (onchange event not happened yet). However rather than load these in the front event I would rather load these in django via the form, if there is a value in the first select. In the debugger when I go back in the browser it generates a GET request, not a POST and so the form is not bound and has no self.data. How do I get the existing value of the fields in a django form when going back in the browser? (note I am using session with database backend) -
nginx can't link uwsgi
I have installed nginx successfully and uwsgi work well but when I want to link nginx with uwsgi.it's wrong This is my nginx.conf and uwsgi.ini #server { listen 80; server_name localhost; #charset koi8-r; charset utf-8; #access_log logs/host.access.log main; location / { include uwsgi_params; uwsgi_pass 127.0.0.1:8000; root html; index index.html index.htm; } and http=127.0.0.1:8000 #socket=/root/project/learning_log/nginx_uwsgi.socket chdir=/root/project/learning_log/ #chmod-socket=664 master=true processes=4 threads=2 module=learning_log.wsgi #wsgi-file=uwsgi_test.py #stats=127.0.0.1:8000 ./nginx & uwsgi3 --ini /root/project/learning_log/uwsgi.ini when I access 127.0.0.1,it's wrong -
django template tag using for loop value
I have a template tag which is an array so for example to display data i use {{ ques.0 }},{{ ques.1 }} {{ ques.2 }}.....I am trying to display this using a for loop in java script x=5; for(var i=0;i<x;i++){ document.getElementById("question").innerHTML="{{ ques.i }}"; } the value of x may vary.. is there a way by which in the line document.getElementById("question").innerHTML="{{ ques.i }}"; I can get the value of i dynamically from java script and then accordingly he result will be displayed