Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
virtualenv - ModuleNotFoundError: No module named 'django'?
New to linux, I have install django in virtualenv, but i am not able to import django. Is there any variable path i need to set ? (virs) akash@akash-Inspiron-3542:/usr/virs/bin$ django-admin --version 1.11.10 (virs) akash@akash-Inspiron-3542:/usr/virs/bin$ python Python 3.6.4 (default, Jan 28 2018, 17:52:01) [GCC 5.4.0 20160609] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import django Traceback (most recent call last): File "<stdin>", line 1, in <module> ModuleNotFoundError: No module named 'django' -
django ModelForms and normal form in POST request
Hi i just have a small doubt can we create a HTML template which will have the Django form and normal HTML form together. I created a HTML template which has both normal HTML input tag and Django forms. I am getting the following error when i do a form.save(commit=False) could not be created because the data didn't validate. My view.py if request.method == 'POST': form_value = request.POST.copy() print form_value form = InfoForm(data=request.POST) post_val = form.save(commit=False) my HTML <div class="form-row"> <div class="form-group col-md-4"> {{form.name}} </div> <div class="form-group col-md-4"> {{form.number}} </div> <div class="form-group col-md-4"> {{form.location}} </div> </div> <div class="form-group"> <label for="Feedback">Feedback</label> <div id="Feedback" class="optionBox1"> <div class="input-group my-add-div"> <input type="text" class="form-control" name="feedback" required> <input type="text" class="form-control" name="feedback" required> <input type="text" class="form-control" name="feedback" required> </div> </div> </div> my form.py class InfoForm(forms.ModelForm): name = forms.CharField(label='Project Name',max_length=100,widget=forms.TextInput(attrs={'class':'form-control','placeholder':'Click to enter text',})) number = forms.DecimalField(label='Project #',widget=forms.NumberInput(attrs={'class':'form-control','placeholder':'Enter the ID',})) location = forms.CharField(label='Location',max_length=100,widget=forms.TextInput(attrs={'class':'form-control','placeholder':'Enter the Location',})) class Meta: model = Info field = ('name','number','location',) My Model.py name = models.CharField(max_length=200,blank=True , null=True) number = models.IntegerField(blank=True , null=True) location = models.CharField(max_length=200,blank=True , null=True) feedback = ArrayField(ArrayField(models.CharField(max_length=200,blank=True,null=True))) Thanks in advance -
Django bakery ImportError: Could not import 'p'. The path must be fully qualified
I'm trying to export my site as flat files with django bakery. I made a dummy site with a sample polls app and I get this error when I run python manage.py build File "python3.6/site-packages/bakery/management/commands/build.py", line 112, in handle self.build_views() File "python3.6/site-packages/bakery/management/commands/build.py", line 240, in build_views view = get_callable(view_str) File "python3.6/site-packages/django/urls/utils.py", line 25, in get_callable raise ImportError("Could not import '%s'. The path must be fully qualified." % lookup_view) ImportError: Could not import 'p'. The path must be fully qualified. I followed all their instructions correctly: polls/views.py: from bakery.views import BuildableTemplateView class HomePageView(BuildableTemplateView): template_name = "home.html" build_path = 'index.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) return context settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'polls', 'bakery' ] BUILD_DIR = '/Users/me/Downloads/build/' BAKERY_VIEWS = ( 'polls.views.HomePageView' ) mysite/urls.py: urlpatterns = [ path('admin/', admin.site.urls), path('polls/', include('polls.urls')), ] polls/urls.py: from django.urls import path from . import views from polls.views import HomePageView urlpatterns = [ path('', HomePageView.as_view(), name='home'), ] Maybe it is something related to the urls? But I can't see what. The site works fine in the browser... -
How can I define a metric for uniqueness of strings on Django model?
Suppose I have a model that represents scientific articles. Doing some research, I may find the same article more than once, with approximately equal titles: Some Article Title Some Article Title Notice that the second title string is slightly different: it has an extra space before "Title". If the problem was because there could be more or less spacing, it would be easy since I could just trim it before saving. But say there could be more small differences that consist of characters other than spaces: Comparison of machine learning techniques to predict all-cause mortality using fitness data: the Henry ford exercIse testing (FIT) project. Comparison of machine learning techniques to predict all-cause mortality using fitness data: the Henry ford exercIse testing (FIT). This is some random article I used here as an example Those titles clearly refer to the same unique work, but the second one for some reason is missing some letters. What is the best way of defining uniqueness in this situation? In my mind, I was thinking of some function that calculates the levenshtein distance and decides if the strings are the same title based on some threshold. But is it possible to do on a … -
How display request error in custom django admin error page
Currently when a 500 erros ocurrs I show the user my custom 500.html error page. The app is used by both administrators and clients, which users are respectively in groups "operator" and "client". The information shown depends on that group. I would like to apply that concept to the error page. I would like to show the same Traceback error shown when DEBUG = True (not neccesary the same style) when logged user is from group "operator". Information I would like to show to the operator I guess there will be an attribute in the request that I can pass throught the template and print the errors, but I can't find out which attribute is that. This is the functiona I use to render the 500.html page: def error_500(request): data = {} if request.user.groups.filter(name='operator').exists(): # fill the data dict with the traceback/errors return render(request,'app/errors/500.html', data) Thanks in advance. -
How is the 'select-wrapper' class added in Materialize?
I'm trying to refactor a Django website containing several forms, among them a 'Case Management' form with 'Status' and 'Package' fields. If I inspect the label for 'Package', I notice it has CSS attributes corresponding to the .input-field label.active selector: However, just one field above, at the 'Status' label, there is no active class but there is a select-wrapper class: In the template, the fields are added manually. Here is a snippet: {% load widget_tweaks %} <div class="row"> <div class="col page-title">Status</div> </div> <div class="row"> <div class="col s6"> <div class="row"> <div class="input-field col s12"> {{ form.status|add_error_class:"invalid" }} {% if form.status.errors %} <span id="{{ form.status.id_for_label }}-error" class="error"> {{ form.status.errors|join:", " }} </span> {% endif %} <label for="{{ form.status.id_for_label }}" class="{% if form.status.errors %}invalid{% endif %}"> Status </label> </div> </div> <div class="row m-b-xs"> <div class="input-field select2-field col s12"> {{ form.package|add_class:"browser-default select2-input"|add_error_class:"invalid"|attr:"style:width: 100%;" }} {% if form.package.errors %} <span id="{{ form.package.id_for_label }}-error" class="error"> {{ form.package.errors|join:", " }} </span> {% endif %} <label for="{{ form.package.id_for_label }}" class="active {% if form.package.errors %}invalid{% endif %}"> Package </label> </div> </div> Note that the "active" class is explicitly added to the Package label, but not to the Status label. What puzzles me, however, is that the Package label does … -
How to resize image in django ModelForm?
I have the following ModelForm: class MyModelForm(ModelForm): def __init__(self, *a, **kw): super().__init__(*a, **kw) self.fields['image'].validators = [] def clean_image(self): img = self.cleaned_data.get('image') if not img: return img # Resize to Max 1024x1024 px new_size = (1024, 1024) if any(x>new_size[0] for x in img.image.size): img.image.thumbnail(new_size) return img It throws an error, when I try upload an image: Exception Type: AttributeError at /some/view Exception Value: 'NoneType' object has no attribute 'read' I suppose it's because of how the ImageField is implemented in django: image = Image.open(file) # verify() must be called immediately after the constructor. image.verify() # Annotating so subclasses can reuse it for their own validation f.image = image According to some sources I should reopen the image file after the verify() has been called, but I'm not sure how can I do this or whether that's the best approach of the problem? -
Why do i get invalid default value?
A1 = 'A1' A2 = 'A2' A3 = 'A3' B1 = 'B1' B2 = 'B2' B3 = 'B3' C1 = 'C1' C2 = 'C2' C3 = 'C3' D1 = 'D1' D2 = 'D2' D3 = 'D3' COHORT_CHOICES = ( ('A1', 'A1'), ('A2', 'A2'), ('A3', 'A3'), ('B1', 'B1'), ('B2', 'B2'), ('B3', 'B3'), ('C1', 'C1'), ('C2', 'C2'), ('C3', 'C3'), ('D1', 'D1'), ('D2', 'D2'), ('D3', 'D3'), ) cohort = models.CharField(max_length=5, choices=COHORT_CHOICES, default='A1') _mysql.connection.query(self, query) django.db.utils.OperationalError: (1067, "Invalid default value for 'cohort'") -
Using foreign key attributes in Angular template
I use Django for backend (Django Rest Framework) and Angular for frontend. In the backend, I have 2 models: class Post(models.Model): category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True) content = models.TextField(max_length=1000) class Category(models.Model): title = models.CharField(max_length=120) which I serialize accordingly: class CategorySerializer(ModelSerializer): class Meta: model = Category fields = '__all__' class PostSerializer(ModelSerializer): class Meta: model = Post fields = '__all__' Then in the component template I want to print the title of the category for a specific post: <li *ngFor='let post of posts'> <div *ngIf='post'> <p>{{ post.category.title }}</p> <p>{{ post.content }}</p> </div> </li> My classes are: export class Post { id: number; category: Category; content: string; } export class Category { id: number; title: string; } Why {{ post.category.title }} doesn't work, while {{ post.content }} works? Is it an issue of my serialization or of my Angular classes? -
Django NoReverseMatch problems with get_absolute_url
I know this probably the single most common Django problem there is, but I can't for the life of me figure this one out. I'll make it quick. # urls.py urlpatterns += [ path('certs/', views.certs, name='certs'), path('certs/<int:id>/', views.view_cert, name='view_cert'), ] - # views.py @login_required def certs(request): certs = Certification.objects.filter(user=request.user) return render(request, 'certs.html', {'certs': certs}) def view_cert(request, id): cert = Certification.objects.get(id=id) return render(request, 'view_cert.html', {'cert': cert}) - # certs.html {% if certs %} <ul class="list-group"> {% for cert in certs %} <li class="list-group-item">{{ cert.name }}</li> <!--<a href="{% url cert.get_absolute_url %}" class="list-group-item list-group-item-action">{{ cert.name }}</a>--> {% endfor %} </ul> {% endif %} - # models.py class Certification(models.Model): ... def get_absolute_url(self): return reverse('crypto:view_cert', kwargs={'id': self.id}) The code works absolutely fine when i load /certs/1 for example. However when I try to load /certs (which should list a users certs), I get a NoReverseMatch. Reverse for '/certs/1/' not found. '/certs/1/' is not a valid view function or pattern name. What's even more confusing is that I can load it absolutely fine from shell: >>> from django.urls import reverse >>> reverse('crypto:view_cert', kwargs={'id': 1}) '/certs/1/' >>> Anyone have any ideas? -
How delete columns in tables2?
i instantiate my table in my view. view.py def my_function(): ... ... #init a new table with data and news columns !!!!! table = ResistanceTable(data=data,newscolumns=geneList) return render(request, 'page.html', {'table': table}) with data a dict of data and geneList a list of name for news columns. tables.py class ResistanceTable(tables.Table): souche = tables.Column(); column_default_show = ['souche'] def __init__(self, data, newscolumns, *args, **kwargs): if newscolumns: for col in newscolumns: self.base_columns[col] = tables.Column(verbose_name=col) super(ResistanceTable, self).__init__( data, newscolumns, *args, **kwargs) class Meta: attrs = {'class': 'table table-bordered table-striped table-condensed'} The problem is when i run my code a first time. I have all i want. But if i run my code a second time, the table model will keep the column define previously. How removes theses columns ???? :/ -
Audio recording through Django
I want to record and save audio to a particular location in my PC. Thank you in advance. And please carefully read problem before marking it as already asked!! -
django "No migrations to apply" after merged from git repository
My partner did some changes in a model of our app. He ran makemigrations and migrate, everything success until now. The migrations files were created and pushed to our git repository. At this point the migrations folder is: 0001_initial.py 0002_field1.py After that I did a merge and I got the new migrations files. Before that I just had 0001_initial.py. Now I got both. Problem is when I run migrate I got that "No migrations to apply". Why not?? if field1 is not yet in my database, but in models does, and I have the latest migrations files, which are not sync with database yet. -
Python: Writing in Parallel using Django_mongokit
How can django_mongokit connection be used to write parallel? Currently I am using python Multiprocessing Pool but it gets stuck as it waits for collection lock. Is there any way to achieve the same without changing mongo connector? I am using python 2.7 and Django 1.6. -
Can't see the django home page
I'm new to django, thus the question. I've a django project set up with two apps both of which seem to work fine. Just that I can't reach the homepage - which should be the default django page. I get the following error, Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/ Using the URLconf defined in core.urls, Django tried these URL patterns, in this order: admin/ ^aggregator/ ^bouncer/ The empty path didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. This is my urls.py urlpatterns = [ path('admin/', admin.site.urls), url(r'^aggregator/', include('aggregator.urls')), url(r'^bouncer/', include('bouncer.urls')), ] What am I missing here? -
Edit form in django doesn't save record after update
I have a little problem I've create a edit form to update the existing records. The form is displaying correctly, but when I click the edit button to update the records, the url redirecting me and record is not updated. My views.py resposible for edit: @login_required def szczegoly_pracownik(request, id): link_pracownik = get_object_or_404(Cudzoziemiec, id=id) return render(request, 'cudzoziemiec/szczegoly_pracownik.html', {'link_pracownik': link_pracownik}) @login_required def edycja_pracownika(request, id): link_pracownik = get_object_or_404(Cudzoziemiec, id=id) if request.method == 'POST': edycja_pracownika = CudzoziemiecForm(request.POST, instance=link_pracownik) if edycja_pracownika.is_valid(): link_pracownik = edycja_pracownika.save(commit=False) link_pracownik.save() return render('szczegoly_pracownik', id=link_pracownik.id) else: edycja_pracownika = CudzoziemiecForm(request.user, instance=link_pracownik) return render(request, 'cudzoziemiec/edycja_pracownika.html', {'edycja_pracownika': edycja_pracownika}) The def szczegoly_pracownika is responsible for displaying the detail view File edycja_pracownika.html {% if request.user.is_authenticated %} <form action="." method="post"> {{ edycja_pracownika.as_p }} {% csrf_token %} <div class="float-right"> <p><input type="submit" value="Edytuj" ></p> {% endif %} and the urls.py responsible for detail view and edit view ... path('pracownik/<id>', edycja_pracownika, name='edycja_pracownika'), path('pracownik/<id>/', szczegoly_pracownik, name='szczegoly_pracownik'), Maybe somebody know where is the bug? -
Using Django bulk_create gives UNIQUE constraint failed:solgeo_hourly.id
I have two models, namely Project and Hourly. Whenever a new project is created, I want to also generate 8760 new Hourly instances. There are two methods, one is very costly since 8760 times a new row is written to the database, i.e.: for i in range(0, 24): clock_time=i*3600 hourly = Hourly.objects.create(project=project, clock_time=clock_time) hourly.save() The other method is by using the Django bulk_create(hourlys) method, which works fine whenever I use the default Hourly() constructor. However I want to use my custom Hourly.objects.create() function. This however gives an UNIQUE constraint error for hourly.id, i.e.: class HourlyManager(models.Manager): """""" def create(self, project, clock_time): hourly = super().create(project=project, clock_time=clock_time) hourly.local_civil_time = services.calc_local_civil_time(clock_time, project.TMZ, project.lon) hourly.save() return hourly class ProjectManager(models.Manager): """""" def create(self, owner, project_name, TMZ, lat, lon): project = super().create(owner=owner, project_name=project_name, TMZ=TMZ, lat=lat, lon=lon) project.save() hourlys = [] for i in range(0, 24): hourlys.append(Hourly.objects.create(project=project, clock_time=clock_time)) Hourly.objects.bulk_create(hourlys) return project class Project(models.Model): objects = ProjectManager() owner = models.ForeignKey('auth.User', related_name='projects', on_delete=models.CASCADE) project_name = models.CharField(max_length=200) TMZ = models.FloatField(default=0) lat = models.FloatField(default=0) # Radians lon = models.FloatField(default=0) # Radians class Hourly(models.Model): objects = HourlyManager() project = models.ForeignKey(Project, related_name='hourlys', on_delete=models.CASCADE) clock_time = models.FloatField(default=0) local_civil_time = models.FloatField(default=0) -
Django - passing argument to custom .save method
I have a custom .save method on my model. The model has a start_date and a last_edited value. If the difference between these values is more than 14 days, it should copy/clone itself on save (instead of saving). You probably already see the problem: infinite recursion. If the clone saves itself, the values will still differ 14 days and the whole copy process will start anew. Therefore I want to to pass these copies a 'copy' argument in their .save parameter, in order to prevent them from triggering the copy process themselves. To this end I've written the following code: def save(self, *args, **kwargs): #check if a submission is older than the 'create a new one' threshold #Create a new one if that is the case delta = self.last_edited - self.start_date print(args) print(kwargs) if 'copy' in kwargs or 'copy' not in args: print('cloning!') if delta.days >= 14: clone = self clone.pk = None clone.save('copy') super(AssessmentSubmission, self).save(*args, **kwargs) However, for some reason clone.save(copy) does not pass the 'copy' variable to the .save method. I even added some print statements to print all args and kwarg arguments, but both return empty lists/ dicts. Does anyone know what I am doing wrong? -
Django - How to properly handle routes and redirect in CRUD App
I have a small app which has index/view/create/delete/store appointment functions. For my store function which simply adds a new appointment entry to database, how do i handle the url so there is no need for /store I want both store and delete to redirect to the index.html so it will rerun the index function, but atm its not doing that. My delete function is an anchor tag which simply calls delete given the appointment_id but this gets confused with the detail function, instead of deleting it tries to show the detail page. urls.py from django.urls import path from . import views app_name = "appointments" urlpatterns = [ path('', views.index, name="index"), path('<int:appointment_id>/', views.detail, name="detail"), path('create/', views.create, name="create"), path('store/', views.store, name="store"), path('<int:appointment_id>/', views.delete, name="delete"), ] views.py from django.shortcuts import get_object_or_404, render, redirect from django.http import HttpResponse from .models import Appointment # Create your views here. def index(request): appointments = Appointment.objects.all() context = { 'appointments': appointments } return render(request, 'appointments/index.html', context) def detail(request, appointment_id): appointment = get_object_or_404(Appointment, pk=appointment_id) context = { 'appointment': appointment } return render(request, 'appointments/detail.html', context) def create(request): return render(request, 'appointments/create.html') def store(request): make = request.POST['make'] model = request.POST['model'] description = request.POST['description'] date_time = request.POST['date_time'] appointment = Appointment(make=make, model=model, description=description, date_time=date_time) … -
Can't install Django 2.0 by pip
I am building new Django app with a new version of Django. I found Django 2.0 is available (2.0.2) https://www.djangoproject.com/download/, and now trying to install it with pip. pip install Django==2.0.2 But it's not working for me. Could not find a version that satisfies the requirement Django==2.0 (from versions: 1.1.3, 1.1.4, 1.2, 1.2.1, 1.2.2, 1.2.3, 1.2.4, 1.2.5, 1.2.6, 1.2.7, 1.3, 1.3.1, 1.3.2, 1.3.3, 1.3.4, 1.3.5, 1.3.6, 1.3.7, 1.4, 1.4.1, 1.4.2, 1.4.3, 1.4.4, 1.4.5, 1.4.6, 1.4.7, 1.4.8, 1.4.9, 1.4.10, 1.4.11, 1.4.12, 1.4.13, 1.4.14, 1.4.15, 1.4.16, 1.4.17, 1.4.18, 1.4.19, 1.4.20, 1.4.21, 1.4.22, 1.5, 1.5.1, 1.5.2, 1.5.3, 1.5.4, 1.5.5, 1.5.6, 1.5.7, 1.5.8, 1.5.9, 1.5.10, 1.5.11, 1.5.12, 1.6, 1.6.1, 1.6.2, 1.6.3, 1.6.4, 1.6.5, 1.6.6, 1.6.7, 1.6.8, 1.6.9, 1.6.10, 1.6.11, 1.7, 1.7.1, 1.7.2, 1.7.3, 1.7.4, 1.7.5, 1.7.6, 1.7.7, 1.7.8, 1.7.9, 1.7.10, 1.7.11, 1.8a1, 1.8b1, 1.8b2, 1.8rc1, 1.8, 1.8.1, 1.8.2, 1.8.3, 1.8.4, 1.8.5, 1.8.6, 1.8.7, 1.8.8, 1.8.9, 1.8.10, 1.8.11, 1.8.12, 1.8.13, 1.8.14, 1.8.15, 1.8.16, 1.8.17, 1.8.18, 1.9a1, 1.9b1, 1.9rc1, 1.9rc2, 1.9, 1.9.1, 1.9.2, 1.9.3, 1.9.4, 1.9.5, 1.9.6, 1.9.7, 1.9.8, 1.9.9, 1.9.10, 1.9.11, 1.9.12, 1.9.13, 1.10a1, 1.10b1, 1.10rc1, 1.10, 1.10.1, 1.10.2, 1.10.3, 1.10.4, 1.10.5, 1.10.6, 1.10.7, 1.10.8, 1.11a1, 1.11b1, 1.11rc1, 1.11, 1.11.1, 1.11.2, 1.11.3, 1.11.4, 1.11.5, 1.11.6, 1.11.7, 1.11.8, 1.11.9, 1.11.10) No matching distribution found for Django==2.0 … -
Won't create a PostgreSQL database on Unix server
I am trying to deploy my django project to a unix server. When I run the command to create the PostgreSQL database using SSH, I encounter the following error: $ createdb elections createdb: could not connect to database template1: could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"? Does the error mean running 'locally' as in the server or my machine? What is stopping it from connecting to the server? How do I fix the error? -
Trying to save two forms, column cannot be null
I have three models bound together by foreign keys: Course > Lecture > FileUpload. I tried to create a form for Lecture model, but I actually ended up creating two forms, another one for FileUpload. And every time I try to submit the forms, I get error: (1048, "Column 'lecture_id' cannot be null") The Lecture form actually submits the information, and I think that the error is related to the second form. Thing is that I want the user to be able to upload many files for the same lecture, just like in the database, and currently only one file could be uploaded which is not working. def classroom(request): if request.method == 'POST': form1 = LectureForm(request.POST) form2 = FileForm(request.POST, request.FILES) if form1.is_valid() and form2.is_valid(): form1.save() form2.save() return redirect('courses/courses.html') else: form1 = LectureForm() form2 = FileForm() context = {'teacher_data': TeacherData.objects.all(), 'teachers': Teacher.objects.all(), 'courses': Course.objects.all(), 'form1': form1, 'form2': form2, } return render(request, 'courses/classroom.html', context) class LectureForm(forms.ModelForm): class Meta: model = Lecture fields = ('course', 'lecture_title', 'lecture_category', 'content') class FileForm(forms.ModelForm): class Meta: model = FileUpload fields = ('files',) class Course(models.Model): name = models.CharField(max_length=50, unique=True) class Lecture(models.Model): LECTURE_CHOICES = ( ('Courses', 'Courses'), ('Seminars', 'Seminars'), ) course = models.ForeignKey('Course', on_delete=models.CASCADE, default='', related_name='lectures',) lecture_category = models.CharField(max_length=10, … -
UnicodeDecodeError Python/Django application
I'm getting this error UnicodeDecodeError at /select_text 'utf-8' codec can't decode byte 0xe7 in position 92: invalid continuation byte Request Method: POST Request URL: http://agata.pgie.ufrgs.br/select_text Django Version: 2.0.1 Exception Type: UnicodeDecodeError Exception Value: 'utf-8' codec can't decode byte 0xe7 in position 92: invalid continuation byte Exception Location: /home/metis/public_html/AGATA/agataenv/lib/python3.4/codecs.py in decode, line 319 Python Executable: /usr/bin/python3 Python Version: 3.4.3 Python Path: ['/home/metis/public_html/AGATA', '/home/metis/public_html/AGATA/agataenv/lib/python3.4', '/home/metis/public_html/AGATA/agataenv/lib/python3.4/plat-x86_64-linux-gnu', '/home/metis/public_html/AGATA/agataenv/lib/python3.4/lib-dynload', '/usr/lib/python3.4', '/usr/lib/python3.4/plat-x86_64-linux-gnu', '/home/metis/public_html/AGATA/agataenv/lib/python3.4/site-packages'] Server time: Thu, 22 Feb 2018 12:29:51 +0000 Unicode error hint The string that could not be encoded/decoded was: Varia��es Traceback Switch to copy-and-paste view /home/metis/public_html/AGATA/agataenv/lib/python3.4/site-packages/django/core/handlers/exception.py in inner response = get_response(request) ... ▶ Local vars /home/metis/public_html/AGATA/agataenv/lib/python3.4/site-packages/django/core/handlers/base.py in _get_response response = self.process_exception_by_middleware(e, request) ... ▶ Local vars /home/metis/public_html/AGATA/agataenv/lib/python3.4/site-packages/django/core/handlers/base.py in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ... ▶ Local vars /home/metis/public_html/AGATA/textMining/views.py in select_text text_mining = TextMining(file_path, keywords) ... ▶ Local vars /home/metis/public_html/AGATA/textMining/TextMining.py in init self.separete_file_sentences() ... ▶ Local vars /home/metis/public_html/AGATA/textMining/TextMining.py in separete_file_sentences file_text = text_file.read().decode('string-escape').decode("utf-8") ... ▶ Local vars /home/metis/public_html/AGATA/agataenv/lib/python3.4/codecs.py in decode (result, consumed) = self._buffer_decode(data, self.errors, final) ... ▶ Local vars on my Django app, already on Apache.., can't figure out what's the problem here, since I'm dealing with encoding (At least I think so..) My code(following the sequence): def select_text(request): book_file = request.FILES['book'] … -
Cbv view object has no attribute 'object' in django
My application in django 1.11, with django floppy forms, after entering the e-mail address - it's ok, sending mail. The problem is when there is no mail address and press the "send" button. I am getting error: 'ProductDetailView' object has no attribute 'object' Traceback said someting about this line in view: context = super(ProductDetailView, self).get_context_data(**kwargs) View.py class ProductDetailView(PageeditorMixin, DetailView, FormView): model = models.Product form_class = forms.DownloadLinkForm template_name = 'products/product_detail.html' def get_success_url(self): return reverse('products:detail', args=[self.kwargs['slug'], self.kwargs['pk']]) def get_context_data(self, **kwargs): context = super(ProductDetailView, self).get_context_data(**kwargs) context['events'] = self.object.events.all() return context def get_form_kwargs(self): kwargs = super(ProductDetailView, self).get_form_kwargs() kwargs['product_pk'] = self.kwargs['pk'] return kwargs def form_valid(self, form): form.send_download_links() return super(ProductDetailView, self).form_valid(form) forms.py from django.core.mail import send_mail from django.template.loader import render_to_string import floppyforms as forms from products import models class DownloadLinkForm(forms.Form): email = forms.EmailField(required=True) email_template = 'products/email.html' def __init__(self, product_pk, *args, **kwargs): super(DownloadLinkForm, self).__init__(*args, **kwargs) self.product = self.get_product_object(product_pk) def get_product_object(self, product_pk): return models.Product.objects.get(pk=product_pk) def get_downloads(self): return self.product.downloads.all() def get_download_links(self): list_download_links = [] for download in self.get_downloads(): list_download_links.append(models.DownloadLink.objects.create(download_file=download, email=self.cleaned_data['email'])) return list_download_links def send_download_links(self): context = { 'list_download_links': self.get_download_links() } html_message = render_to_string(self.email_template, context) return send_mail('Download link', '', 'mail@mail.com', [self.cleaned_data['email']], html_message=html_message) -
How to iterate through dictionary in Django model?
Each brand in our Campaign model has an order count. The count is retrieved by a GET request to the respective brand's site. The GET request requires an API key and password for each respective brand. The keys and passwords are stored and decoupled in settings.py and the count is passed through to a template with a table. How do we loop through our dictionary of keys and passwords (as in the below) to map an order count to each brand? class Campaign(models.Model): brand = models.CharField(max_length=140, default='') api_key = { 'BRAND1': settings.BRAND1_API_KEY, 'BRAND2': settings.BRAND2_API_KEY, } password = { 'BRAND1': settings.BRAND1_PASSWORD, 'BRAND2': settings.BRAND2_PASSWORD, } orders_url = 'https://{}:{}@site.com/admin/orders/count.json'.format(api_key['brand'], password['brand']) orders_response = requests.get(orders_url) orders_json = orders_response.json() orders = mark_safe(json.dumps(orders_json))