Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
The proper Django way to make a form field required on CreateView, but optional on UpdateView?
Let's say I create an model MyModel instance that has a FileField using CreateView and associated MyModelCreateForm, and now I want to update it without uploading the same avatar image: class MyModel(models.Model): name = models.CharField() avatar = models.ImageField() class MyModelCreateForm(forms.ModeForm): class Meta: model = MyModel exclude = None class MyModelCreate(CreateView): model = MyModel form_class = MyModelCreateForm class MyModelCreate(UpdateView): model = MyModel form_class = ? On the CreateView's form the image is compulsory. If I want to make it optional on the update field, what's the most Django-ish way of doing this? Do I need to make a new form for the UpdateView that inherits from MyModelCreateForm but overrides the ImageField required attribute? Or is there a more "batteries-included" way? -
Django: Avoid showing error details in production
I am trying to make sure that my site is properly protected from showing the details of the error in production. I've been struggling with this for a while, as at beginning I understood that in order to avoid Django from showing the error (module, line of code, etc.) all that was needed was changing DEBUG from TRUE to FALSE in settings.py. However, I realized that Django was still showing error details, so investigating a bit more and I came to know that the following was also needed: TEMPLATE_DEBUG = DEBUG in settings.py 404.html and 500.htmlinside the templates folder Is there anything else needed to make sure that the user does not get those messages? And how does Django deal with the other kind of errors, like 400? I saw here that there are handlers for 400 and 403, but I do not understand it and I don't know if they are needed at all for a basic using case. -
Django migrations mixed up with 'PROTECT' and 'CASCADE'
I am stuck with migrations in django. I have two really basic models that will not migrate: from django.db import models # Create your models here. class Instanz(models.Model): type = models.CharField(max_length=30) angelegt_am = models.DateField(auto_now_add=True) class Person(models.Model): instanz_fk = models.ForeignKey('Instanz', on_delete=models.CASCADE) last_name = models.CharField(max_length=30) first_name = models.CharField(max_length=30) geburtsdatum = models.DateField() It will raise the following exception. I dont get why it will search for a field named PROTECT. I used models.PROTECT in earlier migrations, before switching to CASCADE, but not any longer... Operations to perform: Apply all migrations: admin, auth, contenttypes, kundencenter, sessions Running migrations: Applying kundencenter.0001_initial...Traceback (most recent call last): File "C:\Users\Micha\Dropbox\PycharmProjects\vertriebstool_virtualenv\lib\site-packages\django\db\models\options.py", line 617, in get_field return self.fields_map[field_name] KeyError: 'PROTECT' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\Micha\Dropbox\PycharmProjects\vertriebstool\manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "C:\Users\Micha\Dropbox\PycharmProjects\vertriebstool_virtualenv\lib\site-packages\django\core\management\__init__.py", line 367, in execute_from_command_line utility.execute() File "C:\Users\Micha\Dropbox\PycharmProjects\vertriebstool_virtualenv\lib\site-packages\django\core\management\__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Micha\Dropbox\PycharmProjects\vertriebstool_virtualenv\lib\site-packages\django\core\management\base.py", line 294, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Micha\Dropbox\PycharmProjects\vertriebstool_virtualenv\lib\site-packages\django\core\management\base.py", line 345, in execute output = self.handle(*args, **options) File "C:\Users\Micha\Dropbox\PycharmProjects\vertriebstool_virtualenv\lib\site-packages\django\core\management\commands\migrate.py", line 204, in handle fake_initial=fake_initial, File "C:\Users\Micha\Dropbox\PycharmProjects\vertriebstool_virtualenv\lib\site-packages\django\db\migrations\executor.py", line 115, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "C:\Users\Micha\Dropbox\PycharmProjects\vertriebstool_virtualenv\lib\site-packages\django\db\migrations\executor.py", line 145, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "C:\Users\Micha\Dropbox\PycharmProjects\vertriebstool_virtualenv\lib\site-packages\django\db\migrations\executor.py", line 244, in … -
Why do Django forms displaying as table?
Why do Django forms display as table? I did define any table as display. from django import forms class FieldForm(forms.Form): field = forms.CharField(label='Field:', max_length=32) <form action="" method="get"> {{ form }} <input type="submit" value="Submit" /> </form> output: <tr><th><label for="id_field">Field:</label></th><td><input id="id_field" maxlength="32" name="field" type="text" required /></td></tr> -
Django Rest Framework can't find any of my <model>-detail views
Here is the error message I get upon going to a hyperlink from the API root: Reverse for '<model>-detail' with arguments '()' and keyword arguments '{'pk': 2}' not found. 0 pattern(s) tried: [] It can't find <model>-detail for any of my views, and I have no idea why. I tried to follow the Django and DRF tutorials pretty closely. Below are the relevant details of my project. Let me know if I've left out any necessary details. Directory Structure: budgetsite/ budgetsite/ urls.py budgetapp/ models.py serializers.py views.py urls.py budgetsite/urls.py from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^budget/', include('budgetapp.urls')), url(r'^admin/', admin.site.urls), url(r'^api-auth/', include('rest_framework.urls')), ] budgetapp/urls.py from django.conf.urls import url, include from . import views from rest_framework.routers import DefaultRouter app_name = 'budgetapp' # DRF Router router = DefaultRouter() router.register(r'budgets', views.BudgetViewSet) router.register(r'users', views.UserViewSet) router.register(r'categories', views.CategoryViewSet) router.register(r'categorybudgets', views.CategoryBudgetViewSet) router.register(r'incomes', views.IncomeViewSet) router.register(r'budgetgoals', views.BudgetGoalViewSet) router.register(r'longtermgoals', views.LongTermGoalViewSet) router.register(r'categorybudgetgroups', views.CategoryBudgetGroupViewSet) router.register(r'transactions', views.TransactionViewSet) urlpatterns = [ url(r'^', include(router.urls)), ] models.py import datetime import moneyed from djmoney.models.fields import MoneyField from django.db import models from datetime import date class Budget(models.Model): month = models.DateField() owner = models.ForeignKey('auth.User', related_name='budgets') class Category(models.Model): name = models.CharField(max_length=100) owner = models.ForeignKey('auth.User', related_name='categories') class CategoryBudgetGroup(models.Model): name = models.CharField(max_length=100) budget = models.ForeignKey(Budget, on_delete=models.CASCADE) class CategoryBudget(models.Model): … -
DJANGO image processing
I want to create a django app with the base64 help where the users can upload images(specific ".tiff" ext) using DJANGO forms without model and without that images store in my server. and i will the users can be get back new processing image. i have success with encode/decode image with base64 and i can display that image in template using safari because that can display TIFF images. here the code : views.py def convert_to_base64(image_file): base64_string = base64.encodestring(image_file) return "data:image/png;base64,"+base64_string @csrf_exempt def index(request): form = ImageUploadForm(request.POST or None, request.FILES or None) if request.method == "POST" and form.is_valid(): image_file = request.FILES['image'].read() base64_string = convert_to_base64(image_file) file = base64_string.decode('utf8') return render_to_response("blog/success.html", {"image_file":file}) return render_to_response('blog/calc.html', {'form': form}, RequestContext(request)) my problem is now after the base64 i cant use that image for image processing(work fine in standalone python script) and i take two error : RuntimeError at / not a string in the browser and that message in command line : "GET / HTTP/1.1" 200 346 ERROR 4: `II*' does not exist in the file system, and is not recognised as a supported dataset name. here the code : @csrf_exempt def index(request): form = ImageUploadForm(request.POST or None, request.FILES or None) if request.method == "POST" and … -
Django form submit does not work
I have an EventForm form that i want to populate. I use event_form.attributes so I can customize the CSS. But nothing happens when I click submit - the action url is not called or anything. EventForm: class EventForm(forms.ModelForm): name = forms.CharField(max_length=128, help_text="Enter event name") description = forms.CharField(max_length=1024, help_text="Enter event description") date_str = forms.CharField(max_length=128,label="Date", help_text="Enter date in the format: DD/MM/YY") address = forms.CharField(max_length=128, help_text="Enter event address") image = forms.ImageField(label="Event Image") volunteerLimit = forms.IntegerField(initial=10, label="Volunteer Limit") category = forms.ChoiceField(choices=CATEGORY_SELECT, required=True) mininumAge = forms.IntegerField(initial=18, label="Minimum Age") closed = forms.BooleanField(widget=forms.HiddenInput(),initial=False) class Meta: model = Event exclude = ( 'date', 'slug', 'volunteers', "organisation" ) base.html {% csrf_token %} <form id="event_form" method="post" action="/iVolunteer/add_event/"> {% for hidden in event_form.hidden_fields %} {{ hidden }} {% endfor %} <div class="form-group"> {{ event_form.name.errors }} {{ event_form.name.label_tag }} {{ event_form.name|addclass:"form-control form-style"}} </div> <div class="form-group"> {{ event_form.description.errors }} {{ event_form.description.label_tag }} {{ event_form.description|addclass:"form-control form-style"}} </div> <div class="form-group"> {{ event_form.date_str.errors }} {{ event_form.date_str.label_tag }} {{ event_form.date_str|addclass:"form-control form-style"}} </div> <div class="form-group"> {{ event_form.address.errors }} {{ event_form.address.label_tag }} {{ event_form.address|addclass:"form-control form-style"}} </div> <div class="form-group"> {{ event_form.category.errors }} {{ event_form.category.label_tag }} {{ event_form.category|addclass:"form-control form-style"}} </div> <div class="form-group"> {{ event_form.mininumAge.errors }} {{ event_form.mininumAge.label_tag }} {{ event_form.mininumAge|addclass:"form-control form-style"}} </div> <div class="form-group"> {{ event_form.volunteerLimit.errors }} {{ event_form.volunteerLimit.label_tag }} {{ … -
Error when setting the center of a map as a dictionary value
I have an app developed with django: an user enters an integral in a form an gets redirected to a page that, depending of the input, it shows a map or another. The value that the user has entered is in the variable {{linea_numero}} <div id="map"></div> <script> var LatLangParada = [ ["{lat: 40.969092, lng: -5.675925}"], ["{lat: 38.737370, lng: -9.147660}"], ["{lat: 40.412944, lng: -3.681914}"], ["{lat: 41.385691, lng: 2.153859}"], ] var map; function initMap() { map = new google.maps.Map(document.getElementById('map'), { center: LatLangParada[{{linea_numero}}], zoom: 8 }); } </script> I get the error InvalidValueError: setCenter: not a LatLng or LatLngLiteral: in property lat: not a number I tried to delete the "" of the coordinates, but it doesn't work. Thanks in advance -
Conditional expressions on numerical data - Python/Django
Let me show you a situation like this: data = [Station.objects .filter(nr=form.cleaned_data['station']) .aggregate(avg=Avg('residual'), stdev=StdDev('residual'), number=Count('residual'), good_observations = Count(Case(When(abs('residual')<250))), outliers=Count(Case(When(abs('residual')>=250))), )] I want to count rows in database with "residual" (float value) smaller or greater than 250 but it doesn't work. First of all: I've got the TypeEror: init() takes either a Q object or lookups as keyword arguments Secondly: abs() function doesn't work due to TypeError and string value as an input. I hope some of you could help me with this problem :) -
TypeError only with celery
I am using Django. So there is an option CELERY_ALWAYS_EAGER. When I switch off celery workers with CELERY_ALWAYS_EAGER = True, everything is ok. When CELERY_ALWAYS_EAGER = False I get an error: TypeError: unsupported operand type(s) for -: 'unicode' and 'unicode' That's an error when I try to deduct one timestamp from another. Smth like: new_date - old_date What's wrong with celery? How can I avoid it? -
Django Listview.as_view() takes 1 positional argument but 2 were given
Use Listview instead of list_detail in django and failed. How to fix this? I want to get all the books where publisher == name(name from url). def books_by_publisher(request, name): publisher = get_object_or_404(Publisher, name=name) return ListView.as_view(request, queryset=Book.objects.filter(publisher=publisher), template_name='publisher_list_page.html') -
Connecting Django +1.10 with MongoDB
Does anybody replaced the default database engine in Django (+1.10) for MongoDB in the last months? All the info I get in Google is like 6 or 4 years ago. The most commons results includes mongodb-engine which requires django-nonrel (a really old fork from Django 1.5), or mongoengine, also an outdated library that give many errors, so when you patch one, you get a new one. I don't know if there is any "new" way to accomplish this. -
Django project with shuup installation
Pls. I need a hint for a install of shuup (https://github.com/shuup/shuup). I am at a shared hoster and successful installed python 3.4.3 (v3.5 or v 3.6 was not working...) i did: $ python3 -m venv shuup-venv $ source shuup-venv/bin/activate $ pip install -U pip setuptools [at (shuup-venv) master@de1 [~]#] $ pip install shuup [at (shuup-venv) master@de1 [~]#] => everything good: Successfully installed Babel-2.3.4 Django-1.9.12 Jinja2-2.8.1 Markdown-2.6.8 MarkupSafe-0.23 PyJWT-1.4.2 Unidecode-0.4.20 cffi-1.9.1 coreapi-2.2.4 coreschema-0.0.4 cryptography-1.7.1 django-bootstrap3-6.2.2 django-countries-3.4.1 django-enumfields-0.7.4 django-filer-1.2.6 django-filter-1.0.1 django-jinja-1.4.2 django-mptt-0.8.7 django-parler-1.6.2 django-parler-rest-1.4.2 django-polymorphic-0.9.2 django-registration-redux-1.4 django-rest-swagger-2.1.0 django-timezone-field-1.3 djangorestframework-3.5.4 djangorestframework-jwt-1.9.0 easy-thumbnails-2.3 et-xmlfile-1.0.1 factory-boy-2.7.0 fake-factory-0.5.3 idna-2.2 itypes-1.1.0 jdcal-1.3 jsonfield-1.0.3 keyring-10.2 keyrings.alt-2.0 openapi-codec-1.3.1 openpyxl-2.3.5 pillow-3.4.2 pyasn1-0.2.2 pycparser-2.17 pytoml-0.1.11 pytz-2016.10 requests-2.13.0 secretstorage-2.3.1 shuup-1.1.0 simplejson-3.10.0 unicodecsv-0.14.1 uritemplate-3.0.0 xlrd-1.0.0 But with next line $ pip install -e .[everything] [at (shuup-venv) master@de1 [~]#] I got the following error: Directory '.' is not installable. File 'setup.py' not found. ok, It seems there is a disorder in the file structure and the 'setup.py' is missing. hm, why this file disappeared - it was there at the beginning? Whats going wrong? Could you give a hint? -
How to load transliteration API in every text areas?
My Google Transliterate API in location home/googleapi.html is as: <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <script type="text/javascript" src="https://www.google.com/jsapi"> </script> <script type="text/javascript"> // Load the Google Transliterate API google.load("elements", "1", { packages: "transliteration" }); function onLoad() { var options = { sourceLanguage: google.elements.transliteration.LanguageCode.ENGLISH, destinationLanguage: [google.elements.transliteration.LanguageCode.NEPALI], shortcutKey: 'ctrl+g', transliterationEnabled: true }; // Create an instance on TransliterationControl with the required // options. var control = new google.elements.transliteration.TransliterationControl(options); // Enable transliteration in the textbox with id // 'transliterateTextarea'. control.makeTransliteratable(['transliterateTextarea']); } google.setOnLoadCallback(onLoad); </script> </head> <body> <textarea id="transliterateTextarea" type="text" class="form- control" name="{{field}}" placeholder="Enter your {{field }}" style="width:550px;height:40px"></textarea> </body> </html> And my html form is as: {% for field in fields %} {% include "home/googleapi.html" %} {%endfor%} It creates a form with many text fields and I want to convert the English input language to another language in every text fields. The problem is that the input text in first field is only being converted to another language and entered text in all other remaining fields are not being convert. What's exactly going on? How can this API can be used in all other fields? -
Periodic task schedules set through view functions (Django app)
I schedule repeat tasks for my Django app via including them in the CELERYBEAT_SCHEDULE dictionary in my settings.py. For instance: CELERYBEAT_SCHEDULE = { 'tasks.rank_photos': { 'task': 'tasks.rank_photos', 'schedule': timedelta(seconds=5*60), }, 'tasks.trim_whose_online': { 'task': 'tasks.trim_whose_online', 'schedule': timedelta(seconds=10*60), }, } These tasks periodically run (for the life of the app). I was wondering whether there's a way for a regular user of my app to kick off a periodic task? I.e. is there a way to control this kind of scheduling from views.py? If not, why not? And if yes, an illustrative example would be great. Thanks in advance. -
'WSGIRequest' object has no attribute 'user_agent'
I have installed "django-tracking-analyzer" via pip in my virtual environment. Along with this following dependencies have also been installed automatically:- appdirs==1.4.0 Django==1.10.5 django-appconf==1.0.2 django-countries==4.0 django-ipware==1.1.6 django-tracking-analyzer==0.2 django-user-agents==0.3.0 geoip2==2.4.2 maxminddb==1.2.3 mock==2.0.0 packaging==16.8 pbr==1.10.0 pyparsing==2.1.10 pytz==2016.10 requests==2.13.0 six==1.10.0 ua-parser==0.7.3 user-agents==1.0.1 Now the view that keeps track of the product gives me the above error. Here is the view:- from tracking_analyzer.models import Tracker def product_details(request, p_id): q = Product.objects.get(id=p_id) # Track the product Tracker.objects.create_from_request(request, q)#Error context = {"q":q} return render(request, "product_details.html", context) -
Django : Register app but has red underline, url does not work
I just created app which name is 'blog' and registered in settings.py in installed app. However unlike other app that I made, this app name shows red underlines and url setting does not work. When I click button it should send me to 'http://127.0.0.1:8000/blog/add' but instead it send me 'http://127.0.0.1:8000/add/' with page not found error. Here is my settings.py # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'polls', 'blog', ] urls.py in project folder from test.test_xml_etree import namespace from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^polls/', include('polls.urls', namespace="polls")), url(r'^blog/', include('blog.urls', namespace="blog")), ] This is urls.py in blog app. from django.conf.urls import url from blog import views urlpatterns = [ url(r'^$', views.home, name='home'), url(r'^delete/$', views.delete, name='delete'), url(r'^add/$', views.add, name='add'), ] -
Return image using Django REST framework Render
I uploaded images using Django REST Framework. Now I'm trying to return the same image as response.views.py class ImageUploadView(viewsets.ModelViewSet): queryset = ImageModel.objects.all() serializer_class = ImageSerializer def create(self, request, *args, **kwargs): userID = (request.data.get('userID')) serializer = self.get_serializer(data=request.data) if not UserModel.objects.filter(id=userID).exists(): return Response(data={"detail": "Invalid UserID"}) else: if serializer.is_valid(): serializer.save() return Response(ImageModel.objects.get(id=serializer.data['id']).image, content_type="image/png") return Response(data={"detail": "Serializer Error"}) By using the above code, I didn't get neither a valid image (it returns one small square box like image) nor an error Hope someone can help ,Thanks -
django-simple-captcha breaking heroku deploy
I'm using django-simple-captcha and it's working fine locally. The page it's on gives a 500 error once deployed to Heroku (the only log output I get is (2017-02-11T13:26:07.367450+00:00 heroku[router]: at=info method=GET path="/contact/" host=fathomless-harbor-1234.herokuapp.com request_id=37555c3c-c468-40cb-a142-c7dd04519e2c fwd="73.163.191.194" dyno=web.1 connect=1ms service=83ms status=500 bytes=386). I ran the ./manage.py test captcha and got three failed tests, all of which have the similar error of File "/Users/pmn/.virtualenvs/within/lib/python2.7/site-packages/django/template/loader.py", line 43, in get_template raise TemplateDoesNotExist(template_name, chain=chain) TemplateDoesNotExist: captcha_test/image.html I am on django 1.9.6 and django-simple-captcha 0.5.3 forms.py from django import forms from django.template.loader import get_template from django.core.mail import EmailMultiAlternatives from captcha.fields import CaptchaField class ContactForm(forms.Form): contact_name = forms.CharField() contact_email = forms.EmailField() contact_phone = forms.CharField() content = forms.CharField(widget=forms.Textarea) cc_me = forms.BooleanField(required=False, initial=False) captcha = CaptchaField(required=True) def send_email(self): contact_name = self.data["contact_name"] contact_phone = self.data["contact_phone"] contact_email = self.data["contact_email"] content = self.data["content"] template = get_template("contact.txt") context = { "contact_name": contact_name, "contact_phone": contact_phone, "contact_email": contact_email, "content": content, } content = template.render(context) subject, from_email, to = "Inquiry", contact_email, "jason@email.com" cc_address = contact_email if "cc_me" in self.data else None email = EmailMultiAlternatives( subject, content, from_email, ["jason@email.com"], cc=[cc_address], headers={"Reply-To": contact_email} ) email.send() def __init__(self, *args, **kwargs): super(ContactForm, self).__init__(*args, **kwargs) for field in self.fields: self.fields[field].widget.attrs['class'] = 'form-control' (Note if I comment out the two captcha lines, the … -
I got error "Unsupported lookup 'icontains ' for CharField or join on the field not permitted."
I'm trying to make a dynamic query to get data, like follwing: query = request.GET.get('q') kwargs = { '{0}__{1} '.format('first_name','icontains'):query} if query: players_list = players_list.filter(Q(**kwargs)).distinct() then I got this error: Unsupported lookup 'icontains ' for CharField or join on the field not permitted. If I replaced this line kwargs = { '{0}__{1} '.format('first_name','icontains'):query} with this kwargs = { 'first_name__icontains':query} I got no errors can anybody tell me what's the difference between them ?? -
Doesn't worl django-admin.py startproject mysite
I want start a new django project, I use windows 10. If I write to console python -c "import django; print(django.get_version())" return 1.10.3 but if I write django-admin.py startproject mysite it opens ...\appdata\local\programs\python\python35-32\python.exe from django.core import management if __name__ == "__main__": management.execute_from_command_line() and I have path in Environmental Variable: Programs\Python\Python35-32\ How I can do it? -
ValueError with Django form initial
I'm building a reservation app with Django and I want to allow users to use one reservation as template for another. My idea is that I add ?prefill=<reservation_id> to url and then prefill empty form with data from reservation in prefill id. My CreateView looks like this: class ReservationCreateView(LoginRequiredMixin, CreateUpdateMixin, CreateView): model = Reservation form_class = ReservationForm success_url = '/' def get_context_data(self, **kwargs): ctx = super(ReservationCreateView, self).get_context_data() r = Reservation.objects.filter(pk=self.request.GET.get('prefill')) ctx['form'] = ReservationForm(initial=r.values(), request=self.request) return ctx This gives me: dictionary update sequence element #0 has length 30; 2 is required Error stack: Environment: Request Method: GET Request URL: http://localhost:8000/r/create/?prefill=56cc36bd-c766-4e45-8a1b-cdde3cd87dc4 Django Version: 1.10.3 Python Version: 2.7.10 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'tags', 'profiles', 'reservations', 'drivers', 'import_export', 'src', 'crispy_forms', 'rest_framework', 'rest_framework.authtoken', 'corsheaders', 'anymail', 'wf', 'storages', 'djangoformsetjs'] Installed Middleware: ['corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'htmlmin.middleware.HtmlMinifyMiddleware', 'htmlmin.middleware.MarkRequestMiddleware'] Traceback: File "/Users/jhotujec/Documents/projects/optilimo/venv/lib/python2.7/site-packages/django/core/handlers/exception.py" in inner 39. response = get_response(request) File "/Users/jhotujec/Documents/projects/optilimo/venv/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/Users/jhotujec/Documents/projects/optilimo/venv/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/jhotujec/Documents/projects/optilimo/venv/lib/python2.7/site-packages/django/views/generic/base.py" in view 68. return self.dispatch(request, *args, **kwargs) File "/Users/jhotujec/Documents/projects/optilimo/venv/lib/python2.7/site-packages/django/contrib/auth/mixins.py" in dispatch 56. return super(LoginRequiredMixin, self).dispatch(request, *args, **kwargs) File "/Users/jhotujec/Documents/projects/optilimo/venv/lib/python2.7/site-packages/django/views/generic/base.py" in dispatch 88. return handler(request, *args, **kwargs) File "/Users/jhotujec/Documents/projects/optilimo/reservations/mixins.py" in get … -
Redirect to referrer page after modal submission in Django
In my Django app, I have a couple of pages to Create poll question /poll/create-question Edit poll question /poll/edit-question/<question_number> Each of those pages has an option to associate the question with a category name from a drop down list. The user can also create a category on the fly, if the required category is not present in the list. On clicking a button to create the category, a Bootstrap modal pops up and the user can input the category name and submit it. This POST request is handled by a separate view function (with urlpattern /poll/create-category). Also, the create category option is available in both the pages (Create & Edit) Things are working fine. Except that I wanted to redirect to the original page (i.e., Create or Edit) after the modal is closed. The request object has a property call HTTP_REFERER which holds the complete url http://servername:port/poll/create-question. But I wanted just the urlpattern of the referrer page /poll/create-question. Is there a way in Django to get that and redirect to the original page upon submitting a modal? How is this kind of feature usually handled in Django? -
Paramiko django mongodb
So I am using paramiko for SSH tunneling. I want to be able to tunnel to my mongodb and do queries from my django webapp. I cannot seem to get it working. Any ideas? -
Django KeyError: ' size '
When i try add product to cart i have this error. Without size this work but i need size. So what can i do to fix it ? February 11, 2017 - 12:04:30 Django version 1.10.5, using settings 'villain.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. [11/Feb/2017 12:04:41] "GET /8/koszulka-moro/ HTTP/1.1" 200 3624 Internal Server Error: /cart/add/8/ Traceback (most recent call last): File "/home/krystian/.virtualenvs/vpw/lib/python3.5/site-packages/django/core/handlers/exception.py", line 39, in inner response = get_response(request) File "/home/krystian/.virtualenvs/vpw/lib/python3.5/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/krystian/.virtualenvs/vpw/lib/python3.5/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/krystian/.virtualenvs/vpw/lib/python3.5/site-packages/django/views/decorators/http.py", line 40, in inner return func(request, *args, **kwargs) File "/home/krystian/Project/villain/villain/cart/views.py", line 19, in cart_add update_size=cd['size_update'] File "/home/krystian/Project/villain/villain/cart/cart.py", line 34, in add self.cart[product_id]['size'] += size KeyError: 'size' This ii my cart.py class Cart(object): def __init__(self, request): """ Inicjaliazacja koszyka na zakupy. """ self.session = request.session cart = self.session.get(settings.CART_SESSION_ID) if not cart: # pusty koszyk w sesji cart = self.session[settings.CART_SESSION_ID] = {} self.cart = cart def add(self, product, quantity=1, update_quantity=False, update_size=False, size=None): """ Dodanie produktu i zmiana ilości """ product_id = str(product.id) if product_id not in self.cart: self.cart[product_id] = {'quantity': 0, 'price': str(product.price)} if update_quantity: self.cart[product_id]['quantity'] = quantity else: self.cart[product_id]['quantity'] += quantity if update_size: self.cart[product_id]['size'] …