Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python/Django Comparing two float values leads to TypeError: Can't convert 'int' object to str implicitly
I have the following REALLY! strange behavior when i run my functional tests with selenium. I have a javascript that populates an input field within selenium i check for the correct values in that input field which looks like this. The test runs as a class of StaticLiveServerTestCase # Values to compare against lng= 8.63259210000001 # Get the value attribute of the field lng_field = float(self.browser.find_element_by_id('id_lng').get_attribute('value')) # if i use pdb.set_trace() at this position i can do # all the following operations without any problems # When i do any of the following i get an error message mydiff = abs(lng_field-lng) # or lng_field==lng Or any other Operation where there is a comparison or calculation involving lng and lng_field i get the following error: Traceback (most recent call last): File "...", line XXX, in mytest mydiff = abs(lng_field-lng) TypeError: Can't convert 'int' object to str implicitly however everything works within the console when i use pdb.set_trace(). Even when i convert both values to strings and only use the first 5 (mystring[:5]) characters within the string the code line with the comparison leads to the error stated above. The comparison is not even failing, there is just no comparison during runtime β¦ -
Object of type 'AttrList' is not JSON serializable
class SearchSuggest(View): def get(self, request): key_words = request.GET.get('s','') re_datas = [] if key_words: s = JobType.search() s = s.suggest('my_suggest', key_words, completion={ "field":"suggest", "fuzzy":{ "fuzziness":2 }, "size": 10 }) suggestions = s.execute_suggest() for match in suggestions.my_suggest[0].options: source = match._source re_datas.append(source["job_name"]) # return HttpResponse(json.dumps(re_datas), content_type="application/json") return HttpResponse(json.dumps(re_datas), content_type="application/json") # re_datas=list(re_datas) But the result : TypeError: Object of type 'AttrList' is not JSON serializable re_data[] contains like thisthe result So how can i fix this? thanks! -
Django OAuth Toolkit: do not get refresh token when using 'client-credentials' authorization grant type
I am implementing an OAuth2 authentication system for my Django application. Everything works fine and I am able to get and use access tokens. However, I got the following problem: When using 'Resource owner password-based' authentication grant type I am able to get refresh_token. But when I register my application with 'client credentials' grant type, it sends me only access_token but not refresh_token. Is there any way to get refresh_token as well? Thanks in advance -
Django filebrowser upload folder
I need this browser-stuff for my admin-page, and i'd like to be able to upload whole folders. But, at this moment, a can't upload anything. If i get the admin/filebrowser/upload/ url, i can see a page, which say "Select files to upload", but it has no input field. How should I make it work? -
Query still running for django_migrations
I'm developing a django web app and i have notice something strange. The following query will stay in execution in the DB SELECT "django_migrations"."app", "django_migrations"."name" FROM "django_migrations" untill stop the "runserver" Current settings: Django 1.11.2 PostgreSQL 9.2.17 Using Django ORM only All migrations were applied CONN_MAX_AGE setted in settings.py Why Django doesn't close the connection after the query execution? -
Django widget override template
i am new at django. I try to create a custom widget. forms.py: TEST_COLORS = [ u"Blau", u"Rot", u"Gelb" ] color = forms.MultipleChoiceField( label=_("Color"), choices=[(x, x) for x in TEST_COLORS], widget=MultiChoiceFilterWidget, required=False) widget.py: class MultiChoiceFilterWidget(forms.widgets.CheckboxSelectMultiple): template_name = 'project/widgets/filter.html' option_template_name = 'ptoject/widgets/filter_option.html' project/widgets/filter.html: <h1>TEST</h1> But it don't get the new template. It still render it like the old way. Can you give me some tipps? -
No matching distribution found for django
I'm quite fresh in programming - I was using Django 1.10.6 and I tried to switch to 1.18 and that's what happened: (env)$ pip install django==1.18 Collecting django==1.18 Could not find a version that satisfies the requirement django==1.18 (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.11a1, 1.11b1, 1.11rc1, 1.11, 1.11.1, 1.11.2) No matching distribution found for django==1.18 What is wrong? I should upgrade pip? -
django viewflow without gui
I'm using Django Viewflow like a flow engine without gui. Can anyone post an example for creating a process and flow management programmatically? I do not understand how to manage the flow completely from django code (eg from a test class) without a frontend. Do I need to create a flow instance first? How do I know which task I must perform and how do I performs it? I need to use only viewflow without a gui Thanks in advance! MyApp/models.py class MedicalParameters(models.Model): # medical parameters pas = models.IntegerField(verbose_name="Pressione Sistolica") pad = models.IntegerField(verbose_name="Pressione Diastolica") fc = models.IntegerField(verbose_name="Frequenza Cardiaca") class Triage(models.Model): date = models.DateTimeField(auto_now=True) patient_id = models.CharField(max_length=20) first_name = models.CharField(max_length=150) last_name = models.CharField(max_length=150) birth_date = models.DateField(auto_now=False) sex = models.CharField(max_length=1, choices=SEX, default='M') # Medical Parameters parameters = models.ForeignKey(MedicalParameters, blank=True, null=True, on_delete=models.PROTECT) class TriageProcess(Process): triage = models.ForeignKey(Triage, blank=True, null=True, on_delete=models.CASCADE) class Meta: verbose_name_plural = 'Triage process' MyApp/flow.py class TriageFlow(Flow): process_class = TriageProcess process_title = 'Processo di Triage' process_description = 'Processo di Triage' summary_template = """ Triage di {{ process.triage.first_name }} {{ process.triage.last_name }} """ start = ( flow.Start( views.StartView, task_title="Nuovo Triage", task_description="Inizia Triege" ).Permission( auto_create=True ).Next(this.register_measures) ) register_measures = ( flow.View( views.MeasuresView, # fields=["parameters"], task_description="Acquisisci Misure", task_title='Misure da Multiparametrico' ) .Assign(lambda act: act.process.created_by) β¦ -
FileNotFoundError: [WinError 3]
I'm on a Django project which i will scrape some data from various websites. I will use Scrapy to do that. I also found a plugin for Scrapy; Django Dynamic Scraper. I am constantly getting errors when i try to install packages (maybe because i am still using win7 and yes i am drawing figures on my cave's walls). I looked up questions&answers on the web and none of the solutions fixed mine. Anyway, i am getting this error when i try to migrate the project. I added dynamic_scraper to the INSTALLED_APPS. This is my INSTALLED_APPS: INSTALLED_APPS = [ 'item.apps.ItemConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'dynamic_scraper', ] And this is the error: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "C:\Users\systems\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\__init__.py", line 363, in execute_from_command_line utility.execute() File "C:\Users\systems\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\systems\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\systems\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\base.py", line 330, in execute output = self.handle(*args, **options) File "C:\Users\systems\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\commands\migrate.py", line 83, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) File "C:\Users\systems\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\migrations\executor.py", line 20, in __init__ self.loader = MigrationLoader(self.connection) File "C:\Users\systems\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\migrations\loader.py", line 52, in __init__ self.build_graph() File "C:\Users\systems\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\migrations\loader.py", line 203, in build_graph self.load_disk() File "C:\Users\systems\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\migrations\loader.py", line 107, in load_disk for name in os.listdir(directory): β¦ -
How to clear some warning messages using Django and Python
I need some help. I am getting some warnings while running my code using pylint and I need to solve those. I am explaining my code below. W: 11, 0: String statement has no effect (pointless-string-statement) C: 15, 4: Missing method docstring (missing-docstring) R: 15, 4: Method could be a function (no-self-use) W: 18, 4: String statement has no effect (pointless-string-statement) C: 19, 4: Missing method docstring (missing-docstring) E: 21,11: Instance of 'UserCreationForm' has no 'is_valid' member (no-member) R: 19, 4: Method could be a function (no-self-use) C: 28, 4: Missing method docstring (missing-docstring) R: 28, 4: Method could be a function (no-self-use) W: 31, 4: String statement has no effect (pointless-string-statement) C: 32, 4: Missing method docstring (missing-docstring) E: 34,11: Instance of 'AuthenticationForm' has no 'is_valid' member (no-member) R: 32, 4: Method could be a function (no-self-use) C: 38, 0: Missing function docstring (missing-docstring) W: 41, 0: String statement has no effect (pointless-string-statement) C: 43, 0: Missing function docstring (missing-docstring) C: 72, 0: Missing function docstring (missing-docstring) W: 75, 0: String statement has no effect (pointless-string-statement) C: 77, 0: Missing function docstring (missing-docstring) W: 98, 0: String statement has no effect (pointless-string-statement) C:100, 0: Missing function docstring (missing-docstring) My β¦ -
ImportError: No module named TestModel when use manage.py to runserver
I user Django create a project named testdj, and also in it I created a APP named TestModel, see my tree: aircraftdeMacBook-Pro:TestPython ldl$ tree testdj/ testdj/ βββ db.sqlite3 βββ manage.py βββ templates β βββ base.html β βββ ext-1.html β βββ hello.html β βββ index.html βββ testdj βββ TestModel β βββ __init__.py β βββ admin.py β βββ apps.py β βββ migrations β β βββ __init__.py β βββ models.py β βββ tests.py β βββ views.py βββ __init__.py βββ __init__.pyc βββ helloworld.py βββ settings.py βββ settings.pyc βββ urls.py βββ urls.pyc βββ view.py βββ view.pyc βββ wsgi.py βββ wsgi.pyc But when I cd to the testdj/ directory, I want to run the wsgi server: $ python manage.py runserver I get the below error: Unhandled exception in thread started by <function wrapper at 0x10b80ede8> Traceback (most recent call last): File "/Library/Python/2.7/site-packages/Django-1.11.2-py2.7.egg/django/utils/autoreload.py", line 227, in wrapper fn(*args, **kwargs) File "/Library/Python/2.7/site-packages/Django-1.11.2-py2.7.egg/django/core/management/commands/runserver.py", line 117, in inner_run autoreload.raise_last_exception() File "/Library/Python/2.7/site-packages/Django-1.11.2-py2.7.egg/django/utils/autoreload.py", line 250, in raise_last_exception six.reraise(*_exception) File "/Library/Python/2.7/site-packages/Django-1.11.2-py2.7.egg/django/utils/autoreload.py", line 227, in wrapper fn(*args, **kwargs) File "/Library/Python/2.7/site-packages/Django-1.11.2-py2.7.egg/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/Library/Python/2.7/site-packages/Django-1.11.2-py2.7.egg/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/Library/Python/2.7/site-packages/Django-1.11.2-py2.7.egg/django/apps/config.py", line 94, in create module = import_module(entry) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) ImportError: No module named β¦ -
When I use Django to develop a blog, the static html page in the form of some problems
How can I get back to the index page after I click on the submit button. I wrote some code he can normally return to the index page but there is no content, that some of the title content and the like urls: urlpatterns = [ url(r'^xadmin/', xadmin.site.urls), url(r'^$', index,), url(r'^bbs/', index,), url(r'^details/(\d+)/$', get_details), url(r'^bbs_pub/$', bbs_pub,name='publish'), url(r'^bbs_sub/$', bbs_sub,name='sub'), ] views: def bbs_sub(request): title = request.POST.get('title') contet = request.POST.get('content') author = models.BBSuser.objects.get(username='merinw') models.BBS.objects.create( title=title, summary='dsad', content=contet, author=author, view_count = 10 ) return render(request,'index.html',) index.html: <div class="container"style="margin-top: 70px"> {% block page-content %} <div class="border"> <a href="{% url 'publish' %}"> <div style="margin-right: 30px; "> <span class="glyphicon glyphicon-edit" aria-hidden="false" style="font-size: 40px" ></span> </div> </a> <div class="jumbotron"> {% for bbs in bbs_list %} <h4> <a href="/details/{{ bbs.id }}" >{{ bbs.title }}</a></h4> <br> {{ bbs.summary }} <hr> {% endfor %} </div> publish.html <form method="post" action="/bbs_sub/" class="editor"> {% csrf_token %} <label>ζη« ζ ι’ <input type="text" name="title" class="title"> </label> <textarea id="mytextarea" name="content"></textarea> <input type="submit" value="ζδΊ€" class="subbtu"> {% csrf_token %} When I run the end, the index page is emptyοΌwho can give me some suggestionsγ -
Create multiple new objects in bulk in Django
I have this model: class School(BaseModel): name = models.CharField(max_length=256) I want to create a form where user can create multiple schools at the same time. I know that there is inlineformset_factory for such cases and all discussions I found online related to creating multiple children of a parent. But in my case I just need multiple parents. I tried to use formset_factory SchoolFormSet = formset_factory(SchoolForm, extra=5) which renders the form properly, but form_valid method is never called and instead form_invalid is called with an error indicating that I did not fill in 'name'...which is not true. This is my form: class SchoolForm(forms.Form): name = forms.CharField( widget=forms.TextInput(attrs=dict( placeholder=_('NΓ‘zev Ε‘koly') )), required=True ) This is my view: class SchoolCreate(CreateView): model = School fields = ['name'] template_name = 'school_create.html' def get_context_data(self, **kwargs): data = super(SchoolCreate, self).get_context_data(**kwargs) if self.request.POST: data['school_formset'] = SchoolFormSet(self.request.POST) else: data['school_formset'] = SchoolFormSet() return data def form_valid(self, form): context = self.get_context_data() schools = context['school_formset'] print(schools) with transaction.commit_on_success(): form.instance.created_by = self.request.user form.instance.updated_by = self.request.user self.object = form.save() if schools.is_valid(): schools.instance = self.object schools.save() return super(SchoolCreate, self).form_valid(form) def form_invalid(self, form): print(form.errors) pass -
Streaming & downloading Large CSV files using StreamingHttpResponse
So the issue I am facing is trying to get our webservers export to CSV button working, one requirement is the file cannot be saved locally and must be streamed straight to the client. At the moment I am just trying to get a basic CSV file streamed and saved on the local machine from the server before I worry about rendering actual data. So, I have, on button click a post to my views where I wish to render then return a response. This was a $.ajax function but I have since changed it during testing and it now looks like this looks like: $("#exportbutton").click(function(e){ $.post("{% url 'doner:download' %}", function(data) { console.log(data); }); }) The code in the view looks like this (which happens to be a CTRL+V of an example from SO): def download(request): def stream(): buffer_ = io.StringIO() writer = csv.writer(buffer_) for row in rows: writer.writerow(row) buffer_.seek(0) data = buffer_.read() buffer_.seek(0) buffer_.truncate() yield data response = StreamingHttpResponse( stream(), content_type='text/csv' ) disposition = "attachment; filename=file.csv" response['Content-Disposition'] = disposition return response So after a lot of tinkering this is as far as I have got, it will 'stream'(?) the data back into the HTML page, the console.log will output β¦ -
Django REST Framework - PDF Generator
I created a new endpoint for an API (Django REST Framework) that generates a PDF from an HTML template. I follow the example from the plugin django-easy-pdf. It's working, but I would like to improve and to know what could be done in a better way. Asset is an object from the database with information. The idea is to print some rows on an HTML template to then convert to PDF. The HTML is fine, but I'm just not sure if I could improve on this view. URLs: url(r'^report/asset/(?P<pk>[0-9]+)$', api.DemoPDFView.as_view()), views.py from easy_pdf.views import PDFTemplateResponseMixin, PDFTemplateView class DemoPDFView(PDFTemplateView): template_name = 'reports/asset.html' pdf_filename = 'asset.pdf' def get_context_data(self, **kwargs): pk = self.kwargs.get('pk', None) asset = Asset.objects.get(id=pk) project = asset.project.name id = asset.id name = asset.title return super(DemoPDFView, self).get_context_data( pagesize='A4', title='Asset', project=project, name=name, id=id, **kwargs ) The plugin is available: http://django-easy-pdf.readthedocs.io/en/v0.2.0-dev1/ -
django+celery beat can not trigger task
1.django+celery beat can not trigger task 2.code : app/tasks.py from celery.task import periodic_task @periodic_task(run_every=10,name="task.get.list") def task_get_list(): with open('/tmp/1.log','a') as f: f.write('aaa\n') celery log [2017-06-21 17:15:13,127: INFO/MainProcess] Scheduler: Sending due task task.get.list (task.get.list) [2017-06-21 17:15:23,129: INFO/MainProcess] Scheduler: Sending due task task.get.list (task.get.list) -
Converting HTML to PDF using Django
I am trying to convert my HTML into PDF but I am getting the following error: 'dict' object has no attribute 'render_context'. The code is below: utils.py from io import BytesIO from django.http import HttpResponse from django.template.loader import get_template from xhtml2pdf import pisa def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None views.py from django.http import HttpResponse import datetime from django.template.loader import get_template from admin.views.utils import render_to_pdf # created in step 4 def get_pdf_view(request, *args, **kwargs): template = get_template('certificate_appreciation_pdf.html') context = { 'today': datetime.date.today(), 'amount': 39.99, 'customer_name': 'Cooper Mann', 'order_id': 1233434, } html = template.render(context) pdf = render_to_pdf('certificate_appreciation_pdf.html', context) certificate_appreciation_pdf.html <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>Title</title> </head> <body> <div class='wrapper'> <div class='header'> <p class='title'>Invoice # </p> </div> <div> <div class='details'> Bill to: {{ order_id }}<br/> Amount: {{ amount }} <br/> Date: {{ today }} <hr class='hrItem' /> </div> </div> </body> </html> I don't know where I am making an error. Error I got when rendering to that page AttributeError at /pdf/ 'dict' object has no attribute 'render_context' Request Method: GET Request URL: http://0.0.0.0:8001/pdf/ Django Version: 1.5.5 Exception Type: AttributeError Exception β¦ -
Django for/if in template
I have a simple question, but at the moment I'm to dumb to solve it. I have different lists passed from a view to a template to create data for a googletable. It's working quite well and looks like the following: var input_class = 'bc'; if(input_class == 'ab') { var rawData = [['ab'], {%for ab in ab_list%}['{{ab}}'], {% endfor %}]; } else if(input_class == 'bc') { var rawData = [['bc'], {%for bc in bc_list%}['{{bc}}'], {% endfor %}]; } else { var rawData = [['cd'], {%for cd in cd_List%}['{{cd}}'], {% endfor %}]; } For obvious reasons I want to put it in something like the following: {% for key, value in filter_lists.iteritems %} {% if input_class == '{{key}}' %} var rawData = [['{{key}}'], {% for item in value %}['{{item}}'], {% endfor %} ]; {% endif %} {% endfor %} Sadly it does not work. The keys are all strings like 'ab', the values are all the same lists as in the working example. Thanks for help, Jakob. EDIT: I'm using python 2.7, django 1.11 input_class is changed by a dropdown-menu which is created by a list. The same list is defining the keys of the dict. -
AngularJS and jQuery Datatables Integration
I'm using Django and there I'm serialising a query from my database. After I using GET Method get the JSON in AngularJS, I want to paint this in a datatable, and I am doing this using ng-repeat (I understand that ng-repeat works very slow), but only paint the data and nothing works anymore, when I try to search a data the table show empty. I found this angular-datatables web for can use jQuery Datatables and AngularJS, I tried to use the ajax option and the angular js option (there they also talk about the slowness of ng-repeat for the job), but I can not understand how to implement it in my code, I tried to look for code examples on the page but there is only about Angular (Angular2>) using typescript and in the explanatory code of the documentation it is not very clear to me if I should add ['datatables'] and related things even though the app contains other controllers that have nothing to do with datatables. View.py def listarServicios(request): servicios=Servicio.objects.filter(ofertado=True) data=serializers.serialize('json',servicios) return HttpResponse(data, content_type="application/json") Base.html <html ng-app="appControl"> <!-- Tags... --> {% block content %} {% endblock %} </html> Servicios.html {% extends 'Base.html' %} ... {% block content %} β¦ -
On the formatting of Python datetimes
A slight OCD question here - I'm using the {% humanize %} tag in Django which gives me date times returned in the following format: June 17, 2017 07:24 pm Now, within my post model in Django I am returning the following: def published_date(self): """Returns a humanized date format for Algolia indexing.""" humanized_published_date = str(self.publish.strftime("%B %d, %Y %I:%M%p")) return humanized_published_date All works well. HOWEVER, the format returned in the above method is: June 17, 2017 07:24PM I've had a previous read of the datetime documentation here (https://docs.python.org/2/library/datetime.html) specifically the section "8.1.7. strftime() and strptime() Behavior". I can see what I may need is the de_DE formatting - which displays a 12 hour clock suffix as pm and not PM. So, my question is this. How do I re-format date times to give a format as the following: June 17, 2017 07:24 pm.* (As mentioned in the above code - I'm currently using %B %d, %Y %I:%M%p). *N.B. I'm OCD to the point where I don't want June 17, 2017 07:24PM or even June 17, 2017 07:24pm! i.e., I need that space between the twelve hour clock and the ante meridiem and post meridiem suffixes. -
url is not reaching to a particular view of another app in django
i want to create a search app for my blog project. Following are the codes this navbar.html contains search-bar which is included in every page as template. The search form below takes the search-query to to url = /search/ <nav class="navbar navbar-toggleable-md navbar-inverse bg-primary"> <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <a class="navbar-brand" href="#">ViBlog</a> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav"> <li class="nav-item active"> <a class="nav-link " href="{% url 'posts:home' %}">Home <span class="sr-only">(current)</span></a> </li> <form class="form-inline my-0 my-lg-0 mx-5" method="GET" url="{% url 'search' %}"> <input class="form-control mr-sm-2" type="text" id="search" name="q" placeholder="Search"> <button class="btn btn-outline-success my-2 my-sm-0" type="submit" id="search">Search</button> </form> </ul> </div> urls.py from django.conf import settings from django.conf.urls import url, include from django.conf.urls.static import static from django.contrib import admin from authentication import views as auth_views from search import views as search_views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^login/$', auth_views.login_view, name='login'), url(r'^signup/$', auth_views.signup, name='signup'), url(r'^logout/$', auth_views.logout_view, name='logout'), url(r'^search/$', search_views.search, name='search'), url(r'^draceditor/', include('draceditor.urls')), url(r'^', include('blogs.urls', namespace='posts')), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) views.py at now i am just testing whether search function will run upon calling it. but it does not run. from django.shortcuts import render from django.http import HttpResponse def search(request): return β¦ -
list not defined although it all seems to be correct [on hold]
Hi I am following the book test driven web development with python and I am up to chapter 3 where we have to test the URL for home page. I have writtine the code verbatumn and Ihav e had my code checked by my freind who is a python developer and we cant work out why Idjango cannot deifne lists. I can provide code here if required. File "/home/user/Projects/tdwd/superlist/superlist/urls.py", line 24, in <module> url(r'^$', lists.views.home_page, name='home'), NameError: name 'lists' is not defined -
Whoosh haystack search error in django project
I am using Whoosh / Haystack in a Django project for text indexing and search. There is a search bar on the website. Results are refreshed and shown after every letter entered. I want to search the term 'income tax' through the search bar. When I start writing 'income tax', I get results till 'inc' (first three letters) and after that I get server error when I write 'o','m','e' and ' '. When I write 'ta' from 'tax', I get results shown again and after that again I get server error when I write 'x' of 'tax'. Also, when I search for the term 'income tax' using SearchQueryset in shell, I get a whoosh object containing more than hundred items. I can't understand this weird behaviour. -
django-users2 returns DoesNotExist after configuration
after I install Django-users2 app : https://github.com/mishbahr/django-users2 and after configuration, I get DoesNotExist everytime I hit /accounts/* this is my code : BloggerSquadPlatform is my project name and BloggerSquad is my app: BloggerSquadPlatform/urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^', include('BloggerSquad.urls')), ] BloggerSquad/urls.py urlpatterns = [ url(r'^$', views.index,name='index'), url(r'^accounts/', include('users.urls')), ] this is the only configuration I found in the internet. yet when I go to http://127.0.0.1:8000/accounts/register/ I get DoesNotExist Error. Environment: Request Method: GET Request URL: http://127.0.0.1:8000/accounts/register/ Django Version: 1.11.2 Python Version: 3.4.3 Installed Applications: ['BloggerSquad', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.sites', 'users', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'clear_cache'] Installed Middleware: ['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'] Traceback: File "C:\Users\noon3\Squad\lib\site-packages\django\contrib\sites\models.py" in _get_site_by_request 44. SITE_CACHE[host] = self.get(domain__iexact=host) File "C:\Users\noon3\Squad\lib\site-packages\django\db\models\manager.py" in manager_method 85. return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\noon3\Squad\lib\site-packages\django\db\models\query.py" in get 380. self.model._meta.object_name During handling of the above exception (Site matching query does not exist.), another exception occurred: File "C:\Users\noon3\Squad\lib\site-packages\django\core\handlers\exception.py" in inner 41. response = get_response(request) File "C:\Users\noon3\Squad\lib\site-packages\django\core\handlers\base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "C:\Users\noon3\Squad\lib\site-packages\django\core\handlers\base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\noon3\Squad\lib\site-packages\django\utils\decorators.py" in _wrapped_view 149. response = view_func(request, *args, **kwargs) File "C:\Users\noon3\Squad\lib\site-packages\django\views\decorators\cache.py" in _wrapped_view_func 57. response = view_func(request, *args, **kwargs) File "C:\Users\noon3\Squad\lib\site-packages\users\views.py" in register 75. current_site = get_current_site(request) File "C:\Users\noon3\Squad\lib\site-packages\django\contrib\sites\shortcuts.py" β¦ -
Django - getting a path from a variable when saving models
My app has a simple process, the user uploads a gif file and then the gif is conveted to frames that are saved as objects. For the upload_to part of my gif, I run a function content_file_name() that uses uuid to create a folder path. I want the image frames to be saved to the same folder as the gif. Problem is, I can't set the path as a variable as much as I try. The variable needs to be defined first, but if I define it, it doesn't change no matter what I do. Here's what I got now: currentFilePath = '' # Defining the variable def content_file_name(instance, filename): ext = ''.join(filename.split())[:-4] foldername = "%s/%s" % (uuid.uuid4(), ext) store_random_path('/'.join(['documents', str(foldername)])) # Running a function to change the variable return '/'.join(['documents', str(foldername), filename]) def store_random_path(path): currentFilePath = str(path) # The variable should be changed here class Document(models.Model): docfile = models.ImageField(upload_to=content_file_name) def create_documentfiles(self): gif = Image.open(self.docfile.path) frames = [frame.copy() for frame in ImageSequence.Iterator(gif)] basename, _ext = os.path.splitext(self.docfile.name) for index, frame in enumerate(frames): buffer = BytesIO() frame.convert('RGB').save(fp=buffer, format='JPEG') destname = "{}{}.png".format(basename, index) finalImage = InMemoryUploadedFile(buffer, None, destname, 'image/jpeg', frame.tell, None) imageToSave = DocumentImage(imagefile=finalImage) imageToSave.save() class DocumentImage(models.Model): imagefile = models.ImageField(upload_to=currentFilePath) # Trying to β¦