Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Method Not Allowed (POST): /login/
I'm trying to get the users data using a form which I have in a .html file called login.html. The code for that is: <form class="register-form" method="POST" action="{% url 'login' %}"> {% csrf_token %} <table> <tr> <td>Username: </td> <td><input type="username" name="username"><br></td> </tr> <tr> <td>Password: </td> <td><input type="password" name="password"><br></td> </tr> </table> <br> <input type="submit" value="Login" /> </form> I've already got a database with a bunch of users where username and passwords are stored. I want to create my own login page that checks agains that database. What I'm trying to do is essentially get the user to the login.html page and then let the user enter the details and check against the database. My urls.py looks like this: from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^register$', include('register.urls')), url(r'^login/', include('login.urls')), url(r'^', include('home.urls')), ] effectively it goes to the login.urls where the urls.py for that is: from django.conf.urls import url, include from django.contrib import admin from login import views urlpatterns = [ url(r'^$', views.LoginPageView.as_view(), name='login'), ] my views.py is: from django.shortcuts import render from django.views.generic import TemplateView from person.models import Person class LoginPageView(TemplateView): template_name = "login.html" def get(self, request, **kwargs): print(request) return render(request, 'login.html') Problem is … -
How to store array of Python dicts in PostgreSQL?
I have a Django project and such array in it: {(0,0):{'a':True,'b':False ... },(0,1):{'a':True,'b':True ... },(1,1):{'a':True,'b':False ... }... } I need to store this array in PostgreSQL database. I thought the ArrayField could help, but I just have no idea how to declare such array. I've read https://docs.djangoproject.com/en/1.11/ref/contrib/postgres/fields/ but there was not my situation. Could you show me an example? -
Reverse for 'loan' with arguments '()' and keyword arguments '{u'pk': '', u'cust': ''}' not found
In the template {{ headers }} {% load i18n admin_static material_admin %} {% if results %} <div class="results"> <table id="result_list" class="table bordered highlight"> <thead> <tr> {% for header in result_headers %} {% if 'action_checkbox' in cl.list_display and forloop.counter == 1 %} <th class="action-checkbox"> {{ header.text }}<label for="action-toggle">&nbsp;</label> </th> {% else %} <th scope="col" {{ header.class_attrib }}> {% if header.sortable %} {% if header.sort_priority == 0 %} <a href="{{ header.url_primary }}" data-turbolinks="false">{{ header.text|capfirst }}</a> {% elif header.ascending %} <a href="{{ header.url_primary }}" title="{% trans "Toggle sorting" %}" data-turbolinks="false"><i class="material-icons">arrow_upward</i>{{ header.text|capfirst }}</a> {% else %} <a href="{{ header.url_remove }}" title="{% trans "Remove from sorting" %}" data-turbolinks="false"><i class="material-icons">arrow_downward</i>{{ header.text|capfirst }}</a> {% endif %} {% else %} <span>{{ header.text|capfirst }}</span> {% endif %} </th>{% endif %}{% endfor %} {% if row_actions_template %} <th style="text-align:right;">{% trans "Actions" %}</th> {% endif %} </tr> </thead> <tbody> {% for row in results %} <tr class="{% cycle 'row1' 'row2' %}"> {% for item in row.cols %} {{ item }} {% endfor %} {% if row_actions_template %} <td class="row-actions">{% include row_actions_template with object=row.object %}</td> {% endif %} </tr> {% endfor %} </tbody> </table> </div> {% endif %} {% include "loanwolf/pagination.inc.html" %} the part following part worked well <tbody> {% for … -
DJango: Error in formatting: ProgrammingError: relation
I need help I can not find this error in my code. I am getting an error that states "Error in formatting: ProgrammingError: relation "products_letter" does not exist LINE 1: ...oduct"."views" FROM "products_product" INNER JOIN "products_... ^" Now the app works fine on development server running Postgres. When on heroku is where I run into this issue. Below is the code and traceback. I have ran migrations and also even removed all migrations and ran again. Traceback: Request Method: GET Request URL: https://www.pricereference.com/search/?q=john Django Version: 1.10.4 Python Version: 3.6.0 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'whitenoise.runserver_nostatic', 'django.contrib.sitemaps', 'django.contrib.sites', 'django.contrib.flatpages', 'crispy_forms', 'django.contrib.postgres', 'products', 'blog', 'newsletter'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.gzip.GZipMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware'] Template error: In template /app/templates/search.html, error at line 15 relation "products_letter" does not exist LINE 1: ...oduct"."views" FROM "products_product" INNER JOIN "products_... ^ 5 : <img class="" src="http://stackedservers.com/cdn/background.png"> 6 : <div class="uk-width-medium-1-2 uk-container-center"> 7 : <img class="home-logo" src="http://stackedservers.com/cdn/pr-home.png"> 8 : <form method='GET' action='{% url "search" %}' class="uk-form"> 9 : <fieldset data-uk-margin> 10 : <input class="uk-form-width-large uk-form-large uk-search-field search-form " type="search" placeholder="Search For A Product" name='q' value='{{request.GET.q}}' /> 11 : <button class="uk-button uk-button-large uk-button-primary" type="submit">Search</button> 12 : </fieldset> 13 : </form> 14 : </div> … -
Django unit upload zipfile
For my project made in Django, I have a page with a form allowing the user to upload a zipfile. Then from this zip file, I open it and read a file from there. I started with the unit tests to validate all cases : - Not a .zip extension - zipfile.is_zipfile() return False - Can't find the file I want to read inside - File inside is invalid For my unit tests, I create different files for each error, and upload it using django.test.Client as so : with open_file('wrong_format.zip') as file: response = self.client.post(url, {'archive': file}) self.assertEqual(response.status_code, 200) self.assertContains(response, '<li>Only zip archived are allowed</li>') But I get the following error : UnicodeDecodeError: 'utf-8' codec can't decode byte 0x99 in position 10: invalid start byte It works fine when I do it from the browser -
How do I save data of the user?
I have Model: models.py class UserProfile(models.Model): user = models.OneToOneField(User, related_name='userprofile') points = models.IntegerField(default=0) urls.py urlpatterns = [ url(r'^$', demo), url(r'^demo/$', demo), ] demo.html <form action="" method="POST"> <button type="submit">+</button> </form> views.py def demo(request): if request.method == "POST": # I don't understand how I can get "points" from the model "UserProfile" #to add 1 and to save in the DB return render(request, 'app/demo.html') I would like that after pressing on the button points of the user increased one. I really cannot figure it out. -
Issue in a Django's template
Actually, I know it is impossible in a Django's template, but I would like to execute {{ Perception.objects.filter(loan__request__customer__pk = 207) }} Here is the views I use for that template : class PerceptionIndexView(StaffRestrictedMixin, FrontendListView): page_title = _('Perception') model = Perception template_name = 'loanwolf/perception/index.html' pjax_template_name = 'loanwolf/perception/index.pjax.html' row_actions_template_name = 'loanwolf/perception/list-actions.inc.html' url_namespace = 'perception' def active(self, obj): if obj.is_active: return icon(obj.get_icon(), css_class='green-text', tooltip=_('Active')) else: return icon(obj.get_icon(), css_class='red-text', tooltip=_('Inactive')) def notes_count(self, obj): return obj.notes.count() notes_count_label = _('Notes') def get_change_url(self, obj): return obj.get_absolute_url() def my_view(self, A_pk): filter_perceptions= Perception.objects.filter(loan__request__customer__pk=A_pk) return render_to_response('../template/loanwolf/perception/list-view-#2.inc.html', {'filter_perceptions': filter_perceptions}) I tried to use render_to_response with different path, but nothing happen so far. knowing that my view is located in loanwolf/perception and my template list-view-#2.inc.html is located in loanwolf/templates/loanwolf/perception. Furthermore, it is important to know that FrontendListView use a ListView. I think I could not use a 'render_to_response', but it is unclear. Could anyone have an alternative solution so that I could access the list Perception.objects.filter(loan__request__customer__pk) in my template? -
How to use Django's admin Boolean icons in a custom template?
I'm trying to build a django template that at one point displays a boolean variable. However, I want to display an icon instead of the words "True" or "False". I know the Django Admin does this. I'm trying to avoid having to use something like this everytime I do it: {% if variable %} True Icon HTML {% else %} False Icon HTML {% endif %} Any Ideas? Thanks. Chris -
Django - object values to jQuery
I have Group model with fields: pay ('Free', 'Paid'). I have two objects: 'Default' and 'Premium'. In my form when I choose Premium for example I use jQuery to add another field to my form: $('#id_group').change(function() { var $this = $(this); if ($this.find('option:selected').attr('value') == '1') { $("#group").html('<ul><li>Some text</li></ul>'); $("label[for='id_kod'], #id_kod").slideToggle("fast"); $("label[for='id_category1'], #id_category1, label[for='id_subcategory1'],#id_subcategory1").slideToggle("fast"); } else { $("#group").html('<ul><li>Some text</li>\ <li>Some text</li>\ <li>Some text</li></ul>'); $("#id_kod").attr("required", "true"); $("#group > ul").addClass('premium'); $("label[for='id_kod'], #id_kod").slideToggle("fast"); $("label[for='id_category1'], #id_category1, label[for='id_subcategory1'],#id_subcategory1").slideToggle("fast"); } }) I know that 'Premium' is 'Paid' and I set this that way. I'd like to automate this because user can create new group with "Free" or "Paid" options. I do not have idea how can I check object value and use it in my jQuery code. Something like Group.objects.filter(id=SELECTED_VALUE).Values('pay'). When user choose "Paid" group addictional form field should appear. Please give me some advice. -
how to process IntegrityError in Django Rest Framework Serializer properly?
Model class RoomChatMessageComplaint(TimeStampedModel): room = models.ForeignKey('places.Place', related_name='complaints') message = models.ForeignKey( 'chat.RoomChatMessageHistory', related_name='complaints') abuser = models.ForeignKey( AppUser, related_name='abused_messages') complaint_by = models.ForeignKey( AppUser, related_name='reported_complaints') class Meta: ordering = ('room', 'created', 'abuser') unique_together = ('room', 'message', 'complaint_by') verbose_name = "Complaint" verbose_name_plural = "Complaints" ViewSet class RoomChatMessageComplaintViewSet(viewsets.mixins.CreateModelMixin, viewsets.mixins.ListModelMixin, viewsets.GenericViewSet): """Viewset for chat message complaints """ model = RoomChatMessageComplaint queryset = RoomChatMessageComplaint.objects.all() permission_classes = (IsAuthenticated,) serializer_class = serializers.RoomChatMessageComplaintSerializer filter_backends = (filters.DjangoFilterBackend, filters.OrderingFilter,) filter_class = RoomChatMessageComplaintFilter ordering_fields = ('created',) ordering = ('-created',) def get_queryset(self): pk = self.kwargs['place_foursquare_id'] room = self.get_room(pk) return self.model.objects.filter(room=room) def get_room(self, pk=None): room = get_object_or_404(Place, foursquare_id=pk) self.check_object_permissions(self.request, room) return room def perform_create(self, serializer): room = self.get_room(self.kwargs['place_foursquare_id']) message = RoomChatMessageHistory.objects.get( room=room, msg_uid=serializer.validated_data['message'] ) serializer.save(complaint_by=self.request.user, room=room, message=message, abuser=message.user) Serializer class RoomChatMessageComplaintSerializer(serializers.ModelSerializer): """ Serializer for complaint messages """ message = serializers.CharField(write_only=True) created = DateTimeFieldWithTZ(read_only=True) class Meta: model = RoomChatMessageComplaint fields = ('id', 'message', 'created') def save(self, **kwargs): return self.Meta.model.objects.get_or_create(**kwargs) so if I submit first request POST /api/v1/places/4a8cc725f964a5201f0f20e3/complaints/ HTTP/1.1 Host: localhost:8000 User-Timezone: US/Pacific Authorization: token 38245c088ed6435aae2a2d9e848806c1e41aed81 Content-Type: application/json Cache-Control: no-cache Postman-Token: cd9becce-f3d1-4d61-115e-6a2b5784827f { "message": "8385d721-671c-899d-78f4-0adb58934e8d" } I'm getting response with 'created' field, if I submit again I get properly handled IntegrityError via get_or_create but I don't get the record just empty json {} What am I doing … -
TemplateSyntaxError Could not parse the remainder: '' from 'form.filter()'
I'm trying to put some values of my queryset in a html template. this is my html: <ul class="dropdown-menu"> {% for i in form.filter(university="UPF - Universitat Pompeu Fabra") %} <li ><a href="#">{{ i.degree }}</a></li> <li role="separator" class="divider"></li> {% endfor %} </ul> But when I charge the page, it launch this error: Exception Type: TemplateSyntaxError Exception Value: Could not parse the remainder: '(university="UPF - Universitat Pompeu Fabra")' from 'form.filter(university="UPF - Universitat Pompeu Fabra")' The value of the queryset printed in the shell is the following one: enter image description here My views is the following one: from .models import Universitys def index(request): universitys = Universitys.objects.all() context = {"form":universitys} return render(request,"index.html", context) and models: class Universitys(models.Model): data = models.DateTimeField('date created', auto_now_add=True) university = models.CharField(max_length=50) degree = models.CharField(max_length=50) degreeMark = models.DecimalField(decimal_places=3,max_digits=5) def __str__(self): return '%s %s %f' % (self.university, self.degree, self.degreeMark) If you can help me, I'll it grateful. -
Error in create_group method in a h5py file in python3 (function located in Django REST web service)
I have a function in a web service that was created using Django REST framework, Python3.4. The function would create a HDF5 file with a 2D array, which is contained in a dataset named 'rainfall' inside a group named 'sample_event'. Although the function works well when tested from the VM that contains the web service, it returns error when trying to access as web service. The error is while trying to create a group (in method create_group) in the HDF5 file. The function is something like this (simplified version): def create_pytopkapi_hdf5_from_nc( output_folder=""): import h5py, numpy # output path rainfall_outputFile = os.path.join(output_folder, "out_hdf5.h5") # create a hdf5 file with h5py.File(rainfall_outputFile, 'w') as f: grp = f.create_group('sample_event') ##### THIS IS WHERE I ACCESS ERROR ##### grp.create_dataset('rainfall', shape=(100, 1000), dtype='f') rainArray = f['sample_event']['rainfall'] rainArray[:] = numpy.zeros((100, 1000)) The error traceback looks like this: File "/home/ahmet/ciwater/usu_data_service/views.py" in get 657. result = params'function_to_execute' File "/home/ahmet/ciwater/usu_data_service/pytopkapi_data_service/servicefunctions_pytopkapi.py" in runpytopkapi 1125. create_pytopkapi_hdf5_from_nc(nc_f='ppt.nc', mask_tiff=mask_fname, output_folder=simulation_folder) File "/home/ahmet/ciwater/usu_data_service/pytopkapi_data_service/servicefunctions_pytopkapi.py" in create_pytopkapi_hdf5_from_nc 615. grp = f2.create_group('/sample_event') #.encode('utf-8') File "/usr/local/lib/python3.4/site-packages/h5py/_hl/group.py" in create_group 48. name, lcpl = self._e(name, lcpl=True) File "/usr/local/lib/python3.4/site-packages/h5py/_hl/base.py" in _e 135. return name, get_lcpl(coding) File "/usr/local/lib/python3.4/site-packages/h5py/_hl/base.py" in get_lcpl 117. lcpl = self._lcpl.copy() Here is the google site link to the error … -
How do I set collation_connection in Django?
I put this in settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'HOST': 'localhost', 'NAME': 'db', 'USER': 'root', 'PASSWORD': '', 'OPTIONS': { 'charset': 'utf8mb4', 'init_command': 'set collation_connection=utf8mb4_unicode_ci', }, }, } Then I used the shell to check that it worked: $ ./manage.py shell >>> from django.db import connection >>> cursor = connection.cursor() >>> cursor.execute("show variables like 'collation_connection'") >>> print cursor.fetchall() ((u'collation_connection', u'utf8mb4_general_ci'),) I know it's executing the init_command because if I type in nonsense I get an error. So why is this setting not working? -
Django CheckboxSelectMultiple() widget - Form widget value not selected after saving data options
I have the following model: class AcademicPeople(models.Model): CATHEDRAL_PROFESSOR = 'CATHEDRAL' RESEARCH_PROFESSOR = 'RESEARCH' INSTITUTIONAL_DIRECTIVE = 'DIRECTIVE' OCCUPATION_CHOICES = ( (CATHEDRAL_PROFESSOR, 'Cathedral Professor'), (RESEARCH_PROFESSOR, 'Research Professor'), (INSTITUTIONAL_DIRECTIVE, 'Institutional Directive'), ) occupation = models.CharField( max_length=255, blank = False, ) In the forms.py I have: from .models import from django.forms.widgets import CheckboxSelectMultiple class AcademicPeopleForm(forms.ModelForm): title = "Details" occupation = forms.MultipleChoiceField( required=False, label='Occupation', widget=CheckboxSelectMultiple(), choices=AcademicPeople.OCCUPATION_CHOICES ) class Meta: model = AcademicPeople fields = ('occupation',) When I go to my template in my browser, I get the checkbox select multiple rendered in checkboxes, I select some options and when I save, these options selected does not show their value. How to can I work with multiple select options and that these options selected stay selected ? Some application? Use of JS? Is possible that my approach may be incomplete or miss something ...? -
"Suspicious Operation" calling static files from Amazon S3
I've been through the ringer getting my Django app setup on Heroku using Amazon s3 to host the static and media files. I've been following this guide https://www.caktusgroup.com/blog/2014/11/10/Using-Amazon-S3-to-store-your-Django-sites-static-and-media-files/ and what seems like thousands of other resources, collectstatic has worked and heroku is deploying it - but displays a 400 error. When I try and run it locally i get more info: Attempted access to '/css/reset.css' denied. This is the line that gets highlighted: <link rel="stylesheet" type="text/css" href="{% static '/css/reset.css' %}"> I can load the static files direct from the URL if I grab it from my s3 admin panel so I figured it wasn't a bucket policy issue, I've messed around with https / http options but no joy. So I figure it must be the wrong path is being called somehow in the code - i just can't see where! Any help much appreciated, I don't think I've blinked for about 4 hours straight. Traceback: File "/home/devtop/webdev/projects/intro/myvenv/lib/python3.5/site-packages/storages/backends/s3boto.py" in _normalize_name 358. return safe_join(self.location, name) File "/home/devtop/webdev/projects/intro/myvenv/lib/python3.5/site-packages/storages/backends/s3boto.py" in safe_join 59. raise ValueError('the joined path is located outside of the base path' During handling of the above exception (the joined path is located outside of the base path component), another exception occurred: … -
<iframe> and <object> are both blank, but only in Firefox
I am attempting to embed one site into another site. I control both servers, which I will refer to here as "site1.com" (the site in the browser) and "site2.com" (the site I am trying to embed). HTML embed code Attempt 1, using iframe tag: <iframe height="600" width="600" name="my other site" src="https://site2.com/foo/bar"> Unable to display--your browser does not support frames. </iframe> Attempt 2, using object tag: <object type="text/html" height="600" width="600" name="my other site" data="https://site2.com/foo/bar"></object> Things I know are not the problem Secure/insecure mismatch I've read that Firefox will not allow an HTTP embed into an HTTPS page. Both sites are HTTPS, so there is no mismatch. The loaded resources (CSS, etc) are also https, from same origin, so there is no mixed-content problem. Invalid or untrusted certificates Both sites are using valid certificates, signed by a proper trusted authority, and are not expired. In fact, we are using a subdomain wildcard certificate, so they are both using the same certificate (they both are in the same subdomain). X-Frame-Options The site that I am trying to embed has this response header: X-Frame-Options: ALLOW-FROM SITE1.COM Content-Security-Policy The site that I am trying to embed has this response header (wrapped here for readability): Content-Security-Policy: … -
Generic views request handling Django
I'm relative new in Django. I want to use generic views like this : class photogalleryView(generic.ListView): template_name = 'xxx/photogallery.html' model = Foto query = Foto.objects.all() def get_queryset(self): return self.query and I definitelly don't know how to handle GET or POST request or something like $_SESSION like in PHP, can you please give me some pieces of advice please ? Thank you very much guys ! for example - I want to handle GET request on this URL: http://127.0.0.1:8000/photogallery?filter=smth -
name 'user' is not defined django
I'm creating a summary page of all the posts that the user has created and also favourited. However, it throws the the error above when trying to retrieve the users uploaded posts and I don't know why? Models class Aircraft(AircraftModelBase): user = models.ForeignKey(User) manufacturer = SortableForeignKey(Manufacturer) aircraft_type = SortableForeignKey(AircraftType) body = SortableForeignKey(Body) engines = models.PositiveSmallIntegerField(default=1) View def account_overview(request): fav_aircraft = FavoritedAircraft.objects.filter(user__id=request.user.id) uploaded_aircraft = Aircraft.objects.filter(user=user) <---- HERE!!!! fav_airline = FavoritedAirline.objects.filter(user__id=request.user.id) return render(request, 'account/account_overview.html', {'favAircraft':fav_aircraft, 'favAirline':fav_airline, 'UploadedAircraft':uploaded_aircraft}) Template {% if UploadedAircraft %} <div class="col-md-12"> <i><h1><strong>Your Aircraft Uploads..</strong></h1></i> {% for aircraft in UploadedAircraft %} <div class="col-lg-offset-0 col-md-4 col-sm-3 item"> <div class="box"><img src="{{ aircraft.aircraft.image.url }}" width="200px" height="200px" alt="{{ aircraft.aircraft.title }}"/></a> <h3 class="name">{{ aircraft.aircraft.name }}</h3> <h4><em>Range: {{ aircraft.aircraft.maximum_range }}</em></h4> <a href="{% url 'aircraft_update' %}"><button class="btn btn-default" type="button">Edit </button></a> <button class="btn btn-default" type="button">Delete </button> </div> {% endfor %} </div> </div> {% else %} <h2 class="text-center">Opps.. You don't seem to have any uploads..</h2></div> {% endif %} -
How to integrate andriod app with Django Project
I have developed a django project (Includes REST API ), i want it to connect with Android. Can anyone help me to get a proper documentation? -
Fullcalendar Does not display data
I'm using Fullcalendar. And I can not display the date data in the database here the code! models.py: class Reservacion(models.Model): sala = models.ForeignKey('Sala', on_delete=models.CASCADE, blank=True, null=True) fecha = models.DateField(auto_now =False , auto_now_add=False) hora_inicio = models.TimeField(auto_now =False , auto_now_add=False) hora_termino = models.TimeField(auto_now =False , auto_now_add=False) usuario = models.ForeignKey(User) Use the "fecha" field for the date. views.py: def event(request): all_events = Reservacion.objects.all() get_event_types = Reservacion.objects.only('sala') # if filters applied then get parameter and filter based on condition else return object if request.GET: event_arr = [] if request.GET.get('sala') == "all": all_events = Reservacion.objects.all() else: all_events = Reservacion.objects.filter(sala__icontains=request.GET.get('sala')) for i in all_events: event_sub_arr = {} event_sub_arr['title'] = i.event_name start_date = date(i.fecha.date(), "%Y-%m-%d") end_date = date(i.fecha.date(), "%Y-%m-%d") event_sub_arr['start'] = start_date event_sub_arr['end'] = end_date event_arr.append(event_sub_arr) return HttpResponse(json.dumps(event_arr)) context = { "events":all_events, "get_event_types":get_event_types, } return render(request,'calendardemo.html',context) and template: {% load static from staticfiles %} "links and scripts" $(document).ready(function() { $('#calendar').fullCalendar({ header: { left: 'prev,next today', center: 'title', right: 'month,agendaWeek,agendaDay,listWeek' }, defaultDate: '2017-04-12', navLinks: true, // can click day/week names to navigate views editable: true, eventLimit: true, // allow "more" link when too many events events: [ {% for i in events %} { title: "{{ i.sala}}", start: '{{ i.fecha|date:"Y-m-d" }}', end: '{{ i.fecha|date:"Y-m-d" }}', }, {% endfor … -
django error: Requested Python version () is not installed
$ manage.py runserver Requested Python version () is not installed I get this error with django. I have Python but I have no idea why it says that. -
How to slow down the django debug server
What is a best way to slow down the django runserver in debug mode? I want to emulate the weak server. -
Save uploaded files in subfolder depending on request
I have a website, that lets user upload files. These files are attached to a node, which ID is part of the upload request. Since the same file might be attached to different nodes, Django will rename the file by adding a hash to the filename. Thus if a user downloads a previously uploaded file, it won't have the original filename. Is it possible to create a subdirectory (named after the node ID) inside the media folder a file is uploaded? The closest solution I found was to change the System Storage of the FileField, but this is static for all files of that one model. Or is there another, better way to solve the problem with duplicate files? Model: class Attachment(models.Model): node = models.IntegerField(default=-1) file = models.FileField(upload_to=".") View: def file_upload(request): if request.method == "POST": form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): instance = Attachment(file=request.FILES["file"], node_id=request.POST["node_id"]) instance.save() return HttpResponse(instance.file.url) -
Updating Django - error: 'No module named migration'
I'm upgrading my Django App from Django 1.5.5 tot 1.9, Django-cms from 2.4.3 to 3.3 (and all corresponding packages). After I've plowed through all the errors of depreciated functions I now stumble on an error that I cannot understand: 'No module named migration' I get this error when running (in a virtualenv): - python manage.py runserver and also when I run - python manage.py migrate Traceback (most recent call last): File "manage.py", line 20, in <module> execute_from_command_line(sys.argv) File "/var/www/env/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 350, in execute_from_command_line utility.execute() File "/var/www/env/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 342, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/var/www/env/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 195, in fetch_command klass = load_command_class(app_name, subcommand) File "/var/www/env/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 39, in load_command_class module = import_module('%s.management.commands.%s' % (app_name, name)) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/var/www/env/local/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 16, in <module> from django.db.migrations.autodetector import MigrationAutodetector File "/var/www/env/local/lib/python2.7/site-packages/django/db/migrations/__init__.py", line 1, in <module> from .migration import Migration, swappable_dependency # NOQA ImportError: No module named migration -
Error while installing 'django_admin_bootstrapped'
I'm having some troubles while trying to install django admin bootstrapp, i've tried using pip install django_admin_bootstrapped on the terminal while being on the project folder, but i got the following message (error) Collecting django_admin_bootstrapped Requirement already satisfied: setuptools in /Users/Camilo/anaconda/lib/python3.6/site-packages/setuptools-27.2.0-py3.6.egg (from django_admin_bootstrapped) Collecting Django<1.9,>=1.8 (from django_admin_bootstrapped) Using cached Django-1.8.18-py2.py3-none-any.whl Installing collected packages: Django, django-admin-bootstrapped Found existing installation: Django 1.10.6 Uninstalling Django-1.10.6: Exception: Traceback (most recent call last): File "/Users/Camilo/anaconda/lib/python3.6/shutil.py", line 538, in move os.rename(src, real_dst) PermissionError: [Errno 13] Permission denied: '/Users/Camilo/anaconda/bin/__pycache__/django-admin.cpython-36.pyc' -> '/var/folders/t7/kjwv967n085gdfjg9bjz2bxh0000gn/T/pip-o6dmj5ut-uninstall/Users/Camilo/anaconda/bin/__pycache__/django-admin.cpython-36.pyc' Could affect the fact that i'm working with python 3.6 but the project is done in python 3.4? Any help would be really appreciate.