Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django switch language in template doesn't work
I can't figure out why Django doesn't switch language using dropdown menu for switching languages. If I change the language in settings it works correctly. I've added this code (from Django docs) into my template: <form action="{% url 'set_language' %}" method="post">{% csrf_token %} <input name="next" type="hidden" value="/accounts/registration/"/> <select name="language"> {% get_current_language as LANGUAGE_CODE %} {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} {% for language in languages %} <option value="{{ language.code }}"{% if language.code == LANGUAGE_CODE %} selected="selected"{% endif %}> {{ language.name_local }} ({{ language.code }}) </option> {% endfor %} </select> <input type="submit" value="Go"/> </form> I've added this url: url(r'^i18n/', include('django.conf.urls.i18n')), at the top of url_patterns This is in settings.py: 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', ] from django.conf import global_settings TEMPLATE_CONTEXT_PROCESSORS = ('django.core.context_processors.i18n',) LANGUAGE_CODE = 'en-us' LOCALE_PATHS = ( os.path.join(BASE_DIR, 'locale'), ) LANGUAGES = ( ('sk', u'Slovensky'), ('en', u'English'), ('de', u'Deutch'), ) TIME_ZONE = 'UTC' USE_I18N = True As you can see Django doesn't probably set language cookie. What do I have to do? -
Not getting images from json url link in django
i made a simple generic api in django with 3 models name, image, date. I am getting the url for the image but getting 400 Not Found response. json response { "id": 1, "title": "Demo Image", "qoute": "I love Yasou.", "date": "2016-08-22", "card_view_image": "http://127.0.0.1:8000/media/media/images/imageicon.png" }, and also i have added the media folder in settings.py -
Django REST Framework serializer validation
How exactly do I use validators in my serializers? I have currently create my validators in app/validators.py and have my serializers in app/serializers.py. class OrderItemSerializer(serializers.ModelSerializer): item_id = serializers.IntegerField() item_date = serializers.DateTimeField() ... class Meta: model = Item validators = [validate_item_date] fields = ('item_id', 'item_date') from rest_framework.serializers import ValidationError validators.py def validate_item_date(item_date): if item_date < {something}: raise ValidationError('') My question basically: do I provide the item_date as parameter here or does it not work like this? -
Processing a Django form when there are multiple possibilities?
What is the correct way to process a Django form within a view if you don't know which form to expect when entering the view? I have a view which determines the type of form to render based on a session variable: # views.py def enter_location(request): country = request.session['country'] if request.method == "POST": if country == 'US': form = USLocationForm(request.POST) elif country == 'GB': form = GBLocationForm(request.POST) elif country == 'CA': form = CALocationForm(request.POST) else: form = OtherLocationForm(request.POST) if form.is_valid(): # do stuff... pass else: if country == 'US': form = USLocationForm(initial={'country': country}) elif country == 'GB': form = GBLocationForm(initial={'country': country}) elif country == 'CA': form = CALocationForm(initial={'country': country}) else: form = OtherLocationForm(initial={'country': country}) context = {'form': form} return render(request, template, context) Clearly this is ugly code and it doesn't scale as I add more countries. I tried to keep my view short by determining the form type via a helper function: # views.py from location.forms import LocationForm def enter_location(request): country = request.session['country'] if request.method == "POST": form = LocationForm.get_form(country) submitted_form = form(request.POST) if submitted_form.is_valid(): # do stuff... pass else: form = LocationForm.get_form(country) context = {'form': form} return render(request, template, context) # location/forms.py class LocationForm(forms.Form): country = forms.ChoiceField(choices = choices.COUNTRIES_AND_EMPTY,) … -
Redirect user to Django 500 error page from function instead of view?
I have a Django view that looks for a variable in the user's session and, if it can't find it, raises a 500 error and redirects the user to my custom 'project/templates/500.html' page. # views.py def process_country(request, template): try: country = request.session['country'] except KeyError as e: msg = "Key %s not found for uid %s" % ('country', request.user.id) log.error(msg, exc_info=True) return render(request, '500.html', status=500) if request.method == "POST": # do stuff... pass else: form = MyForm(initial={'country': country}) context = {'form': form} return render(request, template, context) This view works as intended if the 'country' session variable doesn't exist. However, what I'd like to do is move this ugly block of exception handling code to a helper function: # views.py from utils import get_from_session def process_country(request, template): country = get_from_session(request, 'country') # Helper if request.method == "POST": # do stuff... pass else: form = MyForm(initial={'country': country}) context = {'form': form} return render(request, template, context) # utils.py from django.shortcuts import render def get_from_session(request, key): try: value = request.session[key] return value except KeyError as e: msg = "Key %s not found for uid %s" % (key, request.user.id) log.error(msg, exc_info=True) # Neither of these work! #return render(request, '500.html', status=500) #render(request, '500.html') The problem is that … -
Supervisor on a Digital Ocean docker image
(beginner question) I've successfully setup a nginx+gunicorn+django docker image on a Digital Ocean droplet. My Django project follows the very good Cookie-Cutter-Django pattern (see here). In this doc, there is a description of a supervisor install. What I'm missing here is WHERE is the supervisor supposed to be running? Local or remotely? I understand that if I install the supervisor on my laptop it will "keep-alive" my command "docker-compose up". But what if I take 1 week off and my laptop runs out off battery? Will the supervisor stop its job? If so, I need to install it on my droplet, right? -
Django: remove 'Vary: cookie' response header for static files
I am using Django to serve static files (dev, localhost only). I want these files to be cached by the browser, but they aren't. I therefore added Middleware to change the response header for /static/ urls as described here Turn off caching of static files in Django development server (They were fixing the opposite issue, but also by changing the header). The issue is that the files are still not being cached. I believe this is because of the 'Vary: Cookie' header. How do I get rid of this header? It seems to be added sometime after my Middleware StaticCache is executed. Response header of static files in browser: Cache-Control:public, max-age=315360000 Content-Length:319397 Content-Type:application/javascript Date:Mon, 22 Aug 2016 13:34:04 GMT Expires:Sun, 17-Jan-2038 19:14:07 GMT Last-Modified:Fri, 19 Aug 2016 23:18:48 GMT Server:WSGIServer/0.1 Python/2.7.10 Vary:Accept-Encoding, Cookie settings.py MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', '<app>.middleware.BeforeViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', '<app>.middleware.StaticCache', '<app>.middleware.ExceptionMiddleware', ) middleware.py class StaticCache(object): def process_response(self, request, response): if request.path.startswith('/static/'): response['Cache-Control'] = 'public, max-age=315360000' response['Vary'] = 'Accept-Encoding' response['Expires'] = 'Sun, 17-Jan-2038 19:14:07 GMT' return response urls.py url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT}), -
Django apps resolving to the wrong namespace
In my project I have three apps, "abc", "xyz" and "common." Common isn't a real app inasmuch as it just stores templates, models and views that are inherited and extended by both apps. Project-level urls.py looks like so, and properly redirects requests to the respective app: urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^abc/', include('abc.urls')), url(r'^xyz/', include('xyz.urls')), ] Both apps' url.py files look like so; the ONLY difference is replace every instance of ABC with XYZ: from django.conf.urls import url from views import ABCAlertList as AlertList from views import ABCEventList as EventList from views import ABCEventDetail as EventDetail from views import ABCEventReplay as EventReplay from views import ABCUploadView as UploadView urlpatterns = [ url(r'^$', AlertList.as_view(), name='view_alerts'), url(r'^entities/(?P<uid>\w+)/$', EventList.as_view(), name='view_uid'), url(r'^entities/(?P<uid>\w+)/replay/$', EventReplay.as_view(), name='view_replay'), url(r'^entities/(?P<uid>\w+)/event/(?P<eid>\w+)/$', EventDetail.as_view(), name='view_event'), url(r'^upload/$', UploadView.as_view(), name='upload_file'), ] Again, all the views are common between both apps so there is nothing app-specific to either of them. Both apps make use of the same line in the same common template: <a href="{% url 'view_uid' alert.uid %}"> Now, the problem: App ABC works fine on the top-level page. But the urls it's rendering to go past that point point to the wrong app. For example, I'll be in http://localhost:8888/abc/ and the urls on … -
Where are my files / Docker Django Digital Ocean
(beginner question) I've deployed a Docker container in a droplet on Digital Ocean, following this tuto Everything is up and running. But where are stored my files within my droplet? My Dockerfile mention a /app, but there isn't any when I ssh my droplet. FROM python:3.5 ENV PYTHONUNBUFFERED 1 # Requirements have to be pulled and installed here, otherwise caching won't work COPY ./requirements /requirements RUN pip install -r /requirements/production.txt \ && groupadd -r django \ && useradd -r -g django django COPY . /app RUN chown -R django /app COPY ./compose/django/gunicorn.sh /gunicorn.sh COPY ./compose/django/entrypoint.sh /entrypoint.sh RUN sed -i 's/\r//' /entrypoint.sh \ && sed -i 's/\r//' /gunicorn.sh \ && chmod +x /entrypoint.sh \ && chown django /entrypoint.sh \ && chmod +x /gunicorn.sh \ && chown django /gunicorn.sh WORKDIR /app ENTRYPOINT ["/entrypoint.sh"] -
Displaying nested models in admin.py in Django
I'm trying to write an app to store and view recipes in Django. I'm having troubles with how to properly write admin.py to do what I want. The functionality I want is that I can register types of ingredients that should include the name and the type of unit that goes with it, for instance, the ingredient type flour should have the unit gramsassociated with it. Then I want to register the recipes, select the appropriate ingredient type and input a quantity for that type in that recipe, i.e. each recipe has a set of ingredient types associated with it and each type has a quantity associated with it, unique to that recipe. Here are my models so far: class IngredientType(models.Model): ingredient_name = models.CharField(max_length = 64, blank = False, null = False) unit = models.CharField(max_length = 16, blank = True, null = True, default = None) def __str__(self): return self.ingredient_name class Ingredient(models.Model): ingredient_type = models.ForeignKey(IngredientType) quantity = models.DecimalField(max_digits = 5, decimal_places = 2, blank = True, null = True, default = None) class Recipe(models.Model): recipe_name = models.CharField(max_length = 256) ingredients = models.ManyToManyField(Ingredient) def __str__(self): return self.recipe_name What I've tried in admin.py is the following: class IngredientTypeInline(admin.TabularInline): model = Recipe.ingredients.through class … -
Django: how to switch to another view with the click of a button?
I am building a django app using django 1.9.5 and Python 2.7.11. My project (which I named djan_web) directory looks like the following: djan_web\ manage.py djan_frontend\ views.py templates\ djan_frontend\ upload.html djan_homepage\ index.html djan_web/ urls.py I am able to load index.html, which is my homepage here. In index.html, I have a button, which when clicked, I would like to load upload.html. Here are my the relevant files: index.html: <!DOCTYPE html> <html> <head> <title >Django Wed Project</title> <meta http-equiv="Content-Type" content="text/html;charset=utf-8"/> </head> <body> <div class="header"> <p> some text </p> <div class="container" style="width:95%"> <center> <div class="col-md-1 center-block text-center" style="font-size: xx-large"> <a href="/upload-file" class="dark" style="cursor: pointer;"> <span class="glyphicon glyphicon-upload"></span>Let's get started!</a> </div> </center> </body> </html> urls.py: from django.conf.urls import include, url from django.contrib import admin from djan_frontend import views from django.views.generic import TemplateView urlpatterns = [ url(r'^', views.homepage, name="homepage"), url(r'^admin/', admin.site.urls), url(r'^upload-file/$', views.upload, name='upload') ] views.py: from django.http import HttpResponseRedirect from django.shortcuts import render from django.core.urlresolvers import reverse from .upload_file import UploadFileForm from .models import Document from .tasks import process_csv def homepage(request): return render(request, 'djan_frontend/djan_homepage/index.html') def upload(request): return render(request, 'djan_frontend/upload.html') I am able to load index.html, but when I click the button Let's get started nothing happens except for the URL, where upload-file/ gets appended … -
Setting session variables in template
I want to pass few values from the template to the views. The best way I found is to pass them through the session. I tried to write the values to the session in the javascript like this: sessionStorage.setItem("key", value); and to recieve it in the views like this: value = request.session['key'] but it gives an error that the key doesn't exsit. All the answers I got were how to get the value from the session in the template but not how to set it! How can I do this? Thank you very much. -
django rest framework filter on related model
I have a model countries and a model of persons on holiday in a certain year to a country. I want to have an Api of Countries in which I can filter only the countries in which certain persons had a holiday in a certain year. Models.py from django.db import models class Country(models.Model): id = models.CharField(max_length=50,primary_key=True) country = models.CharField(max_length=255,null=True) class PersonYear(models.Model): id = models.IntegerField(primary_key=True) person = models.CharField(max_length=255,null=True) year = models.IntegerField(null=True) country = models.ForeignKey(Country, related_name='personyears') Contents of model Country id|country 1|France 2|Italy 3|Spain Contents of model PersonYear id|person|year|country_id 1|John|2014|1 2|John|2015|1 3|Mary|2014|1 serializers.py from apiapp.models import PersonYear,Country from rest_framework import serializers class PersonyearSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = PersonYear fields = ('id','person','year') class CountrySerializer(serializers.HyperlinkedModelSerializer): personyears = PersonyearSerializer(many=True) class Meta: model = Country fields = ('id','country','personyears') Views.py import rest_framework_filters as filters class PersonyearFilter(filters.FilterSet): id = filters.AllLookupsFilter(name='id') person = filters.AllLookupsFilter(name='person') year = filters.AllLookupsFilter(name='year') class Meta: model = PersonYear class PersonyearViewSet(viewsets.ModelViewSet): queryset = PersonYear.objects.all() serializer_class = PersonyearSerializer filter_backends = (filters.backends.DjangoFilterBackend,) filter_fields = ['id','person','year'] filter_class = PersonyearFilter class CountryFilter(filters.FilterSet): id = filters.AllLookupsFilter(name='id') nm = filters.AllLookupsFilter(name='country') personyears = filters.RelatedFilter(PersonyearFilter,name='personyears') class Meta: model = Country class CountryViewSet(viewsets.ModelViewSet): queryset = Country.objects.all() serializer_class = CountrySerializer filter_backends = (filters.backends.DjangoFilterBackend,) filter_fields = ['id','country','personyears'] filter_class = CountryFilter I want a selection of all countries … -
Formatting in CSV using Django CSV library
In views.py File import csv from django.http import HttpResponse from django.contrib.auth.models import User def export_users_csv(request): response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="users.csv"' writer = csv.writer(response) writer.writerow(['Username', 'First name', 'Last name', 'Email address']) users = User.objects.all().values_list('username', 'first_name', 'last_name', 'email') for user in users: writer.writerow(user) return response I want make formatting of column name. ie. bold , italic , etc. Please note : Its csv file and as per my need can not work with xls. looking for any feedback -
Toogle text with delay in jQuery
I have the following code where the user clicks on a button and runs an executable in the background. Once the executable is complete it proceeds to a new page. It takes a few seconds to load the new page and I want to display a small animation to the user. At the moment I am able to change the text of the button from Execute to Loading... once the user clicks on the button. How can I animate or loop the text from Loading... -> Loading.. -> Loading. until the new page loads? I just want to animate the periods. Any resources on this is helpful. <form class="navbar-form navbar-left" method='POST' action='App/Address'>{% csrf_token %} <div class="form-group"> <input type = 'submit' class="btn-lg btn-danger" value = 'Execute' name ='action'{% if read %} disabled {% endif %} id="loading" data-loading-text="Loading..." autocomplete="off"/> </div> </form> <script> $(document).ready(function(){ $('#loading').on('click', function(){ $( this ).button( 'loading' ).delay() }); }); </script> -
populate data in FilteredSelectMultiple after ajax call
I have a django adimin form which contains a Choice field (select dropdown) and a filteredSelectMultiple widget. I want to populate data in the filteredSelectMultiple widget after the user has selected a drop down option from the previous element. I am making an ajax call when the user selects the drop down option and then populating data in filteredSelectMultiple widget. But then all the functionality of the widget are not working (like search, move to choosen item). Everything gets cleared. class DNCF(forms.ModelChoiceField): def label_from_instance(self,obj): return "%s (%s)" % (obj.f_name,obj.l_name) class UserForm(forms.ModelForm): class Media: js = ( settings.STATIC_URL + "js/filter_widget.js",) d=DNCF(queryset=D.objects.all()) v= UserModelMultipleChoiceField( widget=FilteredSelectMultiple( verbose_name='Details', is_stacked=False ), queryset=V.objects.none() ) And I am doing this in my js file. options.push('<select multiple="multiple" class="selectfilter" name="v" id="id_v">'); for (var i = 0; i < v.length; i++) { options.push('<option value="' + v[i]['id'] + '">' +v[i]['v_name'] + ' (' + v[i]['b_name'] + ')' + '</option>'); } options.push('</select>'); jQuery('#id_v').html(options.join('')); SelectFilter.init(null, "Available V", 0, "/path/to/django/media/"); -
Weird caching using Django and Chosen
I have a field where you can delete one or more customers. However if certain conditions are met, the deletion is prevented. The problem is that when the form validation comes back with the error message, the customer is not there anymore and this causes confusion among the users whether it has been removed for not. For example: Let's pretend I want to remove the customer bellow: An error: However the customer is not in the field anymore. It seems to be due to some kind of caching with Javascript - I am not sure. If I refresh the page I can see the customer has not been removed, because it comes back. How can I make sure the value comes back after the validation? -
Django multiple exists() aggregate
class Order(models.Model): # Some fields.. status = models.IntegerField() user = models.ForeignKey(User) the status field can get four values: 1,2,3,4 I want to perform a query which will return a single row (tuple), with an indicator, according to: if in the queryset there is a row with status=1, return 1 elif there's row with status=3, return 3 elif there's row with status=4, return 4 elif there's row with status=2, return 2 In this priority (i.e, in this order, similar to how switch-case works). I query them for a specific user to display some status message. So it should start somewhat like this: Order.objects.filter(user=request.user) # ...? .aggregate() maybe ? And I only need the indicator, not any Order objects. I think in the db level it goes to something like Case, but I couldn't get that to work with django. EDIT: to explain better, I could do it like that if Order.objects.filter(user=request.user, status=1).exists(): return 1 elif Order.objects.filter(user=request.user, status=3).exists(): return 3 elif Order.objects.filter(user=request.user, status=4).exists(): return 4 elif Order.objects.filter(user=request.user, status=2).exists(): return 2 But obviously I want to avoid doing 4 queries.. -
Reports With Django
I'm trying to create a pretty advanced query within django and im having problems doing so, i can use the basic: for obj in Invoice.objects.filter(): but if i try and move this into raw PostgreSQL query i get an error telling me that the relation does not exist am i doing something wrong, i am following the Preforming raw SQL on the django documents but i keep getting same error full code: def csv_report(request): response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="somefilename.csv"' writer = csv.writer(response, csv.excel) response.write(u'\ufeff'.encode('utf8')) writer.writerow([ smart_str(u"ID"), smart_str(u"value"), smart_str(u"workitem content type"), smart_str(u"created date"), smart_str(u"workitem.id"), smart_str(u"workitem"), smart_str(u"workitem_content_type"), ]) for obj in Invoice.objects.raw('SELECT * from twm_Invoice'): writer.writerow([ smart_str(obj.pk), smart_str(obj.value), smart_str(obj.workitem_content_type), smart_str(obj.created_date), smart_str(obj.workitem_id), smart_str(obj.workitem), smart_str(obj.workitem_content_type), ]) return response i have tried to use the app now within front of the model name and without none of them seem to work. Thanks J -
Spliting up data to match a certian criteria in my view and template django
I want to be able to split up my reading(reading is Inspeciton_vals object) data into multiple rows based off of a description(description is a object from my dimension model) So far I haven't figured out any way of doing so, any help would be greatly appreciated. To break it down I have a Inspeciton_vals model that has a foreign key to dimension each dimension will have a determined amount of inspection_vals assigned for my sheet model (object sample_size) for this particular one it is 24 so, my inspection_vals table will have 48 due to it having two dimensions with 24 each. I was thinking about keying off the id in my dimension model to break it down but, I cant seem to figure out a solid solution. Here is my views.py @login_required def shipping(request, id): sheet_data = Sheet.objects.get(pk=id) work_order = sheet_data.work_order customer_data = Customer.objects.get(id=sheet_data.customer_id) customer_name = customer_data.customer_name title_head = 'Shipping-%s' % sheet_data.work_order complete_data = Sheet.objects.raw("""select s.id, d.id d_id, s.work_order, d.target, i.reading, d.description, i.serial_number from app_sheet s left join app_dimension d on s.id = d.sheet_id left join app_inspection_vals i on d.id = i.dimension_id""") for c_d in complete_data: dim_description = Dimension.objects.filter(sheet_id=c_d.id).values_list('description', flat=True).distinct() dim_id = Dimension.objects.filter(sheet_id=c_d.id)[:1] for d_i in dim_id: dim_data = Inspection_vals.objects.filter(dimension_id=d_i.id) … -
Filter safe does not work on the shy tag issue
I have a problem with breaking words in the right place at the Django template. Appears &shy; I'm trying to filter safe, but it does not work. Here is my code: <div class="my_class"> <h3>{{ object.title|safe }}</h3> </div> -
Django-superform does not render
My spec: Django 1.9 Python 3.5.1 django-superform 0.3.1 My goal: I want bod_quota form nested with CustomerForm My attempt I have follow the docs https://github.com/gregmuellegger/django-superform But it does not rendered nested form. customer/model.py class Customer(models.Model): customer_code = models.CharField(max_length=10, unique=True) name_th = models.CharField(max_length=100) name_en = models.CharField(max_length=100) customer/form.py class CustomerForm(SuperModelForm): manual_quota = InlineFormSetField(parent_model=Customer, model=BodQuota, fields = ( "quota_per_occurrence_type", "quota_by_month", "quota_by_year", "quota_count_method_type", ) ) class Meta: model = Customer fields = [ 'customer_code', 'name_th', 'name_en', ] bod_quota/model.py class BodQuota(models.Model): # # Change Quota General Types # class QuotaPerOccurrenceType(DjangoChoices): monthly = ChoiceItem('monthly') yearly = ChoiceItem('yearly') class QuotaCountMethodType(DjangoChoices): circuit_based = ChoiceItem('circuit_based') customer_based = ChoiceItem('customer_based') customer = models.ForeignKey(Customer, default=None) quota_per_occurrence_type = models.CharField( max_length=10, choices=QuotaPerOccurrenceType.choices, validators=[QuotaPerOccurrenceType.validator], default=QuotaPerOccurrenceType.monthly) quota_by_month = models.PositiveSmallIntegerField( null=False, blank=False, default=0, help_text=_("monthly quota")) quota_by_year = models.PositiveSmallIntegerField( null=False, blank=False, default=0, help_text=_("annually quota")) quota_count_method_type = models.CharField( max_length=20, choices=QuotaCountMethodType.choices, validators=[QuotaCountMethodType.validator], default=QuotaCountMethodType.customer_based) bod_quota/forms.py class BodQuotaForm(ModelForm): class Meta: model = BodQuota fields = ( "quota_per_occurrence_type", "quota_by_month", "quota_by_year", "quota_count_method_type", ) BodQuotaFormSet = modelformset_factory(BodQuota, form=BodQuotaForm) Problem: manual_quota does not show in the browser -
Django csv UnicodeDecodeError during opening excel file
I have a model: class Model(models.Model): import_file = models.FileField(upload_to="import") def save(self, *args, **kwargs): super(Model, self).save(*args, **kwargs) with open(self.import_file.name) as csvfile: reader = DictReader(csvfile, dialect='excel') for line in reader: print (line) I got 'utf-8' codec can't decode byte 0x95 in position 15: invalid start byte The string that could not be encoded/decoded was: !f�} I tried with utf16, but then I got error with BOM. Do you guys have any ideas? -
Hendrix missing admin django template
I'm starting my first demo app with Hendrix, my firsts steps come from here (Django / Twisted (or hendrix) help to start). Right now I create the project and only do this 1- Add sitetree extension 2- run migrate to create database 3- create super user When I run "hx start" and enter to admin app, every thing works perfect, but when start the project using this script from hendrix.deploy.base import HendrixDeploy deploy = HendrixDeploy (options={'wsgi':'portal.wsgi.application'}) deploy.run() The project start without error but the template for Admin app is missing, probably I forgot something, but I don't know what. Thank you in advance for any help. Best Regards -
Subdomain throughing 403 forbidden
Working on main domain site (eg. www.mysite.com) and after login into it (eg. www.mysite.com/login) it sets few cookies that are not allowing me to login on sub-domain (eg. work.mysite.com/login) runs on Django framework, it throws the following error: CSRF verification failed. Request aborted. You are seeing this message because this site requires a CSRF cookie when submitting forms. This cookie is required for security reasons, to ensure that your browser is not being hijacked by third parties. If you have configured your browser to disable cookies, please re-enable them, at least for this site, or for 'same-origin' requests. Cookie, which creating problem, keeps the user tracking info ( page references by pageid/name). After deleting all cookies or without login in main domain , my sub-domain works well but I don't know why is it not working in above scenario. Sub-domain has CSRF verification enabled page. Let me know if i have missed something.